J2ME : How to get SDCard's available Free Space - java-me

I am building J2ME application, where I want to get size of available free space on SDCard and on Phone internal storage.

FileConnection fc = (FileConnection) Connector.open("file:///SDCard/");
long total = fc.totalSize();
long used = fc.usedSize();
long free = total - used;

Related

Why does excel VBA code runs 2000 times slower on some machines?

I have created an excel VBA macro with does a lot of data intensive processing. I make a lot of use of Collections. On some PCs it runs very fast, and on others it runs very slow. I have isolated the problem in the example code below. Please note that the example code is not an functional program, it is just to isolate the technical problem I encounter in the bigger program.
I have tested the macro on 4 different machines. See below the output with the CPU info, all use “Microsoft® Excel® for Microsoft 365 MSO (Version 2210 Build 16.0.15726.20188) 32-bit”:
Intel(R) Core(TM) i9-10900K CPU # 3.70GHz, RAM 16.0 GB:
Run loop took 0.09 seconds. Clearing memory took 0.04 seconds.
11th Gen Intel(R) Core(TM) i7-1185G7 # 3.00GHz, RAM 16,0 GB:
Run loop took 0,10 seconds. Clearing memory took 0,05 seconds.
Intel(R) Core(TM) i7-7700K CPU # 4.20GHz, RAM 32,0 GB:
Run loop took 162,58 seconds. Clearing memory took 5,48 seconds.
Intel(R) Core(TM) i7-8665U CPU # 1.90GHz, RAM 16.0 GB:
Run loop took 201,03 seconds. Clearing memory took 6,37 seconds.
Code of the VBA procedure:
Option Explicit
Sub largeCollection()
Dim time1 As Single
Dim time2 As Single
time1 = Timer
Dim myCollection As New Collection
Dim I As Long
Dim aClass1 As Class1
For I = 2 To 50000
Set aClass1 = New Class1
aClass1.d1 = I
aClass1.d2 = I
aClass1.d3 = I
aClass1.d4 = I
aClass1.d5 = I
aClass1.d6 = I
aClass1.d7 = I
aClass1.d8 = I
aClass1.d9 = I
aClass1.d10 = I
aClass1.i1 = I
aClass1.i2 = I
aClass1.i3 = I
aClass1.i4 = I
aClass1.i5 = I
aClass1.i6 = I
aClass1.i7 = I
aClass1.i8 = I
aClass1.i9 = I
aClass1.i10 = I
myCollection.Add aClass1
Next I
time2 = Timer
Set myCollection = Nothing
'Notify user in seconds
Debug.Print "Run loop took " & Format((time2 - time1), "0.00") & " seconds. Clearing memory took " & Format((Timer - time2), "0.00") & " seconds."
End Sub
Code of the custom class "Class1":
Option Explicit
Public s1 As String
Public s2 As String
Public s3 As String
Public s4 As String
Public s5 As String
Public s6 As String
Public s7 As String
Public s8 As String
Public s9 As String
Public s10 As String
Public s11 As String
Public s12 As String
Public s13 As String
Public s14 As String
Public s15 As String
Public s16 As String
Public s17 As String
Public s18 As String
Public s19 As String
Public s20 As String
Public v1 As Variant
Public v2 As Variant
Public v3 As Variant
Public v4 As Variant
Public v5 As Variant
Public v6 As Variant
Public v7 As Variant
Public v8 As Variant
Public v9 As Variant
Public v10 As Variant
Public i1 As Long
Public i2 As Long
Public i3 As Long
Public i4 As Long
Public i5 As Long
Public i6 As Long
Public i7 As Long
Public i8 As Long
Public i9 As Long
Public i10 As Long
Public d1 As Double
Public d2 As Double
Public d3 As Double
Public d4 As Double
Public d5 As Double
Public d6 As Double
Public d7 As Double
Public d8 As Double
Public d9 As Double
Public d10 As Double
I am running out of options, it would be great if anyone can provide a solution.
We finally have found an answer ourselves, although it is not very comforting... The difference in performance seems to be completely dependent on the trust center macro settings.
If I select the option:
"Disable macros with notification", I have to explicitly "enable content" to enable the macros when I open the workbook. Using this option the macro runs 2000 times slower
"Enable VBA macros (not recommended; potentially dangerous code can run)" the code runs 2000 times faster.
I would expect the 2 options to have the same performance since after I have enabled the content, I have enabled the VBA macros, just as if I would have selected the other option.
This would mean that the only way I can have a performant macro, is to set the option to "Enable VBA macros (not recommended; potentially dangerous code can run)", which would result in all macros for all workbooks being run by default, even if I would open a random excel from a 3rd party, which is a huge security risk.
in Class1 there are a lot of variables, many of them as Variant which requires more memory space. Try to create new collections in the class1 to store the different variables. E.g. Variables v1, v2,…Vn could be a new collection in Class1 with objects from “ClassV”.
Also, you are looping from i=2 to i=50000. Before the Next i, you can set set Class1 = Nothing to free memory.

how to get the microsecond portion of GetSystemTimePreciseAsFileTime/ " cLngLng of FileTime"

Spring boarding off of Gustav's comments(Thanks, G) and another hour of searching, if someone can get me started on how to convert filetime to VBA LongLong, I'm confident I can handle it from there. There are examples of C++ FileTime two part variable to Quadword etc, but I know nothing about C++ so cannot mimic this in VBA.
Example in C++ is Stack Overflow question: FILETIME to __int64, scroll down to "Performing Arithmetic with File Times"
Essentially if I can get a custom cLngLng in VBA to handle FileTime input, I should be good to go.
Original Post:
I'm looking at accuracy of various time stamps in VBA, but hit a roadblock on using GetSystemTimePreciseAsFileTime. Apparently it gives a UTC type timestamp with a resolution of 100nSec in FileTime format. I cant figure out how to extract the last four decimal places of the seconds portion. If I use FileTimeToSystemTime it truncates the time to S.000 accuracy. I want to look at the rest of the GetSystemTimePreciseAsFileTime time stamp, i.e look at the seconds portion to the full S.0000000 resolution.
I was hoping I could extract the data and insert into Excel spreadsheet to let me figure this out..code works in saving the timing data, but I'm stuck. You can see the changes to FileTime.dwLowDate when you convert from file time to system time back to file time...is there a way to look at the changes to dwLowDate that tell you what the last four decimal places are?
Code so far is below. Plus of course the appropriate declarations and kernal32 subs and functions.
Some of my reading suggests I might have to use "quadpart", whatever that is, as part of my calculations. Haven't been able to find out how to use quadpart or even if it exists in VBA.
Can someone steer me in the right direction to get the full resolution of the GetSystemTimePreciseAsFileTime?
Sub TestPrecisionTime()
Dim FileTimePercision As FileTime
Dim FileTimeBack As FileTime
Dim LocalSystemTime As SYSTEMTIME
Dim res As Long
GetSystemTimePreciseAsFileTime FileTimePercision 'Get the precision 100nSec system time
'convert it to System Time
res = FileTimeToSystemTime(lpFileTime:=FileTimePercision, lpSystemTime:=LocalSystemTime)
'Convert it back to FileTime to see what has changed from FileTimePercision.dwLowDateTime
res = SystemTimeToFileTime(lpSystemTime:=LocalSystemTime, lpFileTime:=FileTimeBack)
'Save the results so can try to develop algorithm to extract the last four digits of the time
'seconds down to 100 nsec, so S.0000000 "format", System time only gives S.000 "format"
Dim appAnalysis As Application
Dim wbPrecisionTime As Workbook
Dim wsPrecise As Worksheet
Dim sControlWB As String
If appAnalysis Is Nothing Then Set appAnalysis = Application
sControlWB = ActiveWorkbook.Name
If wbPrecisionTime Is Nothing Then Set wbPrecisionTime = appAnalysis.Workbooks(sControlWB)
If wsPrecise Is Nothing Then Set wsPrecise = wbPrecisionTime.Sheets("Precise")
With wsPrecise
.Range("A2") = FileTimePercision.dwLowDateTime
.Range("B2") = FileTimePercision.dwHighDateTime
.Range("C2") = FileTimeBack.dwLowDateTime
.Range("D2") = FileTimeBack.dwHighDateTime
.Range("E2") = LocalSystemTime.wYear
.Range("F2") = LocalSystemTime.wMonth
.Range("G2") = LocalSystemTime.wDayOfWeek
.Range("H2") = LocalSystemTime.wDay
.Range("I2") = LocalSystemTime.wHour
.Range("J2") = LocalSystemTime.wMinute
.Range("K2") = LocalSystemTime.wSecond
.Range("L2") = LocalSystemTime.wMilliseconds
End With
End Sub
To preserve the high resolution, you must use a FILETIME structure.
As you have found, that page mentions using FileTimeToSystemTime to obtain an "easy to display" value, but it forgets to tell, that this can only hold down to milliseconds.
So, I guess, you will have write your own function to convert/display the returned FILETIME value including microseconds. To hold the value, data type DateTime may not do as it is limited to milliseconds, though it can hold microseconds in a limited range (see VBA.Date):
' Interval with minimum one microsecond resolution.
Public Const MaxMicrosecondDateValue As Date = #5/18/1927#
Public Const MinMicrosecondDateValue As Date = #8/13/1872#
Better suited in VBA will be DateTime2. You could also convert to ticks and use data type BigInt.
Addendum:
This answer, Convert from a Windows filetime to a DateTime, explains the relation between ticks and the DateTime of .Net.
The functions DateDotNet and DotNet from module DateSpan shows how to convert between ticks and DateTime of VBA.

got at <unknown> <0xffffffff> stacktrace error (see code below)

if (this.PendingLocalUARTCreditsCount != 0) return;
this.PendingLocalUARTCreditsCount = this.MaxLocalUARTCreditsCount - this.LocalUARTCreditsCount;
IntPtr value = (IntPtr)(this.PendingLocalUARTCreditsCount);
NSData valueData = NSData.FromBytes(value, 1);
this.CbPeripheral.WriteValue(valueData, this.UartRxCreditsCharacteristic, CBCharacteristicWriteType.WithoutResponse);
Got stacktrace error with NSData valueData = NSData.FromBytes(value, 1);
I haven't solved it though in any way. I am developing in C# for an ipad app project using vs 2019 and a, Mac
Nick
Native Crash Reporting
=================================================================
Got a SIGSEGV while executing native code. This usually indicates a fatal error in the mono runtime or one of the native libraries used by your application.
=================================================================
I got SIGSEGV error not SIGABRT. I can discover connect and disconnect but not set rx credits on the peripheral (using Telit 4.0 Bluetooth low, energy module) and am trying to get communication to work so don't think have to set Bluetooth permissions The problem I think is the pointer (Intpr) pointing to the wrong address as app crashes, when it deferences the data.
Thanks for the input though.
Regards nick
Welcome to SO ! You'd better update content all in question , then other people will know problem more clearly .
Although not knowing why NSData.FromBytes occurs error , however there is a workaround for you to check . Using NSData.FromArrayto transfer int to NSData .
int valueInt = 1234567890;
Byte[] byteData = new Byte[1];
byteData[0] = (Byte)((valueInt & 0xFF));
Console.WriteLine("-----NSData-------" + NSData.FromArray(byteData));
Then output is :
-----NSData-------{length = 1, bytes = 0xd2}
Therefore , shared code can be modified as follow :
...
Byte[] byteData = new Byte[1];
byteData[0] = (Byte)((this.PendingLocalUARTCreditsCount & 0xFF));
NSData valueData = NSData.FromArray(byteData);
...

I get "access denied" when I submit a job in Azure

I upload a video in one asp.net page, save the asset in a session variable, and then in another asp.net page, I use that asset to hopefully encode the video (using azure media services calls). The I get an error when I submit the encoding job (with job.submit). It says that access is denied, and the type of exception is: system.security.cryptography.cryptographicException.
I'm wondering if the reason is that I create a context in the new page?
Here is the code from page #1:
Dim mediaServicesAccountName As String = ConfigurationManager.AppSettings("accountname")
Dim mediaServicesAccountKey As String = ConfigurationManager.AppSettings("accountkey")
Dim mediaCloud As New CloudMediaContext(mediaServicesAccountName, mediaServicesAccountKey)
Dim assetOptions As New AssetCreationOptions()
asset = mediaCloud.Assets.Create(Filename, assetOptions)
Session("azureasset") = asset
Dim assetFile As IAssetFile = asset.AssetFiles.Create(Filename)
Session("assetFile") = assetFile
Here is the code from page #2:
Sub Page_Load
Dim asset As IAsset
asset = CType(Session("azureasset"), IAsset)
Dim assetname As String
assetname = asset.Name ' just for debugging
_context = New CloudMediaContext(_accountName, _accountKey)
CreateEncodingJob(asset)
End Sub
Private Function CreateEncodingJob(asset As IAsset) As IJob
Dim job As IJob = _context.Jobs.Create("My encoding job")
Dim processor As IMediaProcessor = GetLatestMediaProcessorByName("Windows Azure Media Encoder")
Dim task As ITask = job.Tasks.AddNew("My encoding task", processor, "H264 Broadband 720p", Microsoft.WindowsAzure.MediaServices.Client.TaskOptions.ProtectedConfiguration)
task.InputAssets.Add(asset)
' Add an output asset to contain the results of the job.
' This output is specified as AssetCreationOptions.None, which
' means the output asset is not encrypted.
task.OutputAssets.AddNew("Output asset", AssetCreationOptions.None)
' Use the following event handler to check job progress.
Dim ev As New EventHandler(AddressOf StateChanged)
AddHandler job.StateChanged, AddressOf StateChanged
' Launch the job.
job.Submit()
Thanks
I would suggest to only keep AssetID in your session. Then get the IAsset reference from the CloudMediaContext once you create it. Use a code similar to this (C#):
//var assetId = [Get this from Session, not the entire Asset object]
var asset = _context.Assets.Where(x => x.Id.Equals(assetId)).FirstOrDefault();
// no configure the job with this asset..
My best bet goes to the fact that indeed you create the CloudMediaContext again, and the reference to the asset is lost. Your new instance of Media Context does not know anything about this asset object you have in your session.

How to check a proper file in android phone's memory?

I need a method that downloads a picture and save it in SD card for later use. I got it finally, i just need an operation that checks if the file in already exists or not.
If not, the app will download it. If it is exitsts, my image view will use it.
So my question is just simple:
How to check a file in SD?
If i got this place for example:
String imageInSD = "/sdcard/1.png";
You can use the following code
String sdcardState = android.os.Environment.getExternalStorageState();
String fileName = "yourfilename" + ".png";
if (sdcardState.contentEquals(android.os.Environment.MEDIA_MOUNTED))
{
String destPath = android.os.Environment.getExternalStorageDirectory().toString()+ File.separator +fileName;
File output =new File(destPath);
if(output.exists())
\\it exists-use Imageview
else
\\Download the file accordingly
}
else
\\SDCARD not mounted

Resources