html,generator,sublimetext3,magnific-popup
I found a simple solution with Emmet package for Sublime text! (a[href="/img/gallery/nase-aktivity/img$$$$$.jpg" title="title"]>img[src="/img/gallery/nase-aktivity/thmb/img$$$$$.jpg" alt="alt"])*100 ...
asynchronous,generator,tornado
You don't need "asynchronous" in this code example. "gen.engine" is obsolete, use "coroutine" instead. You don't generally need to use "gen.Task" much these days, either. Make four changes to your code: Wrap "post" in "coroutine" "yield" the result of self.json_fetch instead of using the result directly. No need to call...
python,for-loop,generator,yield
Because your yield is nested in your for loop, all your values will be added to the generator expression. Generators are basically equivalent to iterators except, iterators retain the values unless deleted whereas generators generate the values once on the fly. The next method of the generator is implicitly called...
In Python 3.3 or later: def helper(): bar = get_some_value() yield bar save(bar) def foo(): do_something() yield from helper() do_something_else() # more code in between yield from helper() # finishing up In earlier Pythons (including Python 2): def helper(): bar = get_some_value() yield bar save(bar) def foo(): do_something() for x...
python,generator,python-internals
The space a generator takes in memory is just bookkeeping info. In it a reference to the frame object is kept (administration for the running Python code, such as locals), wether or not it is running right now, and a reference to the code object are kept. Nothing more: >>>...
python,random,numbers,generator
This statement doesn't do what you think: number = randrange It's setting number to the function, not to a result from calling the function. If you now did print number(100) you'd see what I mean. Python 2 allows you to compare arbitrary values to each other, even if they're not...
javascript,generator,v8,ecmascript-6
The key was yield *gen.apply(that, arguments) in the anonymous generator wrapper. function Builder() { this.initialState = 'initialState'; }; Builder.prototype.setState = chain(function(k, v) { this[k] = v; }); Builder.prototype.generate = delegate(generate); // Reuses or creates a Builder instance and makes it `this` for calling `f`. // Returns the Builder instance. function...
for-loop,generator,vhdl,synthesis
Those aren't FOR loops. They are FOR..GENERATE statements, and each needs its own label. gen : FOR i IN 0 TO HPORTS - 1 GENERATE gen2: FOR j IN 0 TO PORTS - 1 GENERATE to_Y(( i )) <= to_Y(( i )) + X( j ); END GENERATE; END GENERATE;...
This is a bug in jOOQ 3.5.1 and will be fixed in jOOQ 3.6.0 and 3.5.2.
Well, I have solved. This is the class I wanted class Foo(): id = '' generator = '' def __init__ (self, num, gen) self.id = num self.generator = gen def recallGenerator(param1, param2,...): return self.generator(param1, param2,...) Now, given a generic generator G(param1, param2...) you can create the object and pass it...
python,generator,tornado,cython,coroutine
Tornado coroutines are not currently supported with Cython. The main problem is that a generator compiled by Cython does not pass isinstance(types.GeneratorType) (and last time I looked there was no other class that could be used instead). The best fix for this would be a change to Cython to add...
javascript,node.js,callback,generator,passport.js
You could use co.wrap() which "converts a co-generator-function into a regular function that returns a promise" var co = require('co'); ... var findOrCreateUser = co.wrap(userRepository.findOrCreateUser) findOrCreateUser(profile.id, profile.name, 'pic').then(function() { done(); }); ...
The id you are trying to generate can be seen as a base 36 number. So we can use String#to_i and Fixnum#to_s methods' to convert base systems (between 2 and 36). Note: I also added a String#prev method as it may make sense here; but such a method isn't provided...
java,javascript,random,colors,generator
I like that function in the article from the 2nd answer. In JS, using s = 0.5 and v = 0.95: function randomColor(){ var golden_ratio_conjugate = 0.618033988749895, h = (Math.random() + golden_ratio_conjugate) % 1 *360, rgb = hsvToRgb(h, 50, 95); return "rgb("+rgb[0]+","+rgb[1]+","+rgb[2]+")"; } /** * Converts an HSV color value...
The yield yields a generator object everytime and when the generators were created there was no problem at all. That is why try...except in my_zip is not catching anything. The third time when you executed it, list(arg[2] for arg in args) this is how it got reduced to (over simplified...
It looks like the unsaved-value attribute of the id mapping for the MyReferenceClass is defaulting to 0, and cascading updates aren't enabled for MyClass. When you add an object with an id other than the unsaved-value Hibernate assumes you're referencing an existing row. When you add an object with an...
You don't yield save('bar') because SAVE is synchronous. (Are you sure you want to use save?) Since it's synchronous, you should change this: exports.home = function *(next){ yield save('bar') } to this: exports.home = function *(next){ save('bar') } and it will block execution until it's finished. Almost all other Redis...
This works: a = [[1, 2, 3], [4, 5, 6]] nd_a = np.array(a) So this should work too: nd_a = np.array([[x for x in y] for y in a]) ...
android,android-studio,apk,generator,android-gradle
It actually does create APK file, but not in the root project directory. It does create it on the path project_root/module_name/build/output/apk/ Try searching for APK files in the project root directory with subdirs, and you'll find them and understand what I mean
python,sqlite,generator,python-3.4,python-multiprocessing
Since processing is fast, but writing is slow, it sounds like your problem is I/O-bound. Therefore there might not be much to be gained from using multiprocessing. However, it is possible to peel off chunks of data, process the chunk, and wait until that data has been written before peeling...
python,generator,fibonacci,yield,def
The message means that generators do not support indexing, so iterable[i] fails. Instead, use the next() function to get the next item from the iterator. def take(n, iterable): x = [] if n > 0 itr = iter(iterable) # Convert the iterable to an iterator for _ in range(n): #...
Let's look at what this does: foreach (int integer in integ) { integ[integer] = rand.Next(5,35); } Basically, a foreach loop iterates through the values of integ (which are all initially 0), and sets that value at that index in integ to a random number. So it will only populate the...
javascript,npm,generator,yeoman,meanjs
That is a pretty common error. Yeoman is running the following: bower install & npm install Bower install succeeded, however NPM install is failing because of user permissions. Just run: sudo npm install ...
Generator functions are currently available in node behind a flag --harmony_generators. See Features Implemented in V8 and Available in Node.
python,csv,replace,generator,generator-expression
str.translate might be appropriate; something along the lines of replacements = [ ('abc', 'x'), ('def', 'y'), ('ghi', 'z'), ] trans = str.maketrans({ k: v for l, v in replacements for k in l }) and new_row = [item.translate(trans) for item in row] ...
python,scala,recursion,generator
You can use Stream for a very similar effect: def permute[T](list: List[T]): Stream[List[T]] = if (list.size == 1) Stream(list) else for { i <- Stream.range(0, list.size) l <- list splitAt i match { case (left, el :: right) => permute(left ::: right) map (el :: _) } } yield l...
node.js,promise,generator,stripe-payments,ecmascript-6
The problem you are experiencing stems from a mix of two approaches for asynchrony. The stripe API docs mentions Every resource method accepts an optional callback as the last argument. Additionally, every resource method returns a promise. However, both genny and suspend do work seamlessly with Node callback conventions and...
java,numbers,generator,long-integer
Based on this code A[i] is equal to Factorial(i). When n=11, you calculate Factorial up to 22, and Factorial(22) is larger than the max value of long, so your calculations overflow, and the result is wrong. You can avoid the overflow is you realize that: (Array[count] / (Array[n]*Array[n])) / (n+1)...
The random generator generates an "uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)" Please refer to the documentation: http://docs.oracle.com/javase/7/docs/api/java/util/Random.html You can do: random.nextInt(max - min + 1) + min And it should be fine. Alternatively, Random randomGenerator = new Random(); for (int idx = 1; idx...
I suggest you use either watchdog or pyinotify to monitor changes to your log file. Also, I would suggest to remember last position you read from. After you get IN_MODIFY notification, you could read from last position to the end of file and apply your loop again. Also, reset last...
I wouldn't say "easy" but it's do-able, and very time consuming. It's not something you could whip up in a matter of hours. You have to account for mis-spelling, question format etc. and just pull answers from a database based on what you get. But it depends on how far...
python,iterator,generator,list-comprehension,generator-expression
There's not a better way to do this that I'm aware of. The convention is to do this: samples = [do_sampling() for _ in range(n_samples)] If you're using Python 2.x and not Python 3.x, you can gain a performance improvement by using a generator-version of range, xrange(), rather than range():...
Use Bool#values() to iterate over possible values of your enum: for (Bool large : Bool.values()) for (Bool medium : Bool.values()) for (Bool small : Bool.values()) boosters.add(new Boosters.Builder().setLarge(large).setMedium(medium).setSmall(small)); ...
In your comment you say this started happening after you started adding edges. I think that's where the problem is. You'll get this error if even one node doesn't have the 'category' defined. I think adding edges is resulting in the addition of a few nodes that don't have category...
c,if-statement,generator,money
After you have calculated b and adjusted inclusive so it is now 9, you get to your else case, which sets c to 9 (hence the Ninety output) and d to 0, but immediately afterwards sets d to 9 (hence the Nine in the output). I think you mixed up...
One way to get around the expensive operation is to nest a generator in a list comprehension that simply acts as a filter, for example def foo(x): # assume this function is expensive return 2*x >>> [j for j in (foo(i) for i in range(6)) if j > 4] #...
c,compilation,generator,zero,money
Various subtractions like inclusive = inclusive - (c*10) are suffering round-off error and therefore have a tiny amount left when doing if (d > 0). Suggest rounding to nearest 0.01. Example: inclusive = round(100*(inclusive - (c*10)))/100.0 and other places. Or re-do all in integer number of cents....
python,recursion,iterator,generator
Right now when you recursively call _iterate_on_dir you're just creating a generator object, not actually iterating over it. The fix: self._iterate_on_dir(full_path) should become: for thing in self._iterate_on_dir(full_path): yield thing If you're using Python 3, you can replace that with: yield from self._iterate_on_dir(full_path) ...
You can do this with this code: def generate_matrix(size): """Generate lists which form an eye matrix""" for i in range(size): # First, we create a new list with size 0s. l = [0] * size # At the specified position, we place a 1. l[i] = 1 # We yield...
c,if-statement,compilation,generator
You can use nested if else. First check if it is zero dollars, else carry out your process. Try something like this: if (c == 0 && b == 0 && a == 0){ printf("Zero Dollars and ... "); } else{ if (a > 0){ printNum(a); printf("Thousand "); } if...
You're not losing 2 characters. The first 2 characters are actually empty strings. Change this: var t = new Array(blank, blank1); To this: var t = new Array; ...
I don't think you found that code on the internet. You seem to be missing the entire point of that blog post, and if you use g = g.next() instead of g.next() like it's shown there, then it makes sense and it works. But to answer your question, why it...
T is a sequence type. For simplicity, let's take a special and familiar case and say T is an array. Then the type of thing contained in the array is T.Generator.Element. This is because of the way the Array struct is defined. Keep in mind that Array is a generic....
python,graph,generator,networkx
You might like connected_component_subgraphs() better since it will give you subgraphs instead of just the nodes. In [1]: import networkx as nx In [2]: G = nx.Graph() In [3]: G.add_path([1,2,3,4]) In [4]: G.add_path([10,20,30,40]) In [5]: components = nx.connected_component_subgraphs(G) In [6]: components Out[6]: [<networkx.classes.graph.Graph at 0x102ca7790>, <networkx.classes.graph.Graph at 0x102ca77d0>] In [7]:...
python,tree,generator,itertools
Chaining multiple chains results in a recursive functions call overhead proportional to the amount of chains chained together. First of all, our pure python chain implementation so that we won't lose stack info. The C implementation is here and you can see it does basically the same thing - calls...
We must ensure that it is possible to have numbers such that we can reach the minimum total, and numbers such that we can not exceed the maximum total. For each number, recalculate the its minimum and maximum value such that the intended sum is still reachable. function getRandomInt(min, max)...
javascript,function,generator,ecmascript-6,ecmascript-harmony
Generators created with function are part of earlier ES6 draft. //They have differrent prototypes console.log(a.prototype.constructor.constructor,b.prototype.constructor.constructor);//function Function() function GeneratorFunction() let a1=a(10); let b1=b(10); //both create generators... console.log(a1,b1);//Generator { } Generator { } //but different generators: one returns value, another returns an object of special format console.log(a1.next(),b1.next());//100 Object { value: 1000, done:...
The short answer is no, you cannot pass state using instance variables of the class. Upon hitting yield for class methods, nose will always figure out which class the method belongs to and will create a new instance of this class that will have no attributes that you tend to...
python,generator,generator-expression
While this is expected behaviour in existing versions of Python at the time of writing, it is scheduled to be changed over the course of the next few point releases of Python 3.x - to quote PEP 479: The interaction of generators and StopIteration is currently somewhat surprising, and can...
What about doing something like this? // A List to hold all the names List<String> namesList = new ArrayList<>(); // Create the full list of names String[] names = {"mike", "Dragon", "jason", "freddy", "john", "mic"}; // Store them into the List namesList = new ArrayList(Arrays.asList(names)); // Randomly get the first...
silverlight,asp.net-web-api,odata,generator,odata-v4
Silverlight does not support the code generated by Microsoft's OData v4 Client Code Generator visx (OData Client T4), but no one's forcing you to use generated code. Simply use the lib of your choice to create a connection to the OData service and reuse your own types (business objects)....
node.js,mongoose,promise,generator,bluebird
Ok, the problem: you created the variable final and returns it afterwars, this happens just before the Mongo-Query has executed. Solution: You should push the Promises to final, and then resolve it all together when you reply to the client. function queryAsync() { var replies = yield query.exec(); // which...
You are replacing your (value, index) tuples with just the value: self.values[index] = self.generators[index].next() You need to replace that with a new tuple: self.values[index] = (self.generators[index].next(), index) otherwise the iterable assignment fails; you cannot assign one int to two variables. Your generator is missing a loop and handling of empty...
python,python-2.7,pyqt4,generator
The PyQt (Or generally speaking, the UI development) usually requires put the long-time run function into backend thread, so this will not blocking your UI thread, make it able to response the UI update/User interactive. so in this case, you need to put "someprocess" into backend thread(possibly inherit from QThread),...
python,list,dictionary,generator
The difference is that only the first expression glist is a generator, the second one gdict is a dict-comprehension. The two would only be equivalent, if you'd change the first one for [x for x in (1, 2, 3)]. A comprehension is evaluated immediately....
javascript,generator,ecmascript-6,es6-promise
WTH are you trying to do? No, it is utterly impossible to wrap a promise in a generator that synchronously yields the promise's result, because promises are always asynchronous. There is no workaround for that, unless you throw mightier weapons like fibers at the asynchrony.
python,multithreading,exception,exception-handling,generator
The problem is that sometimes the KeyboardInterrupt occurs when the main thread is not inside of the call to obj.eep. In Python, signals (like the SIGINT raised when you do a Ctrl+C) are only delivered to the main thread: [O]nly the main thread can set a new signal handler, and...
python,performance,generator,combinatorics
Here are some generators based on algorithms attributed to Knuth. subsets4 generates all subsets of 1..n having k or less elements subsets5 restricts the subsets generated by subsets4 to those having a max difference of w subsets generates all subsets of 1..n of length exactly k subsets2 restricts the subsets...
gen_primes() creates a new generator object every time. Instead, store it in a variable and use next, like this >>> primes = gen_primes() >>> for _ in range(10): ... next(primes) ... ... 2 3 5 7 11 13 17 19 23 29 Instead of you iterating the iterable, leave that...
python,multiprocessing,generator
So you basically create a histogram. This is can easily be parallelized, because histograms can be merged without complication. One might want to say that this problem is trivially parallelizable or "embarrassingly parallel". That is, you do not need to worry about communication among workers. Just split your data set...
I suggest using zip with itertools.repeat. Probably this is simple enough to do inline (where you'll know the order, presumably), but if you want it in a function, you can do that too: def iter_intersperse(iterOver, injectItem, startWithIter = True): if startWithIter: return zip(iterOver, itertools.repeat(injectItem)) return zip(itertools.repeat(injectItem), iterOver) If you're using...
objective-c,xcode,export,generator
Open Xcode, create a new project, choose Single View Application (or something that best suits what you'll be generating) click create. Go to the directory where this project was created, zip it and include it in the project for the App that will do the generating. When it's time...
ionic-framework,generator,yeoman
I use the same generator and enjoy using it. With that said, I would not recommend starting to use a generator until you've made a complete backup of your project. Even then, I'd recommend creating a brand new project using the generator then migrating your existing code into the newly...
python,random,generator,list-comprehension,primes
It's better to just generate the list of primes, and then choose from that line. As is, with your code there is the slim chance that it will hit an infinite loop, either if there are no primes in the interval or if randint always picks a non-prime then the...
python,iterator,generator,itertools
Suppose you have some iterable of pairs: a = zip(range(10), range(10)) IIUC what you're asking, you could generate independent iterators for the firsts and seconds using itertools.tee: xs, ys = itertools.tee(a) xs, ys = (x[0] for x in xs), (y[1] for y in ys) Note this will keep in memory...
zip will eagerly read the entire content of all files so is not memory efficient. Given the fact that the number of lines of each file may also be different, I'd recommend you to use itertools.izip_longest if you want to iterate over the lines at the same time. import itertools...
node.js,generator,ecmascript-6,koa
koa-request or any other library that returns thunks or promises/thenables for asynchronous calls is meant to be used with a co-routine library like co or the koa web application framework, which uses co to handle generator-based control flow. ECMAScript 6 generators are not async-aware but ECMAScript 7 will have async...
javascript,node.js,generator,ecmascript-6,arrow-functions
You can't. Sorry. According to MDN The function* statement (function keyword followed by an asterisk) defines a generator function. From a spec document: The function syntax is extended to add an optional * token: FunctionDeclaration: "function" "*"? Identifier "(" FormalParameterList? ")" "{" FunctionBody "}" ...
python,profiling,generator,list-comprehension
First of all the calls are to next(or __next__ in Python 3) method of the generator object not for some even number check. In Python 2 you are not going to get any additional line for a list comprehension(LC) because LC are not creating any object, but in Python 3...
javascript,php,url,generator,slug
Refer to the answers of this question: Efficiently replace all accented characters in a string? The examples in the above page are for other languages than vietnamese, with much less types of accented characters, so I would advise you to write some special letter-substitution code suited for your language, which...
javascript,node.js,generator,bluebird,koa
Please don't call promisifyAll in runtime code: it's unnecessary, clutters application logic, doesn't belong there and is very very slow. You need to mark the method as coroutine, otherwise it's just a generator. var Promise = require("bluebird"); // Assumes request is promisified else where, like in your init file var...
javascript,node.js,asynchronous,callback,generator
utilize the async package. Specifically, the each, eachSeries, or eachLimit for the loops, as well as waterfall and series for control flow. I'd recommend reading up on... each... of the each functions to figure out which is efficient and consistent/reliable for your situation. function getListOfFiles(callback) { async.waterfall([ // get a...
javascript,generator,ecmascript-6
This can be done purely with a generator. Here's an example of one approach, in which we move the .next() into the timeout itself in order to ensure it doesn't occur early. Additionally, the generator now returns the function off the stack instead of executing it, because you can't call...
Use a default value of 1 for next so you print the letters at least once: def iteration(letters, numbers): # create iterator from numbers it = iter(numbers) # get every letter for x in letters: # either print in range passed or default range of 1 for z in range(next(it,...
You are using the Python interactive interpreter to call next(), and it is a function of that shell to print return values. What you are seeing has nothing to do with generators. Simply assign the return value of the next() call to variable to not have them echoed: ignored =...
javascript,generator,ecmascript-6
To answer your question directly, you can't because this inside a generator function is not the generator instance, it is the context of the function call. You could do: function find(next) { process.nextTick(function() { next(1); }); }; var it = (function* main() { var k = yield find(it.next.bind(it)); console.log(k); })();...
python,python-3.x,random,generator
You cannot skip ahead in a generator. There are ways to iterate and create valid random sample, but you'd have to put an upper limit on how many elements you'd iterate. It then would not represent a valid random selection from all possible values the generator could produce. If you...
ArrayList<Integer> myInts = new ArrayList<Integer>(); myInts.add(1); myInts.add(2); myInts.add(3); myInts.add(4); int i = myInts.get(r.nextInt(myInts.size())); // 1,2,3,4 myInts.remove(3); int j = myInts.get(r.nextInt(myInts.size())); // 1,2,4 The code selects random entry from allowed list of integers. PS Please note, that if you have a big range of numbers, then creating an ArrayList of thousands...
Return a generator expression, like this def duty2015(x): if isinstance(x, list) or isinstance(x, np.ndarray): return (result for xi in x for result in duty2015(xi)) else: ... ... Now, whenever you call duty2015 with a single element you will get individual value, otherwise you will get a generator expression, which has...
javascript,promise,generator,ecmascript-6,bluebird
Here's a halfway-decent solution I found after looking more closely at Bluebird's .map() as Benjamin suggested. I still have the feeling I'm missing something, though. The main reason I started with Bluebird was because of Mongoose, so I left a bit of that in for a more realistic sample. let...
python,generator,nonblocking,coroutine
As I understand it - the non-blocking here is used as not breaking the code execution when a specific error occurs. So these generators don't 'block' my code from running when the exception occurs....
for loop generates disposable variable if you use it like above. For example, a list object is used again and again in a loop but a disposable iterator is deleted automatically after use. And yield is a term like return which is used in functions. It gives a result and...
On python3.3+, you can use yield from: def b(): yield 'A' yield 'B' yield from a() In versions prior to python3.3, you need to yield the values explicitly in a loop: def b(): yield 'A' yield 'B' for item in a(): yield item ...
You need to call glob.iglob (the method), not just glob (the module), like so: glob.iglob(os.path.join(x[0], '*.tif')) ...
java,random,bytearray,generator
You can use the Random class. Generate a random number between 0 and 10 and add 14 to it. Random randomGenerator = new Random(); int randomInt = randomGenerator.nextInt(11) + 14; ...
Is there some built-in which marks the last of a sequence? No, there isn't. Your function is fine except for two points: How does it handle an empty sequence? Instead of raise StopIteration you should just break; eventually a raise StopIteration will result in a RunTimeError (PEP 479). ...
GeneratorOf<T>.generate() returns a copy of itself, and in your code, every copy of it shares the same reference to one i So, when you do countDownGen2 = countDownGen.generate() after countDownGen is exhausted, countDownGen2 is also already exhausted. What you should do is something like: func countDown(start: Int) -> SequenceOf<Int> {...
python,python-3.x,iterator,generator
You could do this with itertools.cycle: Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. which is able to replace your function entirely: from itertools import cycle as endless_s ...
Your line current = self.Next should be current = current?.Next ...
It's not the program, it's the choice of numbers. prev is in the beginning equal to zero, so the first number becomes C. Then, prev is equal to C, which makes prev A*C + C. However, A*C is so small, that when adding it as a floating point to the...
python,python-3.x,iterator,generator,itertools
What about: import itertools list_a = [("A","<",1), ("A","==",5)] list_b = [("B","<",5), ("B","==",7), ("B",">=",8)] list_c = [("C","<",10),("C","<=",6),("C",">",4),("C","<=",6)] lists = [list_a, list_b, list_c] for l in lists: l.insert(0, None) for x in itertools.product(*lists): print list(filter(None, x)) For those lists I get 60 elements, including an empty element. For reference, the index of...
arrays,generator,bluebird,koa,co
Your using co-request which already converts callbacks to thunks, so there is no need to try and promisify things. Here is a simplified runnable example, similar to your code, showing how to run api calls in parallel with Koa (which uses co under the hood). When you yield an array,...
Use the combinations functions from the itertools library. There's both combinations with replacement and without replacement for item in itertools.combinations(Letters, 2): print("".join(item)) https://docs.python.org/3.4/library/itertools.html...
ide,generator,webstorm,ecmascript-6
Go to the Preferences > Languages & Frameworks > JavaScript and chose ECMAScript 6 for JavaScript language version.