Dart Function.appy() does not work on Color.fromARGB(a, r, g, b); - constructor

Experimenting with Function.apply() to pass a list of positional parameters. But why doesn't a constructor method work for class Color?
var x = Function.apply(Color.fromARGB, [255, 66, 165, 245]);
Error Message: The getter 'fromARGB' isn't defined for the class 'Color'.
Here is the constructor.
const Color.fromARGB(int a, int r, int g, int b) :
value = (((a & 0xff) << 24) |
((r & 0xff) << 16) |
((g & 0xff) << 8) |
((b & 0xff) << 0)) & 0xFFFFFFFF;

A named constructor is not a Function in Dart.
The current way to write your sample is:
var x = Function.apply(
(int a, int r, int g, int b) => Color.fromARGB(a, r, g, b),
[255, 66, 165, 245]);
https://github.com/dart-lang/language/issues/216 is the canonical issue to track requesting support for "tearing off" a constructor to treat it as a Function.

Related

Z3Py solver from brute force script

I am working on a reverse-engineering challenge, the program takes a 32 bits hex number as input and do a serie of equations using a keyword, if the final result is 0 then the input is valid otherwise the input is wrong.
I wrote a python brute force script that tries every value from 0x11111111 to 0xffffffff :
username = "skander"
i = 286331153
while i < 4294967295 :
hash = i
print("Testing : %s") % (hex(hash))
for c in username :
hash = hash >> 27 | (hash ^ ord(c)) << 5
hash = hash & 0xffffffff
hash = hash ^ (hash << 8)
hash = hash & 0xffffffff
if hash == 0 :
print("****** FOUND ******")
print(hex(i))
break
else :
i = i + 1
After some attempts, the script gave me the correct value ( 61aebf45 )
I wanted to implement a more elegant way with z3Py and I tried the following script :
from z3 import *
hash = BitVec('hash', 32)
s = Solver()
eq1 = ( hash >> 27 | ((hash ^ ord('s')) << 5)) & 0xffffffff
eq2 = ( eq1 ^ (eq1 << 8)) & 0xffffffff
eq3 = ( eq2 >> 27 | ((eq2 ^ ord('k')) << 5)) & 0xffffffff
eq4 = ( eq3 ^ (eq3 << 8)) & 0xffffffff
eq5 = ( eq4 >> 27 | ((eq4 ^ ord('a')) << 5)) & 0xffffffff
eq6 = ( eq5 ^ (eq5 << 8)) & 0xffffffff
eq7 = ( eq6 >> 27 | ((eq6 ^ ord('n')) << 5)) & 0xffffffff
eq8 = ( eq7 ^ (eq7 << 8)) & 0xffffffff
eq9 = ( eq8 >> 27 | ((eq8 ^ ord('d')) << 5)) & 0xffffffff
eq10 = ( eq9 ^ (eq9 << 8)) & 0xffffffff
eq11 = ( eq10 >> 27 | ((eq10 ^ ord('e')) << 5)) & 0xffffffff
eq12 = ( eq11 ^ (eq11 << 8)) & 0xffffffff
eq13 = ( eq12 >> 27 | ((eq12 ^ ord('r')) << 5)) & 0xffffffff
eq14 = ( eq13 ^ (eq13 << 8)) & 0xffffffff
s.add(eq14 == 0)
while s.check() == sat:
m = s.model()
print(m[hash])
s.add(Or(hash != s.model()[hash]))
But no output (unsat problem) and if I modify
hash = BitVec('hash', 32)
to
hash = BitVec('hash', 64)
The script give me a lot of models
Is the problem not solvable or I did a mistake on the code ?
>> translates to arithmetic shift-right; but what you actually meant was logical-shift right. Use LShR instead. That is, replace all instances of:
hash >> 27
with
LShR(hash, 27)
If you do this, it prints 1638842181 which is the value you seem to be looking for.
Note that you don't have to "unroll" the loop yourself; you can just walk over the input string and code this just like you did the original Python; simply keep assigning to the same symbolic value.

Error "expression must have integral or enum type" in thats code:

Error "expression must have integral or enum type" in thats code:
__global__ void VectorKernel(float *a, float *b, float *c, int n)
{
int i = threadIdx.x;
float y = 0, z = 0;
if (i < n)
y = (b-a) / n;
for (float j = y; j <= n ; j++) {
z = (((j+y) - j) / 6) * function(j) + 4 * (function((j + (y+j)) / 2)) + function(y+j);
c = c + z;
}
}
the error happen in "z", in stretch:
c = c + z;
(i'm beginner in CUDA programming)
c is a pointer. Pointer arithmetic requires a pointer and an integer type expression.
If you want to to add z to the float pointed to by c you should change the expression to:
*c = *c + z;
When you write c = c + z and get an error like this, you should suspect your types are mismatched.
c is a float * and z is a float which are not assignable.
What you probably want to do is store the result of *c + z in the memory location pointed at by c, in which case you'd write:
*c = *c + z.

removing entries in sorted list: efficiently in gpu

I am trying to code the following problem in cuda/thrust. I am given a list of key and three values associated with each keys. I have managed to sort them in lexicographic order. The input now needs to be reduced if inputs with same key have each value-wise relation. In example below, V1(a)<=V1(c) and V2(a)<=V2(c) and V3(a)<=V3(c), implies that Input a < Input c, and hence, Input c is removed from output.
Example Input:
Key V1 V2 V3
a. 1 2 5 3
b. 1 2 6 2
c. 1 2 7 4
d. 1 3 6 5
e. 2 8 8 8
f. 3 1 2 4
Example Output:
Key V1 V2 V3
a. 1 2 5 3
b. 1 2 6 2
e. 2 8 8 8
f. 3 1 2 4
Input a < Input c ==> c removed
Input a < Input d ==> d removed
I’ve been able to solve the above problem using for-loops, and if-statements. I am currently trying to solve this using gpu based cuda/thrust. Could this be done on the gpu (preferably thrust) or an individual kernel has to be written in cuda ?
I have not been to formulate this problem using unique as discussed in Thrust: Removing duplicates in key-value arrays
Edited to include program "stl/c++" program to generate above scenario: section "Reducing myMap" is my implementation using for-loops and if-statements.
#include <iostream>
#include <tr1/array>
#include <vector>
#include <algorithm>
struct mapItem {
mapItem(int k, int v1, int v2, int v3){
key=k;
std::tr1::array<int,3> v = {v1, v2, v3};
values=v;
};
int key;
std::tr1::array<int,3> values;
};
struct sortLexiObj{
bool operator()(const mapItem& lhs, const mapItem& rhs){
return lhs.values < rhs.values;
}
};
struct sortKey{
bool operator()(const mapItem& lhs, const mapItem& rhs){
return lhs.key < rhs.key;
}
};
int main(int argc, char** argv){
std::vector<mapItem> myMap;
// Set up initial matrix:
myMap.push_back(mapItem(3, 1, 2, 4));
myMap.push_back(mapItem(1, 2, 6, 2));
myMap.push_back(mapItem(1, 2, 5, 3));
myMap.push_back(mapItem(1, 3, 6, 5));
myMap.push_back(mapItem(2, 8, 8, 8));
myMap.push_back(mapItem(1, 2, 7, 4));
std::sort(myMap.begin(), myMap.end(), sortLexiObj());
std::stable_sort(myMap.begin(), myMap.end(), sortKey());
std::cout << "\r\nOriginal sorted Map" << std::endl;
for(std::vector<mapItem>::iterator mt=myMap.begin(); mt!=myMap.end(); ++mt){
std::cout << mt->key << "\t";
for(std::tr1::array<int,3>::iterator it=(mt->values).begin(); it!=(mt->values).end(); ++it){
std::cout << *it << " ";
}
std::cout << std::endl;
}
/////////////////////////
// Reducing myMap
for(std::vector<mapItem>::iterator it=myMap.begin(); it!=myMap.end(); ++it){
std::vector<mapItem>::iterator jt=it; ++jt;
for (; jt != myMap.end();) {
if ( (it->key == jt->key)){
if ( it->values.at(0) <= jt->values.at(0) &&
it->values.at(1) <= jt->values.at(1) &&
it->values.at(2) <= jt->values.at(2) ) {
jt = myMap.erase(jt);
}
else ++jt;
}
else break;
}
}
std::cout << "\r\nReduced Map" << std::endl;
for(std::vector<mapItem>::iterator mt=myMap.begin(); mt!=myMap.end(); ++mt){
std::cout << mt->key << "\t";
for(std::tr1::array<int,3>::iterator it=(mt->values).begin(); it!=(mt->values).end(); ++it){
std::cout << *it << " ";
}
std::cout << std::endl;
}
return 0;
}
I think that you can use thrust::unique with a predicate as it's shown in Thrust: Removing duplicates in key-value arrays.
Actually, we can do it because of the following characteristic of unique:
For each group of consecutive elements in the range [first, last) with the same value, unique removes all but the first element of the group.
So, you should define a predicate to test for pseudo-equality that will return true for tuples that have the same key and all values are smaller in the first tuple:
typedef thrust::tuple<int, int, int, int> tuple_t;
// a functor which defines your *uniqueness* condition
struct tupleEqual
{
__host__ __device__
bool operator()(tuple_t x, tuple_t y)
{
return ( (x.get<0>() == y.get<0>()) // same key
&& (x.get<1>() <= y.get<1>()) // all values are smaller
&& (x.get<2>() <= y.get<2>())
&& (x.get<3>() <= y.get<3>()));
}
};
And you have to apply it to a sorted collection. In this way, only the first tuple (the smallest) will not be removed.
A tuple with the same key and a bigger value in V1, V2 or V3 will yield false so it won't be removed.
typedef thrust::device_vector< int > IntVector;
typedef IntVector::iterator IntIterator;
typedef thrust::tuple< IntIterator, IntIterator, IntIterator, IntIterator > IntIteratorTuple;
typedef thrust::zip_iterator< IntIteratorTuple > ZipIterator;
IntVector keyVector;
IntVector valVector1, valVector2, valVector3;
tupleEqual predicate;
ZipIterator newEnd = thrust::unique(
thrust::make_zip_iterator(
thrust::make_tuple(
keyVector.begin(),
valVector1.begin(),
valVector2.begin(),
valVector3.begin() ) ),
thrust::make_zip_iterator(
thrust::make_tuple(
keyVector.end(),
valVector1.end(),
valVector2.end(),
valVector3.end() ) ),
predicate );
IntIteratorTuple endTuple = newEnd.get_iterator_tuple();
keyVector.erase( thrust::get<0>( endTuple ), keyVector.end() );
valVector1.erase( thrust::get<1>( endTuple ), valVector1.end() );
valVector2.erase( thrust::get<2>( endTuple ), valVector2.end() );
valVector3.erase( thrust::get<3>( endTuple ), valVector3.end() );

Code Golf: Numeric Ranges

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Challenge
Compactify a long list of numbers by replacing consecutive runs with ranges.
Example
Input
1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15
The input is guaranteed to be in ascending order and will not contain duplicates.
Output
1 - 4, 7, 8, 10, 12 - 15
Note that ranges of two numbers should be left as is. (7, 8; not 7 - 8)
Rules
You can accept a sorted list of integers (or equivalent datatype) as a method parameter, from the commandline, or from standard in. (pick whichever option results in shorter code)
You can output a list of strings by printing them, or by returning either a single string or set of strings.
Reference Implementation
(C#)
IEnumerable<string> Sample(IList<int> input) {
for (int i = 0; i < input.Count; ) {
var start = input[i];
int size = 1;
while (++i < input.Count && input[i] == start + size)
size++;
if (size == 1)
yield return start.ToString();
else if (size == 2) {
yield return start.ToString();
yield return (start + 1).ToString();
} else if (size > 2)
yield return start + " - " + (start + size - 1);
}
}
Python, 98 characters
def f(a):
for x in a:
if x-1not in a or x+1not in a:print x,"-"if x+1in a and x+2in a else",",
Python - 86 characters
This one doesn't include an extra ',' at the end
f=lambda a:''.join(`x`+",-"[(x+1in a)&x+2in a]for x in a if(x-1in a)&(x+1in a)^1)[:-1]
Python, 83 characters
def f(l,a=2):
for x in l:
b,a=a,(x+1in l)*(x-1in l)
if a<1:print',- '[b],`x`,
Demo:
>>> l=[1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15]
>>> f(l)
1 - 4 , 7 , 8 , 10 , 12 - 15
Ruby, 165 characters
a=[]
def o(a)print "#{#s}#{a[0]}#{"#{a.size<3?',':' -'} #{a[-1]}"if a.size>1}";#s=', 'end
ARGV[0].split(', ').each{|n|if a[0]&&a[-1].succ!=n;o(a);a=[]end;a<<n;};o(a)
C++, 166 characters
#define o std::cout
void f(std::vector<int> v){for(int i=0,b=0,z=v.size();i<z;)i==z-1||v[i+1]>v[i]+1?b?o<<", ":o,(i-b?o<<v[b]<<(i-b>1?" - ":", "):o)<<v[i],b=++i:++i;}
Don't you all just love abusing the ?: operator? ;)
More readable version:
#define o std::cout
void f(std::vector<int> v){
for(int i=0,b=0,z=v.size();i<z;)
i==z-1||v[i+1]>v[i]+1 ?
b?o<<", ":o,
(i-b?o<<v[b]<<(i-b>1?" - ":", "):o)<<v[i],
b=++i
:++i;
}
Common Lisp, 442/206 chars
(defun d (l)
(if l
(let ((f (car l))
(r (d (cdr l))))
(if r
(if (= (+ f 1) (caar r))
(push `(,f ,(cadar r)) (cdr r))
(push `(,f ,f) r))
`((,f ,f))
))
nil))
(defun p (l)
(mapc #'(lambda (x)
(if (= (car x) (cadr x))
(format t "~a " (car x))
(if (= (+ 1 (car x)) (cadr x))
(format t "~a ~a " (car x) (cadr x))
(format t "~a-~a " (car x) (cadr x)))))
(d l)))
The "d" function rewrites the input list into a canonical form. For fun I did this entirely recursively. The "p" function formats the output to the equivalent of the reference implementation.
F#, 188 chars
let r(x::s)=
let f=printf
let p x=function|1->f"%A "x|2->f"%A %A "x (x+1)|n->f"%A-%A "x (x+n-1)
let rec l x n=function|y::s when y=x+n->l x (n+1)s|y::s->p x n;l y 1 s|[]->p x n
l x 1 s
More readable:
let range (x::xs) =
let f = printf
let print x = function
| 1 -> f "%A " x
| 2 -> f "%A %A " x (x+1)
| n -> f "%A-%A " x (x+n-1)
let rec loop x n = function
| y::ys when y=x+n ->
loop x (n+1) ys
| y::ys ->
print x n
loop y 1 ys
| [] ->
print x n
loop x 1 xs
Ruby : 123 characters
def y(n) t=[];r=[];n.each_with_index do |x,i| t<<x;if(x.succ!=n[i+1]);r=((t.size>2)?r<<t[0]<<-t[-1]:r+t);t=[];end;end;r;end
More Readable
def y(n)
t=[];r=[];
n.each_with_index do |x,i|
t << x
if (x.succ != n[i+1])
r = ((t.size > 2) ? r << t[0] << -t[-1] : r+t)
t=[]
end
end
r
end
And execute like
> n=[1, 2, 3, 4, 7, 8, 10, 12, 13, 14, 15]
> y n
=> [1, -4, 7, 8, 10, 12, -15]
PHP 95 chars
(actually it's the second language after python)
Given $a=array(numbers);
Algos:
for($i=0;$i<count($a);$i++){$c=$i;while($a[$i+2]==$a[$i]+2)$i++;echo $a[$c],$i-$c>1?'-':',';}

How to get checksums for strided patterns

I have a 64 bit number (but only the 42 low order bits are used) and need to computer the sum of the 4 bits at n, n+m, n+m*2 and n+m*3 (note: anything that can produce a sum >4 is invalid) for some fixed m and every value of n that places all the bits in the number
as an example using m=3 and given the 16-bit number
0010 1011 0110 0001
I need to compute
2, 3, 1, 2, 3, 0, 3
Does anyone have any (cool) ideas for ways to do this? I'm fine with bit twiddling.
My current thought is to make bit shifted copies of the input to align the values to be summed and then build a logic tree to do a 4x 1bit adder.
v1 = In;
v2 = In<<3;
v3 = In<<6;
v4 = In<<9;
a1 = v1 ^ v2;
a2 = v1 & v2;
b1 = v3 ^ v4;
b2 = v3 & v4;
c2 = a1 & b1;
d2 = a2 ^ b2;
o1 = a1 ^ b1;
o2 = c2 ^ d2;
o4 = a2 & b2;
This does end up with the bits of the result spread across 3 different ints but oh well.
edit: as it happens I need the histogram of the sums so doing a bit-count of o4, o2&o1, o2 and o1 gives me what I want.
a second solution uses a perfect hash function
arr = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4];
for(int i = 0; i < N; i++)
{
out[i] = arr[(In & 0b1001001001) % 30];
In >>= 1;
}
This works by noting that the 4 selected bits can only take on 16 patterns and that (by guess and check) they can be hashed into 0-15 using mod 30. From there, a table of computed values gives the needed sum. As it happens only 3 of the 4 strides I need work this way.
p.s.
Correct trumps fast. Fast trumps clear. I expect to be running this millions of time.
Maybe I am crazy, but I am having fun :D
This solution is based upon the usage of data parallelism and faking a vector cpu without actually using SSE intrinsics or anything similar.
unsigned short out[64];
const unsigned long long mask = 0x0249024902490249ul;
const unsigned long long shiftmask = 0x0001000100010001ul;
unsigned long long t = (unsigned short)(in >> 38) | (unsigned long long)(unsigned short)(in >> 39) > 40) > 41) << 48;
t &= mask;
*((unsigned long long*)(out + 38)) = (t & shiftmask) + (t >> 3 & shiftmask) + (t >> 6 & shiftmask) + (t >> 9 & shiftmask);
[... snipsnap ...]
t = (unsigned short)(in >> 2) | (unsigned long long)(unsigned short)(in >> 3) > 4) > 5) << 48;
t &= mask;
*((unsigned long long*)(out + 2)) = (t & shiftmask) + (t >> 3 & shiftmask) + (t >> 6 & shiftmask) + (t >> 9 & shiftmask);
t = (unsigned short)in | (unsigned long long)(unsigned short)(in >> 1) << 16;
t &= mask;
*((unsigned int*)out) = (unsigned int)((t & shiftmask) + (t >> 3 & shiftmask) + (t >> 6 & shiftmask) + (t >> 9 & shiftmask));
By reordering the computations, we can further reduce the execution time significantly, since it drastically reduces the amount of times that something is loaded into the QWORD. A few other optimizations are quite obvious and rather minor, but sum up to another interesting speedup.
unsigned short out[64];
const unsigned long long Xmask = 0x249024902490249ull;
const unsigned long long Ymask = 0x7000700070007u;
unsigned long long x = (in >> 14 & 0xFFFFu) | (in >> 20 & 0xFFFFu) > 26 & 0xFFFFu) > 32) << 48;
unsigned long long y;
y = x & Xmask;
y += y >> 6;
y += y >> 3;
y &= Ymask;
out[32] = (unsigned short)(y >> 48);
out[26] = (unsigned short)(y >> 32);
out[20] = (unsigned short)(y >> 16);
out[14] = (unsigned short)(y );
x >>= 1;
y = x & Xmask;
y += y >> 6;
y += y >> 3;
y &= Ymask;
out[33] = (unsigned short)(y >> 48);
out[27] = (unsigned short)(y >> 32);
out[21] = (unsigned short)(y >> 16);
out[15] = (unsigned short)(y );
[snisnap]
x >>= 1;
y = x & Xmask;
y += y >> 6;
y += y >> 3;
y &= Ymask;
out[37] = (unsigned short)(y >> 48);
out[31] = (unsigned short)(y >> 32);
out[25] = (unsigned short)(y >> 16);
out[19] = (unsigned short)(y );
x >>= 1;
x &= 0xFFFF000000000000ul;
x |= (in & 0xFFFFu) | (in >> 5 & 0xFFFFu) > 10 & 0xFFFFu) << 32;
y = x & Xmask;
y += y >> 6;
y += y >> 3;
y &= Ymask;
out[38] = (unsigned short)(y >> 48);
out[10] = (unsigned short)(y >> 32);
out[ 5] = (unsigned short)(y >> 16);
out[ 0] = (unsigned short)(y );
[snipsnap]
x >>= 1;
y = x & Xmask;
y += y >> 6;
y += y >> 3;
y &= Ymask;
out[ 9] = (unsigned short)(y >> 16);
out[ 4] = (unsigned short)(y );
Running times for 50 million executions in native c++ (all ouputs verified to match ^^) compiled as a 64 bit binary on my pc:
Array based solution: ~5700 ms
Naive hardcoded solution: ~4200 ms
The first solution: ~2400 ms
The second solution: ~1600 ms
A suggestion that I don't want to code right now is to use a loop, an array to hold partial results, and constants to pick up the bits m at a time.
loop
s[3*i] += x & (1 << 0);
s[3*i+1] += x & (1 << 1);
s[3*i+2] += x & (1 << 2);
x >> 3;
This will pick too many bits in each sum. But you can also keep track of the intermediate results and subtract from the sums as you go, to account for the bit that may not be there anymore.
loop
s[3*i] += p[3*i] = x & (1 << 0);
s[3*i+1] += p[3*i+1] = x & (1 << 1);
s[3*i+2] += p[3*i+2] = x & (1 << 2);
s[3*i] -= p[3*i-10];
s[3*i+1] -= p[3*i-9];
s[3*i+2] -= p[3*i-8];
x >> 3;
with the appropriate bounds checking, of course.
The fastest approach is to just hardcode the sums themselves.
s[0] = (x & (1<<0)) + (x & (1<<3)) + (x & (1<<6)) + (x & (1<<9));
etc. (The shifts occur at compile time.)