_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
21
37k
language
stringclasses
1 value
title
stringclasses
1 value
d19075
test
go to controller/product/product.php run this, to check product in stock: <?php foreach ($products as $product) { if($product['stock'] > 0 && $product['product_id']==$product_id['GIFTBOX']) { } ?>
unknown
d19077
test
There are at least two ways to achieve same results. First one with namespaces. Second one - with static functions in classes. With namespaces: #include <stdio.h> namespace GenericMath { void add(); void dot(); } namespace ArmMath { void add(); using GenericMath::dot; } namespace GenericMath { void add() { printf("generic add"); } void dot() { Math::add(); printf("generic dot"); } } namespace ArmMath { void add() { printf("arm add"); } using GenericMath::dot; } int main() { Math::dot(); return 1; } With classes: #include <stdio.h> class GenericMath { public: static void add(); static void dot(); }; class ArmMath : public GenericMath { public: static void add(); }; void GenericMath::add() { printf("generic add"); } void GenericMath::dot() { printf("generic dot"); Math::add(); } void ArmMath::add() { printf("arm add"); } int main() { Math::add(); Math::dot(); return 1; } IMO inline namespaces make code less readable and too verbose. A: Once issue is that unlike #ifdef, the compiler still compiles all the code that isn't for the current platform. So you can't use it for dealing with platform-specific APIs.
unknown
d19079
test
Before sorting the data you need to count the data. You can try : library(dplyr) Data_I_Have %>% count(Node_A, sort = TRUE) %>% left_join(Data_I_Have, by = 'Node_A') # Node_A n Node_B X.Place_Where_They_Met Years_They_Have_Known_Each_Other What_They_Have_In_Common #1 John 5 Claude Chicago 10 Sports #2 John 5 Peter Boston 10 Movies #3 John 5 Tim Seattle 1 Computers #4 John 5 Tim Boston 5 Computers #5 John 5 Claude Paris 2 Video Games #6 Adam 2 Tim Chicago 3 Sports #7 Adam 2 Henry London 3 Sports #8 Kevin 1 Claude London 10 Computers #9 Peter 1 Henry Paris 8 Sports #10 Tim 1 Kevin Chicago 7 Movies #11 Xavier 1 Claude Paris 5 Video Games Or we can use add_count instead of count so that we don't have to join the data. Data_I_Have %>% add_count(Node_A, sort = TRUE) You can remove the n column from the final output if it is not needed. A: As the last answer of the post you mentionend : Data_I_Have %>% group_by(Node_A) %>% arrange( desc(n())) # Node_A Node_B X.Place_Where_They_Met Years_They_Have_Known_Each_Other What_They_Have_In_Common # <chr> <chr> <chr> <chr> <chr> # 1 John Claude Chicago 10 Sports # 2 John Peter Boston 10 Movies # 3 John Tim Seattle 1 Computers # 4 John Tim Boston 5 Computers # 5 John Claude Paris 2 Video Games # 6 Peter Henry Paris 8 Sports # 7 Tim Kevin Chicago 7 Movies # 8 Kevin Claude London 10 Computers # 9 Adam Tim Chicago 3 Sports # 10 Adam Henry London 3 Sports # 11 Xavier Claude Paris 5 Video Games
unknown
d19081
test
Someone taught me how to do it. I had to add the following below namespace. static class global { public static int Var1; public static int Var2; public static int Var3; public static int Var4; } And then define their values in the same place as InitializeComponent(); is. global.Var1 = 5; global.Var2 = 3; global.Var3 = 1; global.Var4 = 1; And then just change the numbers with the correct variable name. It's fairly easy I suppose, but I din't know it and I hope it might help someone else too.
unknown
d19085
test
The window wrapper is the one you need to change: $("#dialog").kendoWindow({ actions: ["Minimize"], minimize: function(e) { $("#dialog").getKendoWindow().wrapper.css({ width: 200 }); } }); Example: Window size change
unknown
d19087
test
Would this work? function randomString() { var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; var string_length = 8; var randomstring = ''; for (var i = 0; i < string_length; i++) { var rnum = Math.floor(Math.random() * chars.length); randomstring += chars.substring(rnum, rnum + 1); } return randomstring; } document.getElementById("randstring").innerHTML = randomString(); window.setTimeout(function(){document.getElementById("randstring").innerHTML = ""}, 2000); This assumes you have an element with the ID of randstring.
unknown
d19089
test
You are not setting your SqlCommand object to be a stored procedure. You should do a couple of things: * *Remove the EXEC prefix from the string ~(it's not needed) *Set command to be a stored procedure: command.CommandType = CommandType.StoredProcedure; *Not sure how the square braces around the DataTable column names will affect this either, but I suspect it's better with them removed.
unknown
d19091
test
TWithChild extends T & ..., meaning if used as explicit type parameter it can union e.g. {a: 1}, you don't know its exact type, so you can't instantiate it. Define it as a known limited generic type, then it'll work type TWithChild<T> = T & {children: TWithChild<T>[]} function withChildren< T extends { id?: string; parentId?: string; } >(parentItem: T, items: T[]): TWithChild<T> { const children = items.filter((ba) => ba.parentId === parentItem.id); return { ...parentItem, children: children.map((child) => withChildren(child, items)), }; } Playground
unknown
d19093
test
Looks like there are some problems with the embedded derby database. I'd try to completely redeploy ODE so that the database is extracted from the .war again. A: You have to execute Eclipse or NetBeans as Administrator.
unknown
d19095
test
You can match it with a regular expression: var pattern = /\d{4}-\d{4}/; A: If you are not using any javascript library (like jQuery, etc), Javascript Regular Expressions could be used for validating the input.
unknown
d19099
test
Q: I used the method *px = 8 first to change it A: The value of both "x" and "*px" changed to "8", correct? Q: but right after that I used x = 99, and it changed too A: Cool. So now both "x" and "*px" are 99. This is what you expected, correct? Q: so I do not know what is the difference between them. In this example, they're both equivalent. They both accomplish exactly the same thing. Why use pointers at all? Because the variable "x" is tied to a specific memory location: you can't change it. The pointer "px", on the other hand, can be changed at runtime to point to DIFFERENT memory locations, if you needed to. Why is that useful? There are many different reasons. For example: * *When you malloc() dynamic memory, the system gives you a pointer. You don't know or care where in memory it's located: you just use it. *Pointers are frequently needed to traverse the elements in a linked list *The ability to increment (++) and decrement (--) pointers simplifies many algorithms *Etc. etc. You might find these articles helpful: * *C - Pointers *Pointer (computer programming) A: Other answers explained what is happening, but in your question I also read you ask 'why' someone would want to use references instead of direct accessing of a memory address. There are many reasons why anything is the way it is in computer science, but a few I think most people wouldn't argue that are helpful for a beginning theoretical understanding: A lot of Computer Science as a discipline is efficient/optimal management of resources, in many cases computer memory, but I/O and CPU make up two other resources we manage to make 'good' software. You may recall that a simple computer can be thought of as a CPU, RAM, and Storage, connected by a "bus". Up until relatively recently, most software wasn't being run on a machine with lots and lots of RAM. It was necessary that memory be managed for performance purposes, and though we have access to higher memory machines today - memory must still be managed! We manage that in more recently created languages with abstraction - or in this context, doing things for people when we know with a high degree of certainty what they are trying to do. We call languages where much of resource management is abstracted and simplified as "high-level" languages. You are "talking" to the machine with your code at a high level of control relative to machine code (you can think of that as the ones and zeros of binary). TLDR; Memory is finite, and pointers generally take up less space than the data they point to, allowing for an efficiency in address space utilization. It also allows for many other neat things, like virtualized address spaces.
unknown
d19101
test
FirstDispositionNameOrDefault is for reading the values of form controls. You can use the [FromUri] attribute on the parameter: public HttpResponseMessage Photo([FromUri] int id) This tells Web API not to get the parameter from the message body.
unknown
d19103
test
Why do you need to use jQuery at all? You can use this: .content-img:hover { -webkit-filter: grayscale(0%); filter: grayscale(0%); } Here, I made you this fiddle using css only, with :hover selector. But be careful, filter has limited support, look at filter article on MDN.
unknown
d19105
test
First get screen width Display mDisplay = activity.getWindowManager().getDefaultDisplay(); int width = mDisplay.getWidth(); int height = mDisplay.getHeight(); Set Size to Layout LinearLayout layout = (LinearLayout)findViewById(R.id.LayoutID); // Gets the layout params that will allow you to resize the layout LayoutParams params = layout.getLayoutParams(); // Changes the height and width to the specified *pixels* params.height = width; params.width = width; layout.setLayoutParams(params); In XML: <LinearLayout android:layout_width="0dp" android:layout_height="0dp" android:id="@+id/LayoutID" android:orientation="vertical" >
unknown
d19109
test
if you are searching for " How to fit a 3D text in a 3D object" I will explain how to do this, lets begin with the theory, Imagine having a flag with the form of the flag given sin(2*pi) if your camera is watching from y axis (three js axes) then you gonna add a text that exactly fits the function sin(2*pi), right? so, as you can see the idea of this is trying to get some tangets of sin(x) function, the secret of this is to cut the text in the number of tangents that will fit your text... for the text, "Montiel Software" it will be now ["Mon","tiel","Soft","Ware"] Flag: function flag(u,v,vector) { var x = 10*u; var y = 10*v; var z = Math.sin(2*Math.PI*u) ; vector.set(x,y,z);} Create the Geometry: var geometry_sin = new THREE.ParametricGeometry(flag, 100, 100); var material_sin = new THREE.MeshPhongMaterial({map:groundTexture,side:THREE.DoubleSide, color:0x000000} ); var flag = new THREE.Mesh( geometry_sin, material_sin ); Now add the text to flag (choose your tangents here) then the flag to scene: var loader = new THREE.FontLoader(); loader.load('js/examples/fonts/helvetiker_regular.typeface.json',function(font){ var geometry = new THREE.TextGeometry( 'Mon', { font: font, size: 1, height: 0.5, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 0.1 } ); var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff}); var txt_mesh = new THREE.Mesh(geometry, txt_mat); txt_mesh.position.z = 0.2; txt_mesh.position.y = 5; txt_mesh.rotation.y = -Math.PI/8; flag.add(txt_mesh); var geometry = new THREE.TextGeometry( 'tiel', { font: font, size: 1, height: 0.5, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 0.1 } ); var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff}); var txt_mesh = new THREE.Mesh(geometry, txt_mat); txt_mesh.position.z = 1.2; txt_mesh.position.x = 2.5; txt_mesh.position.y = 5; txt_mesh.rotation.y = Math.PI/12; flag.add(txt_mesh); var geometry = new THREE.TextGeometry( '$oft', { font: font, size: 1, height: 0.5, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 0.1 } ); var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff}); var txt_mesh = new THREE.Mesh(geometry, txt_mat); txt_mesh.position.z = 0.28; txt_mesh.position.x = 4.5; txt_mesh.position.y = 5; txt_mesh.rotation.y = Math.PI/7; flag.add(txt_mesh); var geometry = new THREE.TextGeometry( 'Ware', { font: font, size: 1, height: 0.5, curveSegments: 12, bevelEnabled: false, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 0.1 } ); var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff}); var txt_mesh = new THREE.Mesh(geometry, txt_mat); txt_mesh.position.z = -1; txt_mesh.position.x = 7; txt_mesh.position.y = 5; txt_mesh.rotation.y = -Math.PI/8; flag.add(txt_mesh); } ); scene.add(flag); that's the only way I can imagine to do this in three JS, if you are just searching to make a 3D objet, I suggest you to install 3D builder and try options there then load the object to THREE js. A: Simply drawing the text to your 2D canvas will most likely never give you a satisfactory result. You have three possibilities to tackle this issue. * *Using textures loaded with a THREE.TextureLoader. * *several examples here: http://threejs.org/examples *tutorial: http://www.johannes-raida.de/tutorials/three.js/tutorial06/tutorial06.htm *Using THREE.TextGeometry: * *an example: https://threejs.org/docs/index.html?q=textgeo#api/en/geometries/TextGeometry *Using a CSS3D solution. * *a nice blog post on this topic: http://learningthreejs.com/blog/2013/04/30/closing-the-gap-between-html-and-webgl/ Check also the UI example on the THREE.TextGeometry documentation page:
unknown
d19111
test
left child = parent * 2 + 1 right child = parent * 2 + 2 I imagine this is homework so I will let you figure out the searching algorithm. A: To implement a binary tree as an array you put the left child for node i at 2*i+1 and the right child at 2*i+2. So for instance, having 6 nodes here's the indices of the corresponding array 0 | --------- | | ---1-- --2-- | | | | 3 4 5 6 A: I think you are looking for a heap. Or at least, you use a tree when an array structure is not enough for your needs so you can try to implement a tree inside an array but it wouldn't make much sense since every node contains references to its children without any need of indices. But an heap is an array that can also be seen as a binary tree, look it out here. It's a tree in the sense that it organizes data as a tree but without having direct references to the children, they can be inferred from the position.
unknown
d19113
test
Create a javascript function that performs an ajax call to a time function which can decide to set the stream or an image: <div id="stream-content"></div> setInterval(function() { $.ajax({ url : "/gettime.php", type: 'GET', success: function(data){ //check time, if correct, set video to the div #stream-content otherwise, set an image as the content } }); }, 1000);
unknown
d19117
test
Use display:inline-block instead of float:left on your .item-component Living Demo .item-component { width: 33.33333333333333%; display: inline-block; padding-left: 15px; } Or, you can take a look at BootStrap and do it by using the :before element maintaning the float:left as you had it before. You would also need to wrap each row: .col{ float:left; width: 32.33%; min-height: 50px; background: #ccc; padding: 20px; box-sizing: border-box; } .row{ display:block; } /* This do the trick */ .row:before{ content: " "; display: table; box-sizing: border-box; clear: both; } Living example Update If you don't want the gap you will have to look for another HTML markup. You will have to print first each column with each rows. This is the needed html markup: <div class="col"> <div class="row" id="demo">1</div> <div class="row">4</div> <div class="row">7</div> </div> <div class="col"> <div class="row">2</div> <div class="row">5</div> <div class="row">8</div> </div> <div class="col"> <div class="row">3</div> <div class="row">6</div> <div class="row">9</div> </div> And the needed css: .col{ float:left; width: 32.33%; } .row{ display:block; padding: 20px; box-sizing: border-box; background: #ccc; min-height: 50px; } #demo{ height: 150px; background: red; } Living demo A: You can do it in the following way. HTML: <div class="container"> <div class="col">1</div> <div class="col">2</div> <div class="col">3</div> <br class="clear" /> <div class="col">4</div> <div class="col">5</div> <div class="col">6</div> <br class="clear" /> <div class="col">7</div> <div class="col">8</div> <div class="col">9</div> <div> CSS: .col { float: left; width: 100px; min-height: 100px; background: #ccc; padding: 20px; margin: 10px; cursor: pointer; } .col:hover { background: yellow; } JS: $('.col').click(function() { if ($(this).is('.clicked')) { $(this).removeClass('clicked'); } else { $(this).addClass('clicked') } }); Live demo: http://jsfiddle.net/S7r3D/1/ ETA: the problem with this solution is that it moves entire row down. I don't really see how to nicely achieve what you want...You could try to overflow the other divs, but it depends on your needs. Is such solution acceptable? ETA2: actually I made it perfect I think! Have a look here: http://jsfiddle.net/S7r3D/3/ The crucial change was rearranging divs and putting them in columns instead. HTML: <div class="container"> <div class="fleft"> <div class="col">1</div> <div class="col">4</div> <div class="col">7</div> </div> <div class="fleft"> <div class="col">2</div> <div class="col">5</div> <div class="col">8</div> </div> <div class="fleft"> <div class="col">3</div> <div class="col">6</div> <div class="col">9</div> </div> <div> CSS: .col { clear: both; width: 100px; min-height: 100px; background: #ccc; padding: 20px; margin: 10px; cursor: pointer; } .col:hover { background: yellow; } .col.clicked { height: 300px; background-color: red; } .fleft { float: left; } JS: /* same as above */ A: Create three container divs, and afterwards, put {1, 4, 7} into div1, {2, 5, 8} into div2, and {3, 6, 9} into div3. Otherwise you will have it very difficult to control their positioning.
unknown
d19119
test
<div> <p v-if="showName">My name is Simon</p> </div> You should open a p tag under the div tag
unknown
d19121
test
This looks like a classic SQL injection problem. What if the description contains a single apostrophe i.e. "Wasn't available", this will break your code. In addition, if Student is an integer value (i.e. it is an integer/auto-incrementing ID or equivalent in your DB) it should not be wrapped in quotes, giving you - DataRow[] foundRow = dt.Select("Student=" + Student.ID + " AND [Student Description]='" + Student.AbsenceDescription.Trim() + "'");
unknown
d19123
test
could be the SabreCommandLLSRQ which can be used to use host commands but using soap.
unknown
d19129
test
In your btnClick function, you can set the Stretch parameter for each item in self.btnLayout. In this case you want to set the Stretch for the spacer on the left to 0 and the right spacer to 1: def btnClick(self, check=False): print('click') # align button left self.btnLayout.setStretch(0,0) self.btnLayout.setStretch(1,1) self.btnLayout.setStretch(2,1) pass For centering the button, set left and right spacers stretch to 1: # button is centered self.btnLayout.setStretch(0,1) self.btnLayout.setStretch(1,1) self.btnLayout.setStretch(2,1) And to align button on right, set left spacer to 1, right spacer to zero: # align button right self.btnLayout.setStretch(0,1) self.btnLayout.setStretch(1,1) self.btnLayout.setStretch(2,0)
unknown
d19131
test
Solution found: const networkInterface = createNetworkInterface('http://localhost:8080/graphql'); this.client = new ApolloClient({ networkInterface, dataIdFromObject: r => r.id } ); dataIdFromObject is the one thing i am missing during the Apolloclient initiation dataIdFromObject (Object) => string A function that returns a object identifier given a particular result object. it will give unique ID for all result object.
unknown
d19137
test
This code: $this->loadModel($id)->okunma=1; $this->render('view',array( 'model'=>$this->loadModel($id), )); retrieves the model (object), changes the okunma property and throws it away (because the return value of loadModel() call is not being stored anywhere) and the other loadModel() call simply retrieves the model again. I think what you meant was: $model = $this->loadModel($id); $model->okunma=1; $this->render('view',array( 'model' => $model, )); this way the retrieved object is stored in a variable, allowing you to modify it and pass it to render() once modified. And if you want this change to propagate to database as well, you need to save() the model: $model = $this->loadModel($id); $model->okunma=1; $model->save(); A: You shouldn't perform update operation in views. I think you want to set model attribute and show this on view - then solution presented by @Liho is correct. If you want to save data to DB, you should assing $_POST attributes to your model: $model = $this->loadModel($id); $model->okunma=1; if(isset($_POST['yourModelName')) { $model->attributes = $_POST['yourModelName']); if($model->validate()) { $model->save(false); // other operations, eg. redirect } } $this->render('view',array( 'model' => $model, )); A: $model = YourModel::model()->findByPk($id); $model->okunma=1; $model->save(false); $this->render('view',array( 'model' => $model, ));
unknown
d19139
test
Your idea is fine. What's wrong with what you had in your question at the bottom? M = reshape(T, [d1*d2 d3]); This would unroll each 2D slice in your 3D tensor into a single column and stack all of the columns together into a 2D matrix. I don't see where your problem lies, other than the fact that you didn't multiply d1 and d2 together. In general, you would want to do this, given T: M = reshape(T, [size(T,1)*size(T,2) size(T,3)]); Or, you can let MATLAB infer the amount of columns by doing: M = reshape(T, size(T,1)*size(T,2), []); To address your other question, to go back from the converted 2D matrix into its original 3D tensor, just do: T2 = reshape(M, d1, d2, d3); In our case, this would be: T2 = reshape(M, size(T,1), size(T,2), size(T,3)); Bear in mind that you must be cognizant of the original dimensions of T before doing this. Remember, reshape works by going over column by column and reshaping the matrix to whatever dimensions you see fit. This will now take each column and convert it back into a 2D slice, then do this for all columns until you get your original 3D matrix back. To illustrate going back and forth, suppose we have this matrix T: >> T = randi(10,3,3,3) T(:,:,1) = 9 10 3 10 7 6 2 1 10 T(:,:,2) = 10 10 2 2 5 5 10 9 10 T(:,:,3) = 8 1 7 10 9 8 7 10 8 To get our unrolled slices so that they fit into columns, use the first line of code above and you you should get a 9 x 3 matrix: >> M = reshape(T, size(T,1)*size(T,2), []) M = 9 10 8 10 2 10 2 10 7 10 10 1 7 5 9 1 9 10 3 2 7 6 5 8 10 10 8 As you can see, each column is a slice from the 3D tensor unrolled into a single vector. Each column takes every column of a slice and stacks them on top of each other to get a single column. To go backwards: >> T2 = reshape(M, size(T,1), size(T,2), size(T,3)) T2(:,:,1) = 9 10 3 10 7 6 2 1 10 T2(:,:,2) = 10 10 2 2 5 5 10 9 10 T2(:,:,3) = 8 1 7 10 9 8 7 10 8 As you can see, both T and T2 are the same.
unknown
d19145
test
Maximum id value of Member model: use app\models\Member; // ... echo Member::find()->max('id');
unknown
d19147
test
The problem is that you create an array of size MAX(a) with a the list of your n numbers. This is inefficient if MAX(a) = 10^5 for example. You should find another way to check if a number A is multiple of number B, for example A%B == 0 (use of modulo). Try to remove countSieve and changed countMultiples. def countMultiples(query, numbers): count = 0 for i in numbers: if i%query == 0: count += 1 return count n=int(input()) numbers = [] for i in range(n): j=int(input()) numbers.append(j) q=int(input()) queries = [] for i in range(q): c=int(input()) queries.append(c) for i in queries: print(countMultiples(i, numbers)) EDIT : Here is an optimization. First I search for numbers divisors, for each divisor I increment a counter in a dict d, then for a query q I print d[q], which is the exact amount of multiples present in the n numbers. The method to search divisors of a number n : I make a loop until the square root of n, then for each divisor i, I also add r = n//i. I also use a dict divs to store divisors for each number n, in order not to re-calculate them if I already found them. Try this (it succeeded the problem https://hack.codingblocks.com/app/dcb/938) : import math d = {} divs = {} for _ in range(int(input())): num = int(input()) if num in divs: for e in divs[num]: d[e] = d.get(e, 0) + 1 else: div_list = [] for i in range(1, math.floor(math.sqrt(num)) + 1): if not num % i: div_list.append(i) d[i] = d.get(i, 0) + 1 r = num // i if (not num % r and r != i): div_list.append(r) d[r] = d.get(r, 0) + 1 divs[num] = div_list for i in range(int(input())): q = int(input()) print(d.get(q, 0)) A: Alternatively, you could try counting how often each number appears and then checking the counts for each multiple of k up to the largest of the N numbers. import collections n = int(input()) nums = [int(input()) for _ in range(n)] counts = collections.Counter(nums) m = max(nums) q = int(input()) for _ in range(q): k = int(input()) x = sum(counts[i] for i in range(k, m+1, k)) print(x) At first sign, this does not look much different than the other approaches, and I think this even still has O(N*Q) in theory, but for large values of Q this should give quite a boost. Let's say Q = 100,000. For all K > 10 (i.e. all except 10 values for K) you will only have to check at most 10,000 multiples (since m <= 100,000). For all K > 10,000 (i.e. 90% of possible values) you only have to check at most 10 multiples, and for 50% of Ks only K itself! I other words, unless there's an error in my logic, in the worst case of N = Q = 100,000, you only have about 1,1 million check instead of 10,000,000,000. >>> N = Q = 100000 >>> sum(N//k for k in range(1,Q+1)) 1166750 (This assumes that all K are different, but if not, you can cache the results in a dict and then will only need a single check for the duplicates, too.) On closer inspection, this approach is in fact pretty similar to what your sieve does, just a bit more compact and computing the values for each k as needed instead of all at once. I did some timing analysis using random inputs using gen_input(n, q, max_k). First, all the algorithms seem to produce the same results. For small-ish input sizes, there is no dramatic difference in speed (except for naive modulo), and your original sieve is indeed the fastest. For larger inputs (maximal values), yours is still the fastest (even by a larger margin), and the divisors approach is considerably slower. >>> n, q = gen_input(10000, 1000, 1000) >>> modulo(n, q) == mine(n, q) == sieve(n, q) == modulo(n, q) True >>> %timeit modulo(n, q) 1 loop, best of 3: 694 ms per loop >>> %timeit mine(n, q) 10 loops, best of 3: 160 ms per loop >>> %timeit sieve(n, q) 10 loops, best of 3: 112 ms per loop >>> %timeit divisors(n, q) 1 loop, best of 3: 180 ms per loop >>> n, q = gen_input(100000, 100000, 100000) >>> %timeit mine(n, q) 1 loop, best of 3: 313 ms per loop >>> %timeit sieve(n, q) 10 loops, best of 3: 131 ms per loop >>> %timeit divisors(n, q) 1 loop, best of 3: 1.36 s per loop Not sure why you are getting timeouts for yours and mine algorithm while @phoenixo's divisors allegedly works (did not try it, though)...
unknown
d19149
test
These are the jquery selectors (as of jQuery 1.10 and jQuery 2.0): * *All Selector ("*") Selects all elements. *:animated Selector Select all elements that are in the progress of an animation at the time the selector is run. *Attribute Contains Prefix Selector [name|="value"] Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-). *Attribute Contains Selector [name*="value"] Selects elements that have the specified attribute with a value containing the a given substring. *Attribute Contains Word Selector [name~="value"] Selects elements that have the specified attribute with a value containing a given word, delimited by spaces. *Attribute Ends With Selector [name$="value"] Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive. *Attribute Equals Selector [name="value"] Selects elements that have the specified attribute with a value exactly equal to a certain value. *Attribute Not Equal Selector [name!="value"] Select elements that either don’t have the specified attribute, or do have the specified attribute but not with a certain value. *Attribute Starts With Selector [name^="value"] Selects elements that have the specified attribute with a value beginning exactly with a given string. *:button Selector Selects all button elements and elements of type button. *:checkbox Selector Selects all elements of type checkbox. *:checked Selector Matches all elements that are checked or selected. *Child Selector ("parent > child") Selects all direct child elements specified by “child” of elements specified by “parent”. *Class Selector (“.class”) Selects all elements with the given class. *:contains() Selector Select all elements that contain the specified text. *Descendant Selector ("ancestor descendant") Selects all elements that are descendants of a given ancestor. *:disabled Selector Selects all elements that are disabled. *Element Selector (“element”) Selects all elements with the given tag name. *:empty Selector Select all elements that have no children (including text nodes). *:enabled Selector Selects all elements that are enabled. *:eq() Selector Select the element at index n within the matched set. *:even Selector Selects even elements, zero-indexed. See also odd. *:file Selector Selects all elements of type file. *:first-child Selector Selects all elements that are the first child of their parent. *:first-of-type Selector Selects all elements that are the first among siblings of the same element name. *:first Selector Selects the first matched element. *:focus Selector Selects element if it is currently focused. *:gt() Selector Select all elements at an index greater than index within the matched set. *Has Attribute Selector [name] Selects elements that have the specified attribute, with any value. *:has() Selector Selects elements which contain at least one element that matches the specified selector. *:header Selector Selects all elements that are headers, like h1, h2, h3 and so on. *:hidden Selector Selects all elements that are hidden. *ID Selector (“#id”) Selects a single element with the given id attribute. *:image Selector Selects all elements of type image. *:input Selector Selects all input, textarea, select and button elements. *:lang() Selector Selects all elements of the specified language. *:last-child Selector Selects all elements that are the last child of their parent. *:last-of-type Selector Selects all elements that are the last among siblings of the same element name. *:last Selector Selects the last matched element. *:lt() Selector Select all elements at an index less than index within the matched set. ***Multiple Attribute Selector [name="value"][name2="value2"] Matches elements that match all of the specified attribute filters. *Multiple Selector (“selector1, selector2, selectorN”) Selects the combined results of all the specified selectors. *Next Adjacent Selector (“prev + next”) Selects all next elements matching “next” that are immediately preceded by a sibling “prev”. *Next Siblings Selector (“prev ~ siblings”) Selects all sibling elements that follow after the “prev” element, have the same parent, and match the filtering “siblings” selector. *:not() Selector Selects all elements that do not match the given selector. *:nth-child() Selector Selects all elements that are the nth-child of their parent. *:nth-last-child() Selector Selects all elements that are the nth-child of their parent, counting from the last element to the first. *:nth-last-of-type() Selector Selects all elements that are the nth-child of their parent, counting from the last element to the first. *:nth-of-type() Selector Selects all elements that are the nth child of their parent in relation to siblings with the same element name. *:odd Selector Selects odd elements, zero-indexed. See also even. *:only-child Selector Selects all elements that are the only child of their parent. *:only-of-type Selector Selects all elements that have no siblings with the same element name. *:parent Selector Select all elements that have at least one child node (either an element or text). *:password Selector Selects all elements of type password. *:radio Selector Selects all elements of type radio. *:reset Selector Selects all elements of type reset. *:root Selector Selects the element that is the root of the document. *:selected Selector Selects all elements that are selected. *:submit Selector Selects all elements of type submit. *:target Selector Selects the target element indicated by the fragment identifier of the document’s URI. *:text Selector Selects all elements of type text. *:visible Selector Selects all elements that are visible. Source: http://api.jquery.com/category/selectors/
unknown
d19155
test
var current = $(this).attr('href').slice(1); alert(current); A: I assume you're dealing with a <a> element? this.hash.substring(1); // yes, it's that simple... A: As easy as this, just use replace: var current = $(this).attr('href').replace('#','');
unknown
d19157
test
I must say https://github.com/gabrielg/periscope_api/ implementation is a bit complicated. Author using 2 sets of keys (IOS_* and PERISCOPE_*) when you actually need only one to access API. I didn't tried to broadcast but in my PHP library all other functions works without troubles with only what he call PERISCOPE_* set of keys. You will get session_secret and session_key from Twitter after getting access to it as Periscope application. So Periscope's login via Twitter process looks like * *Request OAuth token via https://api.twitter.com/oauth/request_token *Redirect user to https://api.twitter.com/oauth/authorize?oauth_token=[oauth_token] *Wait for user login and get oauth_token and oauth_verifier from redirect url *Get oauth_token, oauth_token_secret, user_id and user_name via request to https://api.twitter.com/oauth/access_token?oauth_verifier=[oauth_verifier] *Send request to https://api.periscope.tv/api/v2/loginTwitter { "bundle_id": "com.bountylabs.periscope", "phone_number": "", "session_key": "oauth_token", "session_secret": "oauth_token_secret", "user_id": "user_id", "user_name": "user_name", "vendor_id": "81EA8A9B-2950-40CD-9365-40535404DDE4" } *Save cookie value from last response and add it to all JSON API calls as some kind of authentication token. Requests in 1 and 4 steps should be signed with proper Authorization header which requires Periscope application's consumer_key and consumer_secret. While consumer_key can be sniffed right in first step (if you are able to bypass certificate pinning) consumer_secret never leaves your device and you can't get it with simple traffic interception. There is PHP example of login process https://gist.github.com/bearburger/b4d1a058c4f85b75fa83 A: Periscope's API is not public and the library you are referring to is sort of a hack. To answer the original question, oauth_key & oauth_secret are keys sent by your actual device to periscope service. You can find them by sniffing network traffic sent by your device.
unknown
d19165
test
Given that forks is claiming to provide the same interface as threads I'd be more inclined to report it against forks over HTML::DOM. Especially since the forks is the one doing the deep magic, whereas HTML::DOM is just a normal everyday module. Its not likely the HTML::DOM authors will have any idea what you're on about. A: Problem "solved". I had a weird settings in $PERLLIB and $PERL5LIB, that linked to non-existing directories or directories with outdated libraries. Once I fixed that, forks started working as it should. So, if you have similar troubles with forks, check your $PERLLIB and $PERL5LIB, if it links where it should link.
unknown
d19173
test
The reason you get the PHP source itself, rather than the output it should be rendering, is that your local HTTP server - receiving your request targeted at http://localhost/test.php - decided to serve back the PHP source, rather than forward the HTTP request to a PHP processor to render the output. Why this happens? that has to do with your HTTP server's configuration; there might be a few reasons for that. For starters, you should validate your HTTP server's configuration. * *Which HTTP server are you using on your machine? *What happens when you browse http://localhost/test.php through your browser? A: The problem here is not the Java code - the problem lies with the web server. You need to investigate why your webserver is not executing your PHP script but sending it back raw. You can begin by testing using a simple PHP scipt which returns a fixed result and is accessed using a GET request (from a web browser). Once that is working you can test using the one that responds to POST requests.
unknown
d19175
test
Looks like index = row * width + column to me.
unknown
d19177
test
Magick::Image#read returns an array of images, because this method may be used for reading animated gifs. Simply call .first on the result: img = Magick::Image.read('public/images/bg.png').first Another problem is that you should call annotate on instance of Draw, passing img as first parameter: Magick::Draw.new.annotate(img, 0, 0, 90, 15, 'hello world') do # set options here self.gravity = Magick::SouthEastGravity # … end
unknown
d19181
test
Try this $(document).ready(function() { /* fetch elements and stop form event */ $("form.follow-form").submit(function(e) { /* stop event */ e.preventDefault(); /* "on request" */ $(this).find('i').addClass('active'); /* send ajax request */ $.ajax({ type: "POST", url: "ajax_more.php", data: $(this).serialize(), cache: false, success: function(html) { $("ul.statuses").append(html); $("form.follow-form").remove(); } }); $(".morebox").html('The End'); return false; }); });​ A: You’ve got an else, but no if. Here’s the code with some proper indentation — indentation makes the code much easier to understand, so you spot errors more quickly. $(document).ready(function(){ /* fetch elements and stop form event */ $("form.follow-form").submit(function (e) { /* stop event */ e.preventDefault(); /* "on request" */ $(this).find('i').addClass('active'); /* send ajax request */ $.ajax({ type: "POST", url: "ajax_more.php", data: $(this).serialize(), cache: false, success: function(html){ $("ul.statuses").append(html); $("form.follow-form").remove(); } }); ======> /* HERE’S THE ELSE WITHOUT AN IF */ else { $(".morebox").html('The End'); } return false; }); });
unknown
d19183
test
You would have to use a custom decorator. You can see the code for the Django decorator here. It's already returned a response before your code is reached at all, so absolutely nothing you do in your view function would be run anyway. There is nothing wrong with manually returning a redirect if the request is not a POST. If you use this pattern in a few different places in your code I would then refactor it into a decorator later. But if this is the first place you are using it then it's overkill. A: A custom decorator is the way to go. I myself use one similar to the one you need and I'll post the code. Do upvote @aychedee s answer since he was first. :) def require_post_decorator(function=None, redirect_url='/'): def _decorator(view_function): def _view(request, *args, **kwargs): if request.method == 'POST': #do some before the view is reached stuffs here. return view_function(request, *args, **kwargs) else: return HttpResponseRedirect(redirect_url) _view.__name__ = view_function.__name__ _view.__dict__ = view_function.__dict__ _view.__doc__ = view_function.__doc__ return _view if function: return _decorator(function) return _decorator
unknown
d19185
test
Two ideas: a) limit the depth your "bomb" is going to fork: @echo off set args=%* if "%args%" EQU "" (set args=0) else set /a args=%args%+1 if %args% LSS 8 start /min thisfile.bat (this will produce 2^9 -1 command windows, but only your main window is open.) b) kill the cmd.exe process in the main batch file @echo off SET args=%* :repeat start /min thisfile.bat.bat some_arg if "%args%" NEQ "" goto repeat pause taskkill /im cmd.exe pressing any key in the initial batch file will instamntly kill all cmd windows currently open. These solutions were tested with some restrictions, so if they work in a "hot" forkbomb, please let me know. hope this helps. EDIT: c)implement a time switch in the original bat: (still stops even if you can't get past pause) @echo off set args=%* :repeat start /min thisfile.bat some_arg if "%args%" NEQ "" goto repeat timeout /T 10 taskkill /im cmd.exe or, using the smaller "bomb": @echo off set args=%* if "%args%" NEQ "" (%0 some_arg|%0 some_arg) else start /min thisfile.bat some_arg timeout /T 10 taskkill /im cmd.exe A: If you're out to just show your friend fork bombs why not go for a silent but deadly approach? The fork bomb is in vbs, the cleanup is in batch. Do note, the vbs fork bomb does nothing turning your pc off/on wont fix, it just floods your session proccess's. The fork bomb: Do until true = false CreateObject("Wscript.Shell").Run Wscript.ScriptName Loop Source Cleanup: title=dontkillme FOR /F "tokens=2 delims= " %%A IN ('TASKLIST /FI ^"WINDOWTITLE eq dontkillme^" /NH') DO SET tid=%%A echo %tid% taskkill /F /IM cmd.exe /FI ^"PID ne %tid%^" Source A: If it runs in an accessible directory, you could try IF EXIST kill.txt (exit /b) ELSE (%0|%0) and make a file called kill.txt in the directory to stop the bomb.
unknown
d19187
test
Try to rollback on exception.. and also close the session no matter what heppens: Session session = this.sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); for (StepFlow stepFlow : stepFlows) { session.save(stepFlow); session.flush(); session.clear(); } tx.commit(); } catch (JDBCException e) { SQLException cause = (SQLException) e.getCause(); System.out.println(cause.getMessage()); tx.rollback(); }finally{ session.close(); }
unknown
d19189
test
Try that: <telerik:GridBoundColumn DataField="fromDate" DataType="System.DateTime" HeaderText="تاريخ البداية" UniqueName="fromDate" DataFormatString="{0:dd/MM/yyyy}" HtmlEncode="false"/>
unknown
d19191
test
You just need to add the package name while getting the file For example if your properties name is "ABC.properties" in package a.b.c then the below code will work perfectly ResourceBundle labels = ResourceBundle.getBundle("a.b.c.ABC"); A: Just copy the resource file over to where your class files are. In my case my directory was: bin - com - brookf - all my packages here. copy your resource file to the bin folder. A: Follow the hints in this post and see if you made one of those mistakes, which could be (copy pasted from the link): * *These resource properties files are loaded by classloader, similar to java classes. So you need to include them in your runtime classpath. *These resources have fully-qualified-resource-name, similar to a fully-qualified-class-name, excerpt you can't import a resource into your java source file. Why? because its name takes the form of a string. *ResourceBundle.getBundle("config") tells the classloader to load a resource named "config" with default package (that is, no package). It does NOT mean a resource in the current package that has the referencing class. *ResourceBundle.getBundle("com.cheng.scrap.config") tells the classloader to load a resource named "config" with package "com.cheng.scrap." Its fully-qualified-resource-name is "com.cheng.scrap.config" A: Loading the Properties file for localization stuff is also affected by the package naming. If you put your Properties file in a package like org.example.com.foobar and load it just by its name abc you have to add the prefix org.example.com.foobar, too. If you have the properties at a different location (like in the root directory or in another subdir) you have to change either the name to load or the classpath. I run fine in placing the properties file in the same location where the .java file is and using something like private static ResourceBundle RES = ResourceBundle.getBundle(NameOfTheCurrentClass.class.getCanonicalName()); A: I had the same issue today and it took me a while until I figured out a fix (I'm using Eclipse as an IDE). My project folder contains the *.properties-Files in the following path: project/src/strings Since strings is a sub-folder of src and src is already in the build path of the project (see Property Window), all I needed was to add an Inclusion-Pattern for the *.properties-Files: **/*.properties There should be already an Inclusion-Pattern for *.java-Files (**/*.java) Maybe there is something similar for your IDE A: Is the file in your classpath? If it is, try renaming it to abc_en_US.properties
unknown
d19201
test
I'm not sure what you exactly want but according to your input/output I think you want to flatten the nested object(?) and for that you can use the next piece of code- nested_obj = {"message": "Hey you", "nested_obj": {"id": 1}} flattened_obj = Object.assign( {}, ...function _flatten(o) { return [].concat(...Object.keys(o) .map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]}) ) ); }(nested_obj) ) console.log(JSON.stringify(flattened_obj));
unknown
d19207
test
Ok, found it. kernel.Bind<IPrincipal>() .ToMethod(context => HttpContext.Current.User) .InRequestScope(); Will allow anyone injecting IPrincipal to get the current user name.
unknown
d19209
test
Try: heartBeatThread = (HANDLE)_beginthreadex(NULL, 0 , _StartAddress/*&TestFunction*/, (void*)this, CREATE_SUSPENDED, &hbThreadID); A: I'd strongly suggest making a typedef for the function pointer, and using this everywhere else: typedef unsigned int _stdcall (*Pfn)(void*); // typedefs to "Pfn" void ExecuteLocalThread(Pfn _StartAddress) { HANDLE heartBeatThread; unsigned int hbThreadID; heartBeatThread = (HANDLE)_beginthreadex(NULL, 0, _StartAddress, (void*)this, CREATE_SUSPENDED, &hbThreadID); ResumeThread( heartBeatThread ); } It's easier to type, easier to read and harder to mess up ;) Even casting gets easier with it: To cast somePtr to your function pointer type: (Pfn)somePtr
unknown
d19211
test
You could break up text into two arrays of sentences and then use a function like the similar_text function to recursively check for similar strings. Another idea, to find outright pauperism. You could break down text into sentences again. But then put into a database and run a query that selects count of index column and groups by sentence column. If any results comes back greater than 1, you to have an exact match for that sentence.
unknown
d19213
test
Try like this: <a href="javascript:void(0)" title="Update" onclick="fnUpdate('<s:property value='roleTypeUid'/>');"> A: The called function within onclick has to be a string, you can't reference variables directly in it. onclick="fnUpdate(\"<s:property value='roleTypeUid'/>\");" That string is evalled onclick and thus becomes a function. That's why it may be better to add handlers unobtrusive
unknown
d19215
test
You could loop through an array of file extensions and check them i've made a sample script to show what i mean listed below $array = array('.jpg','.png','.gif'); foreach($array as $key => $value){ $file = 'images/img_' . $post->_id . $value; // images/img_1.jpg if (file_exists($file) && is_file($file)) { $filefound = '<img src="' . $file . '" class="img-responsive" />'; } } if(isset($filefound)){ echo $filefound; }else{ echo '<img src="images/default.gif" class="img-responsive" />'; } A: The most efficient way to do this is probably to store the extension in the database, that way you're not scanning your file system for matches. However, you could also use the glob();; function and check if results has anything. $result = glob('images/img_' . $post->_id . '.*'); If you want to further narrow down your extension types you can do that like this: $result = glob('images/img_' . $post->_id . '.{jpg,jpeg,png,gif}', GLOB_BRACE) New code might look something like this (untested but you get the idea): $result = glob('images/img_' . $post->_id . '.{jpg,jpeg,png,gif}', GLOB_BRACE); if(!empty($result)) { //show the image echo '<img src="' . $result[0]. '" class="img-responsive" />'; } else { // show default image echo '<img src="images/default.gif" class="img-responsive" />'; } A: It is obvious that your script will check only for .jpg not for others because you have written statically the file extension. $file = 'images/img_' . $post->_id . '.jpg'; ^ Now Make change in this line to make available the extension dynamically. I am supposing that you are storing the image name with extension than: $file = 'images/img_' . $post->_id . $post->image_name; Note : $post->image_name should be like : $post->image_name = abc.png (image_name.extension);
unknown
d19217
test
I suggest you to check the following thread: Thread 1: signal SIGABRT in Xcode 9 Quoting from my answer: SIGABRT happens when you call an outlet that is not there. * *No view is connected *Duplicate might be there Outlets are references to storyboard/xib-based UI elements inside your view controller. Make sure whatever you are trying to call is there.
unknown
d19221
test
I'm not sure why Visual Studio express is fine as opposed to full VS.NET given your reasons. Both develop for Windows based platforms. Have you looked at the WCF Test Client (WcfTestClient.exe)? You can find out more information about it here: http://msdn.microsoft.com/en-us/library/bb552364.aspx A: This is really simple, or I found it really simple when I did it with our Java based web-service hosted in tomcat. * *Start a new Solution of any kind in Visual Studio (should work in express). *Right click the References folder in your Project and select Service Reference. *Then put in your wsdl path into the address box and click Go. *This retrieves information about your webservice from the wsdl and you'll be able to create a WebService reference from that. *Then you can just use this like a Class and call the methods. Sorry this isn't really well written and thought out but I don't currently have much time, good luck.
unknown
d19223
test
As per the Java Docs of current build of Selenium Java Client v3.8.1 you cannot use public Actions doubleClick() as the documentation clearly mentions that DoubleClickAction is Deprecated. Here is the snapshot : Hence you may not be able to invoke doubleClick() from Package org.openqa.selenium.interactions Solution : If you need to execute doubleClick() two possible solutions are available as follows : * *Use Actions.doubleClick(WebElement) *Use JavascriptExecutor to inject a script defining doubleClick(). A: You have to pass element argument to doubleClick() menthod. actions.doubleClick(anyClickableWebElement).build().perform();
unknown
d19227
test
I have found the solution, I should just add this tag to the SmtpAppender: <filter type="log4net.Filter.LevelRangeFilter"> <levelMin value="ERROR" /> <levelMax value="FATAL" /> </filter> A: Try using: <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender"> ... <threshold value="WARN"/> ... </appender> (or threshold value="ERROR" since you say you want to limit to Error and Fatallevels) rather than: <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender"> ... <evaluator type="log4net.Core.LevelEvaluator"> <threshold value="WARN"/> </evaluator> ... </appender> The log4net documentation or this message in the log4net user mailing list explains the difference.
unknown
d19231
test
I thought I would update how I resolved the issue in case someone is facing the same issue. There are number of things I did: * *Updated package.config as some of the packages were not using 4.6.1. I'm not sure how it worked until a certain point in time. *Deleted local repo. Cloned the code from the repository, built the solution, and tested if the local instance is working. At this point, it was not. *I noticed that the solution was compiling and producing libraries but the libraries were not copied into the \bin\Debug folder even though the output path was set to bin\Debug folder. So I updated the properties to change the output path to \bin, rebuilt the solution, and then changed the path back to bin\Debug and rebuilt it again. The local instance launched without any issues this time. *Added the new webform (.aspx) file again and rebuilt the solution. This time the local instance launched without any issues.
unknown
d19233
test
HERMES accepts MAT files (*.mat) and Fieldtrip structures. MAT files should consist on one single matrix with as many columns as channels and as many rows as temporal points (and, in the case of event-related data, the third dimension will be for the different trials). For example, for one subject and condition: a matrix of (30 channels x 1000 samples (x 50 trials)). Therefore, to be able to load your data easily, you'll need to obtain your MAT files as described above. Thanks to Guiomar Niso for providing this answer.
unknown
d19235
test
You forgot to use the sorted array! I made it easier to follow by renaming the variables a bit. {% assign sortedOrders = customer.orders | sort: 'order.shipping_address.name' %} {% for order in sortedOrders %} ... {% endfor %} Hope you're getting enough sleep!
unknown
d19237
test
This error is often caused by the zip code not matching the city and state format. I would suggest using usps.com zip code verfication to make sure the zip matches the postal service city and state. You can find this tool here: https://tools.usps.com/go/ZipLookupAction!input.action Using this tool usually helps me clear the error. If this doenst help resolve the issue, please show the address and zip details that you are currently sending. Hope this helps. Thanks,
unknown
d19239
test
Add nodes to a JTree using the DefaultTreeModel's insertNodeInto method. To quote the API This will then message nodesWereInserted to create the appropriate event. This is the preferred way to add children as it will create the appropriate event. For example: ((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, root, 0);//inserts at beginning //((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, root, root.getChildCount() - 1);//inserts at end
unknown
d19241
test
Problem fixed :) Below is the working code $(function(){ $('#datepicker').datepicker({ startDate: '-0m' //endDate: '+2d' }).on('changeDate', function(ev){ $('#sDate1').text($('#datepicker').data('date')); $('#datepicker').datepicker('hide'); }); })
unknown
d19245
test
Yes, there is a way to use this inside your IIFE's, you can bind the thisValue with bind() before calling the IIFE. (function() { this.css('color', '#f00') }).bind($('.' + c))(); A: You can use bind() or call() or apply() and pass 'this' through them as your scope changed for 'this'... It's always a good practice using these functions in javascript, rather then attach it to the function... The best option is call for your code... (function() { this.css('color', '#f00') }).call($('.' + c)); Also using click handler in your javascript, make your code much cleaner and can make your coding structure better, you also can use multiple selection in jQuery to keep HTML clean if needed more selectors handle this function...
unknown
d19249
test
This is a client error because the client specified a restaurant_id that didn't exist. The default code for any client error is 400, and it would be fitting here too. There are slightly more specific client error codes that might work well for this case, but it's not terribly important unless there is something a client can do with this information. * *422 - could be considered correct. The JSON is parsable, it just contains invalid information. *409 - could be considered correct, if the client can create the restaurant with that specific id first. I assume that the server controls id's, so for that reason it's probably not right here. So 400, 422 is fine. 500 is not. 500 implies that there's a server-side problem, but as far as I can tell you are describing a situation where the client used an incorrect restaurant_id.
unknown
d19251
test
You probably generated whatever file you're reading on Windows in UTF-16. You should read and write your files in UTF-8. See \377\376 Appended to file (Windows -> Unix) for more details on this pretty common problem. If you need to read files in UTF-16 in C++, see std::codecvt. That will help you get it over to UTF-8, which is what most of the Mac libraries expect.
unknown
d19253
test
You ask for "if any element in the list is greater than x". If you just want one element, you could just find the greatest element in the list using the max() function, and check if it's larger than x: if max(list) > x: ... There's also a one-liner you can do to make a list of all elements in the list greater than x, using list comprehensions (here's a tutorial, if you want one): >>> x = 22 >>> list = [10, 20, 30, 40] >>> greater = [i for i in list if i > x] >>> print(greater) [30, 40] This code generates a list greater of all the elements in list that are greater than x. You can see the code responsible for this: [i for i in list if i > x] This means, "Iterate over list and, if the condition i > x is true for any element i, add that element to a new list. At the end, return that new list." A: Use any, Python's natural way of checking if a condition holds for, well, any out of many: x = 22 lst = [10, 20, 30] # do NOT use list as a variable anme if any(y > x for y in lst): # do stuff with lst any will terminate upon the first truthy element of the iterable it is passed and, thus, not perform any spurious iterations which makes it preferable to max or list comprehension based approaches that have to always iterate the entire list. Asymptotically however, its time complexity is, of course, still linear. Also, you should not shadow built-in names like list. A: You could use filter and filter your list for items greater than 22, if the len of this filtered list is > 0 that means your original list contains a value larger than 22 n = 22 lst = [10,20,30] if len(list(filter(lambda x: x > n, lst))) > 0: # do something to lst A: List comprehension would suit your use case. In [1]: x=22 In [2]: l=[10,20,30] In [3]: exist = [n for n in l if n > x] In [4]: if exist: ...: print "elements {} are greater than x".format(exist) ...: elements [30] are greater than x If your list is very long, use generator so that you do not have to iterate through all elements of the list. In [5]: exist = next(n for n in l if n > x) In [6]: if exist: print "Element {} is greater than x".format(exist) ...: Element 30 is greater than x
unknown
d19255
test
I use this simple replace Date: <input name=x size=10 maxlength=10 onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"> Try it with jsfiddle A: I made a simple example for your purpose: var date = document.getElementById('date'); date.addEventListener('keypress', function (event) { var char = String.fromCharCode(event.which), offset = date.selectionStart; if (/\d/.test(char) && offset < 8) { if (offset === 2 || offset === 5) { offset += 1; } date.value = date.value.substr(0, offset) + char + date.value.substr(offset + 1); date.selectionStart = date.selectionEnd = offset + 1; } if (!event.keyCode) { event.preventDefault(); } }); Here is a fiddle A: Here is a shorter version: $("#txtDate").keyup(function(){ if ($(this).val().length == 2 || $(this).val().length == 5){ $(this).val($(this).val() + "/"); } });
unknown
d19259
test
I have created a CSV tax rates import file for all EU countries based on the DE VAT rate (19%). Magento CSV Steuersätze Import-Datei für alle EU-Länder (2013). Ich habe eine CSV Steuersätze Import-Datei für alle EU-Länder auf dem DE MwSt.-Satz (19%) basiert. (magento_eu_tax_rates.csv) Code,Country,State,Zip/Post Code,Rate,Zip/Post is Range,Range From,Range To,default,germany AT,AT,*,,19,,,,VAT, BE,BE,*,,19,,,,VAT, BG,BG,*,,19,,,,VAT, HR,HR,*,,19,,,,VAT, CY,CY,*,,19,,,,VAT, CZ,CZ,*,,19,,,,VAT, DK,DK,*,,19,,,,VAT, EE,EE,*,,19,,,,VAT, FI,FI,*,,19,,,,VAT, FR,FR,*,,19,,,,VAT, DE,DE,*,,19,,,,VAT, GR,GR,*,,19,,,,VAT, HU,HU,*,,19,,,,VAT, IE,IE,*,,19,,,,VAT, IT,IT,*,,19,,,,VAT, LV,LV,*,,19,,,,VAT, LT,LT,*,,19,,,,VAT, LU,LU,*,,19,,,,VAT, MT,MT,*,,19,,,,VAT, NL,NL,*,,19,,,,VAT, PL,PL,*,,19,,,,VAT, PT,PT,*,,19,,,,VAT, RO,RO,*,,19,,,,VAT, SK,SK,*,,19,,,,VAT, SI,SI,*,,19,,,,VAT, ES,ES,*,,19,,,,VAT, SE,SE,*,,19,,,,VAT, GB,GB,*,,19,,,,VAT, A: An up to date CSV for EU tax rates in 2014 that works with Magento 1.9.0.1 (note that this is the current UK VAT rate of 20%). It should also be noted that Iceland, Liechtenstein, Norway and Switzerland are exempt from UK VAT. Code,Country,State,Zip/Post Code,Rate,Zip/Post is Range,Range From,Range To,default GB,GB,*,,20.0000,,,,VAT AL,AL,*,,20.0000,,,,VAT AD,AD,*,,20.0000,,,,VAT AT,AT,*,,20.0000,,,,VAT BY,BY,*,,20.0000,,,,VAT BE,BE,*,,20.0000,,,,VAT BA,BA,*,,20.0000,,,,VAT BG,BG,*,,20.0000,,,,VAT HR,HR,*,,20.0000,,,,VAT CY,CY,*,,20.0000,,,,VAT CZ,CZ,*,,20.0000,,,,VAT DK,DK,*,,20.0000,,,,VAT EE,EE,*,,20.0000,,,,VAT FO,FO,*,,20.0000,,,,VAT FI,FI,*,,20.0000,,,,VAT FR,FR,*,,20.0000,,,,VAT DE,DE,*,,20.0000,,,,VAT GI,GI,*,,20.0000,,,,VAT GR,GR,*,,20.0000,,,,VAT HU,HU,*,,20.0000,,,,VAT IS,IS,*,,0.0000,,,,VAT IE,IE,*,,20.0000,,,,VAT IT,IT,*,,20.0000,,,,VAT LV,LV,*,,20.0000,,,,VAT LB,LB,*,,20.0000,,,,VAT LI,LI,*,,0.0000,,,,VAT LT,LT,*,,20.0000,,,,VAT LU,LU,*,,20.0000,,,,VAT MT,MT,*,,20.0000,,,,VAT MD,MD,*,,20.0000,,,,VAT MC,MC,*,,20.0000,,,,VAT ME,ME,*,,20.0000,,,,VAT NL,NL,*,,20.0000,,,,VAT NO,NO,*,,0.0000,,,,VAT PL,PL,*,,20.0000,,,,VAT PT,PT,*,,20.0000,,,,VAT RO,RO,*,,20.0000,,,,VAT RS,RS,*,,20.0000,,,,VAT SK,SK,*,,20.0000,,,,VAT SI,SI,*,,20.0000,,,,VAT ES,ES,*,,20.0000,,,,VAT SJ,SJ,*,,20.0000,,,,VAT SE,SE,*,,20.0000,,,,VAT CH,CH,*,,0.0000,,,,VAT TR,TR,*,,20.0000,,,,VAT UA,UA,*,,20.0000,,,,VAT VA,VA,*,,20.0000,,,,VAT
unknown
d19261
test
How about this: select group_concat(name) as names, time from table t group by time having count(*) > 1; This will give you output such as: Names Time Richard,Luigi 8:00 . . . Which can then format on the application side.
unknown
d19263
test
a base solution. To split df by ID, then paste the Attributes together. Then rbind the list of results. do.call(rbind, by(df, df$ID, function(x) data.frame(ID=x$ID[1], Attributes=paste(x$Attributes, collapse=",")) )) data: df <- read.table(text="ID Attributes 1 apple 1 banana 1 orange 1 pineapple 2 apple 2 banana 2 orange 3 apple 3 banana 3 pineapple", header=TRUE) A: A tidyverse approach would be to group_by your ID and summarise with paste. library(dplyr) df <- read.table(text = " ID Attributes 1 apple 1 banana 1 orange 1 pineapple 2 apple 2 banana 2 orange 3 apple 3 banana 3 pineapple", header = TRUE, stringsAsFactors = FALSE) df %>% group_by(ID) %>% summarise( Attributes = paste(Attributes, collapse = ", ") ) # # A tibble: 3 x 2 # ID Attributes # <int> <chr> # 1 1 apple, banana, orange, pineapple # 2 2 apple, banana, orange # 3 3 apple, banana, pineapple
unknown
d19267
test
Ok the answer is simple. This is not XmlAttribute ... this is XmlElement. Change attribute to: [XmlElement("startDate")] public DateTime StartDate { get; set; } Are you sure element "weeks" works properly and is marked with XmlAttribute ?
unknown
d19271
test
Asynchronously, by default. If you need them to be one-after-the-other, you can do a few things: * *Place the second in the callback of the first. *Set $.ajax({async:false}) *You could possibly even set these up in a queue. The cleanest way is probably option 2. A: Yes, the full call for load is: load( url, [data], [callback] ) the third optional parameter is a callback method that will be called when the asynchronous load method completes.
unknown
d19275
test
If you want all possible combinations regardless or left/right order you can do: select a.player_id, b.player_id from player a join player b on b.player_id < a.player_id
unknown
d19279
test
Please see this - you may have IO issues - and physical drive issues http://blogs.msdn.com/chrissk/archive/2008/06/19/i-o-requests-taking-longer-than-15-seconds-to-complete-on-file.aspx
unknown
d19283
test
Assuming that dataframe is named 'dat' then aggregate.formula which is one of the generics of aggregate: > aggregate( Z ~ X + Y, data=dat, FUN=sum) X Y Z 1 1 1 2435 2 2 1 534 3 1 2 91 4 2 2 97 5 1 3 1924 6 2 3 161 7 1 4 582 8 2 4 122 9 2 5 403 Could also have used xtabs which returns a table object and then turn it into a dataframe with as.data.frame: as.data.frame( xtabs( Z ~ X+Y, data=dat) )
unknown
d19287
test
Use lookaheads (zero-width assertion) for both patterns: (?=(foo))(?=(fooba)) RegEx Demo
unknown
d19289
test
You should not need to refresh the page in order to save information into the PHP Session object. PHP Session information is stored on the server, so you can do an asynchronous HTTP request to the backend, and store information the PHP Session. I would suggest using the jQuery.ajax function (http://api.jquery.com/jQuery.ajax/) to do your async HTTP requests. If you are not familiar with jQuery, I highly suggest you get familiar with it. I also suggest you look into how AJAX works. Also, if you are using the PHP session, if you are not using some kind of framework which does session management, you must make sure to call session_start() before using the $_SESSION variable.
unknown
d19295
test
Just use the OrderBy method: Records.OrderBy(record => record.Started) or: from r in Records order by r.Started select r A: Could it be this easy? records.OrderBy(r=>r.Started)
unknown
d19299
test
try to use this code if (count($results) > 0) { $this->set("message", "Sorry, that data already exists. <a href=\"http://www.example.com/\">Need help?</a>"); return; } A: $this->set("message", 'Sorry, that data already exists.<a href="http://www.example.com/">'); Doing this will get the anchor in as part of the string, and if you need to echo it, it should be generated as HTML. A: it's simply: if (count($results) > 0) { $this->set("message", 'Sorry, that data already exists. <a href="http://www.example.com/">'); return; } Better use single quotes ' and you don't need to escape " in tags attributes. Or store link in variable: if (count($results) > 0) { $link = '<a href="http://www.example.com/">'; $this->set("message", "Sorry, that data already exists. $link"); return; }
unknown
d19301
test
The string "hostednetwork" will never be the same as the string "started" Also, you have a syntax error with your elsestatement. Nevertheless, you don't need it: netsh wlan show hostednetwork|find "Status"|find "started">nul && goto stop || goto start A: For anyone who would like to use this method, here is the complete working code @ECHO OFF netsh wlan show hostednetwork|find "Status"|find "Started">nul && goto stop || goto start :start netsh wlan start hostednetwork goto end :stop netsh wlan stop hostednetwork goto end :end PAUSE Thanks to those who put into the creation of this method
unknown
d19303
test
You can use ToByteArray() function and then the Guid constructor. byte[] buffer = Guid.NewGuid().ToByteArray(); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 0; Guid guid = new Guid(buffer); A: Since the Guid struct has a constructor that takes a byte array and can return its current bytes, it's actually quite easy: //Create a random, new guid Guid guid = Guid.NewGuid(); Console.WriteLine(guid); //The original bytes byte[] guidBytes = guid.ToByteArray(); //Your custom bytes byte[] first4Bytes = BitConverter.GetBytes((UInt32) 0815); //Overwrite the first 4 Bytes Array.Copy(first4Bytes, guidBytes, 4); //Create new guid based on current values Guid guid2 = new Guid(guidBytes); Console.WriteLine(guid2); Fiddle Keep in mind however, that the order of bytes returned from BitConverter depends on your processor architecture (BitConverter.IsLittleEndian) and that your Guid's entropy decreases by 232 if you use the same number every time (which, depending on your application might not be as bad as it sounds, since you have 2128 to begin with). A: The question is about replacing bits, but if someone wants to replace first characters of guid directly, this can be done by converting it to string, replacing characters in string and converting back. Note that replaced characters should be valid in hex, i.e. numbers 0 - 9 or letters a - f. var uniqueGuid = Guid.NewGuid(); var uniqueGuidStr = "1234" + uniqueGuid.ToString().Substring(4); var modifiedUniqueGuid = Guid.Parse(uniqueGuidStr);
unknown
d19305
test
You can simply limit the queryset for those fields by overriding the init method in the PersonAdminForm class: class PersonAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PersonAdminForm, self).__init__(*args, **kwargs) self.fields['fathers'].queryset = Person.objects.filter(sex='m') self.fields['mothers'].queryset = Person.objects.filter(sex='f')
unknown
d19307
test
Usually component routing doesn't reload because angular works as SPA(single page application) - but you can make your components to load in order to reduce the browser size if that is the only case Use href and your path name insted of routerLink on your sidebar anchor link - this will make your component to reload everytime when you click - everytime it will load all your js from server - if you are using lazy load this process is not the right way - this will only helps you to reduce the browser RAM usage on every click and doesn't maintain any previous data but routing will work as the same So href will be the word for your question - but make sure that you really want to load your components Hope it helps - Happy Coding:) A: If you want to reload the entire page, just use window.location.reload();
unknown
d19309
test
You cannot do this on a stock device. Your best bet is to create a launcher that only allows launching your app. The user needs to agree to run it however, and it can always be changed and/or disabled in Settings.
unknown
d19311
test
I'd try Apache POI, the Java API for Microsoft documents. Its based on Java and I've seen it used in Android before. I haven't used it myself though, so I can't accredit to how well it works. A: Check out the source code of APV - it's a PDF viewer based on MuPdf library - both are free. You can probably assemble something quickly.
unknown
d19315
test
Google Translate says he said: "Matus know the těchhle point I stopped, I'm a beginner and do not know what I stand on it all night" Sounds like you need to read up on some JavaScript and jQuery tutorials. I began with something like this: jQuery for Absolute Beginners: The Complete Series Really hope this helps. A: You have a number of problems you need to solve. Break them down into smaller chunks and tackle it from there. Only numbers You could watch the field (check out .on) for a change and then delete any character that's not part of the set [\d] or [0-9], but that could get messy. A better idea might be to watch for a keydown event and only allow the keys that represent numbers. The Dot Trying to dynamically stop the user from deleting the dot is messy, so let's just focus on adding it back in when the field is blurred. That's pretty easy, right? Just check for a . and if there isn't one, append ".00" to the end of the field. Decimal Places This is really the same problem as above. You can use .indexOf('.') to determine if the dot is present, and if it is, see if there are digits after it. If not, append "00" if so, make sure there's 2 digits, and append a "0" if there's only 1. String Pattern This could really be solved any number of ways, but you can reuse your search for the decimal place from above to split the string into "Full Dollar" and "Decimal" parts. Then you can use simple counting on the "Full Dollar" part to add spaces. Check out the Javascript split and splice functions to insert characters at various string indexes. Good luck!
unknown
d19325
test
Using Object#keys: const getPropertyNames = (arr = []) => arr.length > 0 ? Object.keys(arr[0]) : []; const data = [ { "name": "Tiger Nixon", "position": "System Architect", "salary": "320800", "start_date": "2011\/04\/25", "office": "Edinburgh", "rating": "5421" }, { "name": "Garrett Winters", "position": "Accountant", "salary": "170750", "start_date": "2011\/07\/25", "office": "Tokyo", "rating": "8422" }, { "name": "Ashton Cox", "position": "Junior Technical Author", "salary": "86000", "start_date": "2009\/01\/12", "office": "San Francisco", "rating": "1562" }, { "name": "Cedric Kelly", "position": "Senior Javascript Developer", "salary": "433060", "start_date": "2012\/03\/29", "office": "Edinburgh", "rating": "6224" } ]; console.log( getPropertyNames(data) );
unknown
d19329
test
System.out.println(new BigDecimal("58.15")); To construct a BigDecimal from a hard-coded constant, you must always use one of constants in the class (ZERO, ONE, or TEN) or one of the string constructors. The reason is that one you put the value in a double, you've already lost precision that can never be regained. EDIT: polygenelubricants is right. Specifically, you're using Double.toString or equivalent. To quote from there: How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0. A: Yes, println (or more precisely, Double.toString) rounds. For proof, System.out.println(.1D); prints 0.1, which is impossible to represent in binary. Also, when using BigDecimal, don't use the double constructor, because that would attempt to precisely represent an imprecise value. Use the String constructor instead. A: out.println and Double.toString() use the format specified in Double.toString(double). BigDecimal uses more precision by default, as described in the javadoc, and when you call toString() it outputs all of the characters up to the precision level available to a primitive double since .15 does not have an exact binary representation.
unknown
d19333
test
You should add dev and prod variables to your settings.json file, and load them locally with meteor --settings settings.json. The settings.json file would look something like this: { "dev": { "public": { "facebook": { "appId": "abc123" } }, "private": { "facebook": { "secret": "456def789" } } }, "prod": { "public": { "facebook": { "appId": "def234" } }, "private": { "facebook": { "secret": "789ghi101112" } } } You could then access them just as you were before: Meteor.settings.dev.public.facebook.appId. The public/private may be overkill for your project (and I may have messed up the brackets), but this should convey the general concept. For more info, check out this oft-cited post.
unknown
d19335
test
I was able to fix the issue by setting "equals" to "In a List". here is the steps In DataSets -> Query Designer -> Filter -> Any of section click on equals then select In a List
unknown
d19337
test
Most likely, you also need the mono runtime and all the support libraries that are needed. Run your app once from the debugger (or at least deploy from within Visual Studio/Xamarin Studio), and you will a) get a notice (in deploy output) about all the libraries/frameworks being installed before the app launches, this can actually take a minute before first launch b) you have those supports installed for the future, so as long as you target the same framework version, you can simply directly install the .apks Normally, you don't use .apks directly, since most often your first shot is not perfect anyway, so the debugging helps a lot. :)
unknown
d19339
test
ASP.NET Scaffolding is expecting Entity Framework based Data Model classes in order to help you creating views/controllers . But you are using View Model ,view model doesn't been persist in a database and also it doesn't have any primary key field, hence it cannot be scaffolded. And also when using scaffold wizard you always need to choose data context . But a view model has no relationship with your data context. You should use your actual data model instead of a viewmodel to perform scaffolding , then modify the codes to use view model to transfer data between views and controllers Inside your controller action that you could map the view model back to your data model that will be persisted using EF. You could use AutoMapper to map between your view models and data models.
unknown
d19343
test
Like <include> the only attributes that ViewStub lets you override are the layout attributes and which id the child view will have after inflation.
unknown
d19345
test
Path only contains information about where a file (or other thing) is located, it does not provide any information on how to process it. As you know the Path is a file then you can use the File class to process it, in this case to open a stream on it. In language terms Path does not have a newOutputStream method so it will fail to compile. From Oracle documentation on Path Paths may be used with the Files class to operate on files, directories, and other types of files.
unknown
d19347
test
git reset --hard will bring you back to the last commit, and git reset --hard origin/master will bring you back to origin/master. A: You can revert the change Read more: http://book.git-scm.com/4_undoing_in_git_-_reset,_checkout_and_revert.html A: Another option is just to discard all your changes git checkout . And then git pull
unknown
d19351
test
How about using: $args = func_get_args(); call_user_func_array('mysql_safe_query', $args); A: N.B. In PHP 5.6 you can now do this: function mysql_row_exists(...$args) { $result = mysql_safe_query(...$args); return mysql_num_rows($result) > 0; } Also, for future readers, mysql_* is deprecated -- don't use those functions. A: Depending on the situation, following might also work for you and might be a little faster. function mysql_safe_query($format) { $args = func_get_args(); $args = is_array($args[0]) ? $args[0] : $args; // remove extra container, if needed // ... Which now allows for both types of calling, but might be problematic if your first value is supposed to be an actual array, because it would be unpacked either way. You could additionally check on the length of your root-array, so it might not be unpacked if if there are other elements, but as mentioned: It is not really that "clean" in general, but might be helpful and fast :-)
unknown
d19353
test
I strongly suggest using the Boost C++ regex library. If you are developing serious C++, Boost is definitely something you must take into account. The library supports both Perl and POSIX regular expression syntax. I personally prefer Perl regular expressions since I believe they are more intuitive and easier to get right. http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/boost_regex/syntax.html But if you don't have any knowledge of this fine library, I suggest you start here: http://www.boost.org/doc/libs/1_46_0/libs/regex/doc/html/index.html A: I found the answer here: #include <regex.h> #include <stdio.h> int main() { int r; regex_t reg; if (r = regcomp(&reg, "\\b[A-Z]\\w*\\b", REG_NOSUB | REG_EXTENDED)) { char errbuf[1024]; regerror(r, &reg, errbuf, sizeof(errbuf)); printf("error: %s\n", errbuf); return 1; } char* argv[] = { "Moo", "foo", "OlOlo", "ZaooZA~!" }; for (int i = 0; i < sizeof(argv) / sizeof(char*); i++) { if (regexec(&reg, argv[i], 0, NULL, 0) == REG_NOMATCH) continue; printf("matched: %s\n", argv[i]); } return 0; } The code above will provide us with matched: Moo matched: OlOlo matched: ZaooZA~! A: Manuals should be easy enough to find: POSIX regular expression functions. If you don't understand that, I would really recommend trying to brush up on your C and C++ skills. Note that actually replacing a substring once you have a match is a completely different problem, one that the regex functions won't help you with.
unknown
d19357
test
You can extract your data this way: 1> Message = [[<<>>], 1> [<<"10">>,<<"171">>], 1> [<<"112">>,<<"Gen20267">>], 1> [<<"52">>,<<"20100812-06:32:30.687">>]] . [[<<>>], [<<"10">>,<<"171">>], [<<"112">>,<<"Gen20267">>], [<<"52">>,<<"20100812-06:32:30.687">>]] 2> [Data] = [X || [<<"112">>, X] <- Message ]. [<<"Gen20267">>] 3> Data. <<"Gen20267">> Another way: 4> [_, Data] = hd(lists:dropwhile(fun([<<"112">>|_]) -> false; (_)->true end, Message)). [<<"112">>,<<"Gen20267">>] 5> Data. <<"Gen20267">> And another one as function in module (probably fastest): % take_data(Message) -> Data | not_found take_data([]) -> not_found; take_data([[<<"112">>, Data]|_]) -> Data; take_data([_|T]) -> take_data(T).
unknown
d19359
test
When installing Bootstrap from their GitHub repository, you get a large amount of files that are only required for debugging, testing, compiling from source, etc. It includes many operations that are only needed if you are trying to contribute to Bootstrap. The NPM version is just a packaged, production-ready version of Bootstrap. Even after running npm install, you don't get all of the GitHub files, as they are unnecessary for a production environment. You cannot therefore build the NPM version, except by adding basically everything from the GitHub version.
unknown
d19365
test
You can not get identifier by value, but you can make your identifier name look like a value and get it by string name, So what I suggest, use your String resource name something like, resource_150 <string name="resource_150">150</string> Now here resource_ is common for your string entries in string.xml file, so in your code, String value = "150"; int resourceId = this.getResources(). getIdentifier("resource_"+value, "string", this.getPackageName()); Now resourceId value is as equivalent to R.string.resource_150 Just make sure here this represent your application context. In your case MainActivity.this will work. A: EDIT You can't search for a resource Id by the string value. You could make your own Map of the values and resourceIds and use that as a look up table, but I believe just choosing an intelligent naming convention like in the accepted answer is the best solution. A: I have found some tips here: Android, getting resource ID from string? Below an example how to get strings and their values defined in strings.xml. The only thing you have to do is making a loop and test which string is holding your value. If you need to repeat this many times it might be better to build an array. //--------- String strField = ""; int resourceId = -1; String sClassName = getPackageName() + ".R$string"; try { Class classToInvestigate = Class.forName(sClassName); Field fields[] = classToInvestigate.getDeclaredFields(); strField = fields[0].getName(); resourceId = getResourceId(strField,"string",getPackageName()); String test = getResources().getString(resourceId); Toast.makeText(this, "Field: " + strField + " value: " + test , Toast.LENGTH_SHORT).show(); } catch (ClassNotFoundException e) { Toast.makeText(this, "Class not found" , Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(this, "Error: " + e.getMessage() , Toast.LENGTH_SHORT).show(); } } public int getResourceId(String pVariableName, String pResourcename, String pPackageName) { try { return getResources().getIdentifier(pVariableName, pResourcename, pPackageName); } catch (Exception e) { e.printStackTrace(); return -1; } } A: In addition to user370305, you could make an extension and use it the same was as with int ids. import android.app.Activity fun Activity.getString(id: String): String { val resourceId = this.resources.getIdentifier(id, "string", this.packageName) return getString(resourceId) }
unknown
d19367
test
If price_nodes is correctly fill i.e. price_nodes = <span id="SkuNumber" itemprop="identifier" content="sku:473768" data-nodeid="176579" class="product-code col-lg-4 col-md-4">ΚΩΔ. 473768</span> You just have to do this: datanode = price_nodes.get('data-nodeid') Full code should be: from bs4 import BeautifulSoup as soup html = '<div><span id="SkuNumber" itemprop="identifier" content="sku:473768" data-nodeid="176579" class="product-code col-lg-4 col-md-4">ΚΩΔ. 473768</span></div>' page = soup(html, 'html.parser') price_nodes = page.find('span', {'id': 'SkuNumber'}) datanode = price_nodes.get('data-nodeid') A: from bs4 import BeautifulSoup html = '<span id="SkuNumber" itemprop="identifier" content="sku:473768" data-nodeid="176579" class="product-code col-lg-4 col-md-4">ΚΩΔ. 473768</span></div>' soup = BeautifulSoup(html) price_nodes = soup.find('span', attrs={'id': 'SkuNumber'}) print(price_nodes['data-nodeid'])
unknown
d19369
test
In the ".Net" SDK, each of the models has a "Validate()" method. I have not yet found anything similar in the Powershell commands. In my experience, the (GUI) validation is not foolproof. Some things are only tested at runtime. A: I know it has been a while and you said you didn't want the validation to work in an year - but after a couple of years we finally have both the Validate all and Export ARM template features from the Data Factory user experience via a publicly available npm package @microsoft/azure-data-factory-utilities. The full guidance can be found on this documentation.
unknown
d19371
test
Since the locking mechanism isn't specified I'd assume it uses a normal mutex in which case the obvious problem is this: A a; a[0] = a[1]; Put differently, it is very easy to dead-lock the program. This problem is avoided with recursive mutexes. The other obvious problem is that the code depends on copy-elision which is not guaranteed to always happen. If the copy is not elided upon return the temporary will release the lock and the copy will release it again which normally is undefined behavior. In addition, access to the member is unguarded and will potentially introduce data races. To avoid this problem you should define a move constructor and make sure that the moved from state doesn't try to release the mutex, e.g.: A::Proxy::Proxy(Proxy&& other) : val(other.val) , parent(other.parent) { other.parent = 0; } A::Proxy::~Proxy() { if (parent){ parent->unlock(); } } The not so obvious issue is that it is unlikely to result in an efficient implementation.
unknown
d19375
test
As per the source code of iniparser (https://github.com/ndevilla/iniparser/blob/deb85ad4936d4ca32cc2260ce43323d47936410d/src/iniparser.c#L312): in iniparser_dumpsection_ini function, there is this line: fprintf(f, "%-30s = %s\n", d->key[j]+seclen+1, d->val[j] ? d->val[j] : ""); As you can see, key is printed with format specifier %-30s which is probably causing this issue. So, you can clone the repo source code and make the changes. Example, replace format specifier with %s, like: fprintf(f, "%s = %s\n", // CHANGE HERE d->key[j]+seclen+1, d->val[j] ? d->val[j] : "");
unknown
d19377
test
You just write a second loop to join the threads totalPoints = [] def workThread(i): global totalPoints totalPoints += i threads = [] for i in range(NUMBER_OF_THREADS): t = threading.Thread(target=workThread, args=(i,)) t.start() threads.append(t) for t in threads: t.join() Your code will fail at totalPoints += i because totalPoints is a list. You don't handle exceptions in your threads so you may fail silently and not know what happened. Also, you need to be careful how you access a shared resource such as totalPoints to be thread safe. A: does this help: ? #!/usr/bin/env python # -*- coding: utf-8 -*- import threading import time import random NUMBER_OF_THREADS=20 totalPoints = [] def workThread(i): global totalPoints time.sleep(random.randint(0, 5)) totalPoints.append((i, random.randint(0, 255))) threads = [] for i in range(NUMBER_OF_THREADS): t = threading.Thread(target=workThread, args=(i,)) t.start() threads.append(t) for t in threads: t.join() print totalPoints It always prints something like this: [(1, 126), (10, 169), (11, 154), (0, 214), (9, 243), (12, 13), (15, 152), (6, 24), (17, 238), (13, 28), (19, 78), (16, 130), (2, 110), (3, 186), (8, 55), (14, 70), (5, 35), (4, 39), (7, 11), (18, 14)] or this [(2, 132), (3, 53), (4, 15), (6, 84), (8, 223), (12, 39), (14, 220), (0, 128), (9, 244), (13, 80), (19, 99), (7, 184), (11, 232), (17, 191), (18, 207), (1, 177), (5, 186), (16, 63), (15, 179), (10, 143)]
unknown
d19379
test
C++11 has introduced noexcept, throw is somewhat deprecated (and according to this less efficient) noexcept is an improved version of throw(), which is deprecated in C++11. Unlike throw(), noexcept will not call std::unexpected and may or may not unwind the stack, which potentially allows the compiler to implement noexcept without the runtime overhead of throw(). When an empty throw specification is violated, your program is terminated; this means you should only declare your functions as non throwing, only when they have a no throw exception guarantee. Finally you need a move constructor to be non throwing (specified with noexcept) to be able to use the r-value ref version of std::vector<T>::push_back (see a better explanation here) A: The standard throw() doesn't enhance optimizability. If a method is marked as throw() then the compiler is forced to check if an exception is thrown from the method and unwind the stack - just like if the function is not marked as throw(). The only real difference is that for a function marked throw() the global unexpected_handler will be called (which generally calls terminate()) when the exception leaves the function, unwinding the stack to that level, instead of the behavior for functions without an exception specification which will handle the exception normally. For pre-C++11 code, Sutter & Alexandrescu in "C++ Coding Standards" suggested: Avoid exception specifications. Take exception to these specifications: Don’t write exception specifications on your functions unless you’re forced to (because other code you can’t change has already introduced them; see Exceptions). ... A common but nevertheless incorrect belief is that exception specifications statically guarantee that functions will throw only listed exceptions (possibly none), and enable compiler optimizations based on that knowledge In fact, exception specifications actually do something slightly but fundamentally different: They cause the compiler to inject additional run-time overhead in the form of implicit try/catch blocks around the function body to enforce via run-time checking that the function does in fact emit only listed exceptions (possibly none), unless the compiler can statically prove that the exception specification can never be violated in which case it is free to optimize the checking away. And exception specifications can both enable and prevent further compiler optimizations (besides the inherent overhead already described); for example, some compilers refuse to inline functions that have exception specifications. Note that in some versions of Microsoft's compilers (I'm not sure if this behavior has changed in more recent versions, but I don't think so), throw() is treated in a non-standard way. throw() is equivalent to __declspec(nothrow) which does allow the compiler to assume that the function will not have an exception thrown and undefined behavior will result if one is. C++11 deprecates the C++98 style exception specification and introduced the noexcept keyword. Bjarne Stroustup's C++11 FAQ says this about it: If a function declared noexcept throws (so that the exception tries to escape, the noexcept function) the program is terminated (by a call to terminate()). The call of terminate() cannot rely on objects being in well-defined states (i.e. there is no guarantees that destructors have been invoked, no guaranteed stack unwinding, and no possibility for resuming the program as if no problem had been encountered). This is deliberate and makes noexcept a simple, crude, and very efficient mechanism (much more efficient than the old dynamic throw() mechanism). In C++11 if an exception is thrown from a function marked as noexcept the compiler is not obligated to unwind the stack at all. This affords some optimization possibilities. Scott Meyers discusses the new noexcept in his forthcoming book "Effective Modern C++".
unknown