In documentation String.hash for iOS it says:
You should not rely on this property having the same hash value across
releases of OS X.
(strange why they speak of OS X in iOS documentation)
Well, I need a hasshing function that will not change with iOS releases. It can be simple I do not need anything like SHA. Is there some library for that?
There is another question about this here but the accepted (and only) answer there simply states that we should respect the note in documentation.
Here is a non-crypto hash, for Swift 3:
func strHash(_ str: String) -> UInt64 {
var result = UInt64 (5381)
let buf = [UInt8](str.utf8)
for b in buf {
result = 127 * (result & 0x00ffffffffffffff) + UInt64(b)
}
return result
}
It was derived somewhat from a C++11 constexpr
constexpr uint64_t str2int(char const *input) {
return *input // test for null terminator
? (static_cast<uint64_t>(*input) + // add char to end
127 * ((str2int(input + 1) // prime 127 shifts left almost 7 bits
& 0x00ffffffffffffff))) // mask right 56 bits
: 5381; // start with prime number 5381
}
Unfortunately, the two don't yield the same hash. To do that you'd need to reverse the iterator order in strHash:
for b in buf.reversed() {...}
But that will run 13x slower, somewhat comparable to the djb2hash String extension that I got from https://useyourloaf.com/blog/swift-hashable/
Here are some benchmarks, for a million iterations:
hashValue execution time: 0.147760987281799
strHash execution time: 1.45974600315094
strHashReversed time: 18.7755110263824
djb2hash execution time: 16.0091370344162
sdbmhash crashed
For C++, the str2Int is roughly as fast as Swift 3's hashValue:
str2int execution time: 0.136421
Related
I have the following math operation:
var _baseFontSize = _userfontsize*8;
if (_baseFontSize > 14) { _baseFontSize = 14.0; }
Essentially whatever the _userfontsize is, my _baseFontSize should be 8x that number, but never exceeding 14.0.
Instead of doing this math operation in 2 lines as might be conventional, is there a way to set a max limit to this (or any given) math operation in dart?
You can import dart:math and do something like this with min:
var _baseFontSize = min(_userfontsize * 8, 14.0);
T min<T extends num>(T a, T b)
Returns the lesser of two numbers.
Unfortunately I am not able to post the code I am debugging as it is not mine and I am bound not to show it... BUT I will describe it as detailed as possible.
There are 4 strategies base on 4 indicators, custom, and not-custom ones. So basically instead of 4 different EAs running in 4 different charts with the same 4 indicators each... The client asked me to optimise them by putting them all in one to run 4 into 1 EAs in the same chart.
EVERYTHING is the same. They are tested as well that they are the same. They open the same trades, on the same moments. Nothing is changed 100%. The only thing I did (for this part of the debugging, because obviously I had a lot more to do before that) is to copy functions and code. And I seperated all different strategies with an "if" as input
input bool strategy1enabled = true; etc... so he/she can disable/enable individual strategies if wanted.
everything works BUT....
All but 1 strategies, does not show the Comment on the trades.
All 4 use the same Buy/Sell/CloseOrder functions so I just input the values to keep the code shorter.
//---
bool OrdClose (int ticket_number, double lt, int slp)
{
return OrderClose(ticket_number,lt,iClose(NULL,0,0),slp,clrViolet);
}
//---
int Buy(double lt, int slp, int slss, int tpft, string cmt, int mgc)
{
return OrderSend(NULL,OP_BUY,lt,Ask,slp,Ask-slss*Point,Ask+tpft*Point,cmt,mgc,0,clrDarkBlue);
}
//---
int Sell(double lt, int slp, int slss, int tpft, string cmt, int mgc)
{
return OrderSend(NULL,OP_SELL,lt,Bid,slp,Bid+slss*Point,Bid-tpft*Point,cmt,mgc,0,clrDarkRed);
}
1 strategy just refuses to put comment. Any ideas why? When used seperated WITH THE SAME CODE and the EXACT SAME functions... comment shows...
EDIT:
2021.05.04 18:30:48.670 The_Big_Holla_v1_8_EA CADJPY,H1: open #85710545 buy 0.06 CADJPY at 88.755 sl: 88.655 tp: 88.955 ok
2021.05.04 18:30:48.462 The_Big_Holla_v1_8_EA CADJPY,H1: Holla v4.9 || GreedInjectionMode
2021.05.04 18:30:48.462 The_Big_Holla_v1_8_EA CADJPY,H1: Holla v4.9 || GreedInjectionMode
Comment is passed properly and checked before being passed to function and before OrderSend within function:
The function:
int Sell(double lt, int slp, int slss, int tpft, string cmt, int mgc)
{
Print(cmt);
return OrderSend(NULL,OP_SELL,lt,Bid,slp,Bid+slss*Point,Bidtpft*Point,cmt,mgc,0,clrDarkRed);
}
How the function is called:
Print(EACommentInj);
ticket_val_inj = Buy(lotsizeInj,slippageInj,stoplossInj,takeprofitInj,EACommentInj,MagicInj);
This is how it is initialised and it NEVER changes. It is mentioned only where it is passed. Where I showed you above.
const string EACommentInjGreed = "Holla v4.9 || GreedInjectionMode Greed Mode";
Although this is undocumented, the "string comment=NULL" parameter of the trade function OrderSend() in MQL4 is limited to 31 characters. If this limit is exceeded then the string is rejected as a whole and treated as NULL.
In your code, just before the OrderSend() function, add the following line:
cmt=StringSubstr(cmt,0,31);
I have a Data object in swift that is an array of Int16 objects. For some reason using ".pcmFormatInt16" did not work for the format of my AVAudioPCMBuffer and yielded no sound, or a memory error. Eventually, I was able to get white noise/static to play from the speakers by converting the Int16 to a float and putting that onto both channels of my AVAudioPCMBuffer. I have a feeling that I am getting close to the answer, because whenever I speak into the microphone I hear a different frequency of static. I think the issue is that I am not converting the converted Int16 into the buffer floatChannelData.
Here is my code:
for ch in 0..<2 {
for i in 0..<audio.count {
var val = Float( Int16(audio[i]) ) / Float(Int16.max)
if( val > 1 ){
val = 1;
}
if( val < -1 ){
val = -1;
}
self.buffer.floatChannelData![ch][i+self.bufferCount] = val
self.bufferCount+=1
}
}
self.audioFilePlayer.scheduleBuffer(self.buffer, at:nil, options: .interruptsAtLoop, completionHandler: {
print("played sum")
self.bufferCount=0
})
a typical multi-channel PCM buffer has the channels interleaving on a per sample basis although, not being familiar with swift audio, I find it refreshing to see here channels given a dimension on the buffer datastructure
... a flag goes up when I see your guard checks clamping val > 1 set to val = 1 etc. ... elsewhere that is not needed as those boundary checks are moot as the data nicely falls into place as is
... my guess is your input audio[] is signed int 16 because of your val > 1 and val < -1 ? if true then dividing by max int float is wrong as you would be loosing half your dynamic range ...
I suggest you look closely at your
var val = Float( Int16(audio[i]) ) / Float(Int16.max)
lets examine range of your ints in audio[]
2^16 == 65536 // if unsigned then values range from 0 to (2^16 - 1) which is 0 to 65535
2^15 == 32768 // if signed then values would range from -32768 to (2^15 - 1) which is -32768 to 32767
Please tell is whether input buffer audio[] is signed or not ... sometimes its helpful to identify the max_seen and min_seen values of your input data ... do this and tell us the value of max and min of your input audio[]
Now lets focus on your desired output buffer self.buffer.floatChannelData ... since you are saying its 16 bit float ... what is the valid range here ? -1 < valid_value < 1 ?
We can continue once you tell us answers to these basic questions
I am developing an app that listens for frequency/pitches, it works fine on iPhone4s, simulator and others but not iPhone 5S. This is the message I am getting:
malloc: *** error for object 0x178203a00: Heap corruption detected, free list canary is damaged
Any suggestion where should I start to dig into?
Thanks!
The iPhone 5s has an arm64/64-bit CPU. Check all the analyze compiler warnings for trying to store 64-bit pointers (and other values) into 32-bit C data types.
Also make sure all your audio code parameter passing, object messaging, and manual memory management code is thread safe, and meets all real-time requirements.
In case it helps anyone, I had exactly the same problem as described above.
The cause in my particular case was pthread_create(pthread_t* thread, ...) on ARM64 was putting the value into *thread at some time AFTER the thread was started. On OSX, ARM32 and on the simulator, it was consistently filling in this value before the start_routine was called.
If I performed a pthread_detach operation in the running thread before that value was written (even by using pthread_self() to get the current thread_t), I would end up with the heap corruption message.
I added a small loop in my thread dispatcher that waited until that value was filled in -- after which the heap errors went away. Don't forget 'volatile'!
Restructuring the code might be a better way to fix this -- it depends on your situation. (I noticed this in a unit test that I'd written, I didn't trip up on this issue on any 'real' code)
Same problem. but my case is I malloc 10Byte memory, but I try to use 20Byte. then it Heap corruption.
## -64,7 +64,7 ## char* bytesToHex(char* buf, int size) {
* be converted to two hex characters, also add an extra space for the terminating
* null byte.
* [size] is the size of the buf array */
- int len = (size * 2) + 1;
+ int len = (size * 3) + 1;
char* output = (char*)malloc(len * sizeof(char));
memset(output, 0, len);
/* pointer to the first item (0 index) of the output array */
char *ptr = &output[0];
int i;
for (i = 0; i < size; i++) {
/* "sprintf" converts each byte in the "buf" array into a 2 hex string
* characters appended with a null byte, for example 10 => "0A\0".
*
* This string would then be added to the output array starting from the
* position pointed at by "ptr". For example if "ptr" is pointing at the 0
* index then "0A\0" would be written as output[0] = '0', output[1] = 'A' and
* output[2] = '\0'.
*
* "sprintf" returns the number of chars in its output excluding the null
* byte, in our case this would be 2. So we move the "ptr" location two
* steps ahead so that the next hex string would be written at the new
* location, overriding the null byte from the previous hex string.
*
* We don't need to add a terminating null byte because it's been already
* added for us from the last hex string. */
ptr += sprintf(ptr, "%02X ", buf[i] & 0xFF);
}
return output;
I’ve been looking at a few example programs in order to find better ways to code with Dart.
Not that this example (below) is of any particular importance, however it is taken from rosettacode dot org with alterations by me to (hopefully) bring it up-to-date.
The point of this posting is with regard to Benchmarks and what may be detrimental to results in Dart in some Benchmarks in terms of the speed of printing to the console compared to other languages. I don’t know what the comparison is (to other languages), however in Dart, the Console output (at least in Windows) appears to be quite slow even using StringBuffer.
As an aside, in my test, if n1 is allowed to grow to 11, the total recursion count = >238 million, and it takes (on my laptop) c. 2.9 seconds to run Example 1.
In addition, of possible interest, if the String assignment is altered to int, without printing, no time is recorded as elapsed (Example 2).
Typical times on my low-spec laptop (run from the Console - Windows).
Elapsed Microseconds (Print) = 26002
Elapsed Microseconds (StringBuffer) = 9000
Elapsed Microseconds (no Printing) = 3000
Obviously in this case, console print times are a significant factor relative to computation etc. times.
So, can anyone advise how this compares to eg. Java times for console output? That would at least be an indication as to whether Dart is particularly slow in this area, which may be relevant to some Benchmarks. Incidentally, times when running in the Dart Editor incur a negligible penalty for printing.
// Example 1. The base code for the test (Ackermann).
main() {
for (int m1 = 0; m1 <= 3; ++m1) {
for (int n1 = 0; n1 <= 4; ++n1) {
print ("Acker(${m1}, ${n1}) = ${fAcker(m1, n1)}");
}
}
}
int fAcker(int m2, int n2) => m2==0 ? n2+1 : n2==0 ?
fAcker(m2-1, 1) : fAcker(m2-1, fAcker(m2, n2-1));
The altered code for the test.
// Example 2 //
main() {
fRunAcker(1); // print
fRunAcker(2); // StringBuffer
fRunAcker(3); // no printing
}
void fRunAcker(int iType) {
String sResult;
StringBuffer sb1;
Stopwatch oStopwatch = new Stopwatch();
oStopwatch.start();
List lType = ["Print", "StringBuffer", "no Printing"];
if (iType == 2) // Use StringBuffer
sb1 = new StringBuffer();
for (int m1 = 0; m1 <= 3; ++m1) {
for (int n1 = 0; n1 <= 4; ++n1) {
if (iType == 1) // print
print ("Acker(${m1}, ${n1}) = ${fAcker(m1, n1)}");
if (iType == 2) // StringBuffer
sb1.write ("Acker(${m1}, ${n1}) = ${fAcker(m1, n1)}\n");
if (iType == 3) // no printing
sResult = "Acker(${m1}, ${n1}) = ${fAcker(m1, n1)}\n";
}
}
if (iType == 2)
print (sb1.toString());
oStopwatch.stop();
print ("Elapsed Microseconds (${lType[iType-1]}) = "+
"${oStopwatch.elapsedMicroseconds}");
}
int fAcker(int m2, int n2) => m2==0 ? n2+1 : n2==0 ?
fAcker(m2-1, 1) : fAcker(m2-1, fAcker(m2, n2-1));
//Typical times on my low-spec laptop (run from the console).
// Elapsed Microseconds (Print) = 26002
// Elapsed Microseconds (StringBuffer) = 9000
// Elapsed Microseconds (no Printing) = 3000
I tested using Java, which was an interesting exercise.
The results from this small test indicate that Dart takes about 60% longer for the console output than Java, using the results from the fastest for each. I really need to do a larger test with more terminal output, which I will do.
In terms of "computational" speed with no output, using this test and m = 3, and n = 10, the comparison is consistently around 530 milliseconds for Java compared to 580 milliseconds for Dart. That is 59.5 million calls. Java bombs with n = 11 (238 million calls), which I presume is stack overflow. I'm not saying that is a definitive benchmark of much, but it is an indication of something. Dart appears to be very close in the computational time which is pleasing to see. I altered the Dart code from using the "question mark operator" to use "if" statements the same as Java, and that appears to be a bit faster c. 10% or more, and that appeared to be consistently the case.
I ran a further test for console printing as shown below (example 1 – Dart), (Example 2 – Java).
The best times for each are as follows (100,000 iterations) :
Dart 47 seconds.
Java 22 seconds.
Dart Editor 2.3 seconds.
While it is not earth-shattering, it does appear to illustrate that for some reason (a) Dart is slow with console output, and (b) Dart-Editor is extremely fast with console output. (c) This needs to be taken into account when evaluating any performance that involves console output, which is what initially drew my attention to it.
Perhaps when they have time :) the Dart team could look at this if it is considered worthwhile.
Example 1 - Dart
// Dart - Test 100,000 iterations of console output //
Stopwatch oTimer = new Stopwatch();
main() {
// "warm-up"
for (int i1=0; i1 < 20000; i1++) {
print ("The quick brown fox chased ...");
}
oTimer.reset();
oTimer.start();
for (int i2=0; i2 < 100000; i2++) {
print ("The quick brown fox chased ....");
}
oTimer.stop();
print ("Elapsed time = ${oTimer.elapsedMicroseconds/1000} milliseconds");
}
Example 2 - Java
public class console001
{
// Java - Test 100,000 iterations of console output
public static void main (String [] args)
{
// warm-up
for (int i1=0; i1<20000; i1++)
{
System.out.println("The quick brown fox jumped ....");
}
long tmStart = System.nanoTime();
for (int i2=0; i2<100000; i2++)
{
System.out.println("The quick brown fox jumped ....");
}
long tmEnd = System.nanoTime() - tmStart;
System.out.println("Time elapsed in microseconds = "+(tmEnd/1000));
}
}