qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
33,299,667
I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so: **Here is my full code:** ``` #include <iostream> using namespace std; int main(){ int squareroot = 0; int number; cout << "enter a number sp that i can calculate its squareroot" << endl; cin >> number; while (squareroot * squareroot != number){ squareroot+=0.1; } cout << "the square root is" << squareroot << endl; return 0; } ``` I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner. Thanks in advance.
2015/10/23
[ "https://Stackoverflow.com/questions/33299667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5303568/" ]
Square Root of a number, given that the number is a perfect square. The complexity is log(n) ``` /** * Calculate square root if the given number is a perfect square. * * Approach: Sum of n odd numbers is equals to the square root of n*n, given * that n is a perfect square. * * @param number * @return squareRoot */ public static int calculateSquareRoot(int number) { int sum=1; int count =1; int squareRoot=1; while(sum<number) { count+=2; sum+=count; squareRoot++; } return squareRoot; } ```
``` #include <iostream> using namespace std; int main() { double x = 1, average, s, r; cout << "Squareroot a Number: "; cin >> s; r = s * 2; for ( ; ; ) //for ; ; ; is to run the code forever until it breaks { average = (x + s / x) / 2; if (x == average) { cout << "Answer is : " << average << endl; return 0; } x = average; } } ``` You can try my code :D the method that i used here is the Babylonian Squareroot Method which you can find it here <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots>
33,299,667
I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so: **Here is my full code:** ``` #include <iostream> using namespace std; int main(){ int squareroot = 0; int number; cout << "enter a number sp that i can calculate its squareroot" << endl; cin >> number; while (squareroot * squareroot != number){ squareroot+=0.1; } cout << "the square root is" << squareroot << endl; return 0; } ``` I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner. Thanks in advance.
2015/10/23
[ "https://Stackoverflow.com/questions/33299667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5303568/" ]
Below explanation is given for the integer square root calculation: > > In number theory, the integer square root of a positive > integer n is the positive integer m which is the greatest integer less > than or equal to the square root of n > > > The approach your started is good but needs several correction to make it work: 1. you are working with `int` you want to add 1 to `squareroot` not 0.1 2. you want to stop your calculation when you `squareroot * squareroot` is equal or greater than `number`. Think about the case were the number is 26, you don't have an integer that multiplies itself to 26. 3. in the case of number equal to 26, do you want to return 5 or 6? After your `while` loop the value of `squareroot` will be 6 so you might want to reverse it to 5 (if `squareroot * squareroot` is different than `number`) Below the exemple: ``` #include <iostream> using namespace std; int main(){ int squareroot = 0; int number; cout << "enter a number sp that i can calculate its squareroot" << endl; cin >> number; while (squareroot * squareroot < number){ squareroot+=1; } if (squareroot * squareroot != number) --squareroot; cout << "the square root is" << squareroot << endl; return 0; } ``` Below a more efficient and elegant way of calculating the square root using binary search principle. O(log(n)) ``` int mySqrt(int x) { if (x==0) return 0; int left = 1; int right = x/2 + 1; int res; while (left <= right) { int mid = left + ((right-left)/2); if (mid<=x/mid){ left = mid+1; res=mid; } else { right=mid-1; } } return res; } ```
This function uses Nested Intervals (untested) and you can define the accuracy: ``` #include <math.h> #include <stdio.h> double mySqrt(double r) { double l=0, m; do { m = (l+r)/2; if (m*m<2) { l = m; } else { r = m; } } while(fabs(m*m-2) > 1e-10); return m; } ``` See <https://en.wikipedia.org/wiki/Nested_intervals>
33,299,667
I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so: **Here is my full code:** ``` #include <iostream> using namespace std; int main(){ int squareroot = 0; int number; cout << "enter a number sp that i can calculate its squareroot" << endl; cin >> number; while (squareroot * squareroot != number){ squareroot+=0.1; } cout << "the square root is" << squareroot << endl; return 0; } ``` I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner. Thanks in advance.
2015/10/23
[ "https://Stackoverflow.com/questions/33299667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5303568/" ]
Below explanation is given for the integer square root calculation: > > In number theory, the integer square root of a positive > integer n is the positive integer m which is the greatest integer less > than or equal to the square root of n > > > The approach your started is good but needs several correction to make it work: 1. you are working with `int` you want to add 1 to `squareroot` not 0.1 2. you want to stop your calculation when you `squareroot * squareroot` is equal or greater than `number`. Think about the case were the number is 26, you don't have an integer that multiplies itself to 26. 3. in the case of number equal to 26, do you want to return 5 or 6? After your `while` loop the value of `squareroot` will be 6 so you might want to reverse it to 5 (if `squareroot * squareroot` is different than `number`) Below the exemple: ``` #include <iostream> using namespace std; int main(){ int squareroot = 0; int number; cout << "enter a number sp that i can calculate its squareroot" << endl; cin >> number; while (squareroot * squareroot < number){ squareroot+=1; } if (squareroot * squareroot != number) --squareroot; cout << "the square root is" << squareroot << endl; return 0; } ``` Below a more efficient and elegant way of calculating the square root using binary search principle. O(log(n)) ``` int mySqrt(int x) { if (x==0) return 0; int left = 1; int right = x/2 + 1; int res; while (left <= right) { int mid = left + ((right-left)/2); if (mid<=x/mid){ left = mid+1; res=mid; } else { right=mid-1; } } return res; } ```
The problem with your code, is that it only works if the square root of the number is exactly N\*0.1, where N is an integer, meaning that if the answer is 1.4142 and not 1.400000000 exactly your code will fail. There are better ways , but they're all more complicated and use numerical analysis to approximate the answer, the easiest of which is the Newton-Raphson method. you can use the function below, this function uses the Newton–Raphson method to find the root, if you need more information about the Newton–Raphson method, check [this](https://en.wikipedia.org/wiki/Newton%27s_method) wikipedia article. and if you need better accuracy - but worse performance- you can decrease '0.001' to your likening,or increase it if you want better performance but less accuracy. ``` float mysqrt(float num) { float x = 1; while(abs(x*x - num) >= 0.001 ) x = ((num/x) + x) / 2; return x; } ``` if you don't want to import `math.h` you can write your own `abs()`: ``` float abs(float f) { if(f < 0) f = -1*f; return f; } ```
59,090,987
This is my XML: ``` <?xml version="1.0" encoding="utf-8"?> <Fruit> <Fruit_group name='Tropical'> <fruit_types name ='Tropical Used'> <fruit>bananas</fruit> <fruit>mangoes</fruit> </fruit_types> </Fruit_group> <Fruit_group name='Citrus'> <fruit_types name ='Citruses Used'> <fruit>orange</fruit> <fruit>lime</fruit> <fruit>grapefruit</fruit> <excluded_fruits> <fruit>mandarin</fruit> </excluded_fruits> </fruit_types> </Fruit_group> </Fruit> ``` And this is a sample of my XML text.. Is there a way to deserialize it and keep the name of the elements too.. I mean I would like to have like: ``` Tropical -> Tropical Used -> fruit -> bananas, mangoes Citrus->Citruses Used -> fruit = orange, lime, grapefruit excluded = mandarin.... Something like this... ``` Could someone help me to understand how does this work?
2019/11/28
[ "https://Stackoverflow.com/questions/59090987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7726727/" ]
As you have written, both `Virtual` and `Target` needs to provide a constructor for `Base`. If you make `Virtual` abstract, then it does not need to initialize `Base` any longer. ``` class Base { public: explicit Base(int arg) : arg(arg) {} private: const int arg; }; class Virtual : public virtual Base { public: explicit Virtual(int arg) {} private: virtual void foo() = 0; }; class Target : public virtual Virtual { public: explicit Target(int arg) : Base(arg), Virtual(arg) {} private: virtual void foo() override {} }; ```
It is necessary because otherwise the compiler doesn't know how to call the costructor of `Virtual` on its own, when the object is not a part of furher inheritance chain. You don't have to provide a constructor for `Virtual`, but when you do, you need to initialise `Base` as well. (If you don't provide a constructor for `Virtual`, you cannot make (sub)objects of this class, which makes it useless for most purposes). If `Virtual` is an abstract class then its constructor can never be called on its own (only from further derived classes) and the compiler will let you skip initialisation of `Base`.
49,102,047
I have a checkbox field. I want to display the values from that field in a column view. The values in the field are names such as John Doe Smith. When there are multiple values in the checkbox they are displayed in an awkward manner. For instance John Doe Smith,Jane Doe Smith,Mary Doe Smith I want to remove the commas and replace them with a "comma space" so they are more readable. The above example should look like this John Doe Smith, Jane Doe Smith, Mary Doe Smith I've tried using @Replace and @ReplaceSubstring along with @Text, @Explode, @Implode, etc but I can't get the desired result. Does anyone have a suggestion? Robin-
2018/03/05
[ "https://Stackoverflow.com/questions/49102047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3538181/" ]
[@Implode](https://www.ibm.com/support/knowledgecenter/SSVRGU_9.0.1/basic/H_IMPLODE.html) is the way to go. Your column formula is then: ``` @Implode(YourCheckBoxField; ", ") ```
In the column properties, in the second tab, select the option "Show multiple values in separate entries" Sorry for the English, I'm using google translate
292,996
Hopefully this is something not too difficult! I am trying to get a voltage divider which has a positive and negative rail such as this: ![schematic](https://i.stack.imgur.com/ezVvn.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fezVvn.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) I know with a standard voltage divider the equation for Vo would be (R2/R1+R2)\*Vin which is fine. I know if R1 and R2 are equal, you get half the supply. I know this works with a positive and negative rail also, for example: V+ = +5V V- = -5V R1 = 100R R2 = 100R Then I know Vo will be 0V as this is the halfway point. My question then, is what if the value of R1 or R2 changes? I have done simulations, for example, when I make R2 half the value of R1, my simulation tells me the Vo is -1.67V. When R2 is a quarter of the value, then Vo is -3V. Also, If I change the value of R1, then it gives me the same results, but positive, rather than negative. I have tried to search for an equation to calculate Vo but cannot find one. All the voltage divider calculators online just assume that V- is GND. I have tried to find some way of calculating it by putting the -5 in the equation somewhere but I never get the same result as the simulation. Does anyone know if there is an equation for this, and of so, what is it? Would be useful for a project idea I have in mind! I hope I have worded this well enough and have supplied all the appropriate information, if not, please do not hesitate to ask if I have not communicated something properly.
2017/03/17
[ "https://electronics.stackexchange.com/questions/292996", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/138493/" ]
This is your equation for Vout in terms of V+,V- R1 and R2: VO = V+ - ((V+ - V-)/(R1+R2))\*R1 In short, just find the total voltage, divide by the total resistance to get current, then find the voltage drop across one of the resistors (I used R1) and use that to get VO. If you found the voltage across R1 then do V+ - VR1 or if you found it across R2 then do V- + VR2. Oh, and don't use a divider like that to power any circuitry, if you actually need the rail buffer with an opamp. Also, don't use that circuit as a voltage reference, with 200 Ohm total R you will be throwing away lots of current. --- .
You cannot *really* calculate the voltages across the divider because they depend on the current. This means the voltages depend on the load you plan to connect. This is because of Ohms law (U=I\*R), where I is unknown. In general, a voltage regulator such as the 7805 (positive 5V) or 7905 (negative 5V) is a better idea. Those devices regulate the voltage regardless the current. When you plan a huge load (more than 1 Amp), this will not work anymore. Pleas note that other voltages are available in the 78 series (positive) and the 79 (negative). For example, the 7815 and 7915 are used often in audio applications, where a sinus with a peak to peak voltage of 30V is desired.
292,996
Hopefully this is something not too difficult! I am trying to get a voltage divider which has a positive and negative rail such as this: ![schematic](https://i.stack.imgur.com/ezVvn.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fezVvn.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) I know with a standard voltage divider the equation for Vo would be (R2/R1+R2)\*Vin which is fine. I know if R1 and R2 are equal, you get half the supply. I know this works with a positive and negative rail also, for example: V+ = +5V V- = -5V R1 = 100R R2 = 100R Then I know Vo will be 0V as this is the halfway point. My question then, is what if the value of R1 or R2 changes? I have done simulations, for example, when I make R2 half the value of R1, my simulation tells me the Vo is -1.67V. When R2 is a quarter of the value, then Vo is -3V. Also, If I change the value of R1, then it gives me the same results, but positive, rather than negative. I have tried to search for an equation to calculate Vo but cannot find one. All the voltage divider calculators online just assume that V- is GND. I have tried to find some way of calculating it by putting the -5 in the equation somewhere but I never get the same result as the simulation. Does anyone know if there is an equation for this, and of so, what is it? Would be useful for a project idea I have in mind! I hope I have worded this well enough and have supplied all the appropriate information, if not, please do not hesitate to ask if I have not communicated something properly.
2017/03/17
[ "https://electronics.stackexchange.com/questions/292996", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/138493/" ]
This is your equation for Vout in terms of V+,V- R1 and R2: VO = V+ - ((V+ - V-)/(R1+R2))\*R1 In short, just find the total voltage, divide by the total resistance to get current, then find the voltage drop across one of the resistors (I used R1) and use that to get VO. If you found the voltage across R1 then do V+ - VR1 or if you found it across R2 then do V- + VR2. Oh, and don't use a divider like that to power any circuitry, if you actually need the rail buffer with an opamp. Also, don't use that circuit as a voltage reference, with 200 Ohm total R you will be throwing away lots of current. --- .
try this circuit with GND reference: [![enter image description here](https://i.stack.imgur.com/whuuD.png)](https://i.stack.imgur.com/whuuD.png)
2,981,691
Lets say i have a variable that contains the number of search engine names in a file, what would you name it? * number\_of\_seach\_engine\_names * search\_engine\_name\_count * num\_search\_engines * engines * engine\_names * other name? The first name describes what the variable contains precisely, but isn't it too long?, any advice for choosing variable names? especially how to shorten a name that is too long or what kind of abbreviations to use?
2010/06/05
[ "https://Stackoverflow.com/questions/2981691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82044/" ]
Depends on the context, if its is a local variable, as eg ``` int num = text.scan(SEARCH_ENGINE_NAME).size(); ``` the more explicit the right-hand of the expression the shorter the name I'd pick. The rational is that we are in a limited scope of maybe 4-5 lines and can thus assume that the reader will be able to make the connection between the short name and the right-hand-side expression. If however, it is the field of a class, I'd rather be as verbose as possible.
If it is a local variable in a function, I would probably call it `n`, or perhaps `ne`. Most functions only contain two or three variables, so a long name is unnecessary.
2,981,691
Lets say i have a variable that contains the number of search engine names in a file, what would you name it? * number\_of\_seach\_engine\_names * search\_engine\_name\_count * num\_search\_engines * engines * engine\_names * other name? The first name describes what the variable contains precisely, but isn't it too long?, any advice for choosing variable names? especially how to shorten a name that is too long or what kind of abbreviations to use?
2010/06/05
[ "https://Stackoverflow.com/questions/2981691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82044/" ]
See similar [question](https://stackoverflow.com/questions/2230871/when-is-a-java-method-name-too-long) The [primary technical imperative](http://megakemp.wordpress.com/2008/10/07/mcconnells-primary-technical-imperative/) is to reduce complexity. Variables should be named to reduce complexity. Sometimes this results in shorter names, sometimes longer names. It usually corresponds to how difficult it is for a maintainer to understand the complexity of the code. On one end of the spectrums, you have for loop iterators and indexes. These can have names like i or j, because they are just that common and simple. Giving them longer names would only cause more confusion. If a variable is used frequently but represents something more complex, then you have to give it a clear name so that the user doesn't have to relearn what it means every time they use it. On the other end of the spectrum are variables that are used very rarely. You still want to reduce confusion here, but giving it a short name is less important, because the penalty for relearning the purpose of the variable is not paid very often.
I'd name it "search\_engine\_count", because it holds a count of search engines.
2,981,691
Lets say i have a variable that contains the number of search engine names in a file, what would you name it? * number\_of\_seach\_engine\_names * search\_engine\_name\_count * num\_search\_engines * engines * engine\_names * other name? The first name describes what the variable contains precisely, but isn't it too long?, any advice for choosing variable names? especially how to shorten a name that is too long or what kind of abbreviations to use?
2010/06/05
[ "https://Stackoverflow.com/questions/2981691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82044/" ]
How about `numEngineNames`? Choosing variable names is more art than science. You want something that doesn't take an epoch to type, but long enough to be expressive. It's a subjective balance. Ask yourself, if someone were looking at the variable name for the first time, is it reasonably likely that person will understand its purpose?
See similar [question](https://stackoverflow.com/questions/2230871/when-is-a-java-method-name-too-long) The [primary technical imperative](http://megakemp.wordpress.com/2008/10/07/mcconnells-primary-technical-imperative/) is to reduce complexity. Variables should be named to reduce complexity. Sometimes this results in shorter names, sometimes longer names. It usually corresponds to how difficult it is for a maintainer to understand the complexity of the code. On one end of the spectrums, you have for loop iterators and indexes. These can have names like i or j, because they are just that common and simple. Giving them longer names would only cause more confusion. If a variable is used frequently but represents something more complex, then you have to give it a clear name so that the user doesn't have to relearn what it means every time they use it. On the other end of the spectrum are variables that are used very rarely. You still want to reduce confusion here, but giving it a short name is less important, because the penalty for relearning the purpose of the variable is not paid very often.
2,981,691
Lets say i have a variable that contains the number of search engine names in a file, what would you name it? * number\_of\_seach\_engine\_names * search\_engine\_name\_count * num\_search\_engines * engines * engine\_names * other name? The first name describes what the variable contains precisely, but isn't it too long?, any advice for choosing variable names? especially how to shorten a name that is too long or what kind of abbreviations to use?
2010/06/05
[ "https://Stackoverflow.com/questions/2981691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82044/" ]
I'd name it "search\_engine\_count", because it holds a count of search engines.
Use `Esc`+`_`+`Esc` to write: ``` this_is_a_long_variable = 42 ``` `Esc`+`_`+`Esc` and `_` are not identical characters in Mathematica. That's why you are allowed to use the former but not the latter.
2,981,691
Lets say i have a variable that contains the number of search engine names in a file, what would you name it? * number\_of\_seach\_engine\_names * search\_engine\_name\_count * num\_search\_engines * engines * engine\_names * other name? The first name describes what the variable contains precisely, but isn't it too long?, any advice for choosing variable names? especially how to shorten a name that is too long or what kind of abbreviations to use?
2010/06/05
[ "https://Stackoverflow.com/questions/2981691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82044/" ]
It depends on the scope of the variable. A local variable in a short function is usually not worth a 'perfect name', just call it `engine_count` or something like that. Usually the meaning will be easy to spot, if not a comment might be better than a two-line variable name. Variables of wider scope – i.e. global variables (if they are *really* necessary!), member variables – deserve IMHO a name that is *almost* self documentary. Of course looking up the original declaration is not difficult and most IDE do it automatically, but the identifier of the variable should not be meaningless (i.e. `number` or `count`). Of course, all this depends a lot on your personal coding style and the conventions at your work place.
I'd name it "search\_engine\_count", because it holds a count of search engines.
2,981,691
Lets say i have a variable that contains the number of search engine names in a file, what would you name it? * number\_of\_seach\_engine\_names * search\_engine\_name\_count * num\_search\_engines * engines * engine\_names * other name? The first name describes what the variable contains precisely, but isn't it too long?, any advice for choosing variable names? especially how to shorten a name that is too long or what kind of abbreviations to use?
2010/06/05
[ "https://Stackoverflow.com/questions/2981691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82044/" ]
How about `numEngineNames`? Choosing variable names is more art than science. You want something that doesn't take an epoch to type, but long enough to be expressive. It's a subjective balance. Ask yourself, if someone were looking at the variable name for the first time, is it reasonably likely that person will understand its purpose?
It depends on the scope of the variable. A local variable in a short function is usually not worth a 'perfect name', just call it `engine_count` or something like that. Usually the meaning will be easy to spot, if not a comment might be better than a two-line variable name. Variables of wider scope – i.e. global variables (if they are *really* necessary!), member variables – deserve IMHO a name that is *almost* self documentary. Of course looking up the original declaration is not difficult and most IDE do it automatically, but the identifier of the variable should not be meaningless (i.e. `number` or `count`). Of course, all this depends a lot on your personal coding style and the conventions at your work place.
2,981,691
Lets say i have a variable that contains the number of search engine names in a file, what would you name it? * number\_of\_seach\_engine\_names * search\_engine\_name\_count * num\_search\_engines * engines * engine\_names * other name? The first name describes what the variable contains precisely, but isn't it too long?, any advice for choosing variable names? especially how to shorten a name that is too long or what kind of abbreviations to use?
2010/06/05
[ "https://Stackoverflow.com/questions/2981691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82044/" ]
Depends on the context, if its is a local variable, as eg ``` int num = text.scan(SEARCH_ENGINE_NAME).size(); ``` the more explicit the right-hand of the expression the shorter the name I'd pick. The rational is that we are in a limited scope of maybe 4-5 lines and can thus assume that the reader will be able to make the connection between the short name and the right-hand-side expression. If however, it is the field of a class, I'd rather be as verbose as possible.
When thinking about your code, try to look at it from the perspective of someone else. This will help not only with picking names, but with keeping your code readable as a whole. Having really long variable names will muddle up your code's readability, so you want to avoid those. But on the other end of the spectrum, you want to avoid ultra-short names or acronyms like "n" or "ne." Short, cryptic names like these will cause someone trying to read your code to tear their hair out. Usually one to two letter variables are used for small tasks like being incremented in a for loop, for example. So what you're left with is a balance between these two extremes. "Num" is a commonly used abbreviation, and any semi-experienced programmer will know what you mean immediately. So something like "numEngines" or "numEngineNames" would work well. In addition to this, you can also put a comment in your code next to the variable the very first time it's used. This will let the reader know exactly what you're doing and helps to avoid any possible confusion.
2,981,691
Lets say i have a variable that contains the number of search engine names in a file, what would you name it? * number\_of\_seach\_engine\_names * search\_engine\_name\_count * num\_search\_engines * engines * engine\_names * other name? The first name describes what the variable contains precisely, but isn't it too long?, any advice for choosing variable names? especially how to shorten a name that is too long or what kind of abbreviations to use?
2010/06/05
[ "https://Stackoverflow.com/questions/2981691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82044/" ]
Use `Esc`+`_`+`Esc` to write: ``` this_is_a_long_variable = 42 ``` `Esc`+`_`+`Esc` and `_` are not identical characters in Mathematica. That's why you are allowed to use the former but not the latter.
If it is a local variable in a function, I would probably call it `n`, or perhaps `ne`. Most functions only contain two or three variables, so a long name is unnecessary.
2,981,691
Lets say i have a variable that contains the number of search engine names in a file, what would you name it? * number\_of\_seach\_engine\_names * search\_engine\_name\_count * num\_search\_engines * engines * engine\_names * other name? The first name describes what the variable contains precisely, but isn't it too long?, any advice for choosing variable names? especially how to shorten a name that is too long or what kind of abbreviations to use?
2010/06/05
[ "https://Stackoverflow.com/questions/2981691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82044/" ]
A name is too long when there exists a shorter name that equally conveys the purpose of the variable. I think `engineCount` would be fine here. The number of engine names is presumably equal to the number of engines. See [JaredPar](https://stackoverflow.com/questions/2230871/when-is-a-java-method-name-too-long/2230893#2230893)'s post.
Depends on the context, if its is a local variable, as eg ``` int num = text.scan(SEARCH_ENGINE_NAME).size(); ``` the more explicit the right-hand of the expression the shorter the name I'd pick. The rational is that we are in a limited scope of maybe 4-5 lines and can thus assume that the reader will be able to make the connection between the short name and the right-hand-side expression. If however, it is the field of a class, I'd rather be as verbose as possible.
2,981,691
Lets say i have a variable that contains the number of search engine names in a file, what would you name it? * number\_of\_seach\_engine\_names * search\_engine\_name\_count * num\_search\_engines * engines * engine\_names * other name? The first name describes what the variable contains precisely, but isn't it too long?, any advice for choosing variable names? especially how to shorten a name that is too long or what kind of abbreviations to use?
2010/06/05
[ "https://Stackoverflow.com/questions/2981691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82044/" ]
It depends on the scope of the variable. A local variable in a short function is usually not worth a 'perfect name', just call it `engine_count` or something like that. Usually the meaning will be easy to spot, if not a comment might be better than a two-line variable name. Variables of wider scope – i.e. global variables (if they are *really* necessary!), member variables – deserve IMHO a name that is *almost* self documentary. Of course looking up the original declaration is not difficult and most IDE do it automatically, but the identifier of the variable should not be meaningless (i.e. `number` or `count`). Of course, all this depends a lot on your personal coding style and the conventions at your work place.
Use `Esc`+`_`+`Esc` to write: ``` this_is_a_long_variable = 42 ``` `Esc`+`_`+`Esc` and `_` are not identical characters in Mathematica. That's why you are allowed to use the former but not the latter.
31,405,424
I have used following jquery code ``` jQuery.validator.addMethod("unique", function(value, element, params) { var prefix = params; var selector = jQuery.validator.format("[name!='{0}'][name^='{1}'][unique='{1}']", element.name, prefix); var matches = new Array(); $(selector).each(function(index, item) { if (value == $(item).val()) { matches.push(item); } }); return matches.length == 0; }, "Value is not unique."); jQuery.validator.classRuleSettings.unique = { unique: true }; $("#myform").validate(); $("#validate").click(function() { $("#myform").valid(); }); ``` but due to same input name its not working properly, check here <https://jsfiddle.net/bgzBY/147/> but If I will use different name than that will work,check <http://jsfiddle.net/mysteryh/bgzBY/> So how to fix it?
2015/07/14
[ "https://Stackoverflow.com/questions/31405424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1900235/" ]
You **cannot** use the same `name` on more than one input field. There is no workaround for this requirement of the plugin. (It's how the plugin keeps track of the input elements.) > > So how to fix it? > > > You **must** use a unique `name` on every input. `currency[1]`, `currency[2]`, etc.
It has nothing to do with your names. Your script is not loading properly. Blocked loading mixed active content "<http://ajax.microsoft.com/ajax/jquery.validate/1.8/jquery.validate.min.js>" This is the error shown in console.
57,176,363
I am using a **build\_runner** to generate auto-generated code in the flutter project. Issue: When I make an update in the model class and then I try to run below command, but it does not update auto-generated class. Command: ``` pub run build_runner build ``` Dart Packages: ``` built_value: '>=5.5.5 <7.0.0' build_runner: ^1.5.0 built_value_generator: ^6.6.0 ``` After the execution of the command for **build\_runner**, an auto-generated class should be updated.
2019/07/24
[ "https://Stackoverflow.com/questions/57176363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11157659/" ]
When it conflicts with current generated classes, it may possible that it will not update the generated classes. So I have tested with below command and it's working fine. ``` flutter packages pub run build_runner build --delete-conflicting-outputs ``` This will delete current conflict files and recreate as per the requirements.
You need to use the `watch` sub-command to Continuous generation of code. ``` flutter packages pub run build_runner watch ``` It runs a persistent build server that watches the files system for edits and does rebuilds as necessary.
1,714,286
There are allegedly six mistakes in the following network: [![enter image description here](https://i.stack.imgur.com/yL1Oj.png)](https://i.stack.imgur.com/yL1Oj.png) I was able to identify four: 1. Host A4's IP address 192.168.10.40 is subnet A's broadcast address. 2. Host A5's IP address 192.168.10.39 is outside subnet A. 3. The switch's MAC address in subnet B is incorrect because H is not a hexadecimal number. 4. The interface eth0's IP address contained in subnet B. Where are the remaining two mistakes? I though maybe subnet B has way too many host IP addresses, but that's not really a mistake. Does anyone have an idea?
2022/04/03
[ "https://superuser.com/questions/1714286", "https://superuser.com", "https://superuser.com/users/1681804/" ]
This looks like the kind of homework question where the "correct" answer actually depends on the person who will be grading it. It may depend on what was taught earlier in the course; there are some things that could be overlooked unless you were specifically told "don't do it like that" the previous day. One actual problem is that **the router's eth1 and eth2 interfaces use the "all-zeros" aka "network" address** of their respective subnets, which is typically considered to be reserved in a similar way to the 'broadcast' address. (Many decades ago, the all-zeros address *used to be* the subnet broadcast address. Now it no longer is – the all-ones address is used for broadcast – but all-zeros remains reserved all the same.) This *may or may not* also apply to the router's eth0 as well. It's unclear what the netmask of eth0 is – the address 192.168.13.0 would be a reserved "network address" if the subnet was /24 or smaller, but a perfectly valid host address in /23 or larger. (Of course, this is *in addition to* the problem of eth0 overlapping with eth2, which you already mentioned.) > > * Host A4's IP address 192.168.10.39 is outside subnet A. > * Host A5's IP address 192.168.10.40 is subnet A's broadcast address. > > > These are the wrong way around – `.39` is the broadcast address (the last address within the subnet) which means the *next* address `.40` is outside the subnet. > > The switch's MAC address in subnet B is incorrect because H is not a hexadecimal number. > > > That's true, but I'd question whether it is even *relevant* to a diagram that focuses on IP configuration – switches are "transparent" at MAC layer; their MAC address is only used for protocols that switches themselves participate in (such as STP or LACP) but is never used in frames going *through* that switch (frames sent by a host would directly reference another local host or gateway as their destination MAC). Indeed an umanaged switch that doesn't speak STP/LACP/LLDP would usually not even have a MAC address at all. So perhaps the real mistake is that the switches have their MAC addresses indicated *in the first place* (…or that other devices don't). > > Where are the remaining two mistakes? I though maybe subnet B has way too many host IP addresses, but that's not really a mistake. > > > Using a /23 is not a *technical* mistake in itself. It may be overkill or wasteful from the network designer's perspective, but is completely legal within the protocol.
I guess that depends on how they count errors. Subnet A stops at 192.168.10.38. So, Host A4 is both the broadcast address **and** not addressable. Host A5 is outside the subnet. That gets you to five errors. Is the gateway address on eth0 correct? There's no indication of what network it's supposed to belong to.
16,786,739
I want to use [this](http://www.fileformat.info/info/unicode/char/1f4e1/index.htm) unicode character in my resource file. But whatever I do, I end with dalvikvm crash (tested with Android 2.3 and 4.2.2): ```none W/dalvikvm( 8797): JNI WARNING: input is not valid Modified UTF-8: illegal start byte 0xf0 W/dalvikvm( 8797): string: '' W/dalvikvm( 8797): in Landroid/content/res/StringBlock;.nativeGetString:(II)Ljava/lang/String; (NewStringUTF) E/dalvikvm( 8797): VM aborting F/libc ( 8797): Fatal signal 11 (SIGSEGV) at 0xdeadd00d (code=1), thread 8797 (cz.ipex...) ``` I tried these version in my resource file: ```xml <string name="geolocation_icon" translatable="false">&#x1f4e1;</string> <!-- HTML --> <string name="geolocation_icon" translatable="false">\uD83D\uDCE1</string> <!-- escaped unicode --> <string name="geolocation_icon" translatable="false"></string> <!-- unicode character --> ``` Note that using it in Java String in code works ok: ```java final String geolocation_icon = "\uD83D\uDCE1"; ```
2013/05/28
[ "https://Stackoverflow.com/questions/16786739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946409/" ]
Your character (`U+1F4E1`) is outside of Unicode BMP (Basic Multilingual Plane - range from `U+0000` to `U+FFFF`). Unfortunately, Android has very weak (if any) support for non-BMP characters. `UTF-8` representation for non-BMP characters requires 4 bytes (`0xF0 0x9F 0x93 0xA1`). But, Android `UTF-8` parser only understands 3 bytes maximum (see it **[here](https://android.googlesource.com/platform/dalvik/+/refs/heads/oreo-release/libdex/DexUtf.h#46)** and **[here](https://android.googlesource.com/platform/dalvik/+/refs/heads/oreo-release/libdex/DexSwapVerify.cpp#1984)**). It works for you when you use `UTF-16` surrogate form representation of this character: `"\uD83D\uDCE1"`. If you were able to encode each surrogate `UTF-16` character in modified `UTF-8` (aka `CESU-8`) - it would take 6 bytes total (3 bytes in `UTF-8` for each member of surrogate pair), then it would be possible. But, Android does not support `CESU-8` explicitly either. So, your current solution - hard-coding this symbol in source code as surrogate `UTF-16` pair seems easiest, at least until Android starts fully supporting non-BMP `UTF-8`. **UPDATE**: this seems to be partially fixed in Android 6.0. [This commit](https://android-review.googlesource.com/130121) has been merged into Android 6, and permits presence of 4-byte UTF-8 characters in XML resources. Its not perfect solution - it will simply automatically convert 4-byte UTF-8 into appropriate surrogate pair. However, it allows to move them from your source code into XML resources. Unfortunately, you can't use this solution until your application can stop supporting any Android version except for 6.0 and later.
**Do it this way** Do not keep problematic emoji in the strings.xml add it programmatically ``` <string name="hi_welcome_msg">Hi %1$s</string> getString(R.string.hi_welcome_msg, user.getFullName() + " \uD83D\uDC4B" ); ```
840,207
I have an nginx.conf file currently that looks like this (with brackets replacing sensitive data): ``` worker_processes 3; events { worker_connections 1024; } http { access_log [/...]; error_log [/...] crit; include mime.types; sendfile on; server { server_name [...] [...]; return 301 [...] $request_uri; } server { listen 127.0.0.1:[...]; root [/...]; location / { include uwsgi_params; uwsgi_pass [.../uwsgi.sock]; } } } ``` If I add the following line after the existing location {...} clause, as suggested [here](https://www.digitalocean.com/community/questions/leverage-browser-caching-for-nginx), loading the website will produce "404 not found" errors for image, CSS, and js assets: ``` location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 1d; } ``` How can I implement browser caching, without causing the "404" issue?
2017/03/23
[ "https://serverfault.com/questions/840207", "https://serverfault.com", "https://serverfault.com/users/290914/" ]
It's a simple issue of your location statements being out of order. Your wrote that you put the static file location clause *after* the `location / {}` block. This means your static files will be checked for there, first. Since your uwsgi socket can't find the file paths, it returns 404. What you want will look more like this. ``` http { [..] server { server_name example.com; return 301 ^ $request_uri; } server { listen localhost; root /path/to/webroot/; location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 1d; } location / { include uwsgi_params; uwsgi_pass [...]; } } } ``` The good people at Digital Ocean have [an excellent guide](https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks) explaining how this works. I recommend reading it through.
[The solution](https://stackoverflow.com/a/42998387/4400277) that resolved my issue was to put the `uwsgi_pass [.../uwsgi.sock];` clause inside of each `location {...}` block.
33,510,080
I am getting null pointer exception at the line ``` SessionFactory sesionFactory = new Configuration().configure().buildSessionFactory() ; ``` any suggestion what might be causing it ?? error log says this : ``` Exception in thread "main" java.lang.NullPointerException at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:214) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117) at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131) at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1797) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1755) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840) at com.hussi.model.Main.main(Main.java:15) ``` my Main class File : ``` package com.hussi.model; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class Main { public static void main(String[] args) { User user = new User(); user.setUsername("hussi"); user.setPassword("maria"); SessionFactory sesionFactory = new Configuration().configure().buildSessionFactory() ; Session session = sesionFactory.openSession(); Transaction tr = session.beginTransaction(); session.save(user); session.flush(); session.close(); } } ``` my model file ``` package com.hussi.model; public class User { int user_id; String username; String password; public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String toString() { return "username==>"+this.username+" : password==>"+this.password; } } ``` my user.hbm.xml file ``` <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.hussi.model.User" table="users"> <id name="user_id" type="int" column="user_id"> <generator class="increment" /> </id> <property name="username"> <column name="username"/> </property> <property name="password"> <column name="password"/> </property> </class> </hibernate-mapping> ``` my hibernate configuration file : hibernate.cfg.xml ``` <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc.mysql://localhost:3306/my_hibernate_1</property> <property name="connection.username">root</property> <property name="connecttion.password">root</property> <!-- Database connection settings --> <property name="connection.pool_size">1</property> <!-- MySql Dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">false</property> <mapping resource="user.hbm.xml"/> </session-factory> </hibernate-configuration> ```
2015/11/03
[ "https://Stackoverflow.com/questions/33510080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
CTE it is. ``` DECLARE @BeginPeriod DATETIME = '2010-06-10', @EndPeriod DATETIME = '2011-06-11' ;WITH cte AS ( SELECT DATEADD(month, DATEDIFF(month, 0, @BeginPeriod), 0) AS StartOfMonth, DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, @BeginPeriod) + 1, 0)) AS EndOfMonth UNION ALL SELECT DATEADD(month, 1, StartOfMonth) AS StartOfMonth, DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, DATEADD(month, 1, StartOfMonth)) + 1, 0)) AS EndOfMonth FROM cte WHERE DATEADD(month, 1, StartOfMonth) <= @EndPeriod ) SELECT (CASE WHEN StartOfMonth < @BeginPeriod THEN @BeginPeriod ELSE StartOfMonth END) StartOfMonth, (CASE WHEN EndOfMonth > @EndPeriod THEN @EndPeriod ELSE EndOfMonth END) EndOfMonth FROM cte ``` the last `EndOfMonth` is the value you used as `@EndPeriod` set it to `DATEADD(day, -1, @EndPeriod)` if you want the previous day You can use this to trim the time. ``` SELECT CONVERT(VARCHAR(10), (CASE WHEN StartOfMonth < @BeginPeriod THEN @BeginPeriod ELSE StartOfMonth END), 120) StartOfMonth, CONVERT(VARCHAR(10), (CASE WHEN EndOfMonth > @EndPeriod THEN @EndPeriod ELSE EndOfMonth END), 120) EndOfMonth FROM cte ```
Another options with "Numbers" CTE ``` declare @df datetime, @dt datetime set @df = '20100610' set @dt = '20110611' ;WITH e1(n) AS ( SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 ), -- 10 e2(n) AS (SELECT ROW_NUMBER() OVER (ORDER BY e1.n) FROM e1 CROSS JOIN e1 AS b) -- 10*10 select case when e2.n = 1 then @df else dateadd(day, -day(@df) + 1, dateadd(month, e2.n - 1, @df)) end, case when e2.n = datediff(month, @df, @dt) + 1 then dateadd(month, e2.n -1 , @df) else EOMONTH( dateadd(month, e2.n -1 , @df) ) end from e2 where e2.n ``` Instead of Numbers CTE you can use some other option for example as described here <http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1> I often have Numbers table in my DB for such tasks. I think primarily because I started using this technique before CTEs were added to MS SQL but it is less typing also.
33,510,080
I am getting null pointer exception at the line ``` SessionFactory sesionFactory = new Configuration().configure().buildSessionFactory() ; ``` any suggestion what might be causing it ?? error log says this : ``` Exception in thread "main" java.lang.NullPointerException at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:214) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117) at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131) at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1797) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1755) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840) at com.hussi.model.Main.main(Main.java:15) ``` my Main class File : ``` package com.hussi.model; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class Main { public static void main(String[] args) { User user = new User(); user.setUsername("hussi"); user.setPassword("maria"); SessionFactory sesionFactory = new Configuration().configure().buildSessionFactory() ; Session session = sesionFactory.openSession(); Transaction tr = session.beginTransaction(); session.save(user); session.flush(); session.close(); } } ``` my model file ``` package com.hussi.model; public class User { int user_id; String username; String password; public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String toString() { return "username==>"+this.username+" : password==>"+this.password; } } ``` my user.hbm.xml file ``` <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.hussi.model.User" table="users"> <id name="user_id" type="int" column="user_id"> <generator class="increment" /> </id> <property name="username"> <column name="username"/> </property> <property name="password"> <column name="password"/> </property> </class> </hibernate-mapping> ``` my hibernate configuration file : hibernate.cfg.xml ``` <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc.mysql://localhost:3306/my_hibernate_1</property> <property name="connection.username">root</property> <property name="connecttion.password">root</property> <!-- Database connection settings --> <property name="connection.pool_size">1</property> <!-- MySql Dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">false</property> <mapping resource="user.hbm.xml"/> </session-factory> </hibernate-configuration> ```
2015/11/03
[ "https://Stackoverflow.com/questions/33510080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
CTE it is. ``` DECLARE @BeginPeriod DATETIME = '2010-06-10', @EndPeriod DATETIME = '2011-06-11' ;WITH cte AS ( SELECT DATEADD(month, DATEDIFF(month, 0, @BeginPeriod), 0) AS StartOfMonth, DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, @BeginPeriod) + 1, 0)) AS EndOfMonth UNION ALL SELECT DATEADD(month, 1, StartOfMonth) AS StartOfMonth, DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, DATEADD(month, 1, StartOfMonth)) + 1, 0)) AS EndOfMonth FROM cte WHERE DATEADD(month, 1, StartOfMonth) <= @EndPeriod ) SELECT (CASE WHEN StartOfMonth < @BeginPeriod THEN @BeginPeriod ELSE StartOfMonth END) StartOfMonth, (CASE WHEN EndOfMonth > @EndPeriod THEN @EndPeriod ELSE EndOfMonth END) EndOfMonth FROM cte ``` the last `EndOfMonth` is the value you used as `@EndPeriod` set it to `DATEADD(day, -1, @EndPeriod)` if you want the previous day You can use this to trim the time. ``` SELECT CONVERT(VARCHAR(10), (CASE WHEN StartOfMonth < @BeginPeriod THEN @BeginPeriod ELSE StartOfMonth END), 120) StartOfMonth, CONVERT(VARCHAR(10), (CASE WHEN EndOfMonth > @EndPeriod THEN @EndPeriod ELSE EndOfMonth END), 120) EndOfMonth FROM cte ```
I know that this is an old question, but I just came across with the same problem recently, and wrote an version without CTE. Here's the tested [code](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=dabc4e41c58ab95b8d83c652996bd51c) ``` DECLARE @FromDate DATETIME , @ToDate DATETIME , @UpdateBeginDate BIT , @UpdateEndDate BIT SET @FromDate = '2019-01-15' SET @ToDate = '2021-08-17' SET @UpdateBeginDate = 1 SET @UpdateEndDate = 1 DECLARE @Results TABLE ( MonthStart DATETIME , MonthEnd DATETIME , TheMonth VARCHAR(2) , TheYear VARCHAR(4) ) -- Months in that period INSERT INTO @Results SELECT TOP (DATEDIFF(MONTH, @FromDate, @ToDate)+1) -- calculate how many rows needed DATEADD(MONTH, number, @FromDate) , DATEADD(MONTH, number, @FromDate) , MONTH(DATEADD(MONTH, number, @FromDate)) , YEAR(DATEADD(MONTH, number, @FromDate)) FROM [master].dbo.spt_values WHERE [type] = N'P' ORDER BY number /* by using [master].dbo.spt_values, the total series number are 2048, for month cases, there will be 2048/12 ≈ 170 year range */ -- Update first date of month and last date of month for each row UPDATE @Results SET MonthStart = DATEADD(MONTH, DATEDIFF(MONTH, 0, MonthStart), 0) , MonthEnd = DATEADD(MONTH, ((YEAR(MonthEnd) - 1900) * 12) + MONTH(MonthEnd), -1) /* MonthStart Caculate the month difference from 1900-01-01 (0 represent 1900-01-01) to the current row's MonthStart record (DATEDIFF part) Then add the month difference from 1900-01-01 (DATEADD part) MonthEnd Caculate the year difference from 1900 to the current row's MonthEnd record then multiply 12 and plus the months of the record (The middle part) Then add the month difference from 1899-12-31 (DATEADD part) NOTE: -1 means 1899-12-31 The MonthEnd sentence is equivalent to this, if you keeped the record of TheYear and TheMonth MonthEnd = DATEADD(MONTH, ((TheYear - 1900) * 12) + TheMonth, -1) */ IF @UpdateBeginDate = 1 BEGIN UPDATE @Results SET MonthStart = @FromDate WHERE MonthStart = (SELECT MIN(MonthStart) FROM @Results) END IF @UpdateEndDate = 1 BEGIN UPDATE @Results SET MonthEnd = @ToDate WHERE MonthEnd = (SELECT MAX(MonthEnd) FROM @Results) END select * from @Results ``` I tested this code in MSSQL 2005 and MSSQL 2017, I think other versions might worked well too. Hope this will help other people who want a solution without CTE.
504,615
I have a Snap-On impact driver with a blown diode. I believe it's a flyback diode as it's on the output of the switch up to the motor. I can make out several markings on the diode. C39 and C5, there is also an M or an N. These markings don't make a lot of sense - I think some of the text is missing as the case is cracked and charred (see attached photo). The impact driver uses 18V batteries and I think the trigger mechanism is rated for up to 25A. I've ordered some 1N4001's but I don't think these are going to be up to the job. Trigger switch is a Marquardt 2701.6306. What diode would you recommend I use? [![Diode](https://i.stack.imgur.com/T5ji8.jpg)](https://i.stack.imgur.com/T5ji8.jpg) [![Switch](https://i.stack.imgur.com/6hX4C.jpg)](https://i.stack.imgur.com/6hX4C.jpg)
2020/06/09
[ "https://electronics.stackexchange.com/questions/504615", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/254883/" ]
The diode needs to be a fast recovery type, usually a Schottky too. A regular rectifier diode is too slow and will be overloading the output as you’ve seen.
Any 3Amp diode soldered in that place watching its polarity band, should do the job, it is to absorb high voltage spikes when forward motor current switches off, it generates a reverse current that can destroy the circuit and output switching transistor or hexfet or mosfet used as an output speed control transistor.
504,615
I have a Snap-On impact driver with a blown diode. I believe it's a flyback diode as it's on the output of the switch up to the motor. I can make out several markings on the diode. C39 and C5, there is also an M or an N. These markings don't make a lot of sense - I think some of the text is missing as the case is cracked and charred (see attached photo). The impact driver uses 18V batteries and I think the trigger mechanism is rated for up to 25A. I've ordered some 1N4001's but I don't think these are going to be up to the job. Trigger switch is a Marquardt 2701.6306. What diode would you recommend I use? [![Diode](https://i.stack.imgur.com/T5ji8.jpg)](https://i.stack.imgur.com/T5ji8.jpg) [![Switch](https://i.stack.imgur.com/6hX4C.jpg)](https://i.stack.imgur.com/6hX4C.jpg)
2020/06/09
[ "https://electronics.stackexchange.com/questions/504615", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/254883/" ]
The diode needs to be a fast recovery type, usually a Schottky too. A regular rectifier diode is too slow and will be overloading the output as you’ve seen.
Try 1N5401, or 1N5404. These are 3 A, 50 or 200 V diodes.
38,989,682
I am trying to upload my react-native apk to redmi note 3 but encountered an error unable to upload some apk after downgrading the gradle from 1.3.1 to 1.2.3 i was able to sought it but still after successfully uploading the app I can only see blank white screen. I am unable to see any app screen. I followed <https://github.com/facebook/react-native/issues/2720> but still didn't found any success. I have worked on two version of redmi phone one is redmi note 3 with 5.0.2 android version and Mi pad with 4.4.4 android version and faced the same issue on both i.e blank screen.
2016/08/17
[ "https://Stackoverflow.com/questions/38989682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5850512/" ]
I have the same problem with my Redmi Note4 ( white screen and no develop pop-up menu ) I solved this problem by giving the permission to allow your react-native app to display Pop-up Window. After that the App works fine. It seems that you may have already solved this problem. If not, hope this answer can help you.
i dont know is my answer suitable or not , but i faced this problem , when i tried to root my phone using SuperSU . adb could find my device but i could not installing react-native app . so i restored my phone to before rooting and everything worked good ! my phone is Xiaomi Mi Note 3 .
9,153,616
I have 2 variables: 1. `UIView *view1;` 2. `UIView *view2 = [[UIView alloc] init]` When I assign `view1=view2` - should I release `view2`? Or just release `view1`? Or `view1 = [view2 retain]; [view1 release];` is right way?
2012/02/05
[ "https://Stackoverflow.com/questions/9153616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1160813/" ]
It totally depends on what `view1` and `view2` are at the time of your `view1 = view2`. If it's like this: ``` UIView *view1; UIView *view2 = [[UIView alloc] init]; ``` Then it's totally fine to just do: ``` view1 = view2; ``` If however `view1` already points to an object such as in this: ``` UIView *view1 = [[UIView alloc] init]; UIView *view2 = [[UIView alloc] init]; ``` Then you would want to (probably) do this: ``` [view1 release]; view1 = [view2 retain]; ``` I say probably because, well, it depends on what you are wanting to do. Maybe you don't want the `retain` on `view2` because you might not want to have a strong reference to it. Of course all this is moot if you just use ARC anyway :-D.
If you own an object (allocate, retain or copy it), you must release it. If you don't own it you don't release it. That is to say, that view2 owns the view, and view1 doesn't. You should release view2, but not view1.
32,293,027
Is it possible to use websockets (via socket.io etc.) in a React Native app for bidirectional communication with a custom backend rather that using the supported `fetch()` with polling etc.? For example, neccessary for a chat app with React Native. Their website does not mention an API for this yet.
2015/08/30
[ "https://Stackoverflow.com/questions/32293027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2605049/" ]
If "genre" is not defined in the route that matches the action method as a parameter, it will be passed as query string.
That's called a [query parameter](https://en.wikipedia.org/wiki/Query_string). It's a very common way to pass variables in the URL.
32,293,027
Is it possible to use websockets (via socket.io etc.) in a React Native app for bidirectional communication with a custom backend rather that using the supported `fetch()` with polling etc.? For example, neccessary for a chat app with React Native. Their website does not mention an API for this yet.
2015/08/30
[ "https://Stackoverflow.com/questions/32293027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2605049/" ]
There is typical example. We have one route for BookDetail: ``` routes.MapRoute( name: "BookDetail", url: "{controller}/{action}/{id}", defaults: new { controller = "Book", action = "Detail", id = UrlParameter.Optional } ); ``` **First example** - with one parameter `id` defined in route rule ``` <li>@Html.ActionLink(@item.Name, "Detail", new { id = item.Id })</li> http://localhost:26239/Book/Detail/221 ``` **Second example** - with another parameter `xy` not defined in route ``` <li>@Html.ActionLink(@item.Name, "Detail", new { id = item.Id, xy = item.Xy })</li> http://localhost:26239/Book/Detail/221?xy=SomeValue ``` **Third example** - without parameters (because `id` is optional) ``` <li>@Html.ActionLink(@item.Name, "Detail")</li> http://localhost:26239/Book/Detail ```
That's called a [query parameter](https://en.wikipedia.org/wiki/Query_string). It's a very common way to pass variables in the URL.
50,819,117
I need to separate the three div's, remaining on the same line but the background color of each other does not allow that. The problem is, when I set additional margin or padding, the divs wrap up, not remaining aligned horizontally. ```css #service_container { text-align: center; } .servicon { font-size: 54px; } .service_page_tile { background-color: rgba(161, 204, 239, 0.5); } ``` ```html <div id="service_container" class="container-fluid"> <div id="s_idea" class="container-fluid"> <h2>Idea</h2> <div class="row"> <div class="service_page_tile col-lg-4 col-md-6 col-sm-12"> <i class="servicon far fa-lightbulb"></i><br> Do you have an idea about a website you want to realize? Blog, Company Website, e-shop, V-log channel, web-app or just your personal page, I will pay special attention to the customer's output to achieve. </div> <div class="service_page_tile col-lg-4 col-md-6 col-sm-12"> <i class="servicon fas fa-lightbulb"></i><br> Do you still need to find out what's your deal? Let's check templates and discover what's the best formula chosen by the most succesfull people or business. </div> <div class="service_page_tile col-lg-4 col-md-12 col-sm-12"> <i class="servicon fas fa-video"></i><br> What about a video? A resumé, a clip for a presentation or simply your last travel on the other side of the world. there's nothing more catchy to convey emotions or ideas! </div> </div> </div> ``` <http://jsfiddle.net/Z7mFr/182/>
2018/06/12
[ "https://Stackoverflow.com/questions/50819117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9681305/" ]
When you add margin to your a fixed width element, the calculated width adds the margin value to fixed width which will cause it to go underneath, and thats because there is no more space in the same line **Solution:** Wrap the content of your divs inside another div, and apply margin to the inner div, or just add padding to the outer div since `box-sizing` property is already included in bootstrap **See solution:** ```css #service_container { text-align: center; } .servicon { font-size: 54px; } .service_page_tile { background-color: rgba(161, 204, 239, 0.5); margin:5px; } ``` ```html <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" /> <div id="service_container" class="container-fluid"> <div id="s_idea" class="container-fluid"> <h2>Idea</h2> <div class="row"> <div class="col-lg-4 col-md-6 col-sm-12"> <div class="service_page_tile "> <i class="servicon far fa-lightbulb"></i><br> Do you have an idea about a website you want to realize? Blog, Company Website, e-shop, V-log channel, web-app or just your personal page, I will pay special attention to the customer's output to achieve. </div> </div> <div class=" col-lg-4 col-md-6 col-sm-12"> <div class="service_page_tile"> <i class="servicon fas fa-lightbulb"></i><br> Do you still need to find out what's your deal? Let's check templates and discover what's the best formula chosen by the most succesfull people or business. </div> </div> <div class="col-lg-4 col-md-12 col-sm-12"> <div class="service_page_tile "> <i class="servicon fas fa-video"></i><br> What about a video? A resumé, a clip for a presentation or simply your last travel on the other side of the world. there's nothing more catchy to convey emotions or ideas! </div> </div> </div> </div> ```
The quick-and-dirty solution is to use a transparent border, and then clip the background to its inside boundary: ``` .service_page_tile { background-color: rgba(161, 204, 239, 0.5); background-clip: padding-box; border: 8px solid transparent; } ``` An advantage to this solution is that the tile background color block will have equal height for all three tiles.
265,615
I am trying to advance my coding skills and venture into the world of high-end microcontrollers, coming mainly from a Java background (1 year of android developer as a daytime job plus a bit of C developing around Attiny in Atmel Studio) I fell in love with the abstraction provided by STM's HAL. I am aware that this is a sub-optimal solution from an optimization point of view but decided to go down this way because of how promisingly fast it looks. I started from the very basics, turning on a LED but, after an evening of no luck I really need some help. Here is my code, it is compiling fine, uploading fine but... nothing happens! I'm using an STM32F4-Discovery board. ``` #include "stm32f4xx.h" #include "stm32f4_discovery.h" GPIO_InitTypeDef GPIO_InitStructure; int main(void) { HAL_Init(); __GPIOD_CLK_ENABLE(); GPIO_InitStructure.Pin = GPIO_PIN_15; GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStructure.Pull = GPIO_PULLUP; GPIO_InitStructure.Speed = GPIO_SPEED_HIGH; HAL_GPIO_Init(GPIOD, &GPIO_InitStructure); while (1) { HAL_GPIO_WritePin(GPIOD, GPIO_PIN_15, GPIO_PIN_SET); } } ```
2016/10/25
[ "https://electronics.stackexchange.com/questions/265615", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/127875/" ]
Basically what @bitsmack suggested should look something like this: ``` #include "stm32f4xx.h" #include "stm32f4xx_hal_cortex.h" #include "stm32f4xx_hal.h" void SystemClock_Config(void); int main(void) { /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* Configure the system clock */ SystemClock_Config(); /* Initialize all configured peripherals */ __GPIOD_CLK_ENABLE(); GPIO_InitStructure.Pin = GPIO_PIN_15; GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStructure.Pull = GPIO_PULLUP; GPIO_InitStructure.Speed = GPIO_SPEED_HIGH; HAL_GPIO_Init(GPIOD, &GPIO_InitStructure); while (1) { HAL_GPIO_WritePin(GPIOD, GPIO_PIN_15, GPIO_PIN_SET); } } /** * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = PLL (HSE) * SYSCLK(Hz) = 168000000 * HCLK(Hz) = 168000000 * AHB Prescaler = 1 * APB1 Prescaler = 4 * APB2 Prescaler = 2 * HSE Frequency(Hz) = HSE_VALUE * PLL_M = (HSE_VALUE/1000000u) * PLL_N = 336 * PLL_P = 2 * PLL_Q = 7 * VDD(V) = 3.3 * Main regulator output voltage = Scale1 mode * Flash Latency(WS) = 5 * @param None * @retval None */ void SystemClock_Config(void) { RCC_ClkInitTypeDef RCC_ClkInitStruct; RCC_OscInitTypeDef RCC_OscInitStruct; // Enable Power Control clock __PWR_CLK_ENABLE(); // The voltage scaling allows optimizing the power consumption when the // device is clocked below the maximum system frequency, to update the // voltage scaling value regarding system frequency refer to product // datasheet. __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); // Enable HSE Oscillator and activate PLL with HSE as source RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; // This assumes the HSE_VALUE is a multiple of 1MHz. If this is not // your case, you have to recompute these PLL constants. RCC_OscInitStruct.PLL.PLLM = (HSE_VALUE/1000000u); RCC_OscInitStruct.PLL.PLLN = 336; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 7; HAL_RCC_OscConfig(&RCC_OscInitStruct); // Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 // clocks dividers RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5); } ``` I hope the comments are descriptive enough. This should work with an STM32F4 Discovery. As for the other suggestion, STM32CubeMX, it gives a transparent way to configure your clocks (and other peripherals as well). You can check all the different buses and how they are clocked, switch between clock sources. You can see what for example what the `PLL_M`, `PLL_N`, `PLL_P`, `PLL_Q` values exactly stand for. You can obtain this information from reference manual of the controller as well, but that would be a bit raw compared to this graphical representation. [![enter image description here](https://i.stack.imgur.com/2z0u0.png)](https://i.stack.imgur.com/2z0u0.png)
I haven't used this HAL, but it looks like you are missing some necessary system configuration code. I would expect to see (at least) something like this: ``` RCC_OscInitTypeDef RCC_OscInitStruct; RCC_ClkInitTypeDef RCC_ClkInitStruct; HAL_Init(); // Oscillator settings here: // ... // ... HAL_RCC_OscConfig(&RCC_OscInitStruct); // System clock settings here: // ... // ... HAL_RCC_ClockConfig(&RCC_ClkInitStruct); ``` Since you are using the HAL, I recommend you use the [STM32CubeMX](http://www.st.com/content/st_com/en/products/development-tools/software-development-tools/stm32-software-development-tools/stm32-configurators-and-code-generators/stm32cubemx.html) application build your startup code.
21,029,963
I am making an off-canvas navigation using Foundation, however, I only want the off-canvas nav to display on mobile devices, on desktop browsers I will use a standard navigation menu. My question is, can I reuse the code from my off-canvas nav for my desktop nav, or will I have to code 2 separate navigation menus? Here is what my nav code looks like for the off-canvas nav: ``` <div class="off-canvas-wrap"> <div class="inner-wrap"> <nav class="tab-bar"> <section class="left-small"> <a class="left-off-canvas-toggle menu-icon" ><span></span></a> </section> </nav> <aside class="left-off-canvas-menu"> <ul class="off-canvas-list"> <li {% if page.slug == "index" %}class="active"{% endif %}> <a href="/">Home</a> </li> <li>{% nav site, no_wrapper: true %}</li> </ul> </aside> <section class="main-section"> PAGE CONTENT HERE </section> <a class="exit-off-canvas"></a> </div> </div> ``` Thanks in advance!
2014/01/09
[ "https://Stackoverflow.com/questions/21029963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101431/" ]
You'll need to use separate sets of navigation in order to achieve what you're wanting, unfortunately. In order to use both, however, you'll need to structure your website to accommodate the off-canvas menu, but only call the off-canvas menu when you're on small menus. The menu that you'll use within the main part of the site (within the "main-section") will have to be hidden for small to avoid multiple menus showing. We recently came across this issue with our corporate site and we only wanted to call the navigation once, however it was proving extremely difficult. Here's a basic example of how the structure would look: ``` <div class="off-canvas-wrap"> <div class="inner-wrap"> <nav class="tab-bar show-for-small"> <section class="left-small"> <a class="left-off-canvas-toggle menu-icon" ><span></span></a> </section> <section class="middle tab-bar-section"> <h1 class="title"><a href="/home"><img id="logoSmall" src="/images/main/header_logo_small.png" /></a></h1> </section> </nav> <aside class="left-off-canvas-menu"> <ul class="off-canvas-list"> <li><label>Menu</label></li> <li><a>link1</a></li> <li><a>link2</a></li> <li><a>link2</a></li> </ul> </aside> <section class="main-section"> <!-- All of your website goes here --> <!-- Including the navigation you want to show on medium-and-up--> </section> <a class="exit-off-canvas"></a> </div><!--/innerWrapp--> </div><!--/offCanvasWrap--> ```
hide the navigation as follow: ``` .tab-bar, .left-off-canvas-menu { visibility: hidden; } ``` and display it usind media queries on small devices (150px - 600px): ``` @media only screen and (min-width: 150px) and (max-width: 600px){ /* only --> tells older browsers to ignore this code*/ /* DISPLAY ALTERNATIVE NAVIGATION IN MOBILE MODE */ .tab-bar, .left-off-canvas-menu { display: block; visibility: visible; } } ```
6,196,297
Currently I'm using: ``` <% @items.each do |item| %> <li class="list-item"> <%= render :partial => '/widgets/vertical_widget', :object => item %> </li> <% end %> ``` to render about 20 items on a page (there's also another 20 of a different widget on the same page). When I look at my server logs it's showing ~400ms per widget render, totaling out to ~20k ms for the page. From what I've read using :colletion instead of a loop with :object should help to improve those times however I'm not sure how I can wrap each instance of the widget in an LI if I use :collection. Not ever place the widget is used on the site is in a list so it doesn't make sense to include the LI in the widget code. I could include the widget code directly in the loop rather than in a partial however I don't want to have to make code updates in multiple places. Any other ideas to improve performance would be appreciated!
2011/06/01
[ "https://Stackoverflow.com/questions/6196297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/661469/" ]
Give `content_tag` a try: ``` #some_file.html.erb <ul> <%= render :partial => 'widgets/vertical_widget', :collection => @items, :locals => { :wrap_in => :li } %> </ul> #/widgets/vertical_widget.html.erb #First, render and capture the content once. <% @rendered_content = capture do %> #render the item here <% end %> #Next, decide if the content rendered above should be wrapped in a tag or not #If the "wrap_in" variable was passed-in and it is not nil/empty, then use that #value for the tag; else do not wrap the content in a tag <% if defined?(wrap_in) && !wrap_in.blank? %> <%= content_tag wrap_in do %> <%= @rendered_content %> <% end %> <% else %> <%= @rendered_content %> <% end %> ```
I realize this is a late answer but it may be useful to people with similar questions. Zabba's answer is very good and should help as a general guideline. However, your slowness problem is probably not to do with rendering. If a single render is taking 400ms, then it's likely that you are hitting the database repeatedly within the 'vertical\_widget' partial. Check your logs for what queries are going on and see if you can cache any of that using a local variable.
29,539,871
I tried using the Achart Engine and then GraphView to plot data coming from a sensor (real time, live updating) in opposite x-axis direction. I am doing it this way since I want to plot the Magnitude (y) in function of Frequency (x) and I am receiving these magnitudes in decreasing frequency order (from 6000Hz down to 1000Hz). My problem is that Achartengine sorts the incoming data in increasing x-axis direction, therefore when I try to live update with x values decreasing the app crashes. Whereas GraphView simply reorders the points in the order received to plot them in increasing order again and removing the graph axis... Therefore both libraries don't achieve what I want to do. I tried initializing the plots with some values and then update the plots point by point, but it is not working well (the points are not plotted at the correct place on the plot and the values displayed are not the correct ones). Thanks for any help! :) Here is a small section of my code showing my implementation for Achartengine in my main activity: ``` public void lineGraphHandler() { LinearLayout layout = (LinearLayout) findViewById(R.id.chart); gView = line.getView(this); if (meas_exec == 1 || stim_end == 1 ) { line.clearPoints(); stim_end = 0; } for (int i = 0; i < 22; i++) { Point p = MockData.initialize(i); // We got new // data! Point n = MockData.initialize(i); // We got new // data! line.addNewPoints(p, n); // Add it to our graph } thread = new Thread() { public void run() { for (int i = 21; i >= 0; i--) { if(stim_end == 0) { try { Thread.sleep(1800); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Point p = MockData.getDataFromReceiver1(i); // We got new // data! Point n = MockData.getDataFromReceiver2(i); // We got new // data! line.addNewPoints(p, n); // Add it to our graph gView.repaint(); } } meas_exec = 1; } }; thread.start(); layout.addView(gView); } ``` From my MockData.java: ``` public class MockData { public static Point initialize(int x) { // Our first data double[] xi = { 1,1.091,1.189, 1.297, 1.414, 1.542, 1.682, 1.834, 2, 2.181, 2.378, 2.594, 2.828, 3.084, 3.364, 3.668, 4, 4.362, 4.757, 5.187, 5.657, 6.169}; // x values! double[] yi = { -10, -10, -10, -10, -10, -10, -10, -10, -10, -10, -10, -10, -10, -10, -10, -10, -10, -10, -10, -10, -10, -10 }; // y values! return new Point(xi[x], yi[x]); } public static Point getDataFromReceiver1(int x) { // Our simulated dataset sensor 1 double[] x1 ={ 1,1.091,1.189, 1.297, 1.414, 1.542, 1.682, 1.834, 2, 2.181, 2.378, 2.594, 2.828, 3.084, 3.364, 3.668, 4, 4.362, 4.757, 5.187, 5.657, 6.169}; // x values! double[] y1 = { 1.4, 1.1, 1.5, 8.3, 11.4,-1, 2, 8.3, 11.4, 2, 8.3, 13, -10, 8.3, 11.4, 2, 8.3, 13, -10, 2, 0, 3 }; // y values! return new Point(x1[x], y1[x]); } public static Point getDataFromReceiver2(int x) { // Our simulated dataset sensor 2 double[] x2 = { 1,1.091,1.189, 1.297, 1.414, 1.542, 1.682, 1.834, 2, 2.181, 2.378, 2.594, 2.828, 3.084, 3.364, 3.668, 4, 4.362, 4.757, 5.187, 5.657, 6.169};// x values! double[] y2 = { 3, 3.4,-2, -10.6, -3, -8, -5, 0, 2 ,-3, -8, 2 ,-3, -15.0, -3, -8, 3, 3.4, 0, 2 , 2 ,-3}; // y values! return new Point(x2[x], y2[x]); } } ``` **EDIT** Here is an illustration of what I want to accomplish. The red arrow shows in which direction I want to plot the values (with the 1st ,2nd ,3rd... point order indicated) <http://i61.tinypic.com/164ccz.png> So the first point I plot is around 6kHz and last around 1kHz, but when I look at the plot it should be correctly displayed from 1kHz to 6kHz. So in the beginning the points on the left of the plot will be missing and will gradually be plotted.
2015/04/09
[ "https://Stackoverflow.com/questions/29539871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4658752/" ]
The `time` function typically returns the time in second resolution, which means that if you call `time(NULL)` twice within one second then you will get the same result. That will of course mean that you set the same starting seed to the random-number generator, which means the sequence will be the same. You typically only call `srand` *once*, early in the `main` function.
Move ``` srand ( time(NULL)); ``` to `main()` . You need to call `srand()` once in `main()` and keep calling `rand()`
116,590
On page 292 of the *Dungeon Master Guide*, **Filth Fever** is listed as a **DC 12**. The **Dire Rat** entry in the Monster Manual says the DC of Filth Fever inflicted by such a beast is **DC 11**. I'm currently ruling on the assumption that Filth Fever on it's own is a DC 12, but when inflicted by a Dire Rat it has a DC of 11; but I'd like to know if there's a better way to handle this discrepancy.
2018/03/03
[ "https://rpg.stackexchange.com/questions/116590", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/27573/" ]
You are correct. Sometimes diseases and poisons have specific DC when carried by certain creatures.
This is an intentional difference in the 'lethality' of a disease depending on circumstances like on what creature carries it and their HD, just as various poisons from various creatures have different DC from each other instead of having the same DC whatever the creature is. Here is a list with diseases and their usual DC: <http://www.dandwiki.com/wiki/SRD:Disease> If a certain infection spreads you might want to use the usual DC for further infection rolls unless the creature specifies to use a different one when the disease spreads further than the original infection caused by the creature. Your above example would mean: Dire Rat infection DC for Filth Fever is 11, if you rule that the infected themselves can also infect new victims it might be the usual DC 12, just as in case of *"Those injured while in filthy surroundings might also catch it."*. Injury infected diseases aren't usually contagious (exceptions exist) and ingested-type is probably only transmittable if you have an infected person preparing food.
116,590
On page 292 of the *Dungeon Master Guide*, **Filth Fever** is listed as a **DC 12**. The **Dire Rat** entry in the Monster Manual says the DC of Filth Fever inflicted by such a beast is **DC 11**. I'm currently ruling on the assumption that Filth Fever on it's own is a DC 12, but when inflicted by a Dire Rat it has a DC of 11; but I'd like to know if there's a better way to handle this discrepancy.
2018/03/03
[ "https://rpg.stackexchange.com/questions/116590", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/27573/" ]
The DCs are calculated differently. The Dire Rat's DC is constitution based. 10 + CON modifier. Dire Rat CON = 12 (+1 modifier), therefore DC 11.
This is an intentional difference in the 'lethality' of a disease depending on circumstances like on what creature carries it and their HD, just as various poisons from various creatures have different DC from each other instead of having the same DC whatever the creature is. Here is a list with diseases and their usual DC: <http://www.dandwiki.com/wiki/SRD:Disease> If a certain infection spreads you might want to use the usual DC for further infection rolls unless the creature specifies to use a different one when the disease spreads further than the original infection caused by the creature. Your above example would mean: Dire Rat infection DC for Filth Fever is 11, if you rule that the infected themselves can also infect new victims it might be the usual DC 12, just as in case of *"Those injured while in filthy surroundings might also catch it."*. Injury infected diseases aren't usually contagious (exceptions exist) and ingested-type is probably only transmittable if you have an infected person preparing food.
116,590
On page 292 of the *Dungeon Master Guide*, **Filth Fever** is listed as a **DC 12**. The **Dire Rat** entry in the Monster Manual says the DC of Filth Fever inflicted by such a beast is **DC 11**. I'm currently ruling on the assumption that Filth Fever on it's own is a DC 12, but when inflicted by a Dire Rat it has a DC of 11; but I'd like to know if there's a better way to handle this discrepancy.
2018/03/03
[ "https://rpg.stackexchange.com/questions/116590", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/27573/" ]
Your assumption is correct—it's both! ===================================== When there's a chance of exposure to [filth fever](http://dndsrd.net/abilitiesAndConditions.html#filth-fever) that's *not* dependent upon a creature exposing an adventurer to the disease, the disease filth fever typically requires succeeding on a Fortitude saving throw (DC 12) to avoid infection. That saving throw DC is used if the DM determines that the surroundings are so filthy that filth fever is present: "Those injured while in filthy surroundings might also catch it [i.e. filth fever]" (*Dungeon Master's Guide* 292). However, the extraordinary ability disease of the [dire rat](http://dndsrd.net/monstersDitoDo.html#dire-rat) (*Monster Manual* 64) has its saving throw DC computed like most creatures' special abilities are. The *Monster Manual* on Special Attacks and Special Qualities, in part, says > > When a special ability allows a saving throw, the kind of save and the save DC is noted in the descriptive text. Most saving throws against special abilities have DCs calculated as follows: 10 + 1/2 the attacker’s racial Hit Dice + the relevant ability modifier. The save DC is given in the creature’s description along with the ability on which the DC is based. (6) > > > Thus the saving throw DC against the dire rat's extraordinary ability disease is 10 base then +0 for the dire rat's one Hit Die ([rounded down](http://dndsrd.net/basics.html#rounding-fractions)) then +1 for the dire rat's Constitution modifier for DC 11 total. While this *does* make the disease filth fever *more* dangerous to adventurers when it's present in the environment (Fort DC 12) than when it's carried by the typical dire rat (Fort DC 11), most of the time the environment isn't *also* trying to eat the adventurers. Most of the time.
This is an intentional difference in the 'lethality' of a disease depending on circumstances like on what creature carries it and their HD, just as various poisons from various creatures have different DC from each other instead of having the same DC whatever the creature is. Here is a list with diseases and their usual DC: <http://www.dandwiki.com/wiki/SRD:Disease> If a certain infection spreads you might want to use the usual DC for further infection rolls unless the creature specifies to use a different one when the disease spreads further than the original infection caused by the creature. Your above example would mean: Dire Rat infection DC for Filth Fever is 11, if you rule that the infected themselves can also infect new victims it might be the usual DC 12, just as in case of *"Those injured while in filthy surroundings might also catch it."*. Injury infected diseases aren't usually contagious (exceptions exist) and ingested-type is probably only transmittable if you have an infected person preparing food.
19,229,725
I am trying to run karma as a grunt task on a Ubuntu 12.04 machine in Jenkins CI. The issue I am running into is that karma will not open Chrome and gives the following error: ``` Started by GitHub push by spencerapplegate [EnvInject] - Loading node environment variables. Building in workspace /var/lib/jenkins/jobs/rescour-roomba master/workspace Checkout:workspace / /var/lib/jenkins/jobs/rescour-roomba master/workspace - hudson.remoting.LocalChannel@7b41ce14 Using strategy: Default Last Built Revision: Revision ee61ceea1b8728e90b01db04a1813284a524caed (origin/master) Fetching changes from 1 remote Git repository Fetching upstream changes from origin Commencing build of Revision d3ed5ffd7c7b7a707bd9310c5bce09242e1faced (origin/master) Checking out Revision d3ed5ffd7c7b7a707bd9310c5bce09242e1faced (origin/master) [EnvInject] - Executing scripts and injecting environment variables after the SCM step. [EnvInject] - Injecting as environment variables the properties content CHROME_BIN=/opt/google/chrome/ [EnvInject] - Variables injected successfully. [workspace] $ /bin/sh -xe /tmp/hudson5570746814297674358.sh + sudo npm install + sudo grunt buildProd Loading "express.js" tasks... [31mERROR[39m[31m>> [39mError: Cannot find module 'temp' [4mRunning "clean:build" (clean) task[24m Cleaning ".tmp"...[32mOK[39m Cleaning "build/app"...[32mOK[39m Cleaning "build/app-config"...[32mOK[39m Cleaning "build/components"...[32mOK[39m Cleaning "build/img"...[32mOK[39m Cleaning "build/index.html"...[32mOK[39m Cleaning "build/scripts"...[32mOK[39m Cleaning "build/src"...[32mOK[39m Cleaning "build/styles"...[32mOK[39m [4mRunning "copy:local" (copy) task[24m Created [36m370[39m directories, copied [36m2260[39m files [4mRunning "compass:prod" (compass) task[24m [31m[0m[32mdirectory[0m .tmp/styles/ [31m[0m[32m create[0m .tmp/styles/main.css (1.732s) Compilation took 1.784s [4mRunning "template:prod" (template) task[24m [4mRunning "clean:template" (clean) task[24m Cleaning ".tmp/index.html.template"...[32mOK[39m [4mRunning "karma:unit" (karma) task[24m [36m[2013-10-07 10:07:51.709] [DEBUG] config - [39mautoWatch set to false, because of singleRun [32mINFO [karma]: [39mKarma server started at http://localhost:8079/ [32mINFO [launcher]: [39mStarting browser Chrome [31mERROR [launcher]: [39mCannot start Chrome [32mINFO [launcher]: [39mTrying to start Chrome again. [31mERROR [launcher]: [39mCannot start Chrome [32mINFO [launcher]: [39mTrying to start Chrome again. [31mERROR [launcher]: [39mCannot start Chrome [33mWarning: Task "karma:unit" failed. Use --force to continue.[39m [31mAborted due to warnings.[39m Build step 'Execute shell' marked build as failure SSH: Current build result is [FAILURE], not going to run. Finished: FAILURE ``` I have set CHROME\_BIN=/opt/google/chrome and it seems like it has no issue finding the executable. Other approaches I have taken (all unsuccessful) are: -> Create shell script to open chrome as root with flag --user-data-dir -> Copy all chrome files to a jenkins subdirectory /home/jenkins/opt/google/chrome -> Change ownership of all chrome files in /opt/google/chrome to jenkins The other oddity is that when I log into the machine as the jenkins user, chrome runs the tests fine. Please let me know if there is any more info I need to provide. Thanks
2013/10/07
[ "https://Stackoverflow.com/questions/19229725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1577663/" ]
I had the same problem. After install **xvnc** plugin for Jenkins (<https://wiki.jenkins-ci.org/display/JENKINS/Xvnc+Plugin>), problem disappeared.
For me, it was a misuse of karma start vs karma run. You need to have a karma server running, and use karma run in the jenkins job. See my question and answer [here](https://stackoverflow.com/questions/21124895/karma-cannot-start-firefox-with-jenkins-and-ubuntu-12-04 "here"). **Edit**: Lehu's answer works for both start/run.
36,367,008
I'm trying to install zeromq on OS X 10.11.2. To do this, the following shell commands were suggested: ``` cd libzmq ./autogen.sh && configure && make -j 4 ``` But when I enter the second line, I get the following errors: ``` configure.ac:59: error: missing some pkg-config macros (pkg-config package) If this token and others are legitimate, please use m4_pattern_allow. See the Autoconf documentation. configure.ac:68: error: possibly undefined macro: AC_LIBTOOL_WIN32_DLL configure.ac:69: error: possibly undefined macro: AC_PROG_LIBTOOL configure.ac:253: error: possibly undefined macro: AC_MSG_ERROR configure.ac:427: error: missing some pkg-config macros (pkg-config package) configure:6315: error: possibly undefined macro: AC_DISABLE_STATIC configure:6319: error: possibly undefined macro: AC_ENABLE_STATIC autoreconf: /usr/local/Cellar/autoconf/2.69/bin/autoconf failed with exit status: 1 autogen.sh: error: autoreconf exited with status 0 ``` How can I fix this and successfully install zeromq?
2016/04/01
[ "https://Stackoverflow.com/questions/36367008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5739458/" ]
I had the same problem. Install pkg-config ``` apt-get install pkg-config ```
First of all, do not install anything manually. This adds unmanaged libraries and headers to your file system and you will meet a lot of problems in future. Use homebrew instead ``` brew install zeromq ``` If you really want to compile and install it manually - you are missing pkg-config, which itself must be installed - either via homebrew, or by compiling it manually. ``` cd /tmp curl -OL https://pkg-config.freedesktop.org/releases/pkg-config-0.29.1.tar.gz tar xzvf pkg-config-0.29.1.tar.gz cd pkg-config-0.29.1 ./configure --with-internal-glib make sudo make install ```
5,605,527
Several radio buttons with the same name act as a set, where checking one unchecks the others. What is the scope of this behavior? 1. The form in which the button resides 2. The page / document on which the button resides 3. Does scope pass into `iframe`s? I have always used them in forms, but now writing formless HTML (using ajax for posting), and everything seems to be working just fine, so my guess is #2.
2011/04/09
[ "https://Stackoverflow.com/questions/5605527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/662063/" ]
Radio buttons with the same name in the same form act as a set, but not with those of different forms. Radio buttons with no form act as a set with those with no forms. test it yourself: <http://jsfiddle.net/8qqNC/1/>
Radio buttons are scoped to the form they are in. Frames contain external documents, and nothing in them is considered part of the current document, let alone an element within that document.
12,657,112
I would like to get a String like: ``` Ljava/lang/Class;.getName()Ljava/lang/String; ``` (JNI style type/method description, or called type descriptor) from an `javax.lang.model.type.TypeMirror` object in an `AnnotationProcessor`. Is there any Convenience method or library, which parses the `TypeMirror` object and produces a String like above? I would like to use the String to construct a `org.objectweb.asm.Type` object from the type descriptor string.
2012/09/29
[ "https://Stackoverflow.com/questions/12657112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709013/" ]
I realize this is nearly a decade old, but I've written a library to add TypeMirror/Element support to the ASM library. See here: <https://github.com/soabase/asm-mirror-descriptor> - with this library you can now do: ``` MirrorClassReader reader = new MirrorClassReader(processingEnv, element); reader.accept(myClassVisitor); // standard ASM ClassVisitor ``` or ``` String signature = SignatureMirrorType.getSignature(processingEnv, element); ```
Open console, go to your already compiled classes f.e. : cd ./build/classes . Then type javap -s NameOfYourCompiledClass.class (in console) and you'l get your descriptors. For your situation I'd extend this TypeMirror class with your custom class, overload all methods, compile the project and folow the instructions below for your new class
6,591,346
I have read the Load runner basics and understood an overview of the components of Load Runner and general workflow. As its Load Testing of a website, I need to plan real time scenarios of the functionality of the website with example 100 users who log-in simultaneously. In Load runner,I need to create all these users that emulate steps of real users using the application These which would be virtual users…Vuser. Could you all please help me writing this script? please help me by giving a script to create a vuser and description of the script. The component is VuGen (Virtual User Generator) of Load runner. VuGen then also runs them. How to execute it?
2011/07/06
[ "https://Stackoverflow.com/questions/6591346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/830829/" ]
Works fine: ``` var foo = { foo : 22, bar : 42 }; for(var i in foo); alert(i); // "bar" ``` What, exactly, are you passing to the function?
Your example looks fine. After `getKeyNames` is called, `lastValue` will hold the last key found in the object. However, your example does not call `getKeyNames`, so the `alert(lastValue)` should alert "undefined". If you ARE calling it somewhere, and you find that `lastValue` contains a number, well it's probably because your object contains a number. For example, `for (var i in ['a','b','c'])` will iterate "length", "0", "1", "2".
1,234,972
I am getting sqlcommand timeout issues when I debug the application even though the stored procedure runs in less than 25 seconds in management studio. I set the timeout attribute to 180 seconds and still get the error. Any suggestions?
2009/08/05
[ "https://Stackoverflow.com/questions/1234972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` <asp:Button OnClientClick="return confirm('Are you sure you want to go?');" Text="Confirm" runat="server" onclick="Unnamed1_Click" /> ``` If they click OK, the server onclick event will happen, if they click cancel, it will be like they didn't even press the button, of course, you can always add functionallity to the cancel part. Maybe something like: ``` <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> <script type="text/javascript"> function CompareConfirm() { var str1 = "abc"; var str2 = "def"; if (str1 === str2) { // your logic here return false; } else { // your logic here return confirm("Confirm?"); } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Button OnClientClick="return CompareConfirm();" Text="Confirm" runat="server" onclick="Unnamed1_Click" /> </div> </form> </body> </html> ```
Put the check before rendering the page to the client. Then attach a handler (on the client side, eg. javascript) to the save-button or form that displays the confirmation box (but only if the saving results in a replacement).
1,234,972
I am getting sqlcommand timeout issues when I debug the application even though the stored procedure runs in less than 25 seconds in management studio. I set the timeout attribute to 180 seconds and still get the error. Any suggestions?
2009/08/05
[ "https://Stackoverflow.com/questions/1234972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` <asp:Button OnClientClick="return confirm('Are you sure you want to go?');" Text="Confirm" runat="server" onclick="Unnamed1_Click" /> ``` If they click OK, the server onclick event will happen, if they click cancel, it will be like they didn't even press the button, of course, you can always add functionallity to the cancel part. Maybe something like: ``` <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> <script type="text/javascript"> function CompareConfirm() { var str1 = "abc"; var str2 = "def"; if (str1 === str2) { // your logic here return false; } else { // your logic here return confirm("Confirm?"); } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Button OnClientClick="return CompareConfirm();" Text="Confirm" runat="server" onclick="Unnamed1_Click" /> </div> </form> </body> </html> ```
An alternative, simpler approach which doesn't require AJAX would be to allow the post-back as normal, then in the code-behind, do your checks. If the user confirmation is required, just return the user back to the same page but make an extra panel visible and hide the original 'Save' button. In this extra panel, display your message with another OK / Cancel button. When the user clicks this OK button, perform the save!
1,234,972
I am getting sqlcommand timeout issues when I debug the application even though the stored procedure runs in less than 25 seconds in management studio. I set the timeout attribute to 180 seconds and still get the error. Any suggestions?
2009/08/05
[ "https://Stackoverflow.com/questions/1234972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` <asp:Button OnClientClick="return confirm('Are you sure you want to go?');" Text="Confirm" runat="server" onclick="Unnamed1_Click" /> ``` If they click OK, the server onclick event will happen, if they click cancel, it will be like they didn't even press the button, of course, you can always add functionallity to the cancel part. Maybe something like: ``` <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> <script type="text/javascript"> function CompareConfirm() { var str1 = "abc"; var str2 = "def"; if (str1 === str2) { // your logic here return false; } else { // your logic here return confirm("Confirm?"); } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Button OnClientClick="return CompareConfirm();" Text="Confirm" runat="server" onclick="Unnamed1_Click" /> </div> </form> </body> </html> ```
add a hidden field to your page for example Hiddenfield1 then add this function ``` public bool Confirm(string MSG) { string tmp = ""; tmp = "<script language='javascript'>"; tmp += "document.getElementById('HiddenField1').value=0; if(confirm('" + MSG + "')) document.getElementById('HiddenField1').value=1;"; tmp += "</script>"; Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "ConfirmBox", tmp); if(HiddenField1.Value.Trim()=="0") return false; return true; } ```
1,234,972
I am getting sqlcommand timeout issues when I debug the application even though the stored procedure runs in less than 25 seconds in management studio. I set the timeout attribute to 180 seconds and still get the error. Any suggestions?
2009/08/05
[ "https://Stackoverflow.com/questions/1234972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I appreciate both previous answers and they were helpful but not exactly what I was looking for. After considering the responses and doing more research I'm posting my solution so that maybe it will help someone else. Button code: ``` <asp:Button ID="btnSave" OnClick="btnSaveClick" runat="server" Text="Save" OnClientClick="return CheckForVersion()" /> ``` Javascript: ``` <script language="javascript"> function CheckForVersion() { PageMethods.CheckForVersion(aspnetForm.ctl00$ContentPlaceHolder1$ddlPageName2.value, aspnetForm.ctl00$ContentPlaceHolder1$txtContentName2.value, OnSucceeded, OnFailed); return false; } function OnSucceeded(results) { if(results) { //version exists so prompt user if(confirm("Version already exists. Do you want to overwrite?")) { __doPostBack('ctl00$ContentPlaceHolder1$btnSave',''); } } else { //version does not exist so save it without prompting user __doPostBack('ctl00$ContentPlaceHolder1$btnSave',''); } } function OnFailed(error) { // handle pagemethod error alert(error.get_message()); } </script> ``` C# using Subsonic 2.1: ``` [WebMethod] public static bool CheckForVersion(string pageName, string versionName) { PageContentCollection pages = new PageContentCollection().Where("pageName", pageName).Where("versionName", versionName).Load(); if (pages.Count > 0) return true; else return false; } ```
Put the check before rendering the page to the client. Then attach a handler (on the client side, eg. javascript) to the save-button or form that displays the confirmation box (but only if the saving results in a replacement).
1,234,972
I am getting sqlcommand timeout issues when I debug the application even though the stored procedure runs in less than 25 seconds in management studio. I set the timeout attribute to 180 seconds and still get the error. Any suggestions?
2009/08/05
[ "https://Stackoverflow.com/questions/1234972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
An alternative, simpler approach which doesn't require AJAX would be to allow the post-back as normal, then in the code-behind, do your checks. If the user confirmation is required, just return the user back to the same page but make an extra panel visible and hide the original 'Save' button. In this extra panel, display your message with another OK / Cancel button. When the user clicks this OK button, perform the save!
Put the check before rendering the page to the client. Then attach a handler (on the client side, eg. javascript) to the save-button or form that displays the confirmation box (but only if the saving results in a replacement).
1,234,972
I am getting sqlcommand timeout issues when I debug the application even though the stored procedure runs in less than 25 seconds in management studio. I set the timeout attribute to 180 seconds and still get the error. Any suggestions?
2009/08/05
[ "https://Stackoverflow.com/questions/1234972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Put the check before rendering the page to the client. Then attach a handler (on the client side, eg. javascript) to the save-button or form that displays the confirmation box (but only if the saving results in a replacement).
add a hidden field to your page for example Hiddenfield1 then add this function ``` public bool Confirm(string MSG) { string tmp = ""; tmp = "<script language='javascript'>"; tmp += "document.getElementById('HiddenField1').value=0; if(confirm('" + MSG + "')) document.getElementById('HiddenField1').value=1;"; tmp += "</script>"; Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "ConfirmBox", tmp); if(HiddenField1.Value.Trim()=="0") return false; return true; } ```
1,234,972
I am getting sqlcommand timeout issues when I debug the application even though the stored procedure runs in less than 25 seconds in management studio. I set the timeout attribute to 180 seconds and still get the error. Any suggestions?
2009/08/05
[ "https://Stackoverflow.com/questions/1234972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I appreciate both previous answers and they were helpful but not exactly what I was looking for. After considering the responses and doing more research I'm posting my solution so that maybe it will help someone else. Button code: ``` <asp:Button ID="btnSave" OnClick="btnSaveClick" runat="server" Text="Save" OnClientClick="return CheckForVersion()" /> ``` Javascript: ``` <script language="javascript"> function CheckForVersion() { PageMethods.CheckForVersion(aspnetForm.ctl00$ContentPlaceHolder1$ddlPageName2.value, aspnetForm.ctl00$ContentPlaceHolder1$txtContentName2.value, OnSucceeded, OnFailed); return false; } function OnSucceeded(results) { if(results) { //version exists so prompt user if(confirm("Version already exists. Do you want to overwrite?")) { __doPostBack('ctl00$ContentPlaceHolder1$btnSave',''); } } else { //version does not exist so save it without prompting user __doPostBack('ctl00$ContentPlaceHolder1$btnSave',''); } } function OnFailed(error) { // handle pagemethod error alert(error.get_message()); } </script> ``` C# using Subsonic 2.1: ``` [WebMethod] public static bool CheckForVersion(string pageName, string versionName) { PageContentCollection pages = new PageContentCollection().Where("pageName", pageName).Where("versionName", versionName).Load(); if (pages.Count > 0) return true; else return false; } ```
An alternative, simpler approach which doesn't require AJAX would be to allow the post-back as normal, then in the code-behind, do your checks. If the user confirmation is required, just return the user back to the same page but make an extra panel visible and hide the original 'Save' button. In this extra panel, display your message with another OK / Cancel button. When the user clicks this OK button, perform the save!
1,234,972
I am getting sqlcommand timeout issues when I debug the application even though the stored procedure runs in less than 25 seconds in management studio. I set the timeout attribute to 180 seconds and still get the error. Any suggestions?
2009/08/05
[ "https://Stackoverflow.com/questions/1234972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I appreciate both previous answers and they were helpful but not exactly what I was looking for. After considering the responses and doing more research I'm posting my solution so that maybe it will help someone else. Button code: ``` <asp:Button ID="btnSave" OnClick="btnSaveClick" runat="server" Text="Save" OnClientClick="return CheckForVersion()" /> ``` Javascript: ``` <script language="javascript"> function CheckForVersion() { PageMethods.CheckForVersion(aspnetForm.ctl00$ContentPlaceHolder1$ddlPageName2.value, aspnetForm.ctl00$ContentPlaceHolder1$txtContentName2.value, OnSucceeded, OnFailed); return false; } function OnSucceeded(results) { if(results) { //version exists so prompt user if(confirm("Version already exists. Do you want to overwrite?")) { __doPostBack('ctl00$ContentPlaceHolder1$btnSave',''); } } else { //version does not exist so save it without prompting user __doPostBack('ctl00$ContentPlaceHolder1$btnSave',''); } } function OnFailed(error) { // handle pagemethod error alert(error.get_message()); } </script> ``` C# using Subsonic 2.1: ``` [WebMethod] public static bool CheckForVersion(string pageName, string versionName) { PageContentCollection pages = new PageContentCollection().Where("pageName", pageName).Where("versionName", versionName).Load(); if (pages.Count > 0) return true; else return false; } ```
add a hidden field to your page for example Hiddenfield1 then add this function ``` public bool Confirm(string MSG) { string tmp = ""; tmp = "<script language='javascript'>"; tmp += "document.getElementById('HiddenField1').value=0; if(confirm('" + MSG + "')) document.getElementById('HiddenField1').value=1;"; tmp += "</script>"; Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "ConfirmBox", tmp); if(HiddenField1.Value.Trim()=="0") return false; return true; } ```
1,234,972
I am getting sqlcommand timeout issues when I debug the application even though the stored procedure runs in less than 25 seconds in management studio. I set the timeout attribute to 180 seconds and still get the error. Any suggestions?
2009/08/05
[ "https://Stackoverflow.com/questions/1234972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
An alternative, simpler approach which doesn't require AJAX would be to allow the post-back as normal, then in the code-behind, do your checks. If the user confirmation is required, just return the user back to the same page but make an extra panel visible and hide the original 'Save' button. In this extra panel, display your message with another OK / Cancel button. When the user clicks this OK button, perform the save!
add a hidden field to your page for example Hiddenfield1 then add this function ``` public bool Confirm(string MSG) { string tmp = ""; tmp = "<script language='javascript'>"; tmp += "document.getElementById('HiddenField1').value=0; if(confirm('" + MSG + "')) document.getElementById('HiddenField1').value=1;"; tmp += "</script>"; Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "ConfirmBox", tmp); if(HiddenField1.Value.Trim()=="0") return false; return true; } ```
10,487,250
How Can i specific require and unique condition for a list of select box like below? ``` <form name="signupForm" class="cmxform" id="signupForm" method="get" action=""> <select name="category[]" id="cat_1"> <option value="">Select One</option> <option value="1">aa</option> <option value="2">bb</option> <option value="3">cc</option> <option value="4">dd</option> </select> <select name="category[]" id="cat_2"> <option value="">Select One</option> <option value="5">ee</option> <option value="6">ff</option> <option value="7">gg</option> <option value="8">hh</option> </select> <select name="category[]" id="cat_3"> <option value="">Select One</option> <option value="9">ii</option> <option value="10">jj</option> <option value="11">kk</option> <option value="12">ll</option> </select> <input class="submit" type="submit" value="Submit"> </form> ``` Notice that there are the number of cat is not fixed, it can be more than 3, so how to make it required for each selectbox, and each selectbox chosen value must be unique using jquery validate plugin? Thank you
2012/05/07
[ "https://Stackoverflow.com/questions/10487250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1280996/" ]
``` var $selects = $('form select[name^=category]'), values = []; $(':submit').click(function(e) { e.preventDefault(); values = []; $($selects).each(function() { if($(this).val()) { values.push($(this).val()); } }); if(!values.length) { alert('Please select all categories'); return false; } if(values.length < $selects.length || $.unique(values).length < $selects.length) { alert('Please select all categories and be unique'); return false; } }); ``` ***[DEMO](http://jsfiddle.net/BbkvL/)***
Here is a great jQuery validation plugin that will make your life easier: <http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/> This is all you need to do: (the plugin does the rest) ``` <select id="sport" class="validate[required]" name="sport"> <option value="">--Select--</option> <option value="option1">Tennis</option> <option value="option2">Football</option> <option value="option3">Golf</option> </select> ``` Hope that helps :)
2,817,707
Assume that notepad.exe is opening and the it's window is inactive. I will write an application to activate it. How to make? **Update:** The window title is undefined. So, I don't like to use to FindWindow which based on window's title. My application is Winform C# 2.0. Thanks.
2010/05/12
[ "https://Stackoverflow.com/questions/2817707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253940/" ]
You'll need to P/invoke SetForegroundWindow(). Process.MainWindowHandle can give you the handle you'll need. For example: ``` using System; using System.Diagnostics; using System.Runtime.InteropServices; class Program { static void Main(string[] args) { var prc = Process.GetProcessesByName("notepad"); if (prc.Length > 0) { SetForegroundWindow(prc[0].MainWindowHandle); } } [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); } ``` Note the ambiguity if you've got more than one copy of Notepad running.
You'd need to PInvoke the Windows API calls such as FindWindow and or EnumWindows and GetWindowText (for the title). Ideally you might also want to use GeWindowThreadProcessId so you can tie it down to the actual process.
2,817,707
Assume that notepad.exe is opening and the it's window is inactive. I will write an application to activate it. How to make? **Update:** The window title is undefined. So, I don't like to use to FindWindow which based on window's title. My application is Winform C# 2.0. Thanks.
2010/05/12
[ "https://Stackoverflow.com/questions/2817707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253940/" ]
You'll need to P/invoke SetForegroundWindow(). Process.MainWindowHandle can give you the handle you'll need. For example: ``` using System; using System.Diagnostics; using System.Runtime.InteropServices; class Program { static void Main(string[] args) { var prc = Process.GetProcessesByName("notepad"); if (prc.Length > 0) { SetForegroundWindow(prc[0].MainWindowHandle); } } [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); } ``` Note the ambiguity if you've got more than one copy of Notepad running.
You have to use combination of these - [Toggle Process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden at runtime](https://stackoverflow.com/questions/2647820/toggle-process-startinfo-windowstyle-processwindowstyle-hidden-at-runtime/2648017#2648017) and [Bring another processes Window to foreground when it has ShowInTaskbar = false](https://stackoverflow.com/questions/2636721/bring-another-processes-window-to-foreground-when-it-has-showintaskbar-false/2636915#2636915) You need to find the class of the window and do a search on it. [Read more about it here](http://msdn.microsoft.com/en-us/library/ms633499%28VS.85%29.aspx). Just for info, Notepad's class name is "Notepad" (without quotes). You can verify it using Spy++. Note: You cannot activate a window of an app if it was run with *no window*. Read more options in [API here](http://msdn.microsoft.com/en-us/library/ms632680%28v=VS.85%29.aspx).
41,059,230
okay so i have strings in a list like so: `- String, boolean` I basically want to grab a whole heap of these from a long string list (progressing downward) and throw them into a hashmap like the following so i can simply get the key (the string) and get the `boolean` value from the key. The hashmap: `public HashMap<String, Boolean> keyValues = new HashMap<String, Boolean>();` thanks in advance folks. PS: first time using stackoverflow, lets see how we go!
2016/12/09
[ "https://Stackoverflow.com/questions/41059230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7272355/" ]
If you want to do it in one-line: ``` Pattern.compile("-") .splitAsStream(s) .map(string -> string.split(",")) .collect(Collectors.toMap(k -> k[0], v -> Boolean.valueOf(v[1]))); ``` Where `s` is a string like this: ``` SIGN_COLOUR, false - SIGN_FORMAT, false - SIGN_ASHOP, false - SIGN_PSHOP, false ```
That should be easy, isn't it? ``` public static Map<String,Boolean> toMap(List<String> l) { HashMap<String,Boolean> m = new HashMap<String,Boolean>(); l.forEach((s) -> { String[] t=s.split(","); m.put(t[0], new Boolean(t[1])); }); return m; } ```
41,280,287
I'm trying to make a program that rolls a dice and checks if the user wants to continue every roll, if not, the program should halt. Although, no matter what you input, the program breaks out of the loop. Can someone explain why and give me some tips to making a program that is simpler and works? Thanks ``` import random sideNumber = int(input("Enter the number of sides in the die: ")) print("Dice numbers: ") while True: print(random.randint(0, sideNumber)) print("Do you want to continue?") response = input() if response == "n" or "no": break ```
2016/12/22
[ "https://Stackoverflow.com/questions/41280287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7329691/" ]
If you've only got 1 value in the array, you can use; ``` {{mongoDbData[0]._id.$oid}} ``` For every value in your array, use 0 because it's the first item in your array.
If not mistaken, the issue seems to be that the document object you were expecting in wrapped as the only element of an array. In your controller, do as follows: ``` // assuming document to be the array-wrapped response $scope.documentData = document[0]; ``` so that in your view you can use data binding on `documentData` ``` <span>{{ documentData._id.$oid }}</span> ``` This will remove the need to always fetch the first element of the array in your data binding expression.
75,978
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?
2008/09/16
[ "https://Stackoverflow.com/questions/75978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748/" ]
Use the following (remember to include System.Configuration assembly) ``` ConfigurationManager.OpenExeConfiguration(exePath) ```
You can set it by creating a new app domain: ``` AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ConfigurationFile = fileLocation; AppDomain add = AppDomain.CreateDomain("myNewAppDomain", securityInfo, domainSetup); ```
75,978
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?
2008/09/16
[ "https://Stackoverflow.com/questions/75978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748/" ]
``` using System.Configuration; Configuration config = ConfigurationManager.OpenExeConfiguration("C:\Test.exe"); ``` You can then access the app settings, connection strings, etc from the config instance. This assumes of course that the config file is properly formatted and your app has read access to the directory. Notice the path is ***not*** "C:\Test.exe.config" The method looks for a config file associated with the file you specify. If you specify "C:\Test.exe.config" it will look for "C:\Test.exe.config.config" Kinda lame, but understandable, I guess. Reference here: <http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx>
Use the following (remember to include System.Configuration assembly) ``` ConfigurationManager.OpenExeConfiguration(exePath) ```
75,978
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?
2008/09/16
[ "https://Stackoverflow.com/questions/75978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748/" ]
Use the following (remember to include System.Configuration assembly) ``` ConfigurationManager.OpenExeConfiguration(exePath) ```
``` AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ConfigurationFile = @"D:\Mine\Company\"; string browserName = ConfigurationManager.AppSettings["browser"]; ```
75,978
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?
2008/09/16
[ "https://Stackoverflow.com/questions/75978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748/" ]
``` using System.Configuration; Configuration config = ConfigurationManager.OpenExeConfiguration("C:\Test.exe"); ``` You can then access the app settings, connection strings, etc from the config instance. This assumes of course that the config file is properly formatted and your app has read access to the directory. Notice the path is ***not*** "C:\Test.exe.config" The method looks for a config file associated with the file you specify. If you specify "C:\Test.exe.config" it will look for "C:\Test.exe.config.config" Kinda lame, but understandable, I guess. Reference here: <http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx>
You can set it by creating a new app domain: ``` AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ConfigurationFile = fileLocation; AppDomain add = AppDomain.CreateDomain("myNewAppDomain", securityInfo, domainSetup); ```
75,978
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?
2008/09/16
[ "https://Stackoverflow.com/questions/75978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748/" ]
It appears that you can use the [`AppDomain.SetData`](http://msdn.microsoft.com/en-us/library/37z40s1c.aspx) method to achieve this. The documentation states: > > You cannot insert or modify system entries with this method. > > > Regardless, doing so does appear to work. The documentation for the [`AppDomain.GetData`](http://msdn.microsoft.com/en-us/library/system.appdomain.getdata.aspx) method lists the system entries available, of interest is the `"APP_CONFIG_FILE"` entry. If we set the `"APP_CONFIG_FILE"` before any application settings are used, we can modify where the `app.config` is loaded from. For example: ``` public class Program { public static void Main() { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\Temp\test.config"); //... } } ``` I found this solution documented in [this blog](http://weblogs.asp.net/israelio/archive/2005/01/10/349825.aspx) and a more complete answer (to a related question) can be found [here](https://stackoverflow.com/a/6151688/142794).
You can set it by creating a new app domain: ``` AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ConfigurationFile = fileLocation; AppDomain add = AppDomain.CreateDomain("myNewAppDomain", securityInfo, domainSetup); ```
75,978
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?
2008/09/16
[ "https://Stackoverflow.com/questions/75978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748/" ]
You can set it by creating a new app domain: ``` AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ConfigurationFile = fileLocation; AppDomain add = AppDomain.CreateDomain("myNewAppDomain", securityInfo, domainSetup); ```
``` AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ConfigurationFile = @"D:\Mine\Company\"; string browserName = ConfigurationManager.AppSettings["browser"]; ```
75,978
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?
2008/09/16
[ "https://Stackoverflow.com/questions/75978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748/" ]
``` using System.Configuration; Configuration config = ConfigurationManager.OpenExeConfiguration("C:\Test.exe"); ``` You can then access the app settings, connection strings, etc from the config instance. This assumes of course that the config file is properly formatted and your app has read access to the directory. Notice the path is ***not*** "C:\Test.exe.config" The method looks for a config file associated with the file you specify. If you specify "C:\Test.exe.config" it will look for "C:\Test.exe.config.config" Kinda lame, but understandable, I guess. Reference here: <http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx>
It appears that you can use the [`AppDomain.SetData`](http://msdn.microsoft.com/en-us/library/37z40s1c.aspx) method to achieve this. The documentation states: > > You cannot insert or modify system entries with this method. > > > Regardless, doing so does appear to work. The documentation for the [`AppDomain.GetData`](http://msdn.microsoft.com/en-us/library/system.appdomain.getdata.aspx) method lists the system entries available, of interest is the `"APP_CONFIG_FILE"` entry. If we set the `"APP_CONFIG_FILE"` before any application settings are used, we can modify where the `app.config` is loaded from. For example: ``` public class Program { public static void Main() { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\Temp\test.config"); //... } } ``` I found this solution documented in [this blog](http://weblogs.asp.net/israelio/archive/2005/01/10/349825.aspx) and a more complete answer (to a related question) can be found [here](https://stackoverflow.com/a/6151688/142794).
75,978
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?
2008/09/16
[ "https://Stackoverflow.com/questions/75978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748/" ]
``` using System.Configuration; Configuration config = ConfigurationManager.OpenExeConfiguration("C:\Test.exe"); ``` You can then access the app settings, connection strings, etc from the config instance. This assumes of course that the config file is properly formatted and your app has read access to the directory. Notice the path is ***not*** "C:\Test.exe.config" The method looks for a config file associated with the file you specify. If you specify "C:\Test.exe.config" it will look for "C:\Test.exe.config.config" Kinda lame, but understandable, I guess. Reference here: <http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx>
``` AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ConfigurationFile = @"D:\Mine\Company\"; string browserName = ConfigurationManager.AppSettings["browser"]; ```
75,978
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?
2008/09/16
[ "https://Stackoverflow.com/questions/75978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2748/" ]
It appears that you can use the [`AppDomain.SetData`](http://msdn.microsoft.com/en-us/library/37z40s1c.aspx) method to achieve this. The documentation states: > > You cannot insert or modify system entries with this method. > > > Regardless, doing so does appear to work. The documentation for the [`AppDomain.GetData`](http://msdn.microsoft.com/en-us/library/system.appdomain.getdata.aspx) method lists the system entries available, of interest is the `"APP_CONFIG_FILE"` entry. If we set the `"APP_CONFIG_FILE"` before any application settings are used, we can modify where the `app.config` is loaded from. For example: ``` public class Program { public static void Main() { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\Temp\test.config"); //... } } ``` I found this solution documented in [this blog](http://weblogs.asp.net/israelio/archive/2005/01/10/349825.aspx) and a more complete answer (to a related question) can be found [here](https://stackoverflow.com/a/6151688/142794).
``` AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ConfigurationFile = @"D:\Mine\Company\"; string browserName = ConfigurationManager.AppSettings["browser"]; ```
35,650,551
In a perfect information environment, where we are able to know the state after an action, like playing chess, is there any reason to use Q learning not TD (temporal difference) learning? As far as I understand, TD learning will try to learn V(state) value, but Q learning will learn Q(state action value) value, which means Q learning learns slower (as state action combination is more than state only), is that correct?
2016/02/26
[ "https://Stackoverflow.com/questions/35650551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5985622/" ]
Q-Learning is a TD (temporal difference) learning method. I think you are trying to refer to TD(0) vs Q-learning. I would say it depends on your actions being deterministic or not. Even if you have the transition function, it can be expensive to decide which action to take in TD(0) as you need to calculate the expected value for each of the actions in each step. In Q-learning that would be summarized in the Q-value.
Q learning is a TD **control** algorithm, this means it tries to give you an optimal policy as you said. TD learning is more general in the sense that can include control algorithms and also only prediction methods of V for a fixed policy.
35,650,551
In a perfect information environment, where we are able to know the state after an action, like playing chess, is there any reason to use Q learning not TD (temporal difference) learning? As far as I understand, TD learning will try to learn V(state) value, but Q learning will learn Q(state action value) value, which means Q learning learns slower (as state action combination is more than state only), is that correct?
2016/02/26
[ "https://Stackoverflow.com/questions/35650551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5985622/" ]
Q-Learning is a TD (temporal difference) learning method. I think you are trying to refer to TD(0) vs Q-learning. I would say it depends on your actions being deterministic or not. Even if you have the transition function, it can be expensive to decide which action to take in TD(0) as you need to calculate the expected value for each of the actions in each step. In Q-learning that would be summarized in the Q-value.
Actually Q-learning is the process of using state-action pairs instead of just states. But that doesnt mean Q learning is different from TD. In TD(0) our agent takes one step(which could be one step in state-action pair or just state) and then updates it's Q-value. And same in n-step TD where our agent takes n steps and then updates the Q-values. Comparing TD and Q-learning isn't the right way. You can compare TD and SARSA algorithms instead. And TD and MonteCarlo
35,650,551
In a perfect information environment, where we are able to know the state after an action, like playing chess, is there any reason to use Q learning not TD (temporal difference) learning? As far as I understand, TD learning will try to learn V(state) value, but Q learning will learn Q(state action value) value, which means Q learning learns slower (as state action combination is more than state only), is that correct?
2016/02/26
[ "https://Stackoverflow.com/questions/35650551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5985622/" ]
Given a deterministic environment (or as you say, a "perfect" environment in which you are able to know the state after performing an action), I guess you can simulate the affect of all possible actions in a given state (i.e., compute all possible next states), and choose the action that achieves the next state with the maximum value V(state). However,it should be taken into account that both value functions V(state) and Q functions Q(state,action) are defined for a given policy. In some way, the value function can be considered as an average of the Q function, in the sense that V(s) "evaluates" the state s for all possible actions. So, to compute a good estimation of V(s) the agent still needs to perform all the possible actions in s. In conclusion, I think that although V(s) is simpler than Q(s,a), likely they need a similar quantity of experience (or time) to achieve a stable estimation. You can find more info about value (V and Q) functions in [this section](https://webdocs.cs.ualberta.ca/~sutton/book/ebook/node34.html) of the Sutton & Barto RL book.
Q learning is a TD **control** algorithm, this means it tries to give you an optimal policy as you said. TD learning is more general in the sense that can include control algorithms and also only prediction methods of V for a fixed policy.
35,650,551
In a perfect information environment, where we are able to know the state after an action, like playing chess, is there any reason to use Q learning not TD (temporal difference) learning? As far as I understand, TD learning will try to learn V(state) value, but Q learning will learn Q(state action value) value, which means Q learning learns slower (as state action combination is more than state only), is that correct?
2016/02/26
[ "https://Stackoverflow.com/questions/35650551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5985622/" ]
Given a deterministic environment (or as you say, a "perfect" environment in which you are able to know the state after performing an action), I guess you can simulate the affect of all possible actions in a given state (i.e., compute all possible next states), and choose the action that achieves the next state with the maximum value V(state). However,it should be taken into account that both value functions V(state) and Q functions Q(state,action) are defined for a given policy. In some way, the value function can be considered as an average of the Q function, in the sense that V(s) "evaluates" the state s for all possible actions. So, to compute a good estimation of V(s) the agent still needs to perform all the possible actions in s. In conclusion, I think that although V(s) is simpler than Q(s,a), likely they need a similar quantity of experience (or time) to achieve a stable estimation. You can find more info about value (V and Q) functions in [this section](https://webdocs.cs.ualberta.ca/~sutton/book/ebook/node34.html) of the Sutton & Barto RL book.
Actually Q-learning is the process of using state-action pairs instead of just states. But that doesnt mean Q learning is different from TD. In TD(0) our agent takes one step(which could be one step in state-action pair or just state) and then updates it's Q-value. And same in n-step TD where our agent takes n steps and then updates the Q-values. Comparing TD and Q-learning isn't the right way. You can compare TD and SARSA algorithms instead. And TD and MonteCarlo
50,336,489
In my Xamarin.Forms app, I want my `Grid` background color to be the same as the Navigation Bar's background color, something like this: ``` BackgroundColor="{StaticResource BarBackgroundColor}" ``` How can I do this?
2018/05/14
[ "https://Stackoverflow.com/questions/50336489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136506/" ]
You can retrieve the color of your navbar by casting your current page to a navigation page. Then you can simply change the color of your grid with that retrieved color. On the OnAppearing override of your page, use the following code to obtain your nav bar color: ``` protected override void OnAppearing() { var navPage = Application.Current.MainPage as NavigationPage; if (navPage != null) { var barColor = navPage.BarBackgroundColor; } base.OnAppearing(); } ``` Or, as someone mentioned earlier, you can predefine your colors in App.xaml and then simple use it from there. ``` <Style TargetType="NavigationPage"> <Setter Property="BarBackgroundColor" Value="Blue"/> <Setter Property="BarTextColor" Value="White"/> </Style> ```
The `BarBackgroundProperty` is an attached property from `NavigationPage`. Be aware that it can change on every page you push to your NavigationPage. Supposing you have an App.Current.MainPage set like this: ``` Page main = new MainPage(); Page navigation = new NavigationPage(main) { BarBackgroundColor = Color.Red, BarTextColor = Color.Yellow }; ``` The `navigation` page is the one that owns the `BarBackgroundColor` property. So if you want to retrieve it, you should get it from there. I can't see how you can get this through a `StaticResource`. I guess you can achieve this through a property on your viewmodel. For example: ``` public class MyViewModel { ... public Color BarBackgroundColor { get { return ((NavigationPage)App.Current.MainPage)?.BarBackgroundColor; } } ... } ``` And to use it on your XAML (Once MyViewModel {or some inheritance of it} is the `BindingContext` or your page): ``` BackgroundColor="{Binding BarBackgroundColor}" ``` I hope it helps.
50,336,489
In my Xamarin.Forms app, I want my `Grid` background color to be the same as the Navigation Bar's background color, something like this: ``` BackgroundColor="{StaticResource BarBackgroundColor}" ``` How can I do this?
2018/05/14
[ "https://Stackoverflow.com/questions/50336489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136506/" ]
You can retrieve the color of your navbar by casting your current page to a navigation page. Then you can simply change the color of your grid with that retrieved color. On the OnAppearing override of your page, use the following code to obtain your nav bar color: ``` protected override void OnAppearing() { var navPage = Application.Current.MainPage as NavigationPage; if (navPage != null) { var barColor = navPage.BarBackgroundColor; } base.OnAppearing(); } ``` Or, as someone mentioned earlier, you can predefine your colors in App.xaml and then simple use it from there. ``` <Style TargetType="NavigationPage"> <Setter Property="BarBackgroundColor" Value="Blue"/> <Setter Property="BarTextColor" Value="White"/> </Style> ```
You may use global style by placing the code below into App.xaml ``` <Application.Resources> <ResourceDictionary> <Color x:Key="NavigationPrimary">#1A237E</Color> <Style TargetType="NavigationPage"> <Setter Property="BarBackgroundColor" Value="{StaticResource NavigationPrimary}" /> <Setter Property="BarTextColor" Value="White" /> </Style> <Style TargetType="Grid"> <Setter Property="BackgroundColor" Value="{StaticResource NavigationPrimary}" /> </Style> </ResourceDictionary> </Application.Resources> ```
55,477
I have an old Peugeot Vagabond. It's been sitting out in the New Mexico weather for more than a few years. I'm wondering if it's worth trying to fix up, or if I should just go get a new bike? I tried to get the chain off (yes, with a chain tool), but it's not going to come off without considerable effort. Both sprockets are very rusted. And the derailers. I know I'll need new cables, brake pads, cable tube things. I'm pretty sure the rims are still true-ish, but I'll probably need new bearings. The handlebars also are significantly stiff when turning. I'm thinking the only thing still salvageable is the frame. Ask for more pictures if needed. (Please suggest appropriate tags. I tried.) [![enter image description here](https://i.stack.imgur.com/CgGkp.jpg)](https://i.stack.imgur.com/CgGkp.jpg) [![enter image description here](https://i.stack.imgur.com/8X2dq.jpg)](https://i.stack.imgur.com/8X2dq.jpg)
2018/06/23
[ "https://bicycles.stackexchange.com/questions/55477", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/38323/" ]
It might be salvageable but the cost of: * new chain ($10) * new tires and tubes ($25) * rear cluster (maybe; $20) * new brake cables and pads ($10) * new derailleur cables ($10) which is the minimal repair, is going to be around $75 in just parts, that’s if you get the dirt cheapest versions. If any of your bearings or hubs are seized, you’ll need to rebuild them which isn’t expensive in terms of parts (just bearings and grease), but is labor intensive and requires special tools. You’ll quickly get to the price of a good used bike if you have to pay labor and even if you do it yourself, you’ll quickly rack up a bill. I’d sell the frame to someone who wants to rebuild it and already has all the parts — or find a donor bike with a cracked frame that you can steal all the parts from.
Fundamentally, it’s the frame. If the frame just has a little cosmetic rust or paint problems, but is fundamentally sound, it will be definitely not-not-worth-it. You definitely need some new tires. A little Phil Wood grease in the right places helps a lot In many ways you have a lot of freedom. WD40? why not. A pressure wash? just take apart after. Patience an persistence works. Try riding it as soon as possible . Liking a bike is the real answer. It doesn’t need to be perfect and you should know in an hour worth of riding. Does it feel like it can go faster. How does it feel in a turn.
55,477
I have an old Peugeot Vagabond. It's been sitting out in the New Mexico weather for more than a few years. I'm wondering if it's worth trying to fix up, or if I should just go get a new bike? I tried to get the chain off (yes, with a chain tool), but it's not going to come off without considerable effort. Both sprockets are very rusted. And the derailers. I know I'll need new cables, brake pads, cable tube things. I'm pretty sure the rims are still true-ish, but I'll probably need new bearings. The handlebars also are significantly stiff when turning. I'm thinking the only thing still salvageable is the frame. Ask for more pictures if needed. (Please suggest appropriate tags. I tried.) [![enter image description here](https://i.stack.imgur.com/CgGkp.jpg)](https://i.stack.imgur.com/CgGkp.jpg) [![enter image description here](https://i.stack.imgur.com/8X2dq.jpg)](https://i.stack.imgur.com/8X2dq.jpg)
2018/06/23
[ "https://bicycles.stackexchange.com/questions/55477", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/38323/" ]
It might be salvageable but the cost of: * new chain ($10) * new tires and tubes ($25) * rear cluster (maybe; $20) * new brake cables and pads ($10) * new derailleur cables ($10) which is the minimal repair, is going to be around $75 in just parts, that’s if you get the dirt cheapest versions. If any of your bearings or hubs are seized, you’ll need to rebuild them which isn’t expensive in terms of parts (just bearings and grease), but is labor intensive and requires special tools. You’ll quickly get to the price of a good used bike if you have to pay labor and even if you do it yourself, you’ll quickly rack up a bill. I’d sell the frame to someone who wants to rebuild it and already has all the parts — or find a donor bike with a cracked frame that you can steal all the parts from.
I've seen far worse. Go to a paint store and buy some "wood bleach". Be sure to get the stuff that's a liquid and contains "oxalic acid". Put some of that in a spray bottle and spray down all the rusted bits with it, getting them thoroughly wetted. Wipe well with paper towel or rag. Next spray well with WD-40 & wipe. Finally, oil thoroughly with a good "medium" chain oil, wipe, then oil again. Of course, you need new tires, and the bearings may need to be taken apart and greased, but that's for another question.
55,477
I have an old Peugeot Vagabond. It's been sitting out in the New Mexico weather for more than a few years. I'm wondering if it's worth trying to fix up, or if I should just go get a new bike? I tried to get the chain off (yes, with a chain tool), but it's not going to come off without considerable effort. Both sprockets are very rusted. And the derailers. I know I'll need new cables, brake pads, cable tube things. I'm pretty sure the rims are still true-ish, but I'll probably need new bearings. The handlebars also are significantly stiff when turning. I'm thinking the only thing still salvageable is the frame. Ask for more pictures if needed. (Please suggest appropriate tags. I tried.) [![enter image description here](https://i.stack.imgur.com/CgGkp.jpg)](https://i.stack.imgur.com/CgGkp.jpg) [![enter image description here](https://i.stack.imgur.com/8X2dq.jpg)](https://i.stack.imgur.com/8X2dq.jpg)
2018/06/23
[ "https://bicycles.stackexchange.com/questions/55477", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/38323/" ]
I've seen far worse. Go to a paint store and buy some "wood bleach". Be sure to get the stuff that's a liquid and contains "oxalic acid". Put some of that in a spray bottle and spray down all the rusted bits with it, getting them thoroughly wetted. Wipe well with paper towel or rag. Next spray well with WD-40 & wipe. Finally, oil thoroughly with a good "medium" chain oil, wipe, then oil again. Of course, you need new tires, and the bearings may need to be taken apart and greased, but that's for another question.
Fundamentally, it’s the frame. If the frame just has a little cosmetic rust or paint problems, but is fundamentally sound, it will be definitely not-not-worth-it. You definitely need some new tires. A little Phil Wood grease in the right places helps a lot In many ways you have a lot of freedom. WD40? why not. A pressure wash? just take apart after. Patience an persistence works. Try riding it as soon as possible . Liking a bike is the real answer. It doesn’t need to be perfect and you should know in an hour worth of riding. Does it feel like it can go faster. How does it feel in a turn.
66,965,475
I'm trying to create a simple ontology, following the tutorial on the official website. The code runs smoothly and everything seems fine when running this code: ``` import owlready2 owlready2.JAVA_EXE = r"my-path-to-java-exe" # new.owl is a non-existing file and therefore onto has no pre-defined classes # if you know of any nicer way to define an ontology, I'd appreciate it onto = get_ontology("new.owl") with onto: class Drug(Thing): pass class number_of_tablets(Drug >> int, FunctionalProperty): pass # Creating some properties class price(Drug >> float, FunctionalProperty): pass class price_per_tablet(Drug >> float, FunctionalProperty): pass rule = Imp() # Rule: "Drug instance ?d AND price of ?d is ?p AND drug ?d has number_of_tablets = ?n # AND ?r = ?p/?n -> Drug ?d has price_per_tablet = ?r" rule.set_as_rule("""Drug(?d), price(?d,?p), number_of_tablets(?d,?n), divide(?r, ?p, ?n) -> price_per_tablet(?d, ?r)""") # Create an instance "drug" with properties defined in brackets drug = Drug(number_of_tablets = 10, price = 25.0) #print(drug.iri) # Syncing the reasoner infers new info sync_reasoner_pellet(infer_property_values = True, infer_data_property_values = True) # New property price_per_tablet is now added to drug and we can use it normally: print(drug.price_per_tablet) # Save this ontology with rules in the same folder, filename: test onto.save(file = "test", format = "rdfxml") ``` Problem: When I open the resulting file "test" in Protégé, my instance "drug1" is **not** a part of the previously defined class Drug but of a new class of the same name *Drug* (I'll always denote this one in italic so it doesn't get confusing). Interestingly, this new class *Drug* is not even a subclass of owl:Thing class. I'm not sure what's the problem. According to Protégé, the defined class Drug has IRI: **file:/C:/.../new#Drug**, and the other class *Drug* has IRI: **new#Drug**. When I checked IRIs of all the described objects in Python, they were all synchronized. I'm very confused about what happened here. I checked the "test" file and the part concerning this instance is: ``` <Drug rdf:about="#drug1"> <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#NamedIndividual"/> <number_of_tablets rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">10</number_of_tablets> <price rdf:datatype="http://www.w3.org/2001/XMLSchema#decimal">25.0</price> <price_per_tablet rdf:datatype="http://www.w3.org/2001/XMLSchema#decimal">2.5</price_per_tablet> </Drug> ``` This is confusing because when I opened the file PizzaTutorial.owl from the famous Pizza tutorial, an instance was defined like this: ``` <owl:NamedIndividual rdf:about="http://www.semanticweb.org/pizzatutorial/ontologies/2020/PizzaTutorial#AmericanaHotPizza2"> <rdf:type rdf:resource="http://www.semanticweb.org/pizzatutorial/ontologies/2020/PizzaTutorial#AmericanaHotPizza"/> <hasCaloricContent rdf:datatype="http://www.w3.org/2001/XMLSchema#integer">675</hasCaloricContent> </owl:NamedIndividual> ``` What happened?! Another question: When I inspected the individual in Protégé, I noticed that the properties *number\_of\_tablets* and *price* were added as Annotations, and not as Data Properties. I assume that this is the reason why my SWRL rule (which was correctly exported) doesn't conclude the *price\_per\_tablet* property for this individual when I remove the sync\_reasoner line. Please comment on anything you notice is wrong, I'm a beginner in ontology programming and in both tools and I would very much appreciate your help!
2021/04/06
[ "https://Stackoverflow.com/questions/66965475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15292369/" ]
I found an answer! The problem was in the base IRI, "new.owl" is not acceptable. IRI must be formatted as a link - even if it's a fake one. For example, if IRI is "http://test.org/new.owl", my code works perfectly.
Regarding your extra question, there seems to be an error in how `rdfxml` is saved. Switching to `ntriples` format solves the problem with data and object properties being written out properly (exported using Owlready2 v0.37 and imported in Protégé v5.5.0)
2,693,336
I installed Xcode a long time ago. Apparently I didn't check back then the "UNIX Development Support" checkbox. Now I want to have them but when I click on the installation this is what appears: ![disabled](https://i.stack.imgur.com/fKJ4z.png) The *UNIX Development Support* check box is disabled **Q:** How can I install the UNIX Development Support? Is there a way to run some script that creates all the needed links from `/Developer/` to `/usr/bin` ? **EDIT:** Note: This is for old Xcode 3. Screens and tool names differ for Xcode 4 ("Unix Command Line Tools")
2010/04/22
[ "https://Stackoverflow.com/questions/2693336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
In xcode > 4.5 select Preferences -> Download -> Components -> Command Line Tools
You can also right click the "Install Xcode X.X" icon and Show Package Contents then in `Contents > Resources > Packages`, you will find many packages from among which resides DeveloperToolsCLI.pkg. This package installs the files you want in /usr/bin.
2,693,336
I installed Xcode a long time ago. Apparently I didn't check back then the "UNIX Development Support" checkbox. Now I want to have them but when I click on the installation this is what appears: ![disabled](https://i.stack.imgur.com/fKJ4z.png) The *UNIX Development Support* check box is disabled **Q:** How can I install the UNIX Development Support? Is there a way to run some script that creates all the needed links from `/Developer/` to `/usr/bin` ? **EDIT:** Note: This is for old Xcode 3. Screens and tool names differ for Xcode 4 ("Unix Command Line Tools")
2010/04/22
[ "https://Stackoverflow.com/questions/2693336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
With Xcode 4.3 (from Apple App Store) you can enable Unix Command Line Tools via the Xcode Menu: Preferences -> Download -> Components
You should uninstall and then re-install the developer tools. To uninstall the tools, run the following command in Terminal: ``` sudo /Developer/Library/uninstall-devtools --mode=all ```
2,693,336
I installed Xcode a long time ago. Apparently I didn't check back then the "UNIX Development Support" checkbox. Now I want to have them but when I click on the installation this is what appears: ![disabled](https://i.stack.imgur.com/fKJ4z.png) The *UNIX Development Support* check box is disabled **Q:** How can I install the UNIX Development Support? Is there a way to run some script that creates all the needed links from `/Developer/` to `/usr/bin` ? **EDIT:** Note: This is for old Xcode 3. Screens and tool names differ for Xcode 4 ("Unix Command Line Tools")
2010/04/22
[ "https://Stackoverflow.com/questions/2693336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
Finally. I had to download from [Apple's website](http://developer.apple.com) the latest version of Xcode 3 (3.2) along with the iPhone SDK that I won't use in the near feature. This time the "UNIX Development Support" was enabled: ![Xcode 3.2 Installation](https://i.stack.imgur.com/iEWdx.png) So now I can compile from the command line!
You can also right click the "Install Xcode X.X" icon and Show Package Contents then in `Contents > Resources > Packages`, you will find many packages from among which resides DeveloperToolsCLI.pkg. This package installs the files you want in /usr/bin.
2,693,336
I installed Xcode a long time ago. Apparently I didn't check back then the "UNIX Development Support" checkbox. Now I want to have them but when I click on the installation this is what appears: ![disabled](https://i.stack.imgur.com/fKJ4z.png) The *UNIX Development Support* check box is disabled **Q:** How can I install the UNIX Development Support? Is there a way to run some script that creates all the needed links from `/Developer/` to `/usr/bin` ? **EDIT:** Note: This is for old Xcode 3. Screens and tool names differ for Xcode 4 ("Unix Command Line Tools")
2010/04/22
[ "https://Stackoverflow.com/questions/2693336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
In xcode > 4.5 select Preferences -> Download -> Components -> Command Line Tools
In the Xcode `.dmg` file, there is a `Packages` folder. You can manually install `DeveloperToolsCLI.pkg` which creates the link in `/usr/bin`. *At least, it worked for me.*
2,693,336
I installed Xcode a long time ago. Apparently I didn't check back then the "UNIX Development Support" checkbox. Now I want to have them but when I click on the installation this is what appears: ![disabled](https://i.stack.imgur.com/fKJ4z.png) The *UNIX Development Support* check box is disabled **Q:** How can I install the UNIX Development Support? Is there a way to run some script that creates all the needed links from `/Developer/` to `/usr/bin` ? **EDIT:** Note: This is for old Xcode 3. Screens and tool names differ for Xcode 4 ("Unix Command Line Tools")
2010/04/22
[ "https://Stackoverflow.com/questions/2693336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
With Xcode 4.3 (from Apple App Store) you can enable Unix Command Line Tools via the Xcode Menu: Preferences -> Download -> Components
Finally. I had to download from [Apple's website](http://developer.apple.com) the latest version of Xcode 3 (3.2) along with the iPhone SDK that I won't use in the near feature. This time the "UNIX Development Support" was enabled: ![Xcode 3.2 Installation](https://i.stack.imgur.com/iEWdx.png) So now I can compile from the command line!
2,693,336
I installed Xcode a long time ago. Apparently I didn't check back then the "UNIX Development Support" checkbox. Now I want to have them but when I click on the installation this is what appears: ![disabled](https://i.stack.imgur.com/fKJ4z.png) The *UNIX Development Support* check box is disabled **Q:** How can I install the UNIX Development Support? Is there a way to run some script that creates all the needed links from `/Developer/` to `/usr/bin` ? **EDIT:** Note: This is for old Xcode 3. Screens and tool names differ for Xcode 4 ("Unix Command Line Tools")
2010/04/22
[ "https://Stackoverflow.com/questions/2693336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
You can also right click the "Install Xcode X.X" icon and Show Package Contents then in `Contents > Resources > Packages`, you will find many packages from among which resides DeveloperToolsCLI.pkg. This package installs the files you want in /usr/bin.
You should uninstall and then re-install the developer tools. To uninstall the tools, run the following command in Terminal: ``` sudo /Developer/Library/uninstall-devtools --mode=all ```
2,693,336
I installed Xcode a long time ago. Apparently I didn't check back then the "UNIX Development Support" checkbox. Now I want to have them but when I click on the installation this is what appears: ![disabled](https://i.stack.imgur.com/fKJ4z.png) The *UNIX Development Support* check box is disabled **Q:** How can I install the UNIX Development Support? Is there a way to run some script that creates all the needed links from `/Developer/` to `/usr/bin` ? **EDIT:** Note: This is for old Xcode 3. Screens and tool names differ for Xcode 4 ("Unix Command Line Tools")
2010/04/22
[ "https://Stackoverflow.com/questions/2693336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
With Xcode 4.3 (from Apple App Store) you can enable Unix Command Line Tools via the Xcode Menu: Preferences -> Download -> Components
In xcode > 4.5 select Preferences -> Download -> Components -> Command Line Tools
2,693,336
I installed Xcode a long time ago. Apparently I didn't check back then the "UNIX Development Support" checkbox. Now I want to have them but when I click on the installation this is what appears: ![disabled](https://i.stack.imgur.com/fKJ4z.png) The *UNIX Development Support* check box is disabled **Q:** How can I install the UNIX Development Support? Is there a way to run some script that creates all the needed links from `/Developer/` to `/usr/bin` ? **EDIT:** Note: This is for old Xcode 3. Screens and tool names differ for Xcode 4 ("Unix Command Line Tools")
2010/04/22
[ "https://Stackoverflow.com/questions/2693336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
In the Xcode `.dmg` file, there is a `Packages` folder. You can manually install `DeveloperToolsCLI.pkg` which creates the link in `/usr/bin`. *At least, it worked for me.*
You should uninstall and then re-install the developer tools. To uninstall the tools, run the following command in Terminal: ``` sudo /Developer/Library/uninstall-devtools --mode=all ```
2,693,336
I installed Xcode a long time ago. Apparently I didn't check back then the "UNIX Development Support" checkbox. Now I want to have them but when I click on the installation this is what appears: ![disabled](https://i.stack.imgur.com/fKJ4z.png) The *UNIX Development Support* check box is disabled **Q:** How can I install the UNIX Development Support? Is there a way to run some script that creates all the needed links from `/Developer/` to `/usr/bin` ? **EDIT:** Note: This is for old Xcode 3. Screens and tool names differ for Xcode 4 ("Unix Command Line Tools")
2010/04/22
[ "https://Stackoverflow.com/questions/2693336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
Finally. I had to download from [Apple's website](http://developer.apple.com) the latest version of Xcode 3 (3.2) along with the iPhone SDK that I won't use in the near feature. This time the "UNIX Development Support" was enabled: ![Xcode 3.2 Installation](https://i.stack.imgur.com/iEWdx.png) So now I can compile from the command line!
In the Xcode `.dmg` file, there is a `Packages` folder. You can manually install `DeveloperToolsCLI.pkg` which creates the link in `/usr/bin`. *At least, it worked for me.*
2,693,336
I installed Xcode a long time ago. Apparently I didn't check back then the "UNIX Development Support" checkbox. Now I want to have them but when I click on the installation this is what appears: ![disabled](https://i.stack.imgur.com/fKJ4z.png) The *UNIX Development Support* check box is disabled **Q:** How can I install the UNIX Development Support? Is there a way to run some script that creates all the needed links from `/Developer/` to `/usr/bin` ? **EDIT:** Note: This is for old Xcode 3. Screens and tool names differ for Xcode 4 ("Unix Command Line Tools")
2010/04/22
[ "https://Stackoverflow.com/questions/2693336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
In xcode > 4.5 select Preferences -> Download -> Components -> Command Line Tools
You should uninstall and then re-install the developer tools. To uninstall the tools, run the following command in Terminal: ``` sudo /Developer/Library/uninstall-devtools --mode=all ```
45,350,160
I'm running PHP 7 with the php\_mongodb-1.2.2-7.0-nts-vc14-x64 driver. ``` $ar = new \MongoDB\BSON\UTCDateTime(strtotime('2017-07-27 06:17:25.123000') * 1000); ``` Output of above statement is: > > ISODate("2017-07-27T06:17:25.000+0000") > > > but I need milliseconds also like: > > ISODate("2017-07-27T06:17:25.123+0000") > > > Since I'm so new I can't seem to figure out how to fix this.
2017/07/27
[ "https://Stackoverflow.com/questions/45350160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6841833/" ]
The `Where` method has to return a boolean value. ``` _UoW.OrganisationRepo.Where(x => new GeoCoordinate(x.Latitude, x.Longitude)) ``` Maybe you meant to use a `.Select` there? Would the following code work? ``` _UoW.OrganisationRepo.Select(x => new GeoCoordinate(x.Latitude, x.Longitude)) .Where(x => x.GetDistanceTo(userLocation) < radius).ToList(); ``` Be aware that Entity Framework tries to generate some SQL from the expression provided. I'm afraid that `x.GetDistanceTo(userLocation)` might not work inside the .Where expression, unless you cast it to an `IEnumerable`, or call .`AsEnumerable()` or `.ToList()` or `.ToArray()` before calling `.Where`. Or maybe EF is smart enough to see that `GeoCoordinate` is not mapped to a table, and then stop generating the SQL right there. ### Edit The code you commented won't work: ``` _UoW.OrganisationRepo.All.Select(x => new GeoCoordinate(x.Latitude, x.Longitude).GetDistanceTo(userLocation) < radius).ToList() ``` Notice that you're selecting a list of bools because you're selecting the results instead of filtering by them. You won't know which organizations are within the radius. That's why we use .Select and .Where separately. Try something like this: ``` _UoW.OrganisationRepo.All .Select(x => new GeoCoordinate(x.Latitude, x.Longitude)) .ToEnumerable() //or .ToList() or .ToArray(), make sure it's outside of EF's reach (prevent SQL generation for this) .Where(x=> x.GetDistanceTo(userLocation) < radius).ToList() ``` However, if you want to know which organizations are within the radius, you'll need to carry more information along the path. ``` var nearbyOrganizations = _UoW.OrganisationRepo.All.ToList() .Select(x => new { //use an anonymous type or any type you want Org = x, Distance = new GeoCoordinate(x.Latitude, x.Longitude).GetDistanceTo(userLocation) }) //it's probably outside EF's SQL generation step by now, but you could add one more .Select here that does the math if it fails (return the GeoCoordinate object) .Where(x=> x.Distance < radius) .ToList(); ``` Seems like it would be useful for you to know more about .Where and .Select. They're super useful. .Where is essentialy a filter, and .Select transforms objects. And due to anonymous types, you can do whatever you want. Notice that this will fetch all objects from the database. You probably want to use native features of the database to work with geographical data, and EF probably supports it.
I think your problem is with your first `Where` as you are trying to create a new GeoCoordinate class and `Where` is expecting a bool output from the lambda not a GeoCoordinate instance. I would suggest making the following change: ``` var result = _UoW.OrganisationRepo.Where(x => new GeoCoordinate(x.Latitude, x.Longitude).GetDistanceTo(userLocation) < radius).ToList(); ``` This will give you a list of Organisations back within the radius you are interested in. **Update** The prior won't work with IQueryable as the provider will not be able to create an SQL query because the .GetDistanceTo function is not known within SQL. As an alternative could you not use the Spatial Data types in EF 5 onwards? This blog post by Rick Strahl gives an example of querying geography data stored in SQL by distance from a given location <https://weblog.west-wind.com/posts/2012/jun/21/basic-spatial-data-with-sql-server-and-entity-framework-50>
49,551,377
When I use docker run command, the variable "`SPRING_PROFILES_ACTIVE`" is right, but "`SPRING_MAIN_WEB-APPLICATION-TYPE`" does not work, how to pass "`SPRING_MAIN_WEB-APPLICATION-TYPE`" to dokcer image? ``` sudo docker run -d -e SPRING_PROFILES_ACTIVE=product -e SPRING_MAIN_WEB-APPLICATION-TYPE=SERVLET -e SERVER_PORT=6789 --network mongo_network ```
2018/03/29
[ "https://Stackoverflow.com/questions/49551377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1147265/" ]
Use the xDomain or yDomain props on the XYPlot component `<XYPlot xDomain={[0, 50]}`
From their docs about scales at: <https://uber.github.io/react-vis/documentation/general-principles/scales-and-data> "To redefine a scale, you must pass a prop to the series that uses that scale. The prop names are based on the name of the attribute: name + Domain, name + Range, name + Type, name + Padding (for instance: yDomain, colorType, xRange)." So for your purpose, you would set `<XYPlot yDomain=[0,100]></XYPlot>`
1,065,999
My apache2 service has `PrivateTmp=true`. When the service first starts it works fine, but after a few days, writing to /tmp fails with "no such file or directory". To debug I've tried running `nsenter -t <apache-pid> -m bash` and I've confirmed that `/tmp` exists, but `mkdir /tmp/test` fails with "no such file or directory". I'd rather not remove the `PrivateTmp=true` directive. If I restart the service it starts working again. The mount line for /tmp inside says it is mounted to /dev/nvme0n1 which seems odd to me, but that is the case both when /tmp is working immediately after starting the service and when it is not writable. Anyone know why /tmp suddenly becomes unwritable?
2021/06/07
[ "https://serverfault.com/questions/1065999", "https://serverfault.com", "https://serverfault.com/users/381850/" ]
I found the problem. I had `tmpreaper` enabled and configured to clean up old files and directories under `/tmp`. I didn't have an exclude rule for `/tmp/systemd-private-*`, so tmpreaper was deleting the private tmp directory for apache2.
As I understand it `PrivateTmp=true` forbids exactly what you tried when you were debugging. The daemon will create it's own subdirectory and change it's namespace accordingly. As your problem only occurs after some time I have the following advice: Make sure the application cleans up and does not store large files in the virtual `/tmp` directory. As far as I know this directory is using RAM, no persistent file system. You have limited space here. You might want to log the /tmp directories size for a while. If it keeps growing that's the issue.
22,219,784
I successfully install cocoapods 0.29, and after attempting to run pod setup, it claims I must install 0.29. Can someone please explain this to me?? ```none Successfully installed cocoapods-0.29.0 Parsing documentation for cocoapods-0.29.0 1 gem installed bash-3.2$ pod setup Setting up CocoaPods master repo Already up-to-date. [!] The `master` repo requires CocoaPods 0.29.0 - Update CocoaPods, or checkout the appropriate tag in the repo. ``` UPDATE: After updating cocoapods, I am able to run pod setup, however still getting some error about 0.29 not being installed: (And also, when running pod --version, it says I'm on 0.22.3???) ```none bash-3.2$ sudo gem update cocoapods Updating installed gems Nothing to update bash-3.2$ sudo pod setup Setting up CocoaPods master repo Already up-to-date. Setup completed (read-only access) bash-3.2$ pod install Setting up CocoaPods master repo Already up-to-date. [!] The `master` repo requires CocoaPods 0.29.0 - Update CocoaPods, or checkout the appropriate tag in the repo. /Users/me/.rvm/gems/ruby-2.0.0-p247/gems/claide-0.3.2/lib/claide/command.rb:210:in `rescue in run': undefined method `verbose?' for nil:NilClass (NoMethodError) bash-3.2$ pod --version 0.22.3 ```
2014/03/06
[ "https://Stackoverflow.com/questions/22219784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014164/" ]
navigate this file and delete it **/Users/me/.rvm/gems/ruby-2.0.0-p247/gems/claide-0.3.2/lib/claide** then open ur terminal add this **sudo gem update** its worked for me 100%
Based on your comment ``` $ type -a pod pod is /Users/me/.rvm/gems/ruby-2.0.0-p247/bin/pod pod is /Users/me/.rvm/rubies/ruby-2.0.0-p247/bin/pod pod is /usr/bin/pod ``` it appears you have multiple installations of Cocoapods: one with `gem install cocoapods` in `/Users/me/.rvm/gems/ruby-2.0.0-p247/bin/pod` and another with `sudo gem install cocoapods` in `/usr/bin/pod` (I don't know what `/Users/me/.rvm/rubies/ruby-2.0.0-p247/bin/pod` is). So running `gem install cocoapods` should fix the problem by updating the install in `/Users/me/.rvm/gems/ruby-2.0.0-p247/bin/pod`. I'd recommend cleaning up your install though by removing either the global (with `sudo`) one or the local (without `sudo`) one. **EDIT**: Here's my Jenkins install: Installed Cocoapods with `gem install cocoapods`. Running `type -a pod` yield: ``` $ type -a pod pod is /Users/Shared/Jenkins/Home/gems/bin/pod ``` In the Jenkins global config, I added the following environment variables: ``` GEM_HOME = $JENKINS_HOME/gems GEM_PATH = $JENKINS_HOME/gems:/usr/lib/ruby/gems/1.8/ PATH = $PATH:$HOME/gems/bin ``` I added a "Shell script" build step to each project with: ``` POD_PROJECT_DIRECTORY='MyProject' # Directory where the Podfile is. Probably the same as Xcode plugin's "Xcode Project Directory". cd "$WORKSPACE/$POD_PROJECT_DIRECTORY" # rm -rf ./Pods # Uncomment this line if you want to re-download all the Pods each time pod install --no-color ```
22,219,784
I successfully install cocoapods 0.29, and after attempting to run pod setup, it claims I must install 0.29. Can someone please explain this to me?? ```none Successfully installed cocoapods-0.29.0 Parsing documentation for cocoapods-0.29.0 1 gem installed bash-3.2$ pod setup Setting up CocoaPods master repo Already up-to-date. [!] The `master` repo requires CocoaPods 0.29.0 - Update CocoaPods, or checkout the appropriate tag in the repo. ``` UPDATE: After updating cocoapods, I am able to run pod setup, however still getting some error about 0.29 not being installed: (And also, when running pod --version, it says I'm on 0.22.3???) ```none bash-3.2$ sudo gem update cocoapods Updating installed gems Nothing to update bash-3.2$ sudo pod setup Setting up CocoaPods master repo Already up-to-date. Setup completed (read-only access) bash-3.2$ pod install Setting up CocoaPods master repo Already up-to-date. [!] The `master` repo requires CocoaPods 0.29.0 - Update CocoaPods, or checkout the appropriate tag in the repo. /Users/me/.rvm/gems/ruby-2.0.0-p247/gems/claide-0.3.2/lib/claide/command.rb:210:in `rescue in run': undefined method `verbose?' for nil:NilClass (NoMethodError) bash-3.2$ pod --version 0.22.3 ```
2014/03/06
[ "https://Stackoverflow.com/questions/22219784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014164/" ]
Based on your comment ``` $ type -a pod pod is /Users/me/.rvm/gems/ruby-2.0.0-p247/bin/pod pod is /Users/me/.rvm/rubies/ruby-2.0.0-p247/bin/pod pod is /usr/bin/pod ``` it appears you have multiple installations of Cocoapods: one with `gem install cocoapods` in `/Users/me/.rvm/gems/ruby-2.0.0-p247/bin/pod` and another with `sudo gem install cocoapods` in `/usr/bin/pod` (I don't know what `/Users/me/.rvm/rubies/ruby-2.0.0-p247/bin/pod` is). So running `gem install cocoapods` should fix the problem by updating the install in `/Users/me/.rvm/gems/ruby-2.0.0-p247/bin/pod`. I'd recommend cleaning up your install though by removing either the global (with `sudo`) one or the local (without `sudo`) one. **EDIT**: Here's my Jenkins install: Installed Cocoapods with `gem install cocoapods`. Running `type -a pod` yield: ``` $ type -a pod pod is /Users/Shared/Jenkins/Home/gems/bin/pod ``` In the Jenkins global config, I added the following environment variables: ``` GEM_HOME = $JENKINS_HOME/gems GEM_PATH = $JENKINS_HOME/gems:/usr/lib/ruby/gems/1.8/ PATH = $PATH:$HOME/gems/bin ``` I added a "Shell script" build step to each project with: ``` POD_PROJECT_DIRECTORY='MyProject' # Directory where the Podfile is. Probably the same as Xcode plugin's "Xcode Project Directory". cd "$WORKSPACE/$POD_PROJECT_DIRECTORY" # rm -rf ./Pods # Uncomment this line if you want to re-download all the Pods each time pod install --no-color ```
I found the mismatch of version reported by 'pod --version' and what I was seeing when I updated to be mystifying. Then I realized I had more than one ruby installed on my machine. I changed my $PATH so that the ruby I needed to use came first (e.g. /usr/local/opt/ruby/bin): In a new shell I found that 'pod --version' started reporting the '0.29.0' version I wanted.
22,219,784
I successfully install cocoapods 0.29, and after attempting to run pod setup, it claims I must install 0.29. Can someone please explain this to me?? ```none Successfully installed cocoapods-0.29.0 Parsing documentation for cocoapods-0.29.0 1 gem installed bash-3.2$ pod setup Setting up CocoaPods master repo Already up-to-date. [!] The `master` repo requires CocoaPods 0.29.0 - Update CocoaPods, or checkout the appropriate tag in the repo. ``` UPDATE: After updating cocoapods, I am able to run pod setup, however still getting some error about 0.29 not being installed: (And also, when running pod --version, it says I'm on 0.22.3???) ```none bash-3.2$ sudo gem update cocoapods Updating installed gems Nothing to update bash-3.2$ sudo pod setup Setting up CocoaPods master repo Already up-to-date. Setup completed (read-only access) bash-3.2$ pod install Setting up CocoaPods master repo Already up-to-date. [!] The `master` repo requires CocoaPods 0.29.0 - Update CocoaPods, or checkout the appropriate tag in the repo. /Users/me/.rvm/gems/ruby-2.0.0-p247/gems/claide-0.3.2/lib/claide/command.rb:210:in `rescue in run': undefined method `verbose?' for nil:NilClass (NoMethodError) bash-3.2$ pod --version 0.22.3 ```
2014/03/06
[ "https://Stackoverflow.com/questions/22219784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014164/" ]
navigate this file and delete it **/Users/me/.rvm/gems/ruby-2.0.0-p247/gems/claide-0.3.2/lib/claide** then open ur terminal add this **sudo gem update** its worked for me 100%
I found the mismatch of version reported by 'pod --version' and what I was seeing when I updated to be mystifying. Then I realized I had more than one ruby installed on my machine. I changed my $PATH so that the ruby I needed to use came first (e.g. /usr/local/opt/ruby/bin): In a new shell I found that 'pod --version' started reporting the '0.29.0' version I wanted.
47,150,076
So I'm wondering if/how I can use a value in a object as a arg in a function ex: ``` var mousePos = { chaos: (-950, 22) } console.log(mousePos.chaos) // chaos mouse.Move(mousePos.chaos) // which would take two args, and then output Invalid number of arguments. ```
2017/11/07
[ "https://Stackoverflow.com/questions/47150076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Yes you can if you use an array and `Function.prototype.apply` ``` var mousePos = { chaos: [-950, 22] } mouse.Move.apply(mouse, mousePos.chaos) ``` If you are fancy and are using Node or Babel, you can also use spread syntax: ``` mose.Move(...mousePos.chaos) ```
You are looking for a single object with two value (x,y) for mouse position. so manage your object like key/value base array. ``` var mousePos = { chaos: {x : -950, y:22} }; mouse.move(mousePos.chaos.x,mousePos.chaos.y) // equivalent to mouse.move(-950,22) ```
47,150,076
So I'm wondering if/how I can use a value in a object as a arg in a function ex: ``` var mousePos = { chaos: (-950, 22) } console.log(mousePos.chaos) // chaos mouse.Move(mousePos.chaos) // which would take two args, and then output Invalid number of arguments. ```
2017/11/07
[ "https://Stackoverflow.com/questions/47150076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I think you're looking for an array and [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator): ``` var mousePos = { chaos: [-950, 22] }; console.log(mousePos.chaos) // [-950, 22] mouse.move(...mousePos.chaos) // equivalent to `mouse.move(-950, 22)` ```
You are looking for a single object with two value (x,y) for mouse position. so manage your object like key/value base array. ``` var mousePos = { chaos: {x : -950, y:22} }; mouse.move(mousePos.chaos.x,mousePos.chaos.y) // equivalent to mouse.move(-950,22) ```
290,405
Where I define Cyclomatic complexity density as: ``` Cyclomatic complexity density = Cyclomatic complexity / Lines of code ``` I was reading previous discussions about cyclomatic complexity and there seems to be a sort of consensus that it has mixed usefulness, and as such there probably isn't a strong motive for using it over a simple lines of code (LOC) metric. I.e. As the size of a class or method increases beyond some threshold the probability of defects and of there having been poor design choices goes up. It seems to me that cyclomatic complexity (CC) and LOC will tend to be correlated, hence the argument for use of the simpler LOC metric. However, there may be outlier cases where complexity is higher within some region of code, i.e. there is a higher density of execution branches in some pieces code (compared to the average) and I'm wondering if that will tend to be correlated with the presence of defects. Is there any evidence for or against, or are there any experiences around the use of such a complexity density metric? Or perhaps a better metric is to have both a LOC and a CC threshold, and we consider passing either threshold as bad.
2015/07/21
[ "https://softwareengineering.stackexchange.com/questions/290405", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/32728/" ]
As lxrec pointed out, it'll vary from codebase to codebase. Some applications will allow you to put those kind of business logic into SQL Functions and/or queries and allow you to run those anytime you need to show those values to the user. Sometimes it may seem stupid, but it's better to code for correctness than performance as a primary objective. In your sample, if you're showing the value of the area for a user in a webform, you'd have to: ``` 1) Do a post/get to the server with the values of x and y; 2) The server would have to create a query to the DB Server to run the calculations; 3) The DB server would make the calculations and return; 4) The webserver would return the POST or GET to the user; 5) Final result shown. ``` It's stupid for simple things like the one on the sample, but it may be necessary to more complex stuff like calculating the IRR of an investment of a client in a banking system. **Code for correctness**. If your software is correct, but slow, you'll have chances to optimize where you need (after profiling). If that means keeping some of the business logic in the database, so be it. That's why we have refactoring techniques. If it becomes slow, or unresponsive, than you may have some optimizations to do, like violating the DRY principle, which is not a sin if you surround yourself of the proper unit testing and consistency testing.
I've written a silly example to explain an idea: ``` class BinaryIntegerOperation { public int Execute(string operation, int operand1, int operand2) { var split = operation.Split(':'); var opCode = split[0]; if (opCode == "MULTIPLY") { var args = split[1].Split(','); var result = IsFirstOperand(args[0]) ? operand1 : operand2; for (var i = 1; i < args.Length; i++) { result *= IsFirstOperand(args[i]) ? operand1 : operand2; } return result; } else { throw new NotImplementedException(); } } public string ToSqlExpression(string operation, string operand1Name, string operand2Name) { var split = operation.Split(':'); var opCode = split[0]; if (opCode == "MULTIPLY") { return string.Join("*", split[1].Split(',').Select(a => IsFirstOperand(a) ? operand1Name : operand2Name)); } else { throw new NotImplementedException(); } } private bool IsFirstOperand(string code) { return code == "0"; } } ``` So, if you have some logic: ``` var logic = "MULTIPLY:0,1"; ``` You can re-use it in domain classes: ``` var op = new BinaryIntegerOperation(); Console.WriteLine(op.Execute(logic, 3, 6)); ``` Or in your sql-generation layer: ``` Console.WriteLine(op.ToSqlExpression(logic, "r.width", "r.height")); ``` And, of course, you can change it easily. Try this: ``` logic = "MULTIPLY:0,1,1,1"; ```
290,405
Where I define Cyclomatic complexity density as: ``` Cyclomatic complexity density = Cyclomatic complexity / Lines of code ``` I was reading previous discussions about cyclomatic complexity and there seems to be a sort of consensus that it has mixed usefulness, and as such there probably isn't a strong motive for using it over a simple lines of code (LOC) metric. I.e. As the size of a class or method increases beyond some threshold the probability of defects and of there having been poor design choices goes up. It seems to me that cyclomatic complexity (CC) and LOC will tend to be correlated, hence the argument for use of the simpler LOC metric. However, there may be outlier cases where complexity is higher within some region of code, i.e. there is a higher density of execution branches in some pieces code (compared to the average) and I'm wondering if that will tend to be correlated with the presence of defects. Is there any evidence for or against, or are there any experiences around the use of such a complexity density metric? Or perhaps a better metric is to have both a LOC and a CC threshold, and we consider passing either threshold as bad.
2015/07/21
[ "https://softwareengineering.stackexchange.com/questions/290405", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/32728/" ]
As lxrec pointed out, it'll vary from codebase to codebase. Some applications will allow you to put those kind of business logic into SQL Functions and/or queries and allow you to run those anytime you need to show those values to the user. Sometimes it may seem stupid, but it's better to code for correctness than performance as a primary objective. In your sample, if you're showing the value of the area for a user in a webform, you'd have to: ``` 1) Do a post/get to the server with the values of x and y; 2) The server would have to create a query to the DB Server to run the calculations; 3) The DB server would make the calculations and return; 4) The webserver would return the POST or GET to the user; 5) Final result shown. ``` It's stupid for simple things like the one on the sample, but it may be necessary to more complex stuff like calculating the IRR of an investment of a client in a banking system. **Code for correctness**. If your software is correct, but slow, you'll have chances to optimize where you need (after profiling). If that means keeping some of the business logic in the database, so be it. That's why we have refactoring techniques. If it becomes slow, or unresponsive, than you may have some optimizations to do, like violating the DRY principle, which is not a sin if you surround yourself of the proper unit testing and consistency testing.
You say that the example is artificial, so I don't know if what I'm saying here suits your actual situation, but my answer is - use an [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) (Object-relational mapping) layer to define the structure and querying/manipulation of your database. That way you have no duplicated logic, since everything will be defined in the models. For example, using the [Django](https://www.djangoproject.com/) (python) framework, you would define your rectangle domain class as the following [model](https://docs.djangoproject.com/en/1.8/topics/db/models/): ``` class Rectangle(models.Model): width = models.IntegerField() height = models.IntegerField() def area(self): return self.width * self.height ``` To calculate the total area (without any filtering) you'd define: ``` def total_area(): return sum(rect.area() for rect in Rectangle.objects.all()) ``` As others have mentioned, you should first code for correctness, and only optimize when you really hit a bottleneck. So, if at a later date you decide, you absolutely have to optimize, you could switch to defining a raw query, such as: ``` def total_area_optimized(): return Rectangle.objects.raw( 'select sum(width * height) from myapp_rectangle') ```
290,405
Where I define Cyclomatic complexity density as: ``` Cyclomatic complexity density = Cyclomatic complexity / Lines of code ``` I was reading previous discussions about cyclomatic complexity and there seems to be a sort of consensus that it has mixed usefulness, and as such there probably isn't a strong motive for using it over a simple lines of code (LOC) metric. I.e. As the size of a class or method increases beyond some threshold the probability of defects and of there having been poor design choices goes up. It seems to me that cyclomatic complexity (CC) and LOC will tend to be correlated, hence the argument for use of the simpler LOC metric. However, there may be outlier cases where complexity is higher within some region of code, i.e. there is a higher density of execution branches in some pieces code (compared to the average) and I'm wondering if that will tend to be correlated with the presence of defects. Is there any evidence for or against, or are there any experiences around the use of such a complexity density metric? Or perhaps a better metric is to have both a LOC and a CC threshold, and we consider passing either threshold as bad.
2015/07/21
[ "https://softwareengineering.stackexchange.com/questions/290405", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/32728/" ]
As lxrec pointed out, it'll vary from codebase to codebase. Some applications will allow you to put those kind of business logic into SQL Functions and/or queries and allow you to run those anytime you need to show those values to the user. Sometimes it may seem stupid, but it's better to code for correctness than performance as a primary objective. In your sample, if you're showing the value of the area for a user in a webform, you'd have to: ``` 1) Do a post/get to the server with the values of x and y; 2) The server would have to create a query to the DB Server to run the calculations; 3) The DB server would make the calculations and return; 4) The webserver would return the POST or GET to the user; 5) Final result shown. ``` It's stupid for simple things like the one on the sample, but it may be necessary to more complex stuff like calculating the IRR of an investment of a client in a banking system. **Code for correctness**. If your software is correct, but slow, you'll have chances to optimize where you need (after profiling). If that means keeping some of the business logic in the database, so be it. That's why we have refactoring techniques. If it becomes slow, or unresponsive, than you may have some optimizations to do, like violating the DRY principle, which is not a sin if you surround yourself of the proper unit testing and consistency testing.
As @Machado said, the easiest way to do it is to avoid it and doing all your processing in your main java. However, it is still possible to have to code base with similar code without repeating your self by generating the code for both of code base. For example using [cog](http://nedbatchelder.com/code/cog/) enable to generate the three snippets from a common definition snippet 1: ```sql /*[[[cog from generate import generate_sql_table cog.outl(generate_sql_table("rectangle")) ]]]*/ CREATE TABLE rectangles ( width int, height int ); /*[[[end]]]*/ ``` snippet 2: ```java public class Rectangle { /*[[[cog from generate import generate_domain_attributes,generate_domain_logic cog.outl(generate_domain_attributes("rectangle")) cog.outl(generate_domain_logic("rectangle")) ]]]*/ private int width; private int height; public int area { return width * heigh; } /*[[[end]]]*/ } ``` snippet 3: ```sql /*[[[cog from generate import generate_sql cog.outl(generate_sql("rectangle",""" SELECT sum({area}) FROM rectangles r""")) ]]]*/ SELECT sum((r.width * r.heigh)) FROM rectangles r /*[[[end]]]*/ ``` from one reference file ```py import textwrap import pprint # the common definition types = {"rectangle": {"sql_table_name": "rectangles", "sql_alias": "r", "attributes": [ ["width", "int"], ["height", "int"], ], "methods": [ ["area","int","this.width * this.heigh"], ] } } # the utilities functions def generate_sql_table(name): type = types[name] attributes =",\n ".join("{attr_name} {attr_type}".format( attr_name=attr_name, attr_type=attr_type) for (attr_name,attr_type) in type["attributes"]) return """ CREATE TABLE {table_name} ( {attributes} );""".format( table_name=type["sql_table_name"], attributes = attributes ).lstrip("\n") def generate_method(method_def): name,type,value =method_def value = value.replace("this.","") return textwrap.dedent(""" public %(type)s %(name)s { return %(value)s; }""".lstrip("\n"))% {"name":name,"type":type,"value":value} def generate_sql_method(type,method_def): name,_,value =method_def value = value.replace("this.",type["sql_alias"]+".") return name,"""(%(value)s)"""% {"value":value} def generate_domain_logic(name): type = types[name] attributes ="\n".join(generate_method(method_def) for method_def in type["methods"]) return attributes def generate_domain_attributes(name): type = types[name] attributes ="\n".join("private {attr_type} {attr_name};".format( attr_name=attr_name, attr_type=attr_type) for (attr_name,attr_type) in type["attributes"]) return attributes def generate_sql(name,sql): type = types[name] fields ={name:value for name,value in (generate_sql_method(type,method_def) for method_def in type["methods"])} sql=textwrap.dedent(sql.lstrip("\n")) print (sql) return sql.format(**fields) ```
290,405
Where I define Cyclomatic complexity density as: ``` Cyclomatic complexity density = Cyclomatic complexity / Lines of code ``` I was reading previous discussions about cyclomatic complexity and there seems to be a sort of consensus that it has mixed usefulness, and as such there probably isn't a strong motive for using it over a simple lines of code (LOC) metric. I.e. As the size of a class or method increases beyond some threshold the probability of defects and of there having been poor design choices goes up. It seems to me that cyclomatic complexity (CC) and LOC will tend to be correlated, hence the argument for use of the simpler LOC metric. However, there may be outlier cases where complexity is higher within some region of code, i.e. there is a higher density of execution branches in some pieces code (compared to the average) and I'm wondering if that will tend to be correlated with the presence of defects. Is there any evidence for or against, or are there any experiences around the use of such a complexity density metric? Or perhaps a better metric is to have both a LOC and a CC threshold, and we consider passing either threshold as bad.
2015/07/21
[ "https://softwareengineering.stackexchange.com/questions/290405", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/32728/" ]
You say that the example is artificial, so I don't know if what I'm saying here suits your actual situation, but my answer is - use an [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) (Object-relational mapping) layer to define the structure and querying/manipulation of your database. That way you have no duplicated logic, since everything will be defined in the models. For example, using the [Django](https://www.djangoproject.com/) (python) framework, you would define your rectangle domain class as the following [model](https://docs.djangoproject.com/en/1.8/topics/db/models/): ``` class Rectangle(models.Model): width = models.IntegerField() height = models.IntegerField() def area(self): return self.width * self.height ``` To calculate the total area (without any filtering) you'd define: ``` def total_area(): return sum(rect.area() for rect in Rectangle.objects.all()) ``` As others have mentioned, you should first code for correctness, and only optimize when you really hit a bottleneck. So, if at a later date you decide, you absolutely have to optimize, you could switch to defining a raw query, such as: ``` def total_area_optimized(): return Rectangle.objects.raw( 'select sum(width * height) from myapp_rectangle') ```
I've written a silly example to explain an idea: ``` class BinaryIntegerOperation { public int Execute(string operation, int operand1, int operand2) { var split = operation.Split(':'); var opCode = split[0]; if (opCode == "MULTIPLY") { var args = split[1].Split(','); var result = IsFirstOperand(args[0]) ? operand1 : operand2; for (var i = 1; i < args.Length; i++) { result *= IsFirstOperand(args[i]) ? operand1 : operand2; } return result; } else { throw new NotImplementedException(); } } public string ToSqlExpression(string operation, string operand1Name, string operand2Name) { var split = operation.Split(':'); var opCode = split[0]; if (opCode == "MULTIPLY") { return string.Join("*", split[1].Split(',').Select(a => IsFirstOperand(a) ? operand1Name : operand2Name)); } else { throw new NotImplementedException(); } } private bool IsFirstOperand(string code) { return code == "0"; } } ``` So, if you have some logic: ``` var logic = "MULTIPLY:0,1"; ``` You can re-use it in domain classes: ``` var op = new BinaryIntegerOperation(); Console.WriteLine(op.Execute(logic, 3, 6)); ``` Or in your sql-generation layer: ``` Console.WriteLine(op.ToSqlExpression(logic, "r.width", "r.height")); ``` And, of course, you can change it easily. Try this: ``` logic = "MULTIPLY:0,1,1,1"; ```
290,405
Where I define Cyclomatic complexity density as: ``` Cyclomatic complexity density = Cyclomatic complexity / Lines of code ``` I was reading previous discussions about cyclomatic complexity and there seems to be a sort of consensus that it has mixed usefulness, and as such there probably isn't a strong motive for using it over a simple lines of code (LOC) metric. I.e. As the size of a class or method increases beyond some threshold the probability of defects and of there having been poor design choices goes up. It seems to me that cyclomatic complexity (CC) and LOC will tend to be correlated, hence the argument for use of the simpler LOC metric. However, there may be outlier cases where complexity is higher within some region of code, i.e. there is a higher density of execution branches in some pieces code (compared to the average) and I'm wondering if that will tend to be correlated with the presence of defects. Is there any evidence for or against, or are there any experiences around the use of such a complexity density metric? Or perhaps a better metric is to have both a LOC and a CC threshold, and we consider passing either threshold as bad.
2015/07/21
[ "https://softwareengineering.stackexchange.com/questions/290405", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/32728/" ]
I've written a silly example to explain an idea: ``` class BinaryIntegerOperation { public int Execute(string operation, int operand1, int operand2) { var split = operation.Split(':'); var opCode = split[0]; if (opCode == "MULTIPLY") { var args = split[1].Split(','); var result = IsFirstOperand(args[0]) ? operand1 : operand2; for (var i = 1; i < args.Length; i++) { result *= IsFirstOperand(args[i]) ? operand1 : operand2; } return result; } else { throw new NotImplementedException(); } } public string ToSqlExpression(string operation, string operand1Name, string operand2Name) { var split = operation.Split(':'); var opCode = split[0]; if (opCode == "MULTIPLY") { return string.Join("*", split[1].Split(',').Select(a => IsFirstOperand(a) ? operand1Name : operand2Name)); } else { throw new NotImplementedException(); } } private bool IsFirstOperand(string code) { return code == "0"; } } ``` So, if you have some logic: ``` var logic = "MULTIPLY:0,1"; ``` You can re-use it in domain classes: ``` var op = new BinaryIntegerOperation(); Console.WriteLine(op.Execute(logic, 3, 6)); ``` Or in your sql-generation layer: ``` Console.WriteLine(op.ToSqlExpression(logic, "r.width", "r.height")); ``` And, of course, you can change it easily. Try this: ``` logic = "MULTIPLY:0,1,1,1"; ```
As @Machado said, the easiest way to do it is to avoid it and doing all your processing in your main java. However, it is still possible to have to code base with similar code without repeating your self by generating the code for both of code base. For example using [cog](http://nedbatchelder.com/code/cog/) enable to generate the three snippets from a common definition snippet 1: ```sql /*[[[cog from generate import generate_sql_table cog.outl(generate_sql_table("rectangle")) ]]]*/ CREATE TABLE rectangles ( width int, height int ); /*[[[end]]]*/ ``` snippet 2: ```java public class Rectangle { /*[[[cog from generate import generate_domain_attributes,generate_domain_logic cog.outl(generate_domain_attributes("rectangle")) cog.outl(generate_domain_logic("rectangle")) ]]]*/ private int width; private int height; public int area { return width * heigh; } /*[[[end]]]*/ } ``` snippet 3: ```sql /*[[[cog from generate import generate_sql cog.outl(generate_sql("rectangle",""" SELECT sum({area}) FROM rectangles r""")) ]]]*/ SELECT sum((r.width * r.heigh)) FROM rectangles r /*[[[end]]]*/ ``` from one reference file ```py import textwrap import pprint # the common definition types = {"rectangle": {"sql_table_name": "rectangles", "sql_alias": "r", "attributes": [ ["width", "int"], ["height", "int"], ], "methods": [ ["area","int","this.width * this.heigh"], ] } } # the utilities functions def generate_sql_table(name): type = types[name] attributes =",\n ".join("{attr_name} {attr_type}".format( attr_name=attr_name, attr_type=attr_type) for (attr_name,attr_type) in type["attributes"]) return """ CREATE TABLE {table_name} ( {attributes} );""".format( table_name=type["sql_table_name"], attributes = attributes ).lstrip("\n") def generate_method(method_def): name,type,value =method_def value = value.replace("this.","") return textwrap.dedent(""" public %(type)s %(name)s { return %(value)s; }""".lstrip("\n"))% {"name":name,"type":type,"value":value} def generate_sql_method(type,method_def): name,_,value =method_def value = value.replace("this.",type["sql_alias"]+".") return name,"""(%(value)s)"""% {"value":value} def generate_domain_logic(name): type = types[name] attributes ="\n".join(generate_method(method_def) for method_def in type["methods"]) return attributes def generate_domain_attributes(name): type = types[name] attributes ="\n".join("private {attr_type} {attr_name};".format( attr_name=attr_name, attr_type=attr_type) for (attr_name,attr_type) in type["attributes"]) return attributes def generate_sql(name,sql): type = types[name] fields ={name:value for name,value in (generate_sql_method(type,method_def) for method_def in type["methods"])} sql=textwrap.dedent(sql.lstrip("\n")) print (sql) return sql.format(**fields) ```
290,405
Where I define Cyclomatic complexity density as: ``` Cyclomatic complexity density = Cyclomatic complexity / Lines of code ``` I was reading previous discussions about cyclomatic complexity and there seems to be a sort of consensus that it has mixed usefulness, and as such there probably isn't a strong motive for using it over a simple lines of code (LOC) metric. I.e. As the size of a class or method increases beyond some threshold the probability of defects and of there having been poor design choices goes up. It seems to me that cyclomatic complexity (CC) and LOC will tend to be correlated, hence the argument for use of the simpler LOC metric. However, there may be outlier cases where complexity is higher within some region of code, i.e. there is a higher density of execution branches in some pieces code (compared to the average) and I'm wondering if that will tend to be correlated with the presence of defects. Is there any evidence for or against, or are there any experiences around the use of such a complexity density metric? Or perhaps a better metric is to have both a LOC and a CC threshold, and we consider passing either threshold as bad.
2015/07/21
[ "https://softwareengineering.stackexchange.com/questions/290405", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/32728/" ]
You say that the example is artificial, so I don't know if what I'm saying here suits your actual situation, but my answer is - use an [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) (Object-relational mapping) layer to define the structure and querying/manipulation of your database. That way you have no duplicated logic, since everything will be defined in the models. For example, using the [Django](https://www.djangoproject.com/) (python) framework, you would define your rectangle domain class as the following [model](https://docs.djangoproject.com/en/1.8/topics/db/models/): ``` class Rectangle(models.Model): width = models.IntegerField() height = models.IntegerField() def area(self): return self.width * self.height ``` To calculate the total area (without any filtering) you'd define: ``` def total_area(): return sum(rect.area() for rect in Rectangle.objects.all()) ``` As others have mentioned, you should first code for correctness, and only optimize when you really hit a bottleneck. So, if at a later date you decide, you absolutely have to optimize, you could switch to defining a raw query, such as: ``` def total_area_optimized(): return Rectangle.objects.raw( 'select sum(width * height) from myapp_rectangle') ```
As @Machado said, the easiest way to do it is to avoid it and doing all your processing in your main java. However, it is still possible to have to code base with similar code without repeating your self by generating the code for both of code base. For example using [cog](http://nedbatchelder.com/code/cog/) enable to generate the three snippets from a common definition snippet 1: ```sql /*[[[cog from generate import generate_sql_table cog.outl(generate_sql_table("rectangle")) ]]]*/ CREATE TABLE rectangles ( width int, height int ); /*[[[end]]]*/ ``` snippet 2: ```java public class Rectangle { /*[[[cog from generate import generate_domain_attributes,generate_domain_logic cog.outl(generate_domain_attributes("rectangle")) cog.outl(generate_domain_logic("rectangle")) ]]]*/ private int width; private int height; public int area { return width * heigh; } /*[[[end]]]*/ } ``` snippet 3: ```sql /*[[[cog from generate import generate_sql cog.outl(generate_sql("rectangle",""" SELECT sum({area}) FROM rectangles r""")) ]]]*/ SELECT sum((r.width * r.heigh)) FROM rectangles r /*[[[end]]]*/ ``` from one reference file ```py import textwrap import pprint # the common definition types = {"rectangle": {"sql_table_name": "rectangles", "sql_alias": "r", "attributes": [ ["width", "int"], ["height", "int"], ], "methods": [ ["area","int","this.width * this.heigh"], ] } } # the utilities functions def generate_sql_table(name): type = types[name] attributes =",\n ".join("{attr_name} {attr_type}".format( attr_name=attr_name, attr_type=attr_type) for (attr_name,attr_type) in type["attributes"]) return """ CREATE TABLE {table_name} ( {attributes} );""".format( table_name=type["sql_table_name"], attributes = attributes ).lstrip("\n") def generate_method(method_def): name,type,value =method_def value = value.replace("this.","") return textwrap.dedent(""" public %(type)s %(name)s { return %(value)s; }""".lstrip("\n"))% {"name":name,"type":type,"value":value} def generate_sql_method(type,method_def): name,_,value =method_def value = value.replace("this.",type["sql_alias"]+".") return name,"""(%(value)s)"""% {"value":value} def generate_domain_logic(name): type = types[name] attributes ="\n".join(generate_method(method_def) for method_def in type["methods"]) return attributes def generate_domain_attributes(name): type = types[name] attributes ="\n".join("private {attr_type} {attr_name};".format( attr_name=attr_name, attr_type=attr_type) for (attr_name,attr_type) in type["attributes"]) return attributes def generate_sql(name,sql): type = types[name] fields ={name:value for name,value in (generate_sql_method(type,method_def) for method_def in type["methods"])} sql=textwrap.dedent(sql.lstrip("\n")) print (sql) return sql.format(**fields) ```