Bit shifting signed and unsigned integers - 64-bit

using (MemoryStream mem = new MemoryStream (bytes.Skip(4).toArray()))
{
using (BinaryReader reader = new BinaryReader(mem))
{
UInt32 time1;
UInt32 time2;
Int64 time = 0;
try{
time1 = reader.ReadInt32();
time2 = reader.ReadInt32();
time = (((Int64)time2) << 32) | time1;
return new DateTime(time);
}
catch{
}
}
}
I know this code is dealing with signed/unsigned integers and bit shifting, but I am not exactly sure I understand it as a whole. Could someone explain? Also what would be the reason behind this code giving an OutOfRange exception saying the number must be non-negative and less than or equal to Int32.maxvalue or -1 when this code is called in a Thread.Sleep?

Related

Azure Face API call slow down after ~350 comparsion

I have just created a trial account in Azure and trying to do a batch processing of face comparison through c# program
My program calls DetectWithUrlAsync twice and call VerifyFaceToFaceAsync once for each comparison
It works for a small number of calls, but when tested for 500 pairs of faces, it suddens become very slow after doing 350 comparisons (350x3 calls). Orginal is less than 1 second but now more than a few seconds per call.
I am using the standard plan because I think I am using the $200 free credit. Don't know what is happening.
private async Task<VerifyResult> Verify(IFaceClient faceClient, string url1, string url2, string recognition_model)
{
var faces_1 = faceClient.Face.DetectWithUrlAsync(url1, recognitionModel: recognition_model, detectionModel: DetectionModel.Detection03);
var faces_2 = faceClient.Face.DetectWithUrlAsync(url2, recognitionModel: recognition_model, detectionModel: DetectionModel.Detection03);
Task.WaitAll(new Task<IList<DetectedFace>>[] { faces_1, faces_2 });
return await faceClient.Face.VerifyFaceToFaceAsync((Guid)faces_1.Result[0].FaceId, (Guid)faces_2.Result[0].FaceId);
}
main()
{
for (int i = 0; i < count; i++)
{
VerifyResult result = await Verify(client, url[i].url1, url[i].url2, RECOGNITION_MODEL4);
if (result != null)
{
wks.Cells[2 + i, ColSame] = result.IsIdentical ? "Yes" : "No";
wks.Cells[2 + i, ColConfidence] = result.Confidence;
}
}
}

Error reading JObject from JsonReader. Current JsonReader item is not an object in C#

I have written a piece of code to get a value from a currency converter like below:
WebClient n = new WebClient();
var JsonData = n.DownloadString("http://currencyconverterapi.com/api/v6/convert?q=USD_NRI&compact=ultra&apiKey=");
JsonData = {"USD_INR":69.657026} // Got value result from JsonData
dynamic JObj = JObject.Parse(JsonData);
dynamic JOresult = JObject.Parse(Convert.ToString(JObj.USD_INR)); //Got Error here (Error reading JObject from JsonReader. Current JsonReader item is not an object: Float. Path '', line 1, position 9.)
string JOFilter_Val = Convert.ToString(JOresult.val);
decimal Total = 230 * Convert.ToDecimal(JOFilter_Val);
return Total;
I want to get the value '69.657026' from multiplying with the decimal 230, and return the final result. Can anybody tell me what I'm doing wrong and if possible please correct it?
It's not really clear why you're trying to parse 69.657026 as a JObject - it's not an object.
I suspect you don't need to do that at all - just use JObj.USD_INR as a decimal:
decimal value = JObj.USD_INR; // Use the dynamic conversion to handle this
In general you seem to be converting back and forth far more than you need to. Here's a complete example of what I think you're trying to do:
using Newtonsoft.Json.Linq;
using System;
class Test
{
static void Main()
{
string json = "{ \"USD_INR\": 69.657026 }";
dynamic obj = JObject.Parse(json);
decimal rate = obj.USD_INR;
decimal total = 230 * rate;
Console.WriteLine(total); // 16021.115980
}
}
Alternatively, without dynamic typing:
using Newtonsoft.Json.Linq;
using System;
class Test
{
static void Main()
{
string json = "{ \"USD_INR\": 69.657026 }";
JObject obj = JObject.Parse(json);
decimal rate = (decimal) obj["USD_INR"];
decimal total = 230 * rate;
Console.WriteLine(total);
}
}

Is it normal to solve a TSP with GA(Genetic Algorithyms) implementation takes much time?

I am working on GA for a project. I am trying to solve Travelling Salesman Problem using GA. I used array[] to store data, I think Arrays are much faster than List. But for any reason it takes too much time. e.g. With MaxPopulation = 100000, StartPopulation=1000 the program lasts to complete about 1 min. I want to know if this is a problem. If it is, how can I fix this?
A code part from my implementation:
public void StartAsync()
{
Task.Run(() =>
{
CreatePopulation();
currentPopSize = startPopNumber;
while (currentPopSize < maxPopNumber)
{
Tour[] elits = ElitChromosoms();
for (int i = 0; i < maxCrossingOver; i++)
{
if (currentPopSize >= maxPopNumber)
break;
int x = rnd.Next(elits.Length - 1);
int y = rnd.Next(elits.Length - 1);
Tour parent1 = elits[x];
Tour parent2 = elits[y];
Tour child = CrossingOver(parent1, parent2);
int mut = rnd.Next(100);
if (mutPosibility >= mut)
{
child = Mutation(child);
}
population[currentPopSize] = child;
currentPopSize++;
}
progress = currentPopSize * 100 / population.Length;
this.Progress = progress;
GC.Collect();
}
if (GACompleted != null)
GACompleted(this, EventArgs.Empty);
});
}
In here "elits" are the chromosoms that have greater fit value than the average fit value of the population.
Scientific papers suggest smaller population. Maybe you should follow what is written by the other authors. Having big population does not give you any advantage.
TSP can be solved by GA, but maybe it is not the most efficient approach to attack this problem. Look at this visual representation of TSP-GA: http://www.obitko.com/tutorials/genetic-algorithms/tsp-example.php
Ok. I have just found a solution. Instead of using an array with size of maxPopulation, change new generations with the old and bad one who has bad fitness. Now, I am working with a less sized array, which has length of 10000. The length was 1,000.000 before and it was taking too much time. Now, in every iteration, select best 1000 chromosomes and create new chromosomes using these as parent and replace to old and bad ones. This works perfect.
Code sample:
public void StartAsync()
{
CreatePopulation(); //Creates chromosoms for starting
currentProducedPopSize = popNumber; //produced chromosom number, starts with the length of the starting population
while (currentProducedPopSize < maxPopNumber && !stopped)
{
Tour[] elits = ElitChromosoms();//Gets best 1000 chromosoms
Array.Reverse(population);//Orders by descending
this.Best = elits[0];
//Create new chromosom as many as the number of bad chromosoms
for (int i = 0; i < population.Length - elits.Length; i++)
{
if (currentProducedPopSize >= maxPopNumber || stopped)
break;
int x = rnd.Next(elits.Length - 1);
int y = rnd.Next(elits.Length - 1);
Tour parent1 = elits[x];
Tour parent2 = elits[y];
Tour child = CrossingOver(parent1, parent2);
int mut = rnd.Next(100);
if (mutPosibility <= mut)
{
child = Mutation(child);
}
population[i] = child;//Replace new chromosoms
currentProducedPopSize++;//Increase produced chromosom number
}
progress = currentProducedPopSize * 100 / maxPopNumber;
this.Progress = progress;
GC.Collect();
}
stopped = false;
this.Best = population[population.Length - 1];
if (GACompleted != null)
GACompleted(this, EventArgs.Empty);
}
Tour[] ElitChromosoms()
{
Array.Sort(population);
Tour[] elits = new Tour[popNumber / 10];
Array.Copy(population, elits, elits.Length);
return elits;
}

Windows 10 get DeviceFamilyVersion

I'm working windows 10 10240 Univasal windows app, when i use Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamilyVersion to get deivce version, it return a string "2814750438211605" instead of a version format (major.minor.revision.build).
Anyone can tell me what the string "2814750438211605" means?
The Windows 10 OS version value is located in this string property:
Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamilyVersion
It returns string value like "2814750438211613".
To convert this long number to readable format use this:
string sv = AnalyticsInfo.VersionInfo.DeviceFamilyVersion;
ulong v = ulong.Parse(sv);
ulong v1 = (v & 0xFFFF000000000000L) >> 48;
ulong v2 = (v & 0x0000FFFF00000000L) >> 32;
ulong v3 = (v & 0x00000000FFFF0000L) >> 16;
ulong v4 = v & 0x000000000000FFFFL;
string version = $"{v1}.{v2}.{v3}.{v4}"; // == 10.0.10240.16413
Your application should treat the as opaque data and just log it "as is". It's a 64-bit decimal value as a string.
Remember the intent of this API is to provide a log string from which you can reconstruct the OS version number for support/analytics. On your server-side analysis, you'd convert it if needed or just use it as a unique version identifier... If you are actually trying to parse it runtime, then you are using it incorrectly and quite likely to recreate same problems that resulted in GetVersionEx and VerifyVersionInfo being deprecated in the first place.
Do not parse the string at runtime in your app. Just store "as is" Remember that with Windows 10, a customer really has no idea what you mean if you ask "What version of Windows do you have?". The answer is "10" and will likely still be "10" for a long time to come.
If you found this question and like me you are looking for a way to do this in JavaScript, then you might find this useful.
getDeviceFamilyVersion() {
let deviceFamilyVersion = Windows.System.Profile.AnalyticsInfo.versionInfo.deviceFamilyVersion;
let deviceFamilyVersionDecimalFormat = parseInt(deviceFamilyVersion);
if (isNaN(deviceFamilyVersionDecimalFormat)) {
throw new Error('cannot parse device family version number');
}
let hexString = deviceFamilyVersionDecimalFormat.toString(16).toUpperCase();
while (hexString.length !== 16) { // this is needed because JavaScript trims the leading zeros when converting to hex string
hexString = '0' + hexString;
}
let hexStringIterator = 0;
let versionString = '';
while (hexStringIterator < hexString.length) {
let subHexString = hexString.substring(hexStringIterator, hexStringIterator + 4);
let decimalValue = parseInt(subHexString, 16);
versionString += decimalValue + '.';
hexStringIterator += 4;
}
return versionString.substring(0, versionString.length - 1);
}
Just a nifty way of doing this .. I Creadted a Enum that is used to match predefined device families
public enum DeviceFamily
{
Unknown,
Desktop,
Tablet,
Mobile,
SurfaceHub,
Xbox,
Iot
}
This method will check and parse it into the enum.
var q = ResourceContext.GetForCurrentView().QualifierValues;
if (q.ContainsKey("DeviceFamily"))
{
try
{
Enum.Parse(typeof(DeviceFamily) , q["DeviceFamily"]);
//send the user notification about the device family he is in.
}
catch (Exception ex) { }
}

ftp .net getdirectory size

hi i write method which must to know that is size of specified directory i get response from server which contains flags of file name size and other info and on the different ftp servers format of answer is different how to know format of answer?
unsigned long long GetFtpDirSize(String^ ftpDir) {
unsigned long long size = 0;
int j = 0;
StringBuilder^ result = gcnew StringBuilder();
StreamReader^ reader;
FtpWebRequest^ reqFTP;
reqFTP = (FtpWebRequest^)FtpWebRequest::Create(gcnew Uri(ftpDir));
reqFTP->UseBinary = true;
reqFTP->Credentials = gcnew NetworkCredential("anonymous", "123");
reqFTP->Method = WebRequestMethods::Ftp::ListDirectoryDetails;
reqFTP->KeepAlive = false;
reqFTP->UsePassive = false;
try {
WebResponse^ resp = reqFTP->GetResponse();
Encoding^ code;
code = Encoding::GetEncoding(1251);
reader = gcnew StreamReader(resp->GetResponseStream(), code);
String^ line = reader->ReadToEnd();
array<Char>^delimiters = gcnew array<Char>{
'\r', '\n'
};
array<Char>^delimiters2 = gcnew array<Char>{
' '
};
array<String^>^words = line->Split(delimiters, StringSplitOptions::RemoveEmptyEntries);
array<String^>^DetPr;
System::Collections::IEnumerator^ myEnum = words->GetEnumerator();
while ( myEnum->MoveNext() ) {
String^ word = safe_cast<String^>(myEnum->Current);
DetPr = word->Split(delimiters2);
}
}
Basically, you can't. You are interpreting the raw result and there is no defined format for this data (or is there any requirement that this data be returned at all in the response). And the FTP protocol does not define any other way of getting this.
What that leaves you with is a collection of parsing patterns for the server types you know about and working through them looking for valid data. Not entirely easy.

Resources