qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
2,769
I know you can create a rounded-corner rectangle; but, how do you create a triangle with rounded corners in Photoshop? I am actually interested in making it from scratch, not basing it on a custom shape that is available in Photoshop. Thanks.
2011/07/07
[ "https://graphicdesign.stackexchange.com/questions/2769", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/1854/" ]
There are several ways to do this. You can use the pen tool draw it yourself. My answer is based on the way I've been doing it over the years. ![step 1](https://i.stack.imgur.com/C0ISG.png) Draw a triangle in a new layer. hit cmd+a(select all) then cmd+c(copy) ![step 2](https://i.stack.imgur.com/7FUw4.png) switch to the Channels tab and create a new channel. It will be named "Alpha 1" by default. now paste the triangle you copied from before. Note the triangle will be white. The white area in the channel will become your select mask later. ![step 3](https://i.stack.imgur.com/Nket9.png) now give the entire channel layer a Gaussian blur. note: the blur value here won't translate exactly to the pixel border radius you want. you'll just have to play with it a bit. I'm using 10px blur in my example. ![step 4](https://i.stack.imgur.com/GZqhU.png) After you're done blurring, hit cmd+L(level). In the level menu, adjust input values. use the value I picked in my screenshot. The idea is to get the triangle "sharp" again. Doing so will create the circular tips on each end. ![step 5](https://i.stack.imgur.com/Y98ih.png) Now go back to the Layers tab, hide the triangle layer you drew from before. start a new layer, then to go "Select" -> "Load Selection." In the popup, for "Source" choose "Alpha 1" Now you'll have the rounded cornered triangle outline selected, you then can fill it to whatever color you like.
1. Create a triangle shape of the desired size 2. Place circle shapes of the desired radius in the corners of the triangle, so that they align with the edges but not intersect. 3. Combine shapes. 4. Done. :)
6,258,283
I am trying to merge the latest changes from trunk into a branch of my project, but the problem is I don't know what revision of the trunk I checked out that I eventually created the branch from. I would think SVN logged this somewhere. Does anyone know how I can find the revision number? (In other words, the Subversion equivalent of `git merge-base master branch-name`)
2011/06/06
[ "https://Stackoverflow.com/questions/6258283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200224/" ]
Are you using TortoiseSvn or command line? Command Line: `svn log --stop-on-copy` and then look at the smallest rev number. Tortoise SVN: `right-click, tortoise-svn, show log, make sure 'stop on copy' is *checked* and press refresh. Scroll to the bottom and find the smallest rev number.` ![enter image description here](https://i.stack.imgur.com/bLlPM.jpg)
For the Cornerstone app, to see where a tag or branch originated, look in the timeline.
237,352
**check\_prime.cpp** **Description**: Accepts user input to check if the user entered a prime number. **Notes**: If any text inputted after an integer will be ignored. **For example**: 1234.5678 and 98abc will be interpreted as 1234 and 98, respectively. Please provide any feedback (positive or negative). ``` // check_prime.cpp // Author: Chris Heath // Date: 12/9/2018 // Description: Accepts user input to check if the user entered a prime number. // Notes: If any text inputted after an integer will be ignored. // For example: 1234.5678 and 98abc will be interpreted as 1234 and 98, respectively. #include <iostream> #include <string> #include <limits> using namespace std; int is_prime (unsigned long int num) { unsigned long int n; // avoid loop; 0 or 1 are never prime if (num == 0 || num == 1) return 0; // loop through numbers 0..(n/2)+1, trying to // divide one into the other with no remainder. for (n=2; n < (num/2)+1; n++) { // if we had no remainder during a revision, // input number has a divisor... NOT PRIME! if ((num % n) == 0) return 0; } // made it through gauntlet...prime! return 1; } int main() { unsigned long int i; cout<<"Enter an integer to check if it is a prime: "; cin>>i; while(1) { if(cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout<<"You have entered wrong input.\nPlease try again: "; cin>>i; } if(!cin.fail()) break; } if ( is_prime(i) ) cout<<"\n"<<i<<" IS PRIME!"<<endl; else cout<<"\n"<<i<<" is NOT prime."<<endl; return 0; } ```
2020/02/16
[ "https://codereview.stackexchange.com/questions/237352", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/218519/" ]
* Formatting: Indent your code consistently. This makes it easier to understand and spot errors. Also, it attracts people here to read it at all. Your's is not a mess, but inconsistent still. * Another rather obvious error is not to return a boolean for a function that gives you a true/false result. This is implicit documentation. If you return an int, you need to say what it means and how to interpret it, which the user of a function has to read and understand. With a boolean, that meaning is clear and requires no additional documentation. * `using namespace std;` is okay-ish for an example like this. It's bad as regular habit and it's inacceptable when done in a header file. The problem this causes is the pollution of the global namespace. Replace this with single `using` statements, possibly restricted to a smaller scope like a class or function, or just prefix the `std::`. * Your comment "loop through numbers 0..(n/2)+1" is misleading, your loop starts with value 2. Try to avoid repeating what the code does. Rather, use a comment (when necessary) to explain *why* you did something, in particular the `(n/2)+1` deserves some explanation. * This leads to the point that the limit `(n/2)+1` is not optimal. Assuming there are two numbers `n` and `m` that divide a third value `k` that you're trying to find. If your approach is to try increasing values of `n`, then you can stop as soon as the resulting value of `k / n` is less than `n`. The reason is that `n` and `m` are interchangeable, so any possible result for `m` would have been tried as `n` already. * The while loop could be structured differently, each operation is required only once, to remove redundancy. The first of these is `cin >> i`, the other is checking `cin.fail()`. Other than that the loop is fine and correct. As a strategy, think about how you would describe the steps to a human. Use this description as comments to form a template for your code. This then takes this form: ``` // output a prompt cout<<"Enter an integer to check if it is a prime: "; while (true) { // try to read a single number cin >> i; // if reading succeeded, we're done if(!cin.fail()) break; // skip remainder of the line of input cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); // output a warning and try again cout<<"You have entered wrong input.\nPlease try again: "; } ``` * A stream can be used in a boolean expression to find out whether something failed or not. The above could have been simplified to `if (cin >> i) break;`. * Just to mention it, when input failed, it sometimes makes sense to check for EOF as well. If you were reading numbers in an endless loop, sending an EOF (Control-D or Control-Z, depending on the terminal) can be used to exit that loop. If I send EOF to your program, it endlessly rotates prompting for a new value. * The final `return 0` in `main()` is not necessary. This is a specialty of the `main()` function though, it doesn't apply to other functions.
* `int` is redundant in this variable declaration: `unsigned long int num` See the properties table on this reference page: <https://en.cppreference.com/w/cpp/language/types> * in this case, it is better to use `++n` rather than `n++` for better readability. `++n` precisely describes what this imperative procedure tries to do: increment the value of variable `n` by 1 and save the new value. The code is not relying on the extra step (make and return a copy of the original value) from post-increment operator to be functionally correct. Thus `n++` has a redundant step.
9,600,592
i am working with javafx 2.0 and netbean 7.1, I am facing an problem when doing a drag and drop on a image over a ImageView, .i kept image as a source(one image) and 2 target point(2 box as target point).when trying to drag an image first time, its working fine and after sources image is entered in to target box.and again trying to drag the image, following error is trown "java.lang.IllegalArgumentException: Wrong byte buffer size 18x15 [1080] != 0" Once the image is moved to the destination object, i need to set the listener to change it as source, i feel that its throwing error in this place.. code am using ``` public class DragandDropEx extends Application { /** * @param args the command line arguments */ GridPane Board; ImageView deactivateImageView = new ImageView(); ImageView newImageView = new ImageView(); final Rectangle target = new Rectangle(0, 0, 50, 50); final Rectangle target2 = new Rectangle(0, 0, 50, 50); public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { target.setFill(Color.CHOCOLATE); target2.setFill(Color.BLUE); Image image = new Image(getClass().getResourceAsStream("triangle.png")); getDeactivateImageView().setImage(image); Board = new GridPane(); primaryStage.setTitle("Drag and Drop"); createSource(getDeactivateImageView()); target.setOnDragOver(new EventHandler<DragEvent>() { @Override public void handle(DragEvent events) { events.acceptTransferModes(TransferMode.MOVE); events.consume(); createTargetDrop(target,0,8); } }); target2.setOnDragOver(new EventHandler<DragEvent>() { @Override public void handle(DragEvent events) { events.acceptTransferModes(TransferMode.MOVE); events.consume(); createTargetDrop(target2,0,9); } }); Board.add(getDeactivateImageView(), 0, 1); Board.add(target, 0, 8); Board.add(target2, 0, 9); StackPane root = new StackPane(); root.getChildren().add(Board); primaryStage.setScene(new Scene(root, 300, 250)); primaryStage.show(); } private void createSource(final ImageView imageView) { imageView.setOnDragDetected(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent events) { Dragboard storeImage =imageView.startDragAndDrop(TransferMode.MOVE); ClipboardContent content = new ClipboardContent(); content.putImage(imageView.getImage()); storeImage.setContent(content); **// here i am getting error** events.consume(); } }); } private void createTargetDrop(final Rectangle target,final int xCordination,final int yCordination) { target.setOnDragDropped(new EventHandler<DragEvent>() { @Override public void handle(DragEvent event) { Dragboard db = event.getDragboard(); Image dragedImage = db.getImage(); getNewImageView().setImage(dragedImage); getDeactivateImageView().setVisible(false); setDeactivateImageView(getNewImageView()); Board.add(getDeactivateImageView(),xCordination,yCordination ); event.consume(); createSource(getDeactivateImageView()); // setting listener to new image } }); } } ```
2012/03/07
[ "https://Stackoverflow.com/questions/9600592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1254528/" ]
``` SELECT Company_Name, Company_ID, SUM(Amount) FROM TableName GROUP BY Company_Name, Company_ID ```
You need to use `GROUP BY` and `SUM` function. ``` SELECT Company_Name, Company_ID, SUM(Amount) AS TOTAL_AMOUNT FROM myTable GROUP BY Company_Name, Company_ID ```
12,258
There is much information regarding learning styles and ways to leverage them, along with boosting focus, alertness and concentration. However, I'm looking for accompanying information that would be useful in addition to those answers. **Witnessed countless times:** When one is either learning or working with a new concept that is - complex, untangle, counter-intuitive, tedious, multi-dimensional, boring and difficult, it appears mood is altered to a lower state, very similar to that of a depressive state, however is temporary, until another concepts comes along (still new) that is simple, clear and straight forward. Are there any studies that show correlation to dopamine and serotonin in such a case - and more importantly, are there any studies or know methods that reverse this, causing instead increased dopamine and serotonin during such events?
2015/09/26
[ "https://cogsci.stackexchange.com/questions/12258", "https://cogsci.stackexchange.com", "https://cogsci.stackexchange.com/users/849/" ]
I'm guessing you don't want to generally increase the level of those chemicals in the brain, just in the reward-motivation area. In order to do so, you need to be rewarded and motivated, obviously. The learning need to be exciting, with feedback and reinforcement. Socializing it will help, too. There is a relatively new topic, called gameificatin, that try to do exactly that. It's the process of making the learning a game, so we can learn better,based on the reward-motivation effects. In my opinion, there is no "hacking" the brain. Doing so is using drugs, and there is a price tag for that. If you want to use the normal brain pathways, there are no shortcuts.
This is more of a subjective opinion, (though there are some real world examples) but I feel that the concept of "gamification" (adding game-like qualities to non-gaming tasks) is quite relevant to this topic. Sites like khan academy or codecademy use this pretty effectively, and make the process of learning math or code more enjoyable because you are making small incremental achievements that would otherwise be invisible or ignored while learning through another medium. On another note, working with a friend or a group of friends to learn something complex seems to increase my level of enjoyment while studying the topic because the task is now cooperative and competitive simultaneously. You learn from the mistakes of others while getting different interpretations of complex ideas. The task becomes more of an adventure as you motivate each other to see just how much you can learn and aspire to show off what you know with new ideas. Most of this is purely anecdotal, so I'll look for studies to confirm or deny these ideas.
6,619,042
I downloaded <http://www.cryptopp.com/#download> 5.6.1 and have no clue that to do at this point. I am a total noob and need good instructions. thanks.
2011/07/08
[ "https://Stackoverflow.com/questions/6619042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473795/" ]
Directly from the readme (Which can be found here [Crypto++ Svn Trunk](http://svn.code.sf.net/p/cryptopp/code/trunk/c5/ "Crypto++ SVN Trunk")): **\* MSVC-Specific Information \*** On Windows, Crypto++ can be compiled into 3 forms: a static library including all algorithms, a DLL with only FIPS Approved algorithms, and a static library with only algorithms not in the DLL. (FIPS Approved means Approved according to the FIPS 140-2 standard.) The DLL may be used by itself, or it may be used together with the second form of the static library. MSVC project files are included to build all three forms, and sample applications using each of the three forms are also included. To compile Crypto++ with MSVC, open the "cryptest.dsw" (for MSVC 6 and MSVC .NET 2003) or "cryptest.sln" (for MSVC 2005 - 2010) workspace file and build one or more of the following projects: * cryptopp - This builds the DLL. Please note that if you wish to use Crypto++ as a FIPS validated module, you must use a pre-built DLL that has undergone the FIPS validation process instead of building your own. * dlltest - This builds a sample application that only uses the DLL. * cryptest Non-DLL-Import Configuration - This builds the full static library along with a full test driver. * cryptest DLL-Import Configuration - This builds a static library containing only algorithms not in the DLL, along with a full test driver that uses both the DLL and the static library. To use the Crypto++ DLL in your application, #include "dll.h" before including any other Crypto++ header files, and place the DLL in the same directory as your .exe file. dll.h includes the line #pragma comment(lib, "cryptopp") so you don't have to explicitly list the import library in your project settings. To use a static library form of Crypto++, make the "cryptlib" project a dependency of your application project, or specify it as an additional library to link with in your project settings. In either case you should check the compiler options to make sure that the library and your application are using the same C++ run-time libraries and calling conventions. If you have any questions feel free to ask and i'll update the anwser with my responses.
You'll need to compile the library before using it with anything. You can't just install it. Here is a page from their wiki about compiling the library: <http://www.cryptopp.com/wiki/Compiling>
43,091,923
please take look at Node \*newNode(), i dont understand why i must add \* for p=x i made an Node named x(with data & next), and created a new memory space \*p by using malloc, then let p = x, but by i must add \* for p=x? ``` #include<stdio.h> #include<stdlib.h> struct Node{ int data; Node *next; }; Node *newNode(int data, Node *next){ Node x = {data, next}; Node *p = (Node *)malloc(sizeof(Node)); *p = x; //i dont understand why an * need to be added here return p; } showNode(const struct Node *p){ printf("%d\n", p->data); } int main(){ Node *pHead = NULL; for(int i=4; i>=0; i--) { pHead = newNode(i,pHead); } printf("%d\n", pHead->next->next->next->data); Node* p = pHead; while(p != NULL){ showNode(p); p = p-> next; } p = pHead; while(p != NULL){ Node *pTemp = p; p = p->next; free(pTemp); } } ```
2017/03/29
[ "https://Stackoverflow.com/questions/43091923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7715019/" ]
In your UITabBarController class **viewDidAppear func** , call it's super class, like this ``` override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if goTasks { self.selectedIndex = 0 } else if goTodo { self.selectedIndex = 2 } else if goProjects { self.selectedIndex = 3 } else if goSearch { self.selectedIndex = 0 } } ``` After that, your first viewcontroller will call this method. ``` override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("Entry") } ```
i think you have to call function from super: ``` override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // here what i ment if goTasks { self.selectedIndex = 0 } else if goTodo { self.selectedIndex = 2 } else if goProjects { self.selectedIndex = 3 } else if goSearch { self.selectedIndex = 0 } } ```
40,927,253
I am writing a program where i am using Multi-dimensional array. The concept will enter the subject name and index will be shown that who student is studying that subject. ``` $var= [ 'Abdullah'=>['full_name'=>'Abdullah_Faraz', 'Subject'=>['English','Urdu','Maths']], 'Hamid'=>['full_name'=>'Hamid_Amjad', 'Subject'=>['PHP','Urdu','C++']], 'Abid'=>['full_name'=>'Abid_Ali', 'Subject'=>['OOP','OS','Calculus']], 'Aqeel'=>['full_name'=>'Aqeel_Bhutta', 'Subject'=>['Economics','Statistics','Big_Data']] ``` ]; ``` foreach ($var as $key => $value) { foreach ($value as $key1 => $value1) { foreach ($value1 as $value2) { if($value2='Urdu'){ echo $key; } } } ``` Output Abdullah Hamid but now i want to show the index of those who are not studying Urdu the expected outcome should be ``` Abid Aqeel ``` But i don't know how to achieve this.
2016/12/02
[ "https://Stackoverflow.com/questions/40927253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4506331/" ]
You can use this ``` foreach ($var as $key => $value) { $lang = $value['Subject'][1]; if($lang != 'Urdu'){ echo $key.'<br>'; } } ```
Replace your inner two *foreach* loops with normal for-loop over array length. ``` <?php for ($x = 0; $x < dim-Length; $x++) { echo "The number is: $x <br>"; } ?> ```
502,653
Pretty much the title. I don't like the way that a single scroll wheel 'notch' moves an entire slide. I would rather scroll continuously between slides if possible. Maybe I'm wrong and it would be more annoying that way, but I'd like to try it if I can.
2012/11/08
[ "https://superuser.com/questions/502653", "https://superuser.com", "https://superuser.com/users/74422/" ]
Continuous scroll works in Slide sorter view. Just zoom in slides as much as you want.
You can add a transition between two slides. Try a 'Push from bottom' transition with slow transition speed and you will get a scroll effect, though you wont have a control of scroll as you want like in a pdf file.
123,443
I have a fisheries dataset for which I have calculated value for each grid cell on a map. The value is the proportion of the total fishing sets in that cell for each month/year. So, I have values between 0-1, but not including 0 and 1 (the range is actually very skewed and is: 0.0005347594 to 0.1933216169). I am interested in whether the proportion of fishing sets is higher close to a specific location over time. I have read that there are two ways to do this - either a GLM with a binomial family and logit link, or a beta regression. I have tried both of these methods in R: Binomial GLM: ``` m1 <- glm(PercentTotalSets ~ factor(SetYear) + DayLength + DistTZCF + DistNWHI, family = binomial(link='logit'), data = Totals_CellId) ``` Beta: ``` BetaGLM <- betareg(PercentTotalSets ~ factor(SetYear) + DayLength + DistTZCF + DistNWHI, data = Totals_CellId ) ``` With the binomial GLM, I get very different results than I would if I ran a GLM with a gamma distribution (e.g., `DistNWHI` is not significant with a p-value of .9 whereas before it was significant). With the beta regression, I get very similar results to a GLM with a gamma distribution (e.g., `DistNWHI` is significant with similar p-value). I think that the beta regression is the correct method, because I do not have 0s or 1s and I need to set bounds, but I am not sure if this is correct. I'd appreciate any and all advice.
2014/11/10
[ "https://stats.stackexchange.com/questions/123443", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/60391/" ]
With count data of that form, I'd actually fit a *multinomial* model (at least to start with\*), because several numerators are present in the denominator - each '+1' count could have gone into any of $k$ cells ('sets'). (e.g. see [here](http://en.wikipedia.org/wiki/Multinomial_logistic_regression)) You'll need the denominator you divided by; the model is still for the proportion, but the *variability* depends on the denominator you used to obtain the proportion. \* a particular concern is that you'll have dependence over both space and time (e.g. adjacent locations and adjacent times will tend to be more related than more distant locations or times - at least if there's unmodelled variation that would be accounted for by such effects) Once you have fitted a multinomial model, you would want to assess whether you have both the variance and the correlation modelled reasonably well -- you might need mixed models (GLMM) and possibly also to account for potential remaining overdispersion in addition. You will find a number of discussions of multinomial models here on CV. --- Another possibility is to model the counts as Poisson, by allowing for offsets, factors or continuous predictors related to the variation you mentioned as the reason you scaled to proportions.
Based on your answer of how the proportion is calculated I believe the beta regression is most appropriate. The logistic regression for count binomial would only make sense if you have counts out of a total that is constant. Since your total changes from month to month you have a continuous proportion. Therefore beta regression is the way to go!
58,184,582
After I build my image, there are a bunch of images. When I try to delete them I get “image has dependent child images” errors. Is there anyway to clean this up? These do NOT work: ``` docker rmi $(docker images -q) docker rmi $(docker images | grep “^” | awk “{print $3}”) docker rmi $(docker images -f “dangling=true” -q) ```
2019/10/01
[ "https://Stackoverflow.com/questions/58184582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5729597/" ]
``` docker rmi `docker images | grep "<none>" | awk {'print $3'}` ```
docker rmi `docker images -a | grep "<none>" | awk {'print $3'}` Adding `-a` is required.
69,577,447
I am new to Tailwind CSS and CSS in general. I need to make my buttons stop doing transform/transition effects when they are disabled. Currently, the disabled color changes are getting applied but the transformations/transitions are still taking place on hover. I tried using - ***disabled:transform-none*** and ***disabled:transition-none*** but it is not giving the desired result. Technologies being used is - ***ReactJS, Tailwind CSS*** The dummy code snippet with the classes used is as follows: ``` <button disabled={disableIt} className="text-xs rounded disabled:transform-none disabled:transition-none disabled:bg-gray disabled:cursor-not-allowed disabled:text-white bg-gray-600 mx-1 transition duration-500 ease-in-out transform hover:translate-x-1 hover:scale-110 hover:blue-300 hover:shadow-md" > Click me </button> ``` *Note: **disableIt** is a state that is used to disable or enable the button* My ***tailwind.config.js*** is has the variants section as: ``` variants: { opacity: ({ after }) => after(["disabled"]), backgroundColor: ({ after }) => after(["disabled"]), textColor: ({ after }) => after(["disabled"]), hover: ({ after }) => after(["disabled"]), cursor: ({ after }) => after(["disabled"]), transition: ({ after }) => after(["disabled"]), transform: ({ after }) => after(["disabled"]), extend: { padding: ["hover"], }, }, ``` Please help me out.
2021/10/14
[ "https://Stackoverflow.com/questions/69577447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6081163/" ]
You can [use the `enabled` modifier](https://tailwindcss.com/docs/hover-focus-and-other-states#enabled) to only apply a certain class when the button is enabled. This allows you to specify classes to be added only when the button enabled, rather than attempting to "remove" certain classes when the button is disabled. Here's a simple example based on your original code: ``` <button disabled={disableIt} className="enabled:transition enabled:transform enabled:hover:translate-x-1 enabled:hover:blue-300" > Click me </button> ```
If you want your disabled buttons to not trigger any interaction state like `:hover` or `active`, you can also simply add ``` disabled:pointer-events-none ``` to the tailwind className.
54,615
As far as I know, it's possible to create a radially polarised ring magnet, where one pole is on the inside, and the field lines cross the circumference at right angles. ![Radially polarised ring magnet](https://i.stack.imgur.com/SeYVO.png) So imagine if I made one which was shaped like a sector of a torus. ![Radially polarised ring magnets torus](https://i.stack.imgur.com/JtsWc.png) Then I forced a load of these magnets into a complete torus. ![Impossible torus magnet](https://i.stack.imgur.com/EWaJi.png) Clearly this magnet is impossible because there's no way for the field lines to get back into the middle. So what happens to the field in this case? Does it disappear completely? Do the magnets blow up?
2013/02/21
[ "https://physics.stackexchange.com/questions/54615", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/3220/" ]
I think Emilio Pisanty's answer is good enough. But here is another longer, 'magnetic charge' approach. ( Let's specify the coordinates first (sorry I borrow your picture). ![enter image description here](https://i.stack.imgur.com/bRrdk.png) It's obvious that the toroid is symmetrical under rotation along $\hat{\phi}$ direction. Thus we can't have magnetic field along $\hat{\phi}$. Which means it is sufficient for us to find the magnetic field on the $xz$ plane, and we can generalize later by rotating this $xz$ plane. We have some constrains to consider here due to the shape of torus: * $\vec{B}$ is symmetrical under reflection over $\hat{x}$ axis and $\hat{z}$ axis. * $\nabla\times B=0$. * $\nabla.B=0$ The most general field lines in $xz$ plane that satisfy these conditions roughly looks like this. ![enter image description here](https://i.stack.imgur.com/HMijl.png) Now we only have two possible directions, the one shown in the picture or the opposite of that(or zero everywhere). We can apply magnetic Gauss law here with the Gaussian surface marked with black dotted line(in 3D point of view this black dotted line is rotated along $\phi$ so that the product looks like a mountain). The only part of the Gaussian surface which has magnetic flux through it is the top part. The remaining area is intentionally shaped to follow the field lines tangentially so that there's no flux through it. Now we only need to determine whether the magnetic charge inside the envelope is positive or negative(Positive charges are shown in blue, and negative charges in red). As we can see in the picture, the inner magnetic field which is represented by yellow lines may bend slightly from radial direction towards the direction which allows the envelope to catch more or less positive charge. So the total charge inside the envelope might be positive or negative. However if the yellow lines bend in a way like that, then we will meet a kink somewhere between the inner and outer field or we may also get a non-zero curl field and these are impossible. So we are only left with a radial inner field. And therefore the total charge inside the envelope is zero and there can't be any flux passing through it. So in conclusion the field outside must vanish everywhere.
If all of the segments necessary to form such a toroid could be put in place, it would form a larger, and more powerful, version of one of the segments except that it would be hollow instead of solid. This is possible due to the fact that a magnetic field is capable of penetrating, and passing through, the material of which the segments are made, and also of realigning the particles/atoms of the material. The field, and the alignment of particles/atoms in the material, would simply shift in order to acheive a field as uniformly balanced as possible (one with as close to uniform field pressure as possible).
22,758,460
I´m sure that I`m missing something but it seams to me that the behavior hows the HttpClient sends request differs, when it comes to arguments. The Problem is, that any request with arguments results in the status code 501. With the 4.2 version those requests was handled properly. The tricky part is, that there is nothing spatial about the arguments and the problem also accuser when the arguments are build via URIBuilder as described here: <http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/fundamentals.html> I suppose i need a way to put the params:BasicHttpsParams collection and not concatenate them with the plain uri - since they seam not to get recognized that way by HttpGet. Did something changed between 4.2 and 4.3 at this point? here is the code how our get Method is implemented: ``` private static CloseableHttpClient httpAgent = initializeCloseableHttpClient(connectionManager); private static CloseableHttpClient initializeCloseableHttpClient(PoolingHttpClientConnectionManager connectionManager) { RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(500) .setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT) .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT) .build(); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setCharset(StandardCharsets.UTF_8) .build(); CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .setDefaultConnectionConfig(connectionConfig) .build(); return httpClient; } public static String get(String url, Map<String, String> arguments) { String argumentString = getArgumentString(arguments == null ? EMPTY_COLLECTION : arguments.entrySet()); HttpGet getMethod = new HttpGet(url + argumentString); return request(getMethod, null); } private static String request(HttpUriRequest method, AuthenticationDetails authenticationDetails) { InputStreamProcessor processor = new CopyToStringInputStreamProcessor(); processStream(method, authenticationDetails, processor); return (String) processor.getResult(); } private static void processStream(HttpUriRequest method, AuthenticationDetails authenticationDetails, InputStreamProcessor processor) { try { HttpClientContext context = null; if (authenticationDetails != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(authenticationDetails.getUsername(), authenticationDetails.getPassword()); credsProvider.setCredentials(new AuthScope(method.getURI().getHost(), method.getURI().getPort()), credentials); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); HttpHost targetHost = new HttpHost(method.getURI().getHost(), method.getURI().getPort(), method.getURI().getScheme()); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); } for (int i = 0; i < 3; i++) { CloseableHttpResponse response = httpAgent.execute(method, context); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200 && statusCode != 302) { // redirect is also ok throw new HttpClientException(String.format("A http request responds with failure code: %d (%s), requested uri: %s", statusCode, response.getStatusLine().getReasonPhrase(), method.getRequestLine().getUri())); } try { HttpEntity entity = response.getEntity(); if (entity != null) { try (InputStream responseStream = entity.getContent()) { processor.process(responseStream); EntityUtils.consume(entity); } catch (IOException ex) { throw ex; // In case of an IOException the connection will be released back to the connection manager automatically } catch (RuntimeException ex) { method.abort(); // In case of an unexpected exception you may want to abort the HTTP request in order to shut down the underlying connection and release it back to the connection manager. throw ex; } } } finally { response.close(); } } } catch (IOException e) { throw new HttpClientException(String.format("IO exception while processing http request on url: %s. Message: %s", method.getRequestLine().getUri(), e.getMessage()), e); } catch (Exception e) { throw new HttpClientException(String.format("Exception while processing http request on on url: %s. Message: %s", method.getRequestLine().getUri(), e.getMessage()), e); } } ``` Any advises what might be wrong are highly appreciated. Thanks
2014/03/31
[ "https://Stackoverflow.com/questions/22758460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1195266/" ]
> > I am using Netbeans on a Windows machine, what happens is that if I > run the main java file the look and feel I get is different than in > the case I run the whole program. > > > When you run a Swing application the default Look and Feel is set to a cross-platform L&F also called [Metal](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html#available). On the other hand when you create a new [JFrame](http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html) from NetBeans *New file* wizard it also includes a `main` method just for test purposes, making developers able to "run" the top-level container. Within this `main` method the Look and Feel is set to [Nimbus](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/nimbus.html) as you have included in your *Update 1*. This is well explained in this Q&A: [How can I change the default look and feel of Jframe? (Not theme of Netbeans)](https://stackoverflow.com/questions/22066620/how-can-i-change-the-default-look-and-feel-of-jframe-not-theme-of-netbeans). As stated there you can modify the template associated to `JFrame` form to set the L&F you wish. However be aware of this line: > > A Java application only needs one `main` class so this test-only `main` > methods should be deleted when you will deploy your application. [...] > the L&F should be established only once at the start-up, not in every > top-level container (`JFrame`, `JDialog`...). > > > You also might to take a look to [Programatically Setting the Look and Feel](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html#programmatic) of [How to Set the Look and Feel](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html) article. Edit ---- > > I just did not understand one thing which test-only main methods do i > need to delete and if i delete them how will my prg run properly? > > > A Java application must have only one `main` method that inits the execution. The class which has this `main` method is defined within `MANIFEST.MF` file when you deploy your JAR. So, having a `main` method in each top-level container (`JFrame` or `JDialog`) is not needed and it's not a good practice. However sometimes you don't want to run the whole application to test how a particular frame/dialog works. That's why NetBeans includes this `main` method on `JFrame` or `JDialog` creation. But as stated above when you will deploy your JAR you should delete those "extra" `main` methods. > > and yah, in that you have given how to do it when i create new > jframes, but i already have 20s of them > > > A Swing application tipically has a single `JFrame` and multiple `JDialog`'s. Take a look to this topic for further details: [The Use of Multiple JFrames, Good/Bad Practice?](https://stackoverflow.com/a/9554657/1795530) > > And anyways it is nimbus in there and it is what i want, but that is > not what is opening > > > You just need to programatically set the L&F to Nimbus in your `main` class (the one that is executed when you run the whole application). You can copy-paste the code you've included in your *Update 1* there. Edit 2 ------ When you create a new project in NetBeans it ask you for create a main class too. Let's say I create a new project called `Test`, it will ask me for create a main class like this: ![enter image description here](https://i.stack.imgur.com/Jdkev.jpg) This generated `Test` class will have the `main` method that triggers the application execution: ![enter image description here](https://i.stack.imgur.com/7M35S.jpg) Within this main method you have to put the code you've included in your *Update 1*: ``` public class Test { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { try { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } catch (ClassNotFoundException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } } } } }); } } ``` Then when you run your application the L&F will be set to Nimbus overriding the default cross-platform L&F. Henceforth all created Swing components will have Nimbus as L&F. **Note:** The reason of [SwingUtilities.invokeLater()](http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingUtilities.html#invokeLater%28java.lang.Runnable%29) call is explained in [Initial Threads](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html) article.
I would recommend to try to change your LAF in your main method, like: ``` public static void main(String[] args){ Frame f; // Your (J)Frame or GUI-Class. // some code here... try{ UIManager.setLookAndFeel(new NimbusLookAndFeel()) // Because it seems to be Nimbus what you want. SwingUtilities.updateComponentTreeUI(f); // To refresh your GUI }catch(Exception e){ // Do whatever you want if a problem occurs like LAF not supported. } } ``` Or you could do it without `SwingUtilities.updateComponentTreeUI(f);` if you call ``` f.setVisible(true); ``` after the change of your LAF.
23,566,980
I'm writing an app that gets a `Json` list of objects like this: ``` [ { "ObjectType": "apple", "ObjectSize": 35, "ObjectCost": 4, "ObjectTaste": "good", "ObjectColor": "golden" }, { "ObjectType": "books", "ObjectSize": 53, "ObjectCost": 7, "Pages": 100 }, { "ObjectType": "melon", "ObjectSize": 35, "ObjectTaste": "good", "ObjectCost": 5 }, { "ObjectType": "apple", "ObjectSize": 29, "ObjectCost": 8, "ObjectTaste": "almost good", "ObjectColor": "red" } ] ``` I want to make a base class `ItemToSell` (size,cost), and derive Apple, Melon and Book from it, then make the deserialization based on the "`ObjectType`" field to whatever class it fits. I want it to build a list of `ItemToSell` objects, every object being Apple, Melon or Book. How could I do this in .Net? Thanks in advance :) EDIT: I know how to deserialize it in a Big class with all the fields it can ever contain, like: `Base(ObjectType,ObjectSize,ObjectCost,ObjectColor,Pages)`. But I want it to distinguish between classes by the `ObjectType` so I won't have any usefulness fields like Pages field for every book item or `ObjectTaste` for every book.
2014/05/09
[ "https://Stackoverflow.com/questions/23566980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2426155/" ]
Some time ago I had the same problem. You'll can use Json.NET, but if you don't have control over the json document (as in: 'it has been serialized by some other framework') you'll need to create a custom JsonConverter like this: ``` class MyItemConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(ItemToSell).IsAssignableFrom(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject obj = JObject.Load(reader); string discriminator = (string)obj["ObjectType"]; ItemToSell item; switch (discriminator) { case "apple": item = new Apple(); break; case "books": item = new Books(); break; case "melon": item = new Melon(); break; default: throw new NotImplementedException(); } serializer.Populate(obj.CreateReader(), item); return item; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { } } ``` Then you'll need to add it to the converters of the JsonSerializerSettings like so: ``` JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, }; settings.Converters.Add(new MyItemConverter()); var items = JsonConvert.DeserializeObject<List<ItemToSell>>(response, settings); ```
You can use a [CustomCreationConverter](http://james.newtonking.com/json/help/index.html?topic=html/CustomCreationConverter.htm). This lets you hook into the deserialization process. ``` public abstract class Base { public string Type { get; set; } } class Foo : Base { public string FooProperty { get; set; } } class Bar : Base { public string BarProperty { get; set; } } class CustomSerializableConverter : CustomCreationConverter<Base> { public override Base Create(Type objectType) { throw new NotImplementedException(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jObject = JObject.Load(reader); var type = (string)jObject.Property("Type"); Base target; switch (type) { case "Foo": target = new Foo(); break; case "Bar": target = new Bar(); break; default: throw new InvalidOperationException(); } serializer.Populate(jObject.CreateReader(), target); return target; } } class Program { static void Main(string[] args) { var json = "[{Type:\"Foo\",FooProperty:\"A\"},{Type:\"Bar\",BarProperty:\"B\"}]"; List<Base> bases = JsonConvert.DeserializeObject<List<Base>>(json, new CustomSerializableConverter()); } } ```
8,603,336
Due to me receiving a very bad datafile, I have to come up with code to read from a non delimited textfile from a specific starting position and a specific length to buildup a workable dataset. The textfile is not delimited in **any** way, **but** I do have the starting and ending position of each string that I need to read. I've come up with this code, but I'm getting an error and can't figure out why, because if I replace the 395 with a 0 it works.. e.g. Invoice number starting position = 395, ending position = 414, length = 20 ``` using (StreamReader sr = new StreamReader(@"\\t.txt")) { char[] c = null; while (sr.Peek() >= 0) { c = new char[20];//Invoice number string sr.Read(c, 395, c.Length); //THIS IS GIVING ME AN ERROR Debug.WriteLine(""+c[0] + c[1] + c[2] + c[3] + c[4]..c[20]); } } ``` Here is the error that I get: ``` System.ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection. at System.IO.StreamReader.Read(Char[] b ```
2011/12/22
[ "https://Stackoverflow.com/questions/8603336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1069299/" ]
Solved this ages ago, just wanted to post the solution that was suggested ``` using (StreamReader sr = new StreamReader(path2)) { string line; while ((line = sr.ReadLine()) != null) { dsnonhb.Tables[0].Columns.Add("InvoiceNum" ); dsnonhb.Tables[0].Columns.Add("Odo" ); dsnonhb.Tables[0].Columns.Add("PumpVal" ); dsnonhb.Tables[0].Columns.Add("Quantity" ); DataRow myrow; myrow = dsnonhb.Tables[0].NewRow(); myrow["No"] = rowcounter.ToString(); myrow["InvoiceNum"] = line.Substring(741, 6); myrow["Odo"] = line.Substring(499, 6); myrow["PumpVal"] = line.Substring(609, 7); myrow["Quantity"] = line.Substring(660, 6); ```
I've created a class called `AdvancedStreamReader` into my `Helpers` project on git hub here: <https://github.com/jsmunroe/Helpers/blob/master/Helpers/IO/AdvancedStreamReader.cs> It is fairly robust. It is a subclass of `StreamReader` and keeps all of that functionality intact. There are a few caveats: a) it resets the position of the stream when it is constructed; b) you should not seek the `BaseStream` while you are using the reader; c) you need to specify the newline character type if it differs from the environment and the file can only use one type. Here are some unit tests to demonstrate how it is used. ``` [TestMethod] public void ReadLineWithNewLineOnly() { // Setup var text = $"ƒun ‼Æ¢ with åò☺ encoding!\nƒun ‼Æ¢ with åò☺ encoding!\nƒun ‼Æ¢ with åò☺ encoding!\nHa!"; var bytes = Encoding.UTF8.GetBytes(text); var stream = new MemoryStream(bytes); var reader = new AdvancedStreamReader(stream, NewLineType.Nl); reader.ReadLine(); // Execute var result = reader.ReadLine(); // Assert Assert.AreEqual("ƒun ‼Æ¢ with åò☺ encoding!", result); Assert.AreEqual(54, reader.CharacterPosition); } [TestMethod] public void SeekCharacterWithUtf8() { // Setup var text = $"ƒun ‼Æ¢ with åò☺ encoding!{NL}ƒun ‼Æ¢ with åò☺ encoding!{NL}ƒun ‼Æ¢ with åò☺ encoding!{NL}Ha!"; var bytes = Encoding.UTF8.GetBytes(text); var stream = new MemoryStream(bytes); var reader = new AdvancedStreamReader(stream); // Pre-condition assert Assert.IsTrue(bytes.Length > text.Length); // More bytes than characters in sample text. // Execute reader.SeekCharacter(84); // Assert Assert.AreEqual(84, reader.CharacterPosition); Assert.AreEqual($"Ha!", reader.ReadToEnd()); } ``` I wrote this for my own use, but I hope it will help other people.
1,817,370
I would like to be able to use ediff with "git mergetool". I found some patches that alter the source code, which I don't want to do. Instead, I'd like to add ediff support with my .gitconfig. I know git has builtin support for emerge, but I prefer ediff. I attempted to add these lines to my .gitconfig: ``` [mergetool "ediff"] cmd = emacs --eval "(ediff-merge-files-with-ancestor \"$LOCAL\" \"$REMOTE\" \"$BASE\" nil \"$MERGED\")" ``` But when I try to run this with "git mergetool --tool=ediff", I get this: ``` eval: 1: Syntax error: "(" unexpected ``` What am I doing wrong?
2009/11/30
[ "https://Stackoverflow.com/questions/1817370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205756/" ]
Thanks, it also works in xemacs, however the quoting as in [the reply by pmr](https://stackoverflow.com/questions/1817370/using-ediff-as-git-mergetool/1817763#1817763) doesn't seem to work whereas I think the quoting in all the other replies is fine: ``` [mergetool "ediff"] cmd = xemacs -eval \"(ediff-merge-files-with-ancestor \\\"$PWD/$LOCAL\\\" \\\"$PWD/$REMOTE\\\" \\\"$PWD/$BASE\\\" nil \\\"$PWD/$MERGED\\\")\" [merge] tool = ediff ``` I put this above code in `~/.gitconfig`.
Combining my favorite ideas from above. This configuration uses emacsclient and require therefore that an emacs is already running. This also works for git difftool - it will invoke ediff-files. (When git difftool calls then the ancestor will be equal to the merged.) In .gitconfig: ``` [mergetool "ec-merge"] prompt = false cmd = ec-merge "$LOCAL" "$REMOTE" "$BASE" "$MERGED" trustExitCode = true [merge] tool = ec-merge [difftool] prompt = false ``` In ~/bin/ec-merge (make sure ~/bin is in your PATH): ``` #!/bin/bash set -e LOCAL=$(readlink -f "$1") REMOTE=$(readlink -f "$2") BASE=$(readlink -f "$3") MERGED=$(readlink -f "$4") emacsclient --eval "(jcl-git-merge \"$LOCAL\" \"$REMOTE\" \"$BASE\" \"$MERGED\")" ! egrep -q '^(<<<<<<<|=======|>>>>>>>|####### Ancestor)' "$MERGED" ``` In .emacs: ``` (server-start) (defvar jcl-save-and-kill-buffers-before-merge nil "Normally if emacs already visits any of the concerned files (local, remote, base or merged) ediff will ask it shall save and kill the buffer. If you always want to answer yes to this then set this to non-nil.") (defun jcl-git-merge (local remote ancestor merged) (when jcl-save-and-kill-buffers-before-merge (dolist (file (list local remote ancestor merged)) (setq file (file-truename file)) (let ((old-buffer (and file (find-buffer-visiting file)))) (when old-buffer (with-current-buffer old-buffer (save-buffer)) (kill-buffer old-buffer))))) (prog1 (if (string-equal ancestor merged) (progn (ediff-files local remote (list 'jcl-exit-recursive-edit-at-quit)) (format "ediff compared %s and %s" local remote)) (if ancestor (ediff-merge-files-with-ancestor local remote ancestor (list 'jcl-exit-recursive-edit-at-quit) merged) (ediff-merge-files local remote (list 'jcl-exit-recursive-edit-at-quit merged))) (format "ediff merged %s" merged)) (recursive-edit))) (defun jcl-exit-recursive-edit-at-quit () (add-hook 'ediff-quit-hook (lambda () (throw 'exit nil)) t t)) ``` Normally if emacs already visits any of the concerned files (local, remote, base or merged) ediff will ask it shall save and kill the buffer. If you like me always want to answer yes to this then add also this to your .emacs: ``` (setq jcl-save-and-kill-buffers-before-merge t) ```
35,899,498
I am trying to convert datetime value from this format `Wed Mar 9 09:48:09 PST 2016` into the following format `YYYY-MM-DD HH:mm:ss` I tried to use [moment](https://github.com/moment/moment) but it is giving me a warning. ``` "Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info. Arguments: [object Object] fa/<@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:9493 ia@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:10363 Ca@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15185 Ba@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15024 Aa@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:14677 Da@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15569 Ea@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:15610 a@http://localhost:1820/Resources/Scripts/Plugins/moment.min.js:7:41 @http://localhost:1820/Home/Test:89:29 jQuery.event.dispatch@http://localhost:1820/Resources/Scripts/Jquery/jquery.min.js:5225:16 jQuery.event.add/elemData.handle@http://localhost:1820/Resources/Scripts/Jquery/jquery.min.js:4878:6 " ``` according to <https://github.com/moment/moment/issues/1407> I should not be trying to use moment() to do this since it is not reliable. How can I reliably convert the `Wed Mar 9 09:48:09 PST 2016` into the following format `YYYY-MM-DD HH:mm:ss`?
2016/03/09
[ "https://Stackoverflow.com/questions/35899498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4967389/" ]
You could try using `Date.toJSON()` , `String.prototype.replace()` , `trim()` ```js var date = new Date("Wed Mar 9 09:48:09 PST 2016").toJSON() .replace(/(T)|(\..+$)/g, function(match, p1, p2) { return match === p1 ? " " : "" }); console.log(date); ```
Since you tagged your question with [moment](/questions/tagged/moment "show questions tagged 'moment'"), I'll answer using moment. First, the deprecation is because you are parsing a date string without supplying a format specification, and the string is not one of the standard ISO 8601 formats that moment can recognize directly. Use a format specifier and it will work just fine. ``` var m = moment("Wed Mar 9 09:48:09 PST 2016","ddd MMM D HH:mm:ss zz YYYY"); var s = m.format("YYYY-MM-DD HH:mm:ss"); // "2016-03-09 09:48:09" ``` Secondly, recognize that in the above code, `zz` is just a placeholder. Moment does not actually interpret time zone abbreviations because there are just [too many ambiguities](https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations) ("CST" has 5 different meanings). If you needed to interpret this as `-08:00`, then you'd have to do some string replacements on your own. Fortunately, it would appear (at least from what you asked) that you don't want any time zone conversions at all, and thus the above code will do the job.
17,442,340
I have create an popup menu in my app the problem with it is when i open the popup menu and then scroll the page the popup menu also scrolls up with the page even i tried using data-dismissible="false" but nothing happen still the problem remains same. Thanks in advance.
2013/07/03
[ "https://Stackoverflow.com/questions/17442340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2307391/" ]
There's an easy fix for this problem. Just prevent page scrolling when popup is active. Working **`jsFiddle`** example: <http://jsfiddle.net/Gajotres/aJChc/> For this to work popup needs to have an attribute: **`data-dismissible="false"`** it will prevent popup closure when clicked outside of it. Another attribute can be used: **`data-overlay-theme="a"`** it will color popup overlay div. That is a DIV that covers screen when popup is opened and prevents popup closure. And this javascript will work on every possible popup: ``` $(document).on('popupafteropen', '[data-role="popup"]' ,function( event, ui ) { $('body').css('overflow','hidden'); }).on('popupafterclose', '[data-role="popup"]' ,function( event, ui ) { $('body').css('overflow','auto'); }); ```
For me this method didn't work, it works on browser but not in Phone Gap application. So I resolve it in this way: ``` $('#Popup-id').on({ popupbeforeposition: function(){ $('body').on('touchmove', false); }, popupafterclose: function(){ $('body').off('touchmove'); } }); ``` Hope it helps!
11,994,008
I'm totally new to AWK, however I think this is the best way to solve my problem and a good time to learn AWK. I am trying to read a large data file that is created by a simulation program. The output is made to be readable by humans, so its formatting isn't very consistent. An example of the output is in this image <http://i.imgur.com/0kf8l.png> I need a way to find a line like "He 2 4686A -2.088 0.0071", by specifying the "He 2 4686A" part and get the following two numbers. The problem is the line "He 2 4686A -2.088 0.0071" can appear anywhere in the table. I know how to find the entry "He 2 4686A", but I don't know which of the 4 columns it's in. So I don't know how to address the values that follow it. A command that lets me just read the next two words, or tells me the location of the pattern once a match is found will both help. /He 2 4686A/ finds the line Ca A 3970A -0.900 0.1100 He 2 4686A -2.088 0.0071 S 3 18.67m -0.371 0.3721 Ar 4 444.7A -2.124 0.0066 Any help is appreciated.
2012/08/16
[ "https://Stackoverflow.com/questions/11994008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585760/" ]
I ran into the same problem; it seems you need these three settings in particular: 1. `STATIC_ROOT` must be defined in your `settings.py`, for example: ``` STATIC_ROOT = os.path.join(PROJECT_PATH, 'served/static/') ``` Where `PROJECT_PATH` is your project root (in your case, the absolute path to the `myproject_django` directory. 2. Similarly, `STATIC_URL` must also be set (Django will throw an ImproperlyConfigured error anyway, if you don't). Your current setting of `'/static/'` is fine. 3. In your root `urls.py`, configure the static urls: ``` from django.conf import settings from django.conf.urls.static import static ... urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ``` Finally, run `python manage.py collectstatic`; this will copy all the files from `/path/to/site-packages/django/contrib/admin/static/admin/` to `/served/static/`. (You can read more about how Django serves static files [here](https://docs.djangoproject.com/en/dev/howto/static-files/)). Now when you run `foreman start`, you should see the admin with styling. Don't forget to add `served/static/` to your `.gitignore`!
I found [here](http://www.realpython.com/blog/python/migrating-your-django-project-to-heroku/) good way to resolve all my problems with Django on heroku
7,428,610
Is there a way to get the parameters from a XML view, modify some stuff on it and then use it as content view ? Let's say I have a normal LinearLayout and I want to make that work: ``` LinearLayout layout = (LinearLayout) findViewById(R.layout.main); setContentView(layout); ``` Instead of : ``` setContentView(R.layout.main); ```
2011/09/15
[ "https://Stackoverflow.com/questions/7428610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/880670/" ]
Yes. To be more specific, we need more specific info from you. **Edit** You can, for example, do the following. Say you have in your xml specification a TextView: ``` <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/mytv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="22sp" android:textStyle="bold"/> </RelativeLayout> ``` Now you want to center horizontal the TextView programmatically: ``` setContentView(R.id.main); TextView myTV = (TextView) findViewById(R.id.mytv); RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) myTV.getLayoutParams(); lp.addRule(RelativeLayout.CENTER_HORIZONTAL); myTV.setLayoutParams(lp); ``` You just set the contentview at the start, and don't need to set it again when you change the variables.
You can do anyything you want to the layouts even after setContentView. When you do operations like add items to a layout or set a background, the views in the screen are redrawn. onCreate method is where you can modify layouts as it it about to begin drawing on to a screen.
14,512,182
I am looking for a simple code to create a WebSocket server. I found phpwebsockets but it is outdated now and doesn't support the newest protocol. I tried updating it myself but it doesn't seem to work. ``` #!/php -q <?php /* >php -q server.php */ error_reporting(E_ALL); set_time_limit(0); ob_implicit_flush(); $master = WebSocket("localhost",12345); $sockets = array($master); $users = array(); $debug = false; while(true){ $changed = $sockets; socket_select($changed,$write=NULL,$except=NULL,NULL); foreach($changed as $socket){ if($socket==$master){ $client=socket_accept($master); if($client<0){ console("socket_accept() failed"); continue; } else{ connect($client); } } else{ $bytes = @socket_recv($socket,$buffer,2048,0); if($bytes==0){ disconnect($socket); } else{ $user = getuserbysocket($socket); if(!$user->handshake){ dohandshake($user,$buffer); } else{ process($user,$buffer); } } } } } //--------------------------------------------------------------- function process($user,$msg){ $action = unwrap($msg); say("< ".$action); switch($action){ case "hello" : send($user->socket,"hello human"); break; case "hi" : send($user->socket,"zup human"); break; case "name" : send($user->socket,"my name is Multivac, silly I know"); break; case "age" : send($user->socket,"I am older than time itself"); break; case "date" : send($user->socket,"today is ".date("Y.m.d")); break; case "time" : send($user->socket,"server time is ".date("H:i:s")); break; case "thanks": send($user->socket,"you're welcome"); break; case "bye" : send($user->socket,"bye"); break; default : send($user->socket,$action." not understood"); break; } } function send($client,$msg){ say("> ".$msg); $msg = wrap($msg); socket_write($client,$msg,strlen($msg)); } function WebSocket($address,$port){ $master=socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() failed"); socket_set_option($master, SOL_SOCKET, SO_REUSEADDR, 1) or die("socket_option() failed"); socket_bind($master, $address, $port) or die("socket_bind() failed"); socket_listen($master,20) or die("socket_listen() failed"); echo "Server Started : ".date('Y-m-d H:i:s')."\n"; echo "Master socket : ".$master."\n"; echo "Listening on : ".$address." port ".$port."\n\n"; return $master; } function connect($socket){ global $sockets,$users; $user = new User(); $user->id = uniqid(); $user->socket = $socket; array_push($users,$user); array_push($sockets,$socket); console($socket." CONNECTED!"); } function disconnect($socket){ global $sockets,$users; $found=null; $n=count($users); for($i=0;$i<$n;$i++){ if($users[$i]->socket==$socket){ $found=$i; break; } } if(!is_null($found)){ array_splice($users,$found,1); } $index = array_search($socket,$sockets); socket_close($socket); console($socket." DISCONNECTED!"); if($index>=0){ array_splice($sockets,$index,1); } } function dohandshake($user,$buffer){ console("\nRequesting handshake..."); console($buffer); //list($resource,$host,$origin,$strkey1,$strkey2,$data) list($resource,$host,$u,$c,$key,$protocol,$version,$origin,$data) = getheaders($buffer); console("Handshaking..."); $acceptkey = base64_encode(sha1($key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true)); $upgrade = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: $acceptkey\r\n"; socket_write($user->socket,$upgrade,strlen($upgrade)); $user->handshake=true; console($upgrade); console("Done handshaking..."); return true; } function getheaders($req){ $r=$h=$u=$c=$key=$protocol=$version=$o=$data=null; if(preg_match("/GET (.*) HTTP/" ,$req,$match)){ $r=$match[1]; } if(preg_match("/Host: (.*)\r\n/" ,$req,$match)){ $h=$match[1]; } if(preg_match("/Upgrade: (.*)\r\n/",$req,$match)){ $u=$match[1]; } if(preg_match("/Connection: (.*)\r\n/",$req,$match)){ $c=$match[1]; } if(preg_match("/Sec-WebSocket-Key: (.*)\r\n/",$req,$match)){ $key=$match[1]; } if(preg_match("/Sec-WebSocket-Protocol: (.*)\r\n/",$req,$match)){ $protocol=$match[1]; } if(preg_match("/Sec-WebSocket-Version: (.*)\r\n/",$req,$match)){ $version=$match[1]; } if(preg_match("/Origin: (.*)\r\n/",$req,$match)){ $o=$match[1]; } if(preg_match("/\r\n(.*?)\$/",$req,$match)){ $data=$match[1]; } return array($r,$h,$u,$c,$key,$protocol,$version,$o,$data); } function getuserbysocket($socket){ global $users; $found=null; foreach($users as $user){ if($user->socket==$socket){ $found=$user; break; } } return $found; } function say($msg=""){ echo $msg."\n"; } function wrap($msg=""){ return chr(0).$msg.chr(255); } function unwrap($msg=""){ return substr($msg,1,strlen($msg)-2); } function console($msg=""){ global $debug; if($debug){ echo $msg."\n"; } } class User{ var $id; var $socket; var $handshake; } ?> ``` and the client: ``` var connection = new WebSocket('ws://localhost:12345'); connection.onopen = function () { connection.send('Ping'); // Send the message 'Ping' to the server }; // Log errors connection.onerror = function (error) { console.log('WebSocket Error ' + error); }; // Log messages from the server connection.onmessage = function (e) { console.log('Server: ' + e.data); }; ``` If there is anything wrong in my code can you help me fix it? Console in Firefox says: > > Firefox can't establish a connection to the server at ws://localhost:12345/. > > >
2013/01/24
[ "https://Stackoverflow.com/questions/14512182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1839439/" ]
I was in the same boat as you recently, and here is what I did: 1. I used the [phpwebsockets](http://socketo.me/) code as a reference for how to structure the server-side code. (You seem to already be doing this, and as you noted, the code doesn't actually work for a variety of reasons.) 2. I used PHP.net to read the details about [every socket function](https://www.php.net/manual/en/ref.sockets.php) used in the phpwebsockets code. By doing this, I was finally able to understand how the whole system works conceptually. This was a pretty big hurdle. 3. I read the actual [WebSocket draft](https://www.w3.org/TR/websockets/). I had to read this thing a bunch of times before it finally started to sink in. You will likely have to go back to this document again and again throughout the process, as it is the one definitive resource with correct, up-to-date information about the WebSocket API. 4. I coded the proper handshake procedure based on the instructions in the draft in #3. This wasn't too bad. 5. I kept getting a bunch of garbled text sent from the clients to the server after the handshake and I couldn't figure out why until I realized that the data is encoded and must be unmasked. The following link helped me a lot here: (~~original [link](http://srchea.com/blog/2011/12/build-a-real-time-application-using-html5-websockets/) broken~~) [Archived copy](https://web.archive.org/web/20120918000731/http://srchea.com/blog/2011/12/build-a-real-time-application-using-html5-websockets/). Please note that the code available at this link has a number of problems and won't work properly without further modification. 6. I then came across the following SO thread, which clearly explains how to properly encode and decode messages being sent back and forth: [How can I send and receive WebSocket messages on the server side?](https://stackoverflow.com/questions/8125507/how-can-i-send-and-receive-websocket-messages-on-the-server-side) This link was really helpful. I recommend consulting it while looking at the WebSocket draft. It'll help make more sense out of what the draft is saying. 7. I was almost done at this point, but had some issues with a WebRTC app I was making using WebSocket, so I ended up asking my own question on SO, which I eventually solved: [What is this data at the end of WebRTC candidate info?](https://stackoverflow.com/q/14425382/8112776) 8. At this point, I pretty much had it all working. I just had to add some additional logic for handling the closing of connections, and I was done. That process took me about two weeks total. The good news is that I understand WebSocket really well now and I was able to make my own client and server scripts from scratch that work great. Hopefully the culmination of all that information will give you enough guidance and information to code your own WebSocket PHP script. *Good luck!* --- **Edit**: This edit is a couple of years after my original answer, and while I do still have a working solution, it's not really ready for sharing. Luckily, someone else on GitHub has almost identical code to mine (but much cleaner), so I recommend using the following code for a working PHP WebSocket solution: <https://github.com/ghedipunk/PHP-Websockets/blob/master/websockets.php> --- **Edit #2**: While I still enjoy using PHP for a lot of server-side related things, I have to admit that I've really warmed up to Node.js a lot recently, and the main reason is because it's better designed from the ground up to handle WebSocket than PHP (or any other server-side language). As such, I've found recently that it's a lot easier to set up both Apache/PHP and Node.js on your server and use Node.js for running the WebSocket server and Apache/PHP for everything else. And in the case where you're on a shared hosting environment in which you can't install/use Node.js for WebSocket, you can use a free service like [Heroku](https://www.heroku.com/free) to set up a Node.js WebSocket server and make cross-domain requests to it from your server. Just make sure if you do that to set your WebSocket server up to be able to handle cross-origin requests.
As far as I'm aware [Ratchet](http://socketo.me/) is the best PHP WebSocket solution available at the moment. And since it's [open source](https://github.com/cboden/Ratchet) you can see how the author has built this WebSocket solution using PHP.
674,700
I was for quite some time under the impression that a `for` loop could exist *solely* in the following format: ``` for (INITIALIZER; STOP CONDITION; INC(DEC)REMENTER) { CODE } ``` This is, however, most *definitely* not the case; take a look at this JavaScript implementation of the [Fisher-Yates Shuffle](http://en.wikipedia.org/wiki/Knuth_shuffle): ``` shuffle = function(o) { for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; }; ``` This little snippet completely blows my mind; how in the world is so much going on inside a simple for loop declaration? I mean... it doesn't even open a brace! All of the magic is being done *right there* inside the `for` statement. It'd be absolutely wonderful if somebody could provide a relatively thorough explanation as to how in the world this voodoo is doing what it does. Much appreciated in advance.
2009/03/23
[ "https://Stackoverflow.com/questions/674700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59107/" ]
The code you quote is obfuscated in my opinion. There are much clearer ways to write the same functionality. However, your understanding is pretty much right. The following is the exact same code, except for whitespace and comments. ``` for ( // Initializer var j, x, i = o.length; // Continue condition i; // Operation to be carried out on each loop j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x ) // empty body, equivalent to { } ; ``` It's much clearer to write the equivalent: ``` var j,x,i = o.length; while(i) { j = parseInt(Math.random() * i); x = o[--i]; o[i] = o[j]; o[j] = x; } ``` There are other optimisations that could be made for readability - including using `while(i > 0)` instead of `while(i)`, and splitting out the `--i` into an `i--` on a separate line. There's really no reason for for() to exist, except for readability. These two are equivalent: ``` { // this block is to scope int i int i=0; while(i<100) { myfunc(i); i++; } } for(int i=0; i<100; i++) { myfunc(i); } ``` You should use whichever is most readable for a given time. I'd argue that the author of your code has done the opposite. In fairness, he may have done this in order to achieve a smaller JS file for faster loading (this is the kind of transform an automated code compactor could do).
They've pretty much just moved the body of the loop into the incrementer section. You can re-write the for loop as a while loop to get some idea of what it is doing: ``` shuffle=function(o) { var j; //Random position from 0 up to the current position - 1 var x; //temp holder for swapping positions var i=o.length; //current position while(i>0) { // Loop through the array j = parseInt(Math.random()*i); //get a lower position x = o[--i]; // decrement the position and store that position's value in the temp var o[i]=o[j]; // copy position j to position i o[j]=x; // copy the temp value that stored the old value at position i into position j } return o; } ``` The first three var's are the initialzier expanded out, the check in the while is the stop condition and the body of the while is what was done in the incrementer portion of the for. Edit: Corrected per Gumbo's comment
909,361
i want to realize a construct in MS SQL that would look like this in Oracles PL/SQL: ``` declare asdf number; begin for r in (select * from xyz) loop insert into abc (column1, column2, column3) values (r.asdf, r.vcxvc, r.dffgdfg) returning id into asdf; update xyz set column10 = asdf where ID = r.ID; end loop; end; ``` Any idea how to realize this would be helpful. Thanks in advance
2009/05/26
[ "https://Stackoverflow.com/questions/909361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109321/" ]
If I understood what you asked (I'm not proficient with PL/SQL), looks like a pretty easy task: ``` INSERT INTO abc(column1, column2, column3) SELECT asdf, vcxvc, dffgdfg FROM xyz; UPDATE xyz SET column10 = id; ``` But I'm just guessing your intention, hope haven't misunderstood. P.S.: as someelse already pointed out, you must have already created table abc
Hope this is what you are looking for: ``` declare asdf number; begin for r in (select * from xyz) loop insert into abc (column1, column2, column3) values (r.asdf, r.vcxvc, r.dffgdfg) returning id into asdf; update xyz set column10 = asdf where ID = r.ID; end loop; end; ``` *would become* ``` DECLARE @asdf int DECLARE @ID int DECLARE @MyTmpTableVar table(asdf int, abc_id int) // insert records from your cursor r into table abc, // and return a temporary table with "id" and "asdf" fields from the xyz table INSERT INTO abc(column1, column2, column3) OUTPUT asdf, id INTO @MyTmpTableVar SELECT r.asdf, r.vcxvc, r.dffgdfg FROM xyz // if it would return just one row and you wanted to find the value //SELECT @asdf = asdf, @id = abc_id //FROM @MyTmpTableVar // update the table xyz with the values stored in temporary table // restricting by the key "id" UPDATE xyz SET xyz.column10 = t.asdf FROM @MyTmpTableVar AS t WHERE xyz.id = t.abc_id ``` --- The sqlServer version of the **returning clause** in Oracle is the **OUTPUT** clause. Please visit **[this msdn page](http://msdn.microsoft.com/en-us/library/ms177564.aspx)** for full information
82,937
I'm implementing a D3D10 version of my renderer (not porting to avoid losing Windows XP support). I didn't go straight to D3D11 because MSDN and other sources recommend upgrading to 10 and then to 11. From what I've read so far, what used to be done with `IDirect3D9::SetRenderState` is done in D3D10 with `ID3D10RasterizerState`, `ID3D10BlendState` and `ID3D10DepthStencilState`. You declare and fill a descriptor structure, tell the device to create a state object, and then bind it to the device. For example: ``` //D3D9 m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); //D3D10 //This defines the ID3D10RasterizerStatePtr type used below _COM_SMARTPTR_TYPEDEF(ID3D10RasterizerState, __uuidof(ID3D10RasterizerState) ); //... ID3D10RasterizerStatePtr pRasterState; D3D10_RASTERIZER_DESC rasterDesc; rasterDesc.CullMode = D3D10_CULL_NONE; if( !CheckErrorCode( m_pImpl->pDevice->CreateRasterizerState( &rasterDesc, &pRasterState ), "InitDevice", "CreateRasterizerState" ) ) return false; m_pImpl->pDevice->RSSetState( pRasterState ); ``` However, now that I have to "port" the line... ``` m_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE ); ``` ... I cannot find a related property in any of the descriptors. From what I've seen, most examples implement lighting in HLSL, so perhaps I don't need to explicitly disable lighting, because my shaders don't do it? This is a desktop app, no fancy Metro stuff. Using unmanaged C++.
2014/09/04
[ "https://gamedev.stackexchange.com/questions/82937", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/15732/" ]
Direct3D 10.x and Direct3D 11.x do not support the 'legacy fixed-function' pipeline that your Direct3D 9 code is using. Preparing to move to Direct3D 10 or 11 means eliminating all fixed-function usage and moving to programmable shaders. It is also apparent from your code snippet that you are not using the state objects correctly. In Direct3D 9, you set hundreds of individual settings. In Direct3D 10 and Direct3D 11, you manage all state through a few objects and a few simple individual switches such as primitive topology. You have really need to take a step back and understand the major shifts in technology here. All fixed-function rendering needs to be replaced with programmable shaders, state management needs to be changed from a 'lazy-evaluation 'model to a 'known groups' model. In other words, you cannot meanigfully translate the single line: `m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );` by itself to Direct3D 10.x or 11.x. You need to know the state it is grouped with and how you are using them *all* together to render your scene. ``` ID3D10RasterizerStatePtr pRasterState; D3D10_RASTERIZER_DESC rasterDesc; rasterDesc.CullMode = D3D10_CULL_NONE; if( !CheckErrorCode( m_pImpl->pDevice->CreateRasterizerState( &rasterDesc, &pRasterState ), "InitDevice", "CreateRasterizerState" ) ) return false; ``` This code will always fail because you did not fully initialize the rasterizer state object which also sets fill mode, winding mode, depth bias/clamp, depth clipping, scissors, and MSAA line AA modes all together. And once you create that state object, it is immutable. To change any setting in that object, you create a new one with all the states specified. The [DirectX Tool Kit](https://github.com/Microsoft/DirectXTK) for Direct3D 11 provides a lot of basic functionality that you may find useful for replacing old D3DX9 and concepts like "Draw\*UP", common used state object combinations, and a bunch of stock programmable shaders you can start learning from. Take some time to really learn the Direct3D 11 API basics before jumping into a porting job for an old codebase that is not even really up to the programmable shader model for Direct3D 9.0 (circa 2004). Start with the resources at [Getting Started with Direct3D 11](https://walbourn.github.io/getting-started-with-direct3d-11/) and the samples on [MSDN Code Gallery](https://walbourn.github.io/directx-sdk-samples-catalog/). When you've got a good understanding of how to program for Direct3D 11, then take a look at the seminal 'porting from Direct3D 9' presentation [Windows to Reality: Getting the Most out of Direct3D 10 Graphics in Your Games](https://walbourn.github.io/download/Windows-to-Reality-Getting-the-Most-out-of-Direct3D-10-Graphics-in-your-Games.zip). All those recommendations would apply to moving from Direct3D 9 to Direct3D 11.x as well.
You're right, there is no lighting in D3D10 unless you implement it yourself in shaders.
344,537
I have a work question. In our attempt to give names to fields on a repair card we are now using the phrase "Source card" and "Child card". My opinion is that it would be more logical to use "Parent card" and "Child card", but if I want to keep using the term "Source card" how would I now name the child card??? > > "Parent is related to child" > as > "source is related to \_\_\_\_\_" > > >
2016/08/24
[ "https://english.stackexchange.com/questions/344537", "https://english.stackexchange.com", "https://english.stackexchange.com/users/192864/" ]
Somewhat similar and probably rare and usually circulated in Christian circles. > > Today, I have a meeting with Pastor Pillow and Sister Sheets. > > > It uses a typical term for a Christian leader (pastor and sister), but uses a last name of articles found on a bed. Thereby it refers to scheduled time in bed, probably asleep.
Focusing on the sickness aspect rather than the being in bed part should produce a lot of phrases in English, probably predominantly euphemisms for the actual act of vomiting. If I wanted to make light of having been so ill recently that I'd thrown up, I might pick one of: * driving the porcelain bus (gripping the toilet sides as though it were a steering wheel) * airing the diced carrots (a reference to the seemingly universal presence of carrots in vomit, regardless of how many days/weeks have passed since they were last consumed) * yawning for the hearing impaired (adding a visible dimension to an act that might otherwise look like a yawn if the observer were deaf) * shouting soup * out of stomach experience (parody of an out-of-body experience, where the narrator claims to have observed their own actions from a distance) * had a dodgy curry (when the cause was probably something that would not get as much sympathy) Would any of these delightful imageries work on the average non-native English listener? Probably not, so pick your audience carefully with them..
10,187,280
I'm trying to "select" a img inside a $(this) selector. I know I can find it by using `.find('img')` but is this possible: `$("img",this)` ? What's the most optimal way to do this? Originally code ``` <a class="picture" href="test.html"> <img src="picture.jpg" alt="awesome"> </a> ```
2012/04/17
[ "https://Stackoverflow.com/questions/10187280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1071525/" ]
> > What's the most optimal way to do this? > > > Both `$(this).find('img')` and `$('img', this)` are equivalent. From the docs: > > Internally, selector context is implemented with the .find() method, > so $('span', this) is equivalent to $(this).find('span'). > > > <http://api.jquery.com/jQuery/>
Why can't you use `.find('img')`? it works to me : <http://jsfiddle.net/nnmEY/>
51,070
Is it possible to push or pop a length like parindent? I want to change it temporarily but reset it soon after. I have a solution but looking for something a little nicer. I'll post it as an answer.
2012/04/07
[ "https://tex.stackexchange.com/questions/51070", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/11637/" ]
You can implement a stack without using LaTeX3 as well, by using a token list and some macros. That would work as follows: ``` \documentclass{article} \newtoks\paridstack \paridstack={\empty} \def\push#1#2{% \begingroup\toks0={{#1}}% \edef\act{\endgroup\global#2={\the\toks0 \the#2}}\act }% push #1 onto #2 \def\pop#1{% \begingroup \edef\act{\endgroup\noexpand\splitList\the#1(tail)#1}\act }% pop from #1 \def\splitList#1#2(tail)#3{% \ifx#1\empty Can't pop an empty stack.\else#1\global#3={#2}\fi } \begin{document} \noindent \push{200pt}{\paridstack}% \pop{\paridstack}\\ \push{200pt}{\paridstack}% \push{300pt}{\paridstack}% \push{400pt}{\paridstack}% \pop{\paridstack}\\ \pop{\paridstack}\\ \pop{\paridstack}\\ \pop{\paridstack} \end{document} ``` It will print `200pt` `400pt` `300pt` `200pt` `Can't pop from an empty stack.`. You can of course replace the error message with some error handling code, or some default value to be returned. This is all based on an example in chapter 14 of [TeX by Topic](http://tex.loria.fr/general/texbytopic.pdf). If you want to set `\parindent` directly instead of just printing the value, simply change `#1` in the `\else` of `\splitList` to `\parindent=#1`.
This solution is just a response to Roelof. I hope it is appropriate here. I replace `\empty` by `\roelofstackbegin` in his solution. This is safer than using `\empty`. Roelof's stack looks like an all-purpose stack. So any possible source of failure should be avoided. ``` \documentclass{article} \makeatletter \newtoks\roelofstack \roelofstack={\roelofstackbegin} \def\roelofstackbegin{\empty} % push #1 onto #2: \def\push#1#2{% \begingroup \toks0={{#1}}% \edef\act{\endgroup\global#2={\the\toks0 \the#2}}% \act } % pop from #1: \def\pop#1{% \begingroup \edef\act{\endgroup\noexpand\SplitOff\the#1(tail)#1}% \act } \def\SplitOff#1#2(tail)#3{% \ifx#1\roelofstackbegin \errhelp{Attempting to pop empty stack #3.}% \errmessage{You can't pop an empty stack.}% \else #1\global#3={#2}% \fi } \makeatother % Tests: \begin{document} \noindent \push{\empty}{\roelofstack} \pop{\roelofstack} \push{200pt}{\roelofstack} \pop{\roelofstack}\par \push{200pt}{\roelofstack} \push{300pt}{\roelofstack} \push{400pt}{\roelofstack} \pop{\roelofstack}\par \pop{\roelofstack}\par \pop{\roelofstack}\par % \pop{\roelofstack} % Popping empty stack. \end{document} ```
73,207,202
When load more is clicked, `count` value is not getting updated only on the second click it is getting updated. Expectation is on load more button click value should be passed as `2`, but now it is sending as `1`. what I'm doing wrong here. Please guide Below is the sample code. ``` const [count, setCount] = useState(1); fetchData() { ..... } loadMore() { .... fetchData() } ``` Render HTML Method: ``` <button onClick={ () => { setCount(count + 1); loadMore(); }} ```
2022/08/02
[ "https://Stackoverflow.com/questions/73207202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16491376/" ]
The error was pretty stupid, I wrote "$this->$price" instead of "$this->price". Sorry
``` return User::where('id', $this->seller_id)->update(array('balance' => $money)); ```
8,434,356
Page link I am working on is <http://www.whatcar.com/car-news/subaru-xv-review/260397> I am trying to automate 'clicking the google link' but am having no luck and keep receiving an error. Link HTML: ``` <a tabindex="0" role="button" title="" class="s5 JF Uu" id="button" href="javascript:void(0);" aria-pressed="false" aria-label="Click here to publicly +1 this."></a> ``` My code: ``` @browser.link(:class, "s5 JF Uu").click ``` Error message: ``` unable to locate element, using {:class=>"s5 JF Uu", :tag_name=>"a"} (Watir::Exception::UnknownObjectException) ./step_definitions/11.rb:12:in `/^On the page I click 'Twitter' , Facebook and Google button$/' 11.feature:8:in `When On the page I click 'Twitter' , Facebook and Google+ button' ```
2011/12/08
[ "https://Stackoverflow.com/questions/8434356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1049663/" ]
The link is inside a frame. To make it even more fun, frame `id` is different every time the page is refreshed. ``` browser.frames.collect {|frame| frame.id} => ["I1_1323429988509", "f3593c4f374d896", "f4a5e09c20624c", "stSegmentFrame", "stLframe"] browser.refresh => [] browser.frames.collect {|frame| frame.id} => ["I1_1323430025052", "fccfdf9410ef34", "f11036dad706668", "stSegmentFrame", "stLframe"] ``` `I1_1323429988509` and `I1_1323430025052` is the frame. Since `I1_` part is always the same, and no other frame has that, you can access the frame like this: ``` browser.frame(:id => /I1_/) ``` Since there is only one link inside the frame: ``` browser.frame(:id => /I1_/).as.size => 1 ``` You can click the link like this: ``` browser.frame(:id => /I1_/).a.click ``` Or if you prefer to be more explicit ``` browser.frame(:id => /I1_/).a(:id => "button").click ``` That will open a new browser window, and a new challenge is here! :)
**The technical answer:** The class of the button on the page that you linked is different for me than the class that you list. It looks like it behaves differently based on the cookies on your local machine (which would be absent during a Watir-driven Firefox or IE session). You would need to find a different element that is not dynamic to hook into. **The ethical answer:** It is questionable that you are attempting to automate the promotion of online articles through social media. Watir/Watir-Webdriver is not a spam bot, and the services you are using specifically prohibit the use of automation/bots.
67,981,140
I have an alert component which has a flag `isVisible`, this flag is becoming true when the component is created, and also in the created HOOK I have a `setTimeout` which starts if the component receives DESTROY boolean prop: ``` props: { destroy: { type: Boolean, default: false, }, } ``` ``` data() { return { isVisible: false, } } ``` ``` created() { this.isVisible = true if (this.destroy) { setTimeout(() => { this.isVisible = false }, 2500) }, } ``` I am using VUE UTILS / JEST to test if the component disappears after `setTimeout` is over, I've tried: ``` test('Component dissapears after 2.5 seconds when it receives DESTROY prop', async () => { const component = wrapper.get('[data-test-id="info-alert-wrapper"]') await wrapper.setProps({ destroy: true, }) await wrapper.vm.$options.created.call() expect(component.isVisible()).toBeFalsy() }) ``` But it responds: `TypeError: Cannot set property 'isVisible' of undefined` Can somebody help me with this? thank u! :)
2021/06/15
[ "https://Stackoverflow.com/questions/67981140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16230004/" ]
Your need to use fake timers here. After all imports call `jest.useFakeTimers()`. Then in test after mounting the component call `jest.runTimersToTime(2500)`. And after that you can do your assertions. Test example: ``` jest.useFakeTimers() test('Component disappears after 2.5 seconds when it receives DESTROY prop', () => { const wrapper = shallowMount(YourSuperComponent, { propsData: { destroy: true } }) jest.runTimersToTime(2500) expect(wrapper.vm.isVisible).toBe(false) }) ```
Answer from @Eduardo is correct, just noting that Jest renamed **runTimersToTime()** to **advanceTimersByTime()** since Jest 22.0.0
298,177
Or vice versa. Or perhaps a name for the pair itself? For example: * *hold* an *opinion* * *make* a *complaint* * *offer* an *apology* Also, where might I find a list of such pairs? --- EDIT: I chose my title wording randomly. I have no idea whether 'cognate verb' is the correct term for these things. However, I've just found out that 'cognate objects' are a defined class in linguistics, so perhaps my choice of words was inappropriate. I'm going to leave the title as it is, anyway.
2016/01/06
[ "https://english.stackexchange.com/questions/298177", "https://english.stackexchange.com", "https://english.stackexchange.com/users/61558/" ]
These phrases are sometimes called "collocations". I don't know of a word for one element in the collocation.
As pointed out by others, the name for the phenomenon you've isolated is ***verb noun collocation*** or ***verb + noun collocation***. If you google these phrases, you should be directed to various sites which give examples. I know of no master list, but you could probably start to compile one yourself.
481,947
I am having problems while trying to start my first node using KVM (QEMU 2.0.0) and MAAS. Automatic detection worked fine, and during the commission (virtual machine window) I get errors such as: ``` Booting under MAAS directions... nomodeset iscsi_target_name=(...) maas loading amd64/generic/trusty/release/boot-kernel..... Boot failed: press a key to retry, or wait for reset ......... ``` and ``` modprobe: ERROR: could not insert 'impi_si': no such device Success Success Success (...) ``` And after that, the virtual machine (node) turns off automatically, and the MAAS GUI shows the node as "Ready" (in green) but when trying to start it, I get this error message: ``` The action "Start selected nodes" could not be performed on 1 node because its state does not allow that action. ``` When opening the section with the properties of the node, I get this other error message: ``` You can boot this node using an adequately configured DHCP server. See https://maas.ubuntu.com/docs/nodes.html for instructions. ``` The DHCP server is running on the MAAS server, because the node does get its IP when booting, and it is set up on the Web GUI as well... Any idea of why is my node not starting?
2014/06/11
[ "https://askubuntu.com/questions/481947", "https://askubuntu.com", "https://askubuntu.com/users/287964/" ]
In the later days of the teletypes, it was adopted by the deaf community as a form of communications. Officially called TDD (Telephone Device for the Deaf) with the development & refinement of equipment that used the same communication media of Baudot and Ascii, it was widely adopted by the deaf to sign "TTY" because it's easier to sign than than "TDD". Nowdays, it's fast becoming ancient as deaf people use video relays to communicate. TTY/TDD's are mainly found in public settings at airports, government agencies, public venues, etc. that are hardly used due to the proliferation of wireless devices.
Some of us want a one sentence answer: > > is this just a fancy name for saying "I am using the terminal" or **tty = the "the process associated to the terminal process that exchanges information with the system and you"** > > > I like the visual analogy here: <https://askubuntu.com/a/482244/230288> you can see how the type writer is the physical process that gives the info you type to the system and the paper displays the response from the system. Please correct me if I'm wrong.
21,878,005
I am using dc.js, I want to add filter based on checkbox selection. Here is my scenario ![enter image description here](https://i.stack.imgur.com/cBHUT.png) When i select checkboxes based on that i need filter. Here is my code ``` var ndx = crossfilter(readData); var practiceDimension = ndx.dimension(function (d) { return d.practice_name; }); $('#treeview input[name="practice_name[]"]:checked').each(function() { if(searchPracticeArray.indexOf($(this).val()) == -1) searchPracticeArray.push($(this).val()); // If I added searchPracticeArray as filter parameter then it's not working // searchPracticeArray value are ['LPS','Mercy'] practiceDimension = practiceDimension.filter($(this).val()); bubbleChart.filter($(this).val()); }); ``` Currently i have two checkbox but it should be more then two and more.
2014/02/19
[ "https://Stackoverflow.com/questions/21878005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/998600/" ]
HTTP is stateless protocol and the global variable are not preserved between postback. You can store data required to be preserved in `postback` in ViewState. If the data is not small it would be better for storing it in some persistent medium like XML / database to keep the ViewState as small as possible as it is added to page size ultimately. ``` ViewState["listTempImages"] = listTempImages; ``` Later access the object by getting from `ViewState` ``` listTempImages = ViewState["listTempImages"] as List<string>; ``` Stateless protocol ------------------ > > In computing, a stateless protocol is a communications protocol that > treats each request as an independent transaction that is unrelated to > any previous request so that the communication consists of independent > pairs of requests and responses. A stateless protocol does not require > the server to retain session information or status about each > communications partner for the duration of multiple requests. In > contrast, a protocol which requires the keeping of internal state is > known as a stateful protocol. To read more about state less see this > wikipedia [article](http://en.wikipedia.org/wiki/Stateless_protocol) > > > View state ---------- > > View state is the method that the ASP.NET page framework uses to > preserve page and control values between round trips. When the HTML > markup for the page is rendered, the current state of the page and > values that must be retained during postback are serialized into > base64-encoded strings. This information is then put into the view > state hidden field or fields, [MSDN](http://msdn.microsoft.com/en-us/library/bb386448.aspx) > > >
As Adil says HTTP is stateless. every time request goes to the server you get a refresh page. If viewstate is not doing your work you can store your data in session. But avoid saving large amount of data in session or viewstate. if you have large data to store then use xml to store data.some of the benifite of using xml are > > * very light > * fastest approach to travel data > * licence independent > > > here are some ink for state management refer to [state management](http://msdn.microsoft.com/en-us/library/75x4ha6s.ASPX) and [State Management in ASP.NET](http://www.codeproject.com/Articles/492397/State-Management-in-ASP-NET-Introduction)
275,643
Let $$A(p,q) = \sum\_{k=1}^{\infty} \frac{(-1)^{k+1}H^{(p)}\_k}{k^q},$$ where $H^{(p)}\_n = \sum\_{i=1}^n i^{-p}$, the $n$th $p$-harmonic number. The $A(p,q)$'s are known as *alternating [Euler sums](http://mathworld.wolfram.com/EulerSum.html)*. > > Can someone provide a nice proof that > $$A(1,1) = \sum\_{k=1}^{\infty} \frac{(-1)^{k+1} H\_k}{k} = \frac{1}{2} \zeta(2) - \frac{1}{2} \log^2 2?$$ > > > I worked for a while on this today but was unsuccessful. Summation by parts, swapping the order of summation, and approximating $H\_k$ by $\log k$ were my best ideas, but I could not get any of them to work. (Perhaps someone else can?) I would like a nice proof in order to complete [my answer here](https://math.stackexchange.com/questions/274742/evaluate-int-01-ln1-x-ln-x-ln1x-mathrmdx/275641#275641). Bonus points for proving $A(1,2) = \frac{5}{8} \zeta(3)$ and $A(2,1) = \zeta(3) - \frac{1}{2}\zeta(2) \log 2$, as those are the other two alternating Euler sums needed to complete my answer. --- **Added**: I'm going to change the accepted answer to robjohn's $A(1,1)$ calculation as a proxy for the three answers he gave here. Notwithstanding the other great answers (especially the currently most-upvoted one, the one I first accepted), robjohn's approach is the one I was originally trying. I am pleased to see that it can be used to do the $A(1,1)$, $A(1,2)$, and $A(2,1)$ derivations.
2013/01/11
[ "https://math.stackexchange.com/questions/275643", "https://math.stackexchange.com", "https://math.stackexchange.com/users/2370/" ]
Actually it suffices to know the generating function $$\sum\_{k\geq 1}H^{(p)}\_kx^k=\frac{\mathrm{Li}\_p(x)}{1-x}$$ Upon integrating we obtain $$\sum\_{k\geq 1}\frac{H^{(p)}\_k}{k}x^k=\mathrm{Li}\_{p+1}(x)+\int^x\_0 \frac{\mathrm{Li}\_p(t)}{1-t}\,d t$$ $$\sum\_{k\geq 1}\frac{H\_k}{k}x^k=\mathrm{Li}\_{2}(x)+\frac{1}{2}\log^2(1-x)$$ $$\sum\_{k\geq 1}\frac{H\_k}{k}(-1)^k=-\frac{\pi^2}{12}+\frac{1}{2}\log^2(2)$$
A full derivation of $A(m,1), \ m\ge2$, is found in [this answer](https://math.stackexchange.com/q/3236584), \begin{equation\*} \sum\_{n=1}^{\infty} (-1)^{n-1}\frac{H\_n^{(m)}}{n}=\frac{(-1)^m}{(m-1)!}\int\_0^1\frac{\displaystyle \log^{m-1}(x)\log\left(\frac{1+x}{2}\right)}{1-x}\textrm{d}x \end{equation\*} \begin{equation\*} =\frac{1}{2}\biggr(m\zeta (m+1)-2\log (2) \left(1-2^{1-m}\right) \zeta (m)-\sum\_{k=1}^{m-2} \left(1-2^{-k}\right)\left(1-2^{1+k-m}\right)\zeta (k+1)\zeta (m-k)\biggr), \end{equation\*} where $H\_n^{(m)}=1+\frac{1}{2^m}+\cdots+\frac{1}{n^m}$ represents the $n$th generalized harmonic number of order $m$ and $\zeta$ denotes the Riemann zeta function. Also, a full solution to the case \begin{equation\*} \sum\_{k=1}^{\infty} (-1)^{k-1} \frac{H\_k}{k^{2n}}=\left(n+\frac{1}{2}\right)\eta(2n+1)-\frac{1}{2}\zeta(2n+1)-\sum\_{k=1}^{n-1}\eta(2k)\zeta(2n-2k+1), \ n\ge1. \end{equation\*} may be found in Cornel's new article [here](https://www.researchgate.net/publication/333999069_A_new_powerful_strategy_of_calculating_a_class_of_alternating_Euler_sums).
9,411,711
I'm stuck, this must be very simple to accomplish but i'm not seeing how. I have this code: ``` var divEl = doc.DocumentNode.SelectSingleNode("//div[@id='" + field.Id + "']"); var newdiv = new HtmlGenericControl("div"); newdiv.Attributes.Add("id", label.ID); newdiv.Attributes.Add("text", label.Text); newdiv.Attributes.Add("class", label.CssClass); ``` And i need to do something like this: ``` divEl.AppendChild(newdiv); //not working its expecting a HtmlNode, not a HtmlGenericControl ``` How can i convert this? Thanks for any response in advance, chapas
2012/02/23
[ "https://Stackoverflow.com/questions/9411711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1141518/" ]
Why not just create the node using HAP's API instead? It should work very similarly. ``` var newDiv = HtmlNode.CreateNode("<div/>"); newDiv.Attributes.Add("id", label.ID); newDiv.Attributes.Add("text", label.Text); newDiv.Attributes.Add("class", label.CssClass); divEl.AppendChild(newDiv); ``` There is no easy way to get the outer HTML of the `HtmlGenericControl` instance (AFAIK). If you had it, you could just pass the HTML in to the `HtmlNode.CreateNode()` method to create it. But I would strongly suggest not trying to make that work.
Well there is a way to get your OuterHtml from HtmlGenericControl: ``` using (TextWriter textWriter = new StringWriter()) { using (HtmlTextWriter htmlWriter = new HtmlTextWriter(textWriter)) { HtmlGenericControl control = new HtmlGenericControl("div"); control.Attributes.Add("One", "1"); control.Attributes.Add("Two", "2"); control.InnerText = "Testing 123"; control.RenderControl(htmlWriter); } } ``` the textWriter.ToString() will get you following: ``` <div One="1" Two="2">Testing 123</div> ```
62,725,323
I have an Object that i will later write to a JSON for storage. This particular project is for spawning enemies for an rpg-bot I'm making. I have a "bestiary" with the enemies stats, and I'm trying to spawn multiple enemies in order into an encounter. Here's a code snippet as it is now: ```js SpawnEncounter(message, [0, 2, 5, 1], characterInfoJSON, userID, ServerPrefix) function SpawnEncounter(message, EnemiesIndicies, InfoFile, user, ServerPrefix) { // bestiary is a json containing monster statistics. their keys are numbers let bestiary = JSON.parse(fs.readFileSync("./bestiary.json", "utf8")); let encounterIntro = []; InfoFile[user].CurrentEncounter = {}; InfoFile[user].CurrentEncounter.Target = 0; InfoFile[user].CurrentEncounter.Enemies = {}; // EnemiesIndecies is an array of keys, referring to specific monsters in the bestiary for (const item in EnemiesIndicies) { // Copy the monster stats into one enemy in the encounter InfoFile[user].CurrentEncounter.Enemies[item] = bestiary[EnemiesIndicies[item]]; // Add a Modifiers object to the enemy InfoFile[user].CurrentEncounter.Enemies[item].Modifiers = { StrMod: 0, DefMod: 0, AttackSpeedMod: 0, ACMod: 0, DmgMod: 0, CritMod: 0 } // push the name of the enemy to the list of all enemies that will spawn encounterIntro.push(bestiary[EnemiesIndicies[item]].Name); } // store the encounter once complete fs.writeFile("./playerinfo.json", JSON.stringify(InfoFile), (err) => { if (err) console.log(err) }); // display the new encounter let LastEnemy = encounterIntro.pop() if (encounterIntro.length === 0) { message.channel.send(`All of a sudden, a ${LastEnemy} appears!\nTo attack it, use \`\`${ServerPrefix}attack\`\``); } else if (encounterIntro.length >= 1) { message.channel.send(`All of a sudden, a ${encounterIntro.join(", ")} and a ${LastEnemy} appears!\nTo attack it, use \`\`${ServerPrefix}attack\`\``); } } ``` What I'm hoping to create is something like this: ``` { MyID: { CurrentEncounter: { Target: 0 Enemies: { 0: {insert enemy 0's stats + modifiers}, 1: {insert enemy 2's stats + modifiers}, 2: {insert enemy 5's stats + modifiers}, 3: {insert enemy 1's stats + modifiers} } } } } ``` I realize that's heavily simplified, but i hope it gets the point across. My problem is, each time i run this, and i spawn an encounter, it always says the enemies that are *supposed* to appear, are all called "undefined". I checked the JSON after it was written to, and the structure of the Object is correct, up to Enemies. It shows that there is an object attributed to Enemies, but it's empty. There's nothing in it. This tells me that something is wrong with how I'm spawning the enemies, or assigning information to Enemies's properties, but I can't put my finger on it. What's worse is that there's no error message to go off. This must mean my syntax is right, but it's not pulling the bestiary info, or it's not writing it properly... Can anyone tell me what is wrong, or better yet: propose a better solution?
2020/07/04
[ "https://Stackoverflow.com/questions/62725323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13556588/" ]
**State look be like this** ``` const [name, setName] = useState ('') const [date, setDate] = useState ('') ``` **function look be like this** ``` const onChangeText = e => setName(e.target.value) const onChangeDate = e => setDate(e.target.value) ``` **input look be like this** ``` <TextInput style = {styles.inputText} onChange={onChangeText } value = {text} /> <TextInput style = {styles.inputText} onChange={onChangeDate } value = {date} /> ```
setting the state to object should be done like this, accessing each key-value pair. ``` export default function CreateOrderPage() { const [state, setState] = useState ({ companyName: '', beginDate: '' }) return ( {/* Some code */} <TextInput style = {styles.inputText} placeholder = {'Company name'} placeholderTextColor = {'#B2B2B2'} onChangeText = {text => setState(prev => { companyName: text, beginDate: prev.beginDate })} value = {state.companyName} /> <TextInput style = {styles.inputText} placeholder = {'Order placed date'} placeholderTextColor = {'#B2B2B2'} onChangeText = {text => setState(prev => { companyName: prev.companyName, beginDate: text })} value = {state.beginDate} /> <TouchableOpacity style = {styles.saveButton} onPress = {() => { console.log(state.companyName, state.beginDate); }}> <Text style = {styles.saveButtonText}>Save</Text> </TouchableOpacity> ) } ```
69,764,994
I am trying to insert a value using following code ``` insert_query = """INSERT OR REPLACE INTO results (output_text, processed) VALUES ('html', 1) select user_id, user_token FROM results WHERE user_id = usr_id AND user_token = usr_token""" ``` cur.execute(insert\_query) I am getting > > OperationalError: near "select": syntax error > > > `WHERE` can't be used with `INSERT` that's why I am using `SELECT` but still I am getting this error. Can someone help wit this issue? Thank you
2021/10/29
[ "https://Stackoverflow.com/questions/69764994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7460823/" ]
You'll want to drop that [`await-to-js`](https://www.npmjs.com/package/await-to-js) that transforms promise rejections into error/result tuples here and just use the plain functions. Once you've done that, you can just ``` try { const loginRes = await sa_login(req); const infoRes = await sa_getUserInfo(loginRes); const courseInfoRes = await sa_getCourseInfo(loginRes); } catch (err) { return ctx.sendError("400", err); } ```
Just use `Promise.all()`. But the 1st request has to complete before you can kick off the next two (which can run in parallel): ```js try { const login = await sa_login(req) const [ userInfo, courseInfo ] = await Promise.all([ sa_getUserInfo(login), sa_getCourseInfo(login) ]); // do something useful with userInfo and courseInfo here } catch (err) { return return ctx.sendError('400',err); } ```
42,344,232
I am using laravel 5.1 with mongodb, I need to display users list on a blade, i am using Laravel relationship method(hasMany), i tried but i got ``` error(Undefined property: Illuminate\Database\Eloquent\Collection::$roles) ``` Table structure: ``` users-> userid, username,email, roleid. user_roles->roleid,rolename; ``` my question is simple, i want userdetails from user table with rolename, i have attached my query result image.any suggesstion please? Controller: ``` $users =User::with('roles')->get(); return view('Manage_users', compact('users')); ``` User Model: ``` class User extends Eloquent { protected $collection = 'users'; public function roles() { return $this->hasMany('App\User_role','roleid','roleid'); } } ``` User\_roles Model: ``` class User_role extends Eloquent { protected $collection = 'user_roles'; public function user() { return $this->belongsTo('App\User','roleid','rolename'); } } ``` [My query result image](https://i.stack.imgur.com/TDqa0.png) [My view page result](https://i.stack.imgur.com/qczkd.png)
2017/02/20
[ "https://Stackoverflow.com/questions/42344232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
in controller update your code to this ``` $users = User::with('roles')->whereHas('roles', function ($query) { $query->where('roleid', '>', 0); })->get(); return view('Manage_users', compact('users')); ```
you can use following code in your view. ``` <table> <tr> <th>User Name</th> <th>Role</th> </tr> @foreach($users as $user) <tr> <td>{{ $user->username }}</td> <td>{{ $user->roles->rolename }}</td> </tr> @endforeach </table> ``` Above code will create the table with username and it's role. Hope it helps you!
48,540,460
I'm getting a weird regex validation failure for Kubernetes Api version - "extensions/v1beta1" while creating a deployment. ``` kubectl --kubeconfig=/var/go/.kube/mcc-pp-config --context=sam-mcc2-pp --namespace=sam-mcc2-pp apply -f k8s-config-sam-mcc2-pp/sf-spark-worker-deployment.yaml --record Error from server (BadRequest): error when creating "k8s-config-sam-mcc2-pp/sf-spark-worker-deployment.yaml": Deployment in version "v1beta1" cannot be handled as a Deployment: quantities must match the regular expression '^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$' ``` This is the Kubernetes yaml that I'm using: ``` kind: Deployment apiVersion: extensions/v1beta1 metadata: name: sf-spark-master spec: replicas: 1 progressDeadlineSeconds: 30 selector: matchLabels: app: sf-spark-master strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0 template: metadata: labels: app: sf-spark-master deployment: '$BUILD_VERSION' spec: containers: - name: sf-spark-master env: - name: ENVIRONMENT value: '$ENVIRONMENT' - name: INIT_DAEMON_STEP value: 'setup_spark' image: '$DOCKER_REGISTRY_HOST/salesiq-article-cache-stub:build-$BUILD_VERSION' ports: - containerPort: 8080 protocol: TCP - containerPort: 7077 protocol: TCP - containerPort: 6066 protocol: TCP resources: limits: memory: '$SPARK_MASTER_MEMORY' cpu: '$SPARK_MASTER_CPU' ``` The output for Kubectl version gives: ``` Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T18:44:27Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"} Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.7", GitCommit:"8eb75a5810cba92ccad845ca360cf924f2385881", GitTreeState:"clean", BuildDate:"2017-04-27T09:42:05Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"} ```
2018/01/31
[ "https://Stackoverflow.com/questions/48540460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5887944/" ]
you need to add some methods to your code : FirebaseMessagingService: ``` package com.example.firebasenf.firebasenf; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MyFirebaseMessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage){ Intent intent = new Intent(this,MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); notificationBuilder.setContentTitle("Application Title"); notificationBuilder.setContentText(remoteMessage.getNotification().getBody()); notificationBuilder.setAutoCancel(true); notificationBuilder.setSmallIcon(R.mipmap.ic_launcher); notificationBuilder.setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0,notificationBuilder.build()); } } ``` FirebaseInstanceIdService : ``` package com.example.firebasenf.firebasenf; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String REG_TOKEN = "REG_TOKEN"; @Override public void onTokenRefresh(){ String recent_token = FirebaseInstanceId.getInstance().getToken(); Log.d(REG_TOKEN,recent_token); } } ```
you need to override `onMessageReceived` in `MyFirebaseMessagingService` class to do some actions when notification is pushed. [doc](https://firebase.google.com/docs/cloud-messaging/android/receive) > > By overriding the method FirebaseMessagingService.onMessageReceived, > you can perform actions based on the received RemoteMessage object and > get the message data > > > ``` @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.d(TAG, "From: " + "Notification Received"); // TODO(developer): Handle FCM messages here. Log.d(TAG, "From: " + remoteMessage.getFrom()); // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.d(TAG, "Message data payload: " + remoteMessage.getData()); } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. //You may want show notification } ``` keep in mind `onMessageReceived` will only triggered if the app in foreground > > When your app is in the background, Android directs notification > messages to the system tray. A user tap on the notification opens the > app launcher by default. > > >
6,260,383
I have set up Jenkins, but I would like to find out what files were added/changed between the current build and the previous build. I'd like to run some long running tests depending on whether or not certain parts of the source tree were changed. Having scoured the Internet I can find no mention of this ability within Hudson/Jenkins though suggestions were made to use SVN post-commit hooks. Maybe it's so simple that everyone (except me) knows how to do it! Is this possible?
2011/06/07
[ "https://Stackoverflow.com/questions/6260383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/451079/" ]
With Jenkins pipelines (pipeline supporting APIs plugin 2.2 or above), this solution is working for me: ``` def changeLogSets = currentBuild.changeSets for (int i = 0; i < changeLogSets.size(); i++) { def entries = changeLogSets[i].items for (int j = 0; j < entries.length; j++) { def entry = entries[j] def files = new ArrayList(entry.affectedFiles) for (int k = 0; k < files.size(); k++) { def file = files[k] println file.path } } } ``` See *[How to access changelogs in a pipeline job](https://support.cloudbees.com/hc/en-us/articles/217630098-How-to-access-Changelogs-in-a-Pipeline-Job-)*.
Note: You have to use Jenkins' own SVN client to get a change list. Doing it through a shell build step won't list the changes in the build.
70,147,309
Lately i followed a course of Operating Systems that sent me to the barrier pseudocode from the little book of semaphores. But for a few hours now i'm struggling to implement this barrier, i can't seem to understand it properly. To understand it, i tried a simple program that lets threads come to barrier, and when all threads arrived, let them pass. Here's my code: ```c #include <errno.h> #include <string.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <semaphore.h> #define NR_MAX 5 int n=NR_MAX; int entered = 0; pthread_mutex_t mtx; sem_t smph; void* bariera(void *v){ pthread_mutex_lock(&mtx); entered++ ; printf("thread %d have entered\n", entered); pthread_mutex_unlock(&mtx); if(entered == n) { sem_post(&smph); printf("Out %d \n", entered);} sem_wait(&smph); sem_post(&smph); } int main() { pthread_t thr[NR_MAX]; pthread_mutex_init(&mtx, NULL); sem_init(&smph, 0, 1); for (int i=0; i<NR_MAX; i ){ pthread_create(&thr[i], NULL, bariera, NULL); } for(int i=0; i<NR_MAX; i ){ pthread_join(thr[i], NULL); } return 0; } ``` How should this be actually implemented? Cause for now, it only prints the order they arrive at the barrier and then it only prints the last one that arrived. **EDIT:** Totally forgot, here's the pseudocode: ``` n = the number of threads count = 0 - keeps track of how many threads arrived at the barrier mutex = Semaphore (1) - provides exclusive acces to count barrier = Semaphore (0) - barrier is locked (zero or negative) until all threads arrive; then it should be unlocked(1 or more) rendezvous 2 3 mutex.wait() 4 count = count + 1 5 mutex.signal () 6 7 if count == n: barrier.signal () 8 9 barrier.wait() 10 barrier.signal () 11 12 critical point ``` expected output: ``` Out 5 Out 4 Out 3 Out 2 Out 1 ``` (the order doesn't have to be the same) Actual output: ``` Out 5 ```
2021/11/28
[ "https://Stackoverflow.com/questions/70147309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17329663/" ]
You need to format your float result with the .toFixed(x) method. Here is a full code sample for this: ``` const p1 = parseFloat(product.price1['regionalPrice']); const p2 = parseFloat(product.price2['marketPrice']); const p3 = parseFloat(product.price3['localPrice']); const price = Math.floor((p1 + p2 + p3) * 10) / 10; const displayPrice = price.toFixed(1); ```
You could try rounding your numbers with the number.toFixed() function where you pass 1 as a function argument. I tried it and `num = 22; num = nums.toFixed(1); console.log(num)` prints out 22.0. Hope that this is what you were looking for ^^
3,291,889
All rings are commutative ring with unity. Let $A$ and $B$ are two $R$-algebras and $I$ and $J$ are two ideals of $A$ and $B$ respectively. I want to show that $A\otimes\_R B/(I\otimes\_R B+A\otimes\_R J)\cong (A/I)\otimes\_R (B/J)$. Theres is a map from $A\otimes\_R B/(I\otimes\_R B+A\otimes\_R J)$ to $(A/I)\otimes\_R (B/J)$ (as $I\otimes\_R B+A\otimes\_R J$ is in the kernel of the map $A\otimes\_R B\rightarrow (A/I)\otimes\_R (B/J))$ and this map is also surjective. But how would I show that this is also an injective map? Thank you.
2019/07/13
[ "https://math.stackexchange.com/questions/3291889", "https://math.stackexchange.com", "https://math.stackexchange.com/users/688673/" ]
You can use $\cos 3x=4\cos^3x-3\cos x$, along with $\cos\pi=-1$. If we let $t=\cos\pi/3$, we have $$4t^3-3t=-1$$ $4t^3-3t+1$ factorises as $(t+1)(4t^2-4t+1)$, giving $t=-1$ or $t=\frac12$. These correspond to $t=\cos\pi$ and $t=\cos\pm\pi/3$. Hence $\cos\pi/3=\frac12$.
We have that $\cos(3x)=4\cos^3(x)-3\cos(x)$ (by <https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Triple-angle_formulae>). Then $-1=\cos(\pi)=4\cos^3(\pi/3)-3\cos(\pi/3)$. Try solving the equation $4y^3-3y+1=0$.
15,032,487
(sorry for my english) I can't belive the only way for animations on canvas is the 'setInterval()' somebody know better? setInterval is too slow and its work bad with old devices.
2013/02/22
[ "https://Stackoverflow.com/questions/15032487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1980508/" ]
Use CSS3 animations and transitions. Most modern browsers will hardware accelerate them; they will be much faster than anything you can write in Javascript. If your animations are too complicated for pure CSS, use `requestAnimationFrame()`, which will allow your animations to run at the browser frame rate and avoid unnecessary computation.
Try using `setTimeout` rather than `setInterval`. It often works smoother.
30,840,819
Users upload files into my express app. I need to calc hash of the uploaded file and then write file to disk using calculated hash as a filename. I try to do it using the following code: ``` function storeFileStream(file, next) { createFileHash(file, function(err, hash) { if (err) { return next(err); } var fileName = path.join(config.storagePath, hash), stream = fs.createWriteStream(fileName); stream.on('error', function(err) { return next(err); }); stream.on('finish', function() { return next(); }); file.pipe(stream); }); } function createFileHash(file, next) { var hash = crypto.createHash('sha1'); hash.setEncoding('hex'); file.on('error', function(err) { return next(err); }); file.on('end', function(data) { hash.end(); return next(null, hash.read()); }); file.pipe(hash); } ``` The problem is that after I calc file hash the writed file size is 0. What is the best way do solve this task? **Update** According @poke suggestion I try to duplicate my stream. Now my code is: ``` function storeFileStream(file, next) { var s1 = new pass; var s2 = new pass; file.pipe(s1); file.pipe(s2); createFileHash(s1, function(err, hash) { if (err) { return next(err); } var fileName = path.join(config.storagePath, hash), stream = fs.createWriteStream(fileName); stream.on('error', function(err) { return next(err); }); stream.on('finish', function() { return next(); }); s2.pipe(stream); }); } function createFileHash(file, next) { var hash = crypto.createHash('sha1'); hash.setEncoding('hex'); file.on('error', function(err) { return next(err); }); file.on('end', function(data) { hash.end(); return next(null, hash.read()); }); file.pipe(hash); } ``` The problem of this code is that events `end` and `finish` are not emited. If I comment `file.pipe(s2);` events are emited, but I again get my origin problem.
2015/06/15
[ "https://Stackoverflow.com/questions/30840819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2568741/" ]
The correct and simple way should be as follow: **we should resume the passthroughed stream** ```js function storeFileStream(file, directory, version, reject, resolve) { const fileHashSource = new PassThrough(); const writeSource = new PassThrough(); file.pipe(fileHashSource); file.pipe(writeSource); // this is the key point, see https://nodejs.org/api/stream.html#stream_three_states fileHashSource.resume(); writeSource.resume(); createFileHash(fileHashSource, function(err, hash) { if (err) { return reject(err); } const fileName = path.join(directory, version + '_' + hash.slice(0, 8) + '.zip'); const writeStream = fs.createWriteStream(fileName); writeStream.on('error', function(err) { return reject(err); }); writeStream.on('finish', function() { return resolve(); }); writeSource.pipe(writeStream); }); } function createFileHash(readStream, next) { const hash = crypto.createHash('sha1'); hash.setEncoding('hex'); hash.on('error', function(err) { return next(err); }); hash.on('finish', function(data) { return next(null, hash.read()); }); readStream.pipe(hash); } ```
You could use the [async](https://github.com/caolan/async) module (not tested but should work): ``` async.waterfall([ function(done) { var hash = crypto.createHash('sha1'); hash.setEncoding('hex'); file.on('error', function(err) { done(err); }); file.on('end', function(data) { done(null, hash.read); }); file.pipe(hash); }, function(hash, done) { var fileName = path.join(config.storagePath, hash), stream = fs.createWriteStream(fileName); stream.on('error', function(err) { done(err); }); stream.on('finish', function() { done(null); }); file.pipe(stream); } ], function (err) { console.log("Everything is done!"); }); ```
16,213,498
Currently I'm using InStr to find a string in a string, I'm new to VB.NET and wondering if I can use InStr to search every element of an array in a string, or a similar function like this: ``` InStr(string, array) ``` Thanks.
2013/04/25
[ "https://Stackoverflow.com/questions/16213498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1134550/" ]
Converting SysDragon's answer to classic asp: You need to loop: ``` Dim bFound bFound = False For Each elem In myArray If InStr(myString, elem)>=0 Then bFound = True Exit For End If Next ``` You can transform it into a function to call it more than once easily: ``` Function MyInStr(myString, myArray) Dim bFound bFound = false For Each elem In myArray If InStr(myString, elem)>=0 Then bFound = True Exit For End If Next MyInStr = bFound End Function ``` Then: ``` MyInStr("my string text", Array("my", "blah", "bleh")) ```
`Instr` returns an integer specifying the start position of the first occurrence of one string within another. Refer [this](http://www.homeandlearn.co.uk/net/nets7p4.html) To find string in a string you can use someother method Here is an example of highlighting all the text you search for at the same time but if that is not what you want, you have to solve it on your own. ``` Sub findTextAndHighlight(ByVal searchtext As String, ByVal rtb As RichTextBox) Dim textEnd As Integer = rtb.TextLength Dim index As Integer = 0 Dim fnt As Font = New Font(rtb.Font, FontStyle.Bold) Dim lastIndex As Integer = rtb.Text.LastIndexOf(searchtext) While (index < lastIndex) rtb.Find(searchtext, index, textEnd, RichTextBoxFinds.WholeWord) rtb.SelectionFont = fnt rtb.SelectionLength = searchtext.Length rtb.SelectionColor = Color.Red rtb.SelectionBackColor = Color.Cyan index = rtb.Text.IndexOf(searchtext, index) + 1 End While End Sub ``` This method with search for text "boy" in RichTextBox2, change the textcolor to red and back color to cyan ``` Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click findTextAndHighlight("boy", RichTextBox2) End Sub ```
43,935,283
My goal is to provide a new means of communication to merchants. These merchants will seize their ads on a platform and the beacons will take care of "spreading" them. The mobile application will therefore scan the beacons on the background (the most frequent case) and retrieve merchants' ads based on the ids of the discovered beacons. So I need a very regular scan so that no ads are missed. I have already done a big part of the development however I do not know how to configure the periods of scans. What optimal configuration would you advise me for this case ? Currently the application to this configuration in background: setBackgroundScanPeriod(2000L); setBackgroundBetweenScanPeriod(0L); The foreground setting is the default setting. So I scan for two seconds and then start again immediately. Thank you in advance and sorry for my english.
2017/05/12
[ "https://Stackoverflow.com/questions/43935283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8001849/" ]
Using Gridview Row Databound bind value of label4 ``` Label Label4 = (Label)e.row.findcontrol("Label4"); Label4.text = (Your Value assign here) ``` so display your value
I've had this issue which disappeared when I commented out everything inside my GridView1\_RowDataBound(object sender, GridViewRowEventArgs e) method. I was adding a tooltip to all cells in the row which I think overwritten it. ``` protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e) { // var id = e.Row.Cells[0].Text; //if (e.Row.RowType == DataControlRowType.DataRow) //{ } ```
47,013,147
The JSON Data is as below ``` {"ServerFiles": [ {"filepath": "in/b1_30102017d.ini"}, {"filepath": "in/b1_30102017d.log"}, {"filepath": "in/b1_30102017d.txt"}, {"filepath": "out/b1_30102017d.log"}, {"filepath": "out/b1_30102017d.csv"} ]} ``` I want to get the the path of ini file. This works ``` $.ServerFiles[*].filepath[0]. ``` But the file varies on windows and linux, that means $.ServerFiles[*].filepath[0] returns csv file on windows and not ini file. On linux the same $.ServerFiles[*].filepath[0] returns ini file, so I don't want to hardcode with $.ServerFiles[\*].filepath[0]. Is there any other JSON expressions to retrieve ini file?
2017/10/30
[ "https://Stackoverflow.com/questions/47013147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2587935/" ]
Replace `PSWD` with `PASSWD` and replace `PASSWD="aabbcc"` with `export PASSWD="aabbcc"`.
YES is good now it's been hours that I'm on and I could not see anything! ``` #!/bin/bash USERNAME=$1 # "toto02" export PASSWD=$2 # "aabbcc" ORIGPASS=`grep -w "$USERNAME" /etc/shadow | cut -d: -f2` export ALGO=`echo $ORIGPASS | cut -d"$" -f2` export SALT=`echo $ORIGPASS | cut -d"$" -f3` echo "algo: -$ALGO-" echo "salt: -$SALT-" echo "pw entré: -$PASSWD-" echo "shadow: -$ORIGPASS-" GENPASS="$(perl -e 'print crypt("$ENV{PASSWD}","\$$ENV{ALGO}\$$ENV{SALT}\$")')" echo "pass génére: -$GENPASS-" if [ "$GENPASS" == "$ORIGPASS" ]; then echo "Valid Password" exit 0 else echo "Invalid Password" exit 1 fi algo: -6- salt: -rYc.lGtG- pw entré: -aabbcc- shadow: -$6$rYc.lGtG$wMHAM.nXHk1J5sDRmcHeBLW1sRQA/xQcjJSZxkls4BratyWf.KoQST14pPjNWDiUKwfegC96Lhjgjbj4YbZoc.- pass génére: -$6$rYc.lGtG$wMHAM.nXHk1J5sDRmcHeBLW1sRQA/xQcjJSZxkls4BratyWf.KoQST14pPjNWDiUKwfegC96Lhjgjbj4YbZoc.- Valid Password ``` Thank you very much, but is there a way to have the same type of password with `useradd` and `chpasswd`
22,780,143
OK so i'm trying to clean up my code because it is a mess and what i have is 25 richtext boxes and i want to put their .Visible variable into an array and have a for statement go through and make each false so that the text box doesn't show up what i have tried hasn't worked and i can't figure it out what i have is. ``` bool[] box = new bool[25]; box[0] = richTextBox1.Visible; box[1] = richTextBox2.Visible; box[2] = richTextBox3.Visible; box[3] = richTextBox4.Visible; box[4] = richTextBox5.Visible; box[5] = richTextBox6.Visible; box[6] = richTextBox7.Visible; box[7] = richTextBox8.Visible; box[5] = richTextBox6.Visible; box[6] = richTextBox7.Visible; box[7] = richTextBox8.Visible; box[8] = richTextBox9.Visible; box[9] = richTextBox10.Visible; box[10] = richTextBox11.Visible; box[11] = richTextBox12.Visible; box[12] = richTextBox13.Visible; box[13] = richTextBox14.Visible; box[14] = richTextBox15.Visible; box[15] = richTextBox16.Visible; box[16] = richTextBox17.Visible; box[17] = richTextBox18.Visible; box[18] = richTextBox19.Visible; box[19] = richTextBox20.Visible; box[20] = richTextBox21.Visible; box[21] = richTextBox22.Visible; box[22] = richTextBox23.Visible; box[23] = richTextBox24.Visible; box[24] = richTextBox25.Visible; for(int y = 0; y <25; y++) { box[y] = false; } ```
2014/04/01
[ "https://Stackoverflow.com/questions/22780143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3448117/" ]
You canot change the `bool` in the array and expect that that changes the `Visible` state of the TextBoxes. You have to change that property. Therefore you either have to store these controls in a collection or use a different approach: If they are in the same container control (like `Form`, `GroupBox`, `Panel` etc.) you could use `Enumerable.OfType`. For example: ``` var allRichTextBoxes = this.Controls.OfType<RichTextBox>() .Where(txt => txt.Name.StartsWith("richTextBox")); foreach(var rtb in allRichTextBoxes) rtb.Visible = false; ```
`TextBox.Visible` is a property and as such returns a *value*. Your array of Boolean therefore contains values as well. Changing this value does nothing to your textbox, because it doesn't know anything of the textbox anymore. Storing a reference to a value is not possible in C#, so try the following instead: ``` RichtTextBox[] box = new RichTextBox[25]; box[0] = richTextBox1; box[1] = richTextBox2; box[2] = richTextBox3; box[3] = richTextBox4; box[4] = richTextBox5; // ... for(int y = 0; y <25; y++) { box[y].Visible = false; } ```
232,058
If AV auto-scan will detect and prevent the malware from executing why there is a need to enable schedule/full scans? I'm asking because a full scan can create sometimes overhead on the machine and network, so I'm trying to understand the advantages of enabling full scanning if auto-scan will provide AV protection when a file is used. Terminology: Auto-Protect-- Auto-Protect is the first line of defense against threats by providing real-time protection for your computer. Whenever you access, copy, save, move, open or close a file, Auto-Protect scans the file to ensure that a threat has not attached itself. By default, it loads when you start your computer to guard against threats and security risks. It also monitors your computer for any activity that might indicate the presence of a threat or security risk. Auto-Protect can determine a file's type even when a threat changes the file's extension. Full Scan--WIll scan each file by starting with A to Z its not real-time.
2020/05/23
[ "https://security.stackexchange.com/questions/232058", "https://security.stackexchange.com", "https://security.stackexchange.com/users/188315/" ]
From your description of a full scan a reason why it is better, is if a file or executable on your computer that is malicious was downloaded from the internet, but bypassed the Auto-protect at the time. This is possible if the type of virus was was not known at the time the file was downloaded, (this type of scenario is called a "Zero Day" scenario). Here your description of full scan will work if a future security definition or patch update to the antivirus program, gives the ability to the antivirus program to be able to detect the new virus. Of course the Auto-protect may be able to detect the virus now, but only if the virus is running. If the virus is not running, and is in a dormant state, the only way the Antivirus program will detect the virus is by searching thru every file on the computer. Full Scans usually occur by default when the Antivirus Software is updated, **not a patch update**. Since AV software updates are usually to fix issues where the antivirus programs have flaws where even with a virus definition, a virus if created properly could leverage those flaws. In this situation not even a Full Scan would work, but if the Antivirus Software can be updated before such a scenario or even during (***less likely***), then the virus can get caught. The latter is more of the reason why, as a safe guard that AV programs usually run a full scan after updating the AV software. It also relates to the reason why, other than registry and system monitoring access issues, that AV software after a software update asks to restart a computer. That is why usually after a AV software update, the startup time after the restart is seen to be a bit longer than usually, as the AV is now doing a full system scan. Many AV software do this by default. This only happens during the startup/reboot process after a AV software update.
Typically (and perhaps just personally) I don't perform full scans on schedule or any other method unless I notice actual *symptoms* or suspicious system activity/behavior. On the other hand, some may disagree with this - I would have been among them 10-15 years ago - therefore, if its believed to be a necessity, I suggest a monthly full/schedule scan. However, as I've already mentioned, a quick scan (under reasonable circumstances and/or in most cases) is sufficient assuming the rest of the network or system security features are in place and enabled (i.e. router, firewall, up-to-date software, etc.). As you pointed out, and obviously know from experience, a full system scan is debilitating to even some *higher-end* systems. I was honestly surprised to see how much **my** system was bogged down - my first actual higher-end system in two decades - for some reason I had it in my head that solid-state drives would help tremendously with that (and I'm sure it does) but it still grinds my other activities close to a halt.
3,138
I am looking through unanswered questions (specifically in combinatorics, but this is irrelevant) and I want to ask advice on how to proceed. Apart from questions that I can simply answer or where I can upvote a correct answer that got no votes at all, I found the following type of questions: 1. Hard questions Obviously, some of the hard questions are interesting questions that should just wait around, but many of them are of the type "anyone can construct a diophantine equation that is impossible to solve" (and no one wants to answer that there is no nice way to solve them because you never can know). Should anything be done about them? I want to note that especially in combinatorics there are many elementary-looking questions that even get lots of upvotes for "looking nice" where I am rapidly convinced that there is no nice elementary answer, but proving it would be next to impossible. 2. Vague questions There are questions that might have been interesting questions, but it was too hard to determine the intentions of the OP and after several months, the OP will certainly not return to clarify and no one will be able to answer this kind of question or profit from it. It cannot be closed by several votes after several months, either, because there is no activity. Should I flag it for closing by the mods? For deletion? I am not talking about borderline cases here, but about questions where I genuinely think that they will benefit no one. Also, no reputation is involved, as, by definition I am looking at questions without upvoted answers and the clear-cut cases I am talking about have at most 0 votes. 3. Questions that have actually been answered in the comments and float around as unanswered questions because no one wrote an answer. Very annoying, and there is nothing I can do about this alone, as I cannot move a comment to an answer and upvote it. Why am I opening this thread? I think that this forum would benefit from having primarily precise and answerable questions in the unanswered questions section to improve the chance of newcomers to answer interesting unanswered questions. Edited to add a concrete example: <https://math.stackexchange.com/questions/31330/do-you-have-some-interesting-q-hypergeometric-identities> This questions asks about "interesting q-hypergeometric identities" which is not a well-crafted question at all. In addition, the author offers people email contact. I don't see any possibility for this question to have a good answer, and there is no point for me to give it a lonely close vote at this time. So, should I flag it? Add a close vote and post a link in a new meta thread "please help me to close the following questions or give a good reason against closure"? I can think of no reason to let this type of questions open, but I am of course open to any reason I have overlooked. (And I, in fact, *do* know interesting q-hypergeometric identites, that is, *interesting* to me, in a certain context.)
2011/10/30
[ "https://math.meta.stackexchange.com/questions/3138", "https://math.meta.stackexchange.com", "https://math.meta.stackexchange.com/users/9325/" ]
For case (3) you should just write an answer yourself, summarizing the solution from the comments -- or even just pointing to it, if it is more than a few days old. This will bump the question and hopefully attract someone else to upvote the answer. Some may see this as a way to troll for easy points. Personally I don't mind; getting resolved questions shown as answered is a service to the community that does deserve some reward. But it you're worried about such impressions you could mark your answer as CW (which could here be taken to stand for Credit Waived). *(...or not. It turns out that marking the answer as CW means that [the OP will not get +2 rep for accepting it](http://meta.math.stackexchange.com/questions/5000/cw-answers-considered-harmful), and there's no need to penalize the OP for the fact that someone originally wrote the helpful answer as a comment.)*
Case 2 is partially addressed in [Moderator Clean-up of Abandoned Poor-Quality Questions](https://math.meta.stackexchange.com/questions/2018/moderator-clean-up-of-abandoned-poor-quality-questions) , where the consensus seems to be that moderators shouldn't unilaterally close those questions. For questions that are old and truly vague, and which does not have any answers, a better way is to vote it down (preferably also leaving a comment as to how to improve the question). Completely unanswered, old, and negatively voted questions will be automatically purged from the system from time to time.
61,641,280
I found similar posts, mostly related to linux on venv having an issue with working. [python 3.8 venv missing activate command](https://stackoverflow.com/questions/59557922/python-3-8-venv-missing-activate-command) However, I am confused on how to solve it on windows, and what is happening. I installed python3.8 from downloading it on pythons website. Then I follow the 3.8 documentation <https://docs.python.org/3/library/venv.html> which shows: `python3 -m venv /path/to/new/virtual/environment` I do this but then get the following error: ``` Error: Command '['E:\\py_envs\\hf4\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101. ``` When I use: `python -m venv --without-pip hf4` and then `hf4\Scripts\activate` It works for activation. What I don't understand is that I can then run pip and it is there during the activated environment. It seems a maybe related issue, is that anything I have installed on my system python is also available. For example, in the activated session: ``` (hf4) E:\py_envs>where pip C:\Users\local user\AppData\Local\Programs\Python\Python38\Scripts\pip.exe ``` One question is naturally how to fix this, the other is that I would appreciate an explanation as to what is happening to better understand it. Does it search first for the active environment, and if it can't find it, defaults to a system version?
2020/05/06
[ "https://Stackoverflow.com/questions/61641280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12392112/" ]
I had the same problem (with both Python 3.7 and 3.8), I believe it was due to a Windows update when I enrolled in the Windows Insiders program, but that could have just been a coincidence. ``` PS C:\Users\Your Name\AppData\Local\Programs\Python\Python38> ./python -m venv c:\TEMP\py38-venv Error: Command '['c:\\TEMP\\py38-venv\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101. ``` This worked around the problem in my case: * Uninstall Python. * Install with the Custom option. * Use the "Install for all users". [![Install for all users](https://i.stack.imgur.com/H5Ipa.png)](https://i.stack.imgur.com/H5Ipa.png) After this it worked fine: ``` PS C:\Utilities\PythonBase\Python38> .\python -m venv c:\temp\venv-py38 PS C:\Utilities\PythonBase\Python38> ``` Of course you'll have to go through and fix any venvs you've been using, but if you're in the same situation as me they won't have been working anyway.
Thanks. I faced the same issue and this thread worked around for me. I uninstalled Python and installed 3.9. Python version (which was available for me at the time) checking "Install for all users" in advanced installing. Remember to check "Add the PATH" box so that you can run Python from the command prompt.
67,776,758
I am working on a top-down 2D game project. The character must follow the mouse cursor all the time, this is what I could do so far. I also want the character to slide towards the mouse for a limited distance when clicked. So let's say the character position is: 0, 0, 0 Mouse click position: 8, 4, 0 When clicked, the character must move towards the mouse click position but only for a limited distance, so it must not reach if distance more than 2. So the final character location should be: 2, 2, 0 How can I achieve that? Here is my code; ``` using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovemetn : MonoBehaviour { private float speed = 4; private float slideSpeed = 8; private Vector3 targetPosition; private bool isMoving = false; void Update() { SetTargetPosition(); if (Input.GetMouseButton(0)) { //Slide 2 meters towards mouse location (with the speed of slideSpeed variable) } if (isMoving) { Move(); } } void SetTargetPosition() { targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); targetPosition.z = transform.position.z; isMoving = true; } void Move() { transform.position = Vector2.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime); if (transform.position == targetPosition) { isMoving = false; } } } ```
2021/05/31
[ "https://Stackoverflow.com/questions/67776758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7086686/" ]
The main issue I guess is that you constantly update the targetPosition as long as you hold the mouse button down. This would make it pretty hard to tell from which start point you actually want to allow maximum distance and when exactly you allow a new range. I would assume you allow to move around in a range of `maxDistance` around an `_originalPosition` your object had the moment the mouse went down. Then you can use [`Vector2.ClampMagnitude`](https://docs.unity3d.com/ScriptReference/Vector2.ClampMagnitude.html) to calculate a range around that stored `_originalPosition` like ``` // For 2D use Vector2 right away private Vector2 targetPosition; [SerializeField] private float maxDistance; private void Update() { // Only update the target for the first click position if (Input.GetMouseButtonDown(0)) { SetTargetPosition() } if (isMoving) { Move(); } } void SetTargetPosition() { // as before get your target position var tempTargetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); // Calculate a delta vector _originalPosition -> tempTargetPosition // then make sure its magnitude is maximum maxDistance var delta = Vector2.ClampMagnitude(tempTargetPosition - transform.position, maxDistance); // Calculate and update the actual target position targetPosition = transform.position + delta; isMoving = true; } ```
You can simply calculate the delta distance and its vector between Origin and your Destination. After normalizing those values, you could multiply them with some kind of 'base distance' for example in this case your (2, 2, 0) and add/subtract it from your destination, something like that should do the trick: ``` var delta = (Destination - origin).normalized; delta *= baseDistance; var targetDestination = Destination - delta; ``` But keep in mind that (0,2,0) is closer than (2,2,0), so you might want to adept that calculation
9,866
How can I go about killing IP connections that seem to be sending a lot of requests to the same url? Let's say I have someone who requests the same url for more than 10 times in 5 seconds, I want to "cool" him off. Any ideas on how it's done?
2011/12/19
[ "https://security.stackexchange.com/questions/9866", "https://security.stackexchange.com", "https://security.stackexchange.com/users/6475/" ]
On \*nix, you can use fail2ban with a something like this in your jail.conf (100 requests in 30 seconds means a 5 minute ban). Of course, you'll have to adjust this for how many requests you expect from a legitimate user -- as @Jeff Ferland points out in the comments below, you need to account for the number of requests that you receive on a normal page load (e.g. you have a lot of images on the page). ``` [apache-spammer] enabled = true banaction = apache port = http,https filter = apache-spammer logpath = /srv/*/log/access.log maxretry = 100 findtime = 30 bantime = 300 ``` and a filter like this in `/etc/fail2ban/filter.d/apache-spammer.conf`: ``` [Definition] # Option: failregex # Notes.: regex to match the request messages in the logfile. The # host must be matched by a group named "host". The tag "<HOST>" can # be used for standard IP/hostname matching and is only an alias for # (?:::f{4,6}:)?(?P<host>[\w\-.^_]+) # failregex = ^<HOST>.*/path/to/content.html ``` This is **untested** -- you'll have to experiment a bit to find what works. **Watch your fail2ban.log** to verify that you aren't banning innocent users! An alternative would be a firewall rule that rate-limits requests from a particular IP address.
Would [mod\_evasive](http://www.zdziarski.com/blog/?page_id=442) be what you're looking for? It's focused on DoS attacks and limits the number of requests to a page per second. Otherwise, you might be able to adapt [fail2ban](http://www.fail2ban.org) to help out.
34,425,237
Came across this question in an interview blog. Given free-time schedule in the form `(a - b) i.e., from 'a' to 'b'` of `n` people, print all time intervals where all `n` participants are available. It's like a calendar application suggesting possible meeting timinings. ``` Example: Person1: (4 - 16), (18 - 25) Person2: (2 - 14), (17 - 24) Person3: (6 - 8), (12 - 20) Person4: (10 - 22) Time interval when all are available: (12 - 14), (18 - 20). ``` Please share any known optimal algorithm to solve this problem. I am thinking of the following solution. * Create a `currentList` of intervals that contain one interval from each person. Initially `currentList = [4-16, 2-14, 6-8, 10-22]`. * Look for the `max_start` and `min_end` in `currentList` and output `(max_start, min_end)` if `max_start < min_end`; Update all intervals in `currentList` to have `start` value as `min_end`. Remove the interval that has `min_end` from `currentList` and add the next entry in that person's list to `currentList`. * If `max_start >= min_end` in previous step, update all intervals in `currentList` to have `start` value as `max_start`. If for any interval `i`, `end > start`, replace that interval in `currentList` with the next interval of the corresponding person. Based on the above idea, it will run as below for the given example: ``` currentList = [4-16, 2-14, 6-8, 10-22] max_start=10 >= min_end=8 update start values to be 10 and replace 6-8 with next entry 12-20. currentList = [10-16, 10-14, 12-20, 10-22] max_start=12 <= min_end=14 add max_start-min_end to output and update start values to 14. Output=[12-14] currentList = [14-16, 17-24, 14-20, 14-22] max_start=17 >= min_end=16 update start values to be 17 and replace 14-16 with 18-25 currentList = [18-25, 17-24, 17-20, 17-22] max_start=18 <= min_end=20 add max_start-min_end to output and update start values to 20. Output=[12-14, 18-20] currentList = [20-25, 2-24, - , 2-22] Terminate now since there are no more entry from person 3. ``` I have not implemented the above though. I am thinking of a min-heap and max-heap to get the min and max at any point. But I am concerned about updating the start values because updating the heap may become expensive.
2015/12/22
[ "https://Stackoverflow.com/questions/34425237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/685621/" ]
Got this today during an interview. Came up with an `O(N*logN)` solution. Wondering whether there is an `O(N)` solution available... Overview: Join individual schedules into one list `intervals` --> Sort it by intervals' starting time --> Merge adjacent intervals if crossing --> Returning the availability is easy now. ```py import unittest # O(N * logN) + O(2 * N) time # O(3 * N) space def find_available_times(schedules): ret = [] intervals = [list(x) for personal in schedules for x in personal] intervals.sort(key=lambda x: x[0], reverse=True) # O(N * logN) tmp = [] while intervals: pair = intervals.pop() if tmp and tmp[-1][1] >= pair[0]: tmp[-1][1] = max(pair[1], tmp[-1][1]) else: tmp.append(pair) for i in range(len(tmp) - 1): ret.append([tmp[i][1], tmp[i + 1][0]]) return ret class CalendarTests(unittest.TestCase): def test_find_available_times(self): p1_meetings = [ ( 845, 900), (1230, 1300), (1300, 1500), ] p2_meetings = [ ( 0, 844), ( 845, 1200), (1515, 1546), (1600, 2400), ] p3_meetings = [ ( 845, 915), (1235, 1245), (1515, 1545), ] schedules = [p1_meetings, p2_meetings, p3_meetings] availability = [[844, 845], [1200, 1230], [1500, 1515], [1546, 1600]] self.assertEqual( find_available_times(schedules), availability ) def main(): unittest.main() if __name__ == '__main__': main() ```
I prefer to take a slightly different approach that's set based! I'll let the language elements do the heavy lift for me. As you guys have already figured out I'm making some assumptions that all meetings are on the top of the hour with an interval length of 1 hour. ```py def get_timeslots(i, j): timeslots = set() for x in range (i, j): timeslots.add((x, x + 1)) return timeslots if __name__ == "__main__": allTimeSlots = get_timeslots(0, 24) person1TimeSlots = get_timeslots(4, 16).union(get_timeslots(18, 24)) person2TimeSlots = get_timeslots(2, 14).union(get_timeslots(17, 24)) person3TimeSlots = get_timeslots(6,8).union(get_timeslots(12, 20)) person4TimeSlots = get_timeslots(10, 22) print(allTimeSlots .intersection(person1TimeSlots) .intersection(person2TimeSlots) .intersection(person3TimeSlots) .intersection(person4TimeSlots)) ```
24,863,713
I am new to Scrapy and Python and I am enjoying it. Is it possible to debug a scrapy project using Visual Studio? If it is possible, how?
2014/07/21
[ "https://Stackoverflow.com/questions/24863713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3860415/" ]
You can install [PTVS](http://pytools.codeplex.com/) in visual studio 2012. Then create a python project from existing python code, and import your code. If you are familiar with Visual Studio, it's the same as other languages in Visual Studio, like C++/C#. Just create some break points and start your script with Debugging. As ThanhNienDiCho said, add "-mscrapy.cmdline crawl your\_spider\_name" to your interpreter argument. ![PTVS screenshot](https://i.stack.imgur.com/E82Fe.png)
I had the same problem, and Yuan's [initial answer](https://stackoverflow.com/a/24864440/25507) didn't work for me. To run Scrapy, you need to open `cmd.exe` and ``` cd "project directory" scrapy crawl namespider ``` * scrapy is scrapy.bat. * namespider is the value of the field in spider class. * To run Scrapy from Visual Studio, use input parameters of `-mscrapy.cmdline crawl your_spider_name`. See [http://imgur.com/2PwF3g0](https://imgur.com/2PwF3g0).
20,206,852
I have the following: ``` <tr> <td>Value 1</td> <td>Value 2</td> <td>Value 3</td> </tr> ``` Now, with jQuery I do this: ``` var jTR = $('tr'); var jFirstChild = jTR.find(':first-child'); ``` but jFirstChild.length returns 0. I also find that when I do jTR.length it too returns 0. Ultimately, I am trying to find the first child of the table row and then remove that first child. When I do this: ``` <div> <p>Value 1</p> <p>Value 2</p> <p>Value 3</p> </div> ``` with ``` var jDiv = $('div'); ``` jDiv.length returns 3 as expected. Can I not select a TR element directly?
2013/11/26
[ "https://Stackoverflow.com/questions/20206852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1273008/" ]
If your subclasses vary only in the parameters passed to the superclass, you might be looking for the [Builder Pattern](http://en.wikipedia.org/wiki/Builder_pattern). A builder for the superclass lets you pass in whatever parameters you need without cluttering your constructor, and if you want subclasses for readability, you can just wrap a call to the builder and return its result from the subclass constructors.
One thing to check is: should SuperClass be split into simpler classes? If this can't be done: if you have too many parameters then you can have a special class that holds the parameters; with setters and getters for each parameter. One can fill the values in from property files, so you can have profiles for common cases. ``` class SuperClassParam { void seta(int a); int geta(); //... } class SuperClass { public SuperClass( SuperClassParam params ) { } ```
51,490,700
I do not have admin rights on my work laptop. Have got python and pip installed on my machine, version numbers as below: ``` C:\Users\banand\AppData\Local\Programs\Python\Python36\Scripts>python --version Python 3.6.1 C:\Users\banand\AppData\Local\Programs\Python\Python36\Scripts>pip --version pip 9.0.1 from c:\users\banand\appdata\local\programs\python\python36\lib\site-packages (python 3.6) ``` I need a way to make use of various python modules available online. An example is - [colorama](https://pypi.org/project/colorama/) As per the instructions, I tried the below command without any success: ``` C:\Users\banand\AppData\Local\Programs\Python\Python36\Scripts>pip install colorama --user Collecting colorama Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000001D431204F28>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/colorama/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000001D431204A58>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/colorama/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000001D431204780>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/colorama/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000001D431204BA8>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/colorama/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000001D431204898>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/colorama/ Could not find a version that satisfies the requirement colorama (from versions: ) No matching distribution found for colorama ``` I believe that this has something to do either with the fact that - a. I do not have admin rights, OR b. I am behind a firewall and hence some sort of block is being exercised I want to find out the exact issue here and then answer the question - is there a way to circumvent around these limitation and have a repeatable method to install python modules. Kindly note that I am in an corporate laptop and learning to Python out of interest, so I do not want to go ahead and request Admin rights nor want to get into any trouble because I tried to do something which was not supposed to be experimented on my laptop. Any help is greatly appreciated.
2018/07/24
[ "https://Stackoverflow.com/questions/51490700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5373329/" ]
The post is 7 months old, but this can help others. This worked for me on Windows 10 Pro without admin privileges: python.exe -m pip install
I tried right on Jupiter notebook and it worked perfectly: **code:** ``` import sys !{sys.executable} -m pip install xarray ``` **sysmtem answer:** ``` Collecting xarray Using cached https://files.pythonhosted.org/packages/10/6f/9aa15b1f9001593d51a0e417a8ad2127ef384d08129a0720b3599133c1ed/xarray-0.16.2-py3-none-any.whl Requirement already satisfied: setuptools>=38.4 in c:\anaconda3\lib\site-packages (from xarray) (41.0.1) Requirement already satisfied: numpy>=1.15 in c:\anaconda3\lib\site-packages (from xarray) (1.16.4) Requirement already satisfied: pandas>=0.25 in c:\anaconda3\lib\site-packages (from xarray) (1.2.1) Requirement already satisfied: pytz>=2017.3 in c:\anaconda3\lib\site-packages (from pandas>=0.25->xarray) (2019.1) Requirement already satisfied: python-dateutil>=2.7.3 in c:\anaconda3\lib\site-packages (from pandas>=0.25->xarray) (2.8.0) Requirement already satisfied: six>=1.5 in c:\anaconda3\lib\site-packages (from python-dateutil>=2.7.3->pandas>=0.25->xarray) (1.12.0) Installing collected packages: xarray Successfully installed xarray-0.16.2 ```
786,527
> > Suppose $f:\mathbb{R} \supset E \rightarrow \mathbb{R}$ and $g: \mathbb{R} \supset E \rightarrow \mathbb{R}$ are uniformly continuous. Show that $f+g$ is uniformly continuous. What about $fg$ and $\dfrac{f}{g}$? > > > ### My Attempt Firstly let's state the definition; a function is uniformly continuous if $$\forall \varepsilon >0\ \ \exists \ \ \delta >0 \ \ \text{such that} \ \ |f(x)-f(y)|< \varepsilon \ \ \forall \ \ x,y \in \mathbb{R} \ \ \text{such that} \ \ |x-y|<\delta$$ ### Sum $f+g$ Now to to prove $f+g$ is uniformly continuous; $\bullet$ Choose $\delta\_1 >0$ such that $\forall$ $x,y \in \mathbb{R}$ $|x-y|<\delta\_1$ $\implies$ $|f(x)-f(y)|< \dfrac{\epsilon}{2}$ $\bullet$ Choose $\delta\_2 >0$ such that $\forall$ $x,y \in \mathbb{R}$ $|x-y|<\delta\_2$ $\implies$ $|g(x)-g(y)|< \dfrac{\varepsilon}{2}$ $\bullet$ Now take $\delta := min\{ \delta\_1, \delta\_2\}$ Then we obtain for all $x,y \in \mathbb{R}$ $$ |x-y|<\delta \implies |f(x)+g(x)-f(y)+g(y)| < |f(x)-f(y)| + |g(x)-g(y)| < \dfrac{\varepsilon}{2}+\dfrac{\varepsilon}{2}= \varepsilon$$ --- ### Product $fg$ Now for $fg$ for this to hold both $f:E \rightarrow \mathbb{R}$ and $g:E \rightarrow \mathbb{R}$ must be bounded , if not it doesn't hold. $\bullet$ $\exists \ \ M>0 \ \ such \ that \ \ |f(x)|<M \ \ and \ \ |g(x)|<M \ \ \forall \ x \in E$ $\bullet$ Choose $\delta\_1 >0$ such that $\forall$ $x,y \in \mathbb{R}$ $|x-y|<\delta\_1$ $\implies$ $|f(x)-f(y)|< \dfrac{\epsilon}{2M}$ $\bullet$ Choose $\delta\_2 >0$ such that $\forall$ $x,y \in \mathbb{R}$ $|x-y|<\delta\_2$ $\implies$ $|g(x)-g(y)|< \dfrac{\epsilon}{2M}$ $\bullet$ Now take $\delta := min\{ \delta\_1, \delta\_2\}$. Then, $|x-y|<\delta$ implies for all $x,y \in \mathbb{R}$, that $$|f(x)g(x)-f(y)g(y)| \leq |g(x)||f(x)+f(y)|+|f(y)||g(x)+g(y)| \leq $$ $$ M|f(x)+f(y)| + M|g(x)+g(y)| < M \dfrac{\epsilon}{2M} + M \dfrac{\epsilon}{2M} = \epsilon$$ Are these proofs correct? I am not sure how to approach the $\dfrac{f}{g}$ case.
2014/05/08
[ "https://math.stackexchange.com/questions/786527", "https://math.stackexchange.com", "https://math.stackexchange.com/users/148713/" ]
**Product $fg$** Boundnness is suffient but not necessary for uniform continuity of product $fg$. Here is an example where $f,g$ both are unbounded but their product is uniformly continuous: Let $E=[0,\infty)$ and $f(x)=g(x)=\sqrt{x}$. Here $f$ and $g$ are unbounded but their product $(fg)(x)=x$ is uniformly continuous. **$\frac fg$**: It is not true that $\frac fg$ is always uniformly continuous. Let $E=[1,\infty)$,$f(x)=x$ and $g(x)=\frac{1}{x}$ then $\left(\frac fg\right)(x)=x^2$ is not uniformly continuous on $[1,\infty)$.
As BCLC noted, how you got $$|f(x)g(x)-f(y)g(y)| \leq |g(x)||f(x)+f(y)|+|f(y)||g(x)+g(y)|$$ wasn't very clear. For the case $\frac{f}{g}$, you could note that $$\frac{f}{g} = f \cdot \frac{1}{g}$$ and use the previous part.
114,919
I'm looking for paper(s) that talk about "why low $R^2$ value is acceptable in social science or education research". Please point me to the right journal if you know one.
2014/09/10
[ "https://stats.stackexchange.com/questions/114919", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/55415/" ]
An arm-waving argument that nevertheless has much force works backwards. What would perfect prediction imply? For example, it would imply that we can predict students' performance **exactly** by just knowing their age, sex, race, class, etc. Yet we know that is absurd; it contradicts much else of what we know in social science, not to say everyday life. Moreover, although this is a different issue: many of us would not want to live in such a world.
Abelson's point could be summarised: What is improbable becomes probable in case of sufficiently many repetitions. Evolution is build on this principle: It is improbable that a mutation would be an advantage to the mutant. But, in case of sufficiently many mutations, it is likely that a few are advantageous. By means of selection and progeny, the improable afterwards becomes probable in the population. In both cases, there is a selection mechanism that makes success decisive, and failure not a disaster (for the species at least). Jesper Juul's book about gaming, "The Art of Failure", adds another dimension to Abelson's considerations. Juul's point is that it is not fascinating to play games where you never loose. Actually, there must be a balance between skills and the frequency of failures/successes, before it becomes attactive to play and improve your performance. Gaming and training ensure that failure is not a disaster, and then the selection mechanism is effective and low R2 values are no problem, they may even be preferable. Inversely, when failure is a disaster, high R2-values are very important. More generally, R2 values are important where the event is a game changer. Moreover, gamechanging events often cannot be reduced to a binarity, failure/success: The possible outcomes are multiple and have multiple effects. In that case, the outcome has historical/biographical salience. In case, events are historical and have never happened before, it is basically impossible to estimate R2, even though some analytical description may reduce randomness because history to some extent may resemble itself. In short, you may experience the combination of small R2 and gamechanging events. ... Well, that is life, sometimes ;-)
645,194
I find `array` environment pretty useful for aligning some blocks of equations, especially more flexible way of aligning each column as a whole, unlike `alugn`, however it has a couple of issues 1. You have to put `array` inside another math environment 2. All math like fractions, sum limits, integrals look small, because array isn't a display environment 3. Spacing between rows is different from other amsmath environments like `align`. I want spacing to be **exactly** the same as in `gather` for example Here's a comparison with `align` [![enter image description here](https://i.stack.imgur.com/biR0u.png)](https://i.stack.imgur.com/biR0u.png) The solution that I'm looking for has to take care of all listed issues above, but also keep the key feature of `array`: full control of columns type: `l`, `r` and especially `c` and all other properties like `@{}`, `>{}` `<{}`, vertical lines `c|c` , etc. Basically I need a standalone display variant default `array` that has same spacing as other amsmath environments. Making each row being labeled isn't the most important thing for me, but it would be nice to have such an option. --- Here's the "MWE" of desired environment and it's output ``` \documentclass{article} \begin{document} \begin{displayArray}{ *{3}{c} } a^2+b^2=c^2 & \frac{m}{n} = q & 1+2+3+4+5=15 \\ \sum_{i=1}^n & \int_a^bf(x)dx=F(x) & k=j \end{displayArray} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/RUPZV.png)](https://i.stack.imgur.com/RUPZV.png)
2022/05/22
[ "https://tex.stackexchange.com/questions/645194", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/213149/" ]
This is the way `align` is meant to be used: ``` \documentclass{article} \usepackage{amsmath} \begin{document} some text \begin{align} \frac{a+b}{c} &= d &\quad x+y &=z \\ \frac{k}{i-j} &= n &\quad m &=n \end{align} some more text \end{document} ``` [![output of example code](https://i.stack.imgur.com/3GHFq.png)](https://i.stack.imgur.com/3GHFq.png)
You could always define new column types to set all math in display style, and wrap an `array` into another environment where `\arraystretch` is larger. [![](https://i.stack.imgur.com/TJzSn.png)](https://i.stack.imgur.com/TJzSn.png) ``` \documentclass{article} \usepackage{amsmath} \usepackage{array} \newcolumntype{C}{>{\displaystyle}c} \newcolumntype{L}{>{\displaystyle}l} \newcolumntype{R}{>{\displaystyle}r} \newenvironment{displayArray}[1]{% \let\currentstretch\arraystretch \renewcommand*{\arraystretch}{2} \[\begin{array}{#1} }{% \end{array}\] \let\arraystretch\currentstretch } \begin{document} \begin{displayArray}{LR} \frac{a+b}{c} = d & x+y=z \\ \frac{k}{i-j} = n & m=n \end{displayArray} \end{document} ```
12,231,700
The other night I had the iTunes Visualizer (new not classic) playing. I started to think and wonder if it is possible to create a similar style type effects for transitioning of `div` or other tags to create a flashy effect. Here is the catch, while I assume something of that sort can be done in Flash is it possible to do it *without* flash and use HTML5, CSS3, Javascript, etc. ? I know some amazing effects can be created. After some searching I have not found anything but I ask here two questions: 1. Can something similar to the iTunes visualizer be done? 2. If possible, How? (Note: While I would love to support all browsers I am looking for if it is possible even if not supported in all browsers.)
2012/09/01
[ "https://Stackoverflow.com/questions/12231700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/825757/" ]
With Google Cloud Messaging, your server doesn't talk directly to the client. It goes through the "Cloud" part first. Thus putting the client certificate in your server's trust manager doesn't work. Instead, your server will have to validate the SSL certificate of Google's Cloud Messaging servers. Those are backed by Certificate Authorities already in your operating system's default CA list, so sending a message to the client before adding the trust store will work just fine.
I created a standalone java program which acted as 'server' and could push the message to GCM server which in turn could deliver message to my handset app. I don't had to install any certificate in my jre\lib\security\cacerts file as the shipped trusted entries are sufficient to connect to GCM server. The only dependencies are the following ``` <dependency> <groupId>com.google</groupId> <artifactId>gcm-server</artifactId> <version>1.0.1</version> </dependency> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency> ```
49,090,476
I'm working through a tutorial in Google Colaboratory, and the author has handily hidden some of the solutions cells. When you click the hidden cell, it expands and becomes visible. How can I hide the cells? An example is in this tutorial: [Creating and Manipulating Tensors](https://colab.research.google.com/notebooks/mlcc/creating_and_manipulating_tensors.ipynb?hl=en). [![Hidden Cells example](https://i.stack.imgur.com/fNwV0.png)](https://i.stack.imgur.com/fNwV0.png)
2018/03/03
[ "https://Stackoverflow.com/questions/49090476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326238/" ]
The black triangle, that makes it possible to fold and unfold sections, appears when you create a section (which is equivalent to creating a title). You can create a section by creating a text cell that starts with `# <your section title>`. This is how you create title in Markdown: `# This is a title` `## This is a smaller title` `### This is even a smaller title`... You can fold and unfold sections by clicking on the triangle next to their title. This image illustrates how to create a section: [![This image illustrates how to create a part](https://i.stack.imgur.com/9kOIW.png)](https://i.stack.imgur.com/9kOIW.png) This image is the result of the previous image (**note the magic triangle on the left**): [![This image is the result of the previous image note the triangle on the left](https://i.stack.imgur.com/RBtnz.png)](https://i.stack.imgur.com/RBtnz.png)
Here is the hot key for ya: ``` ctrl + " ``` After setting up the text part in Colab like what others have said, you can press **control and quote** key at the same time and collapse whichever cell/section you want.
6,598
Could anyone please inform me in which case(s) SharePoint groups will NOT be deleted when a site or subsite is deleted?
2010/10/28
[ "https://sharepoint.stackexchange.com/questions/6598", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/-1/" ]
You could somehow serialize or store the groups (Iterate through them somehow and build an XML file representing them to rebuild later on, for example) using a SPWebEventReceiver and extending WebDeleting. Other than this, groups are deleted with SPWeb and SPSite objects.
In my experience the OOTB behavior is that once a site is deleted the groups go with it. That is default behavior. However, I have to imagine that there are some third party tools that might be able to preserve the groups. Perhaps this can be done with STSADM?
42,133,628
I am using Laravel queues for commenting on Facebook posts. Whenever I receive data from a Facebook webhook, based on the received details I comment on the post. To handle 100 responses at once from Facebook webhooks, I am using Laravel queues, so that it can execute one by one. I used the step by step process as mentioned in [Why Laravel Queues Are Awesome](https://scotch.io/tutorials/why-laravel-queues-are-awesome) ``` public function webhooks(Request $request) { $data = file_get_contents('php://input'); Log::info("Request Cycle with Queues Begins"); $job = (new webhookQueue($data)->delay(10); $this->dispatch($job); Log::info("Request Cycle with Queues Ends"); } ``` and this is my job class structure ``` class webhookQueue extends Job implements ShouldQueue { use InteractsWithQueue, SerializesModels; private $data; public function __construct($data) { $this->data = $data; } public function handle() { //handling the data here } } ``` I am hitting the `webhooks()` function continuously, and all the jobs are working simultaneously but not in the queue. None of the jobs are being stored in the jobs table. I have given a delay but it is also not working. And this is my laravel.log: ``` [2017-02-08 14:18:42] local.INFO: Request Cycle with Queues Begins [2017-02-08 14:18:44] local.INFO: Request Cycle with Queues Begins [2017-02-08 14:18:47] local.INFO: Request Cycle with Queues Begins [2017-02-08 14:18:47] local.INFO: Request Cycle with Queues Begins [2017-02-08 14:18:47] local.INFO: Request Cycle with Queues Begins [2017-02-08 14:18:47] local.INFO: Request Cycle with Queues Begins [2017-02-08 14:18:48] local.INFO: Request Cycle with Queues Begins [2017-02-08 14:18:48] local.INFO: Request Cycle with Queues Begins [2017-02-08 14:18:48] local.INFO: Request Cycle with Queues Begins [2017-02-08 14:18:48] local.INFO: Request Cycle with Queues Begins [2017-02-08 14:18:48] local.INFO: Request Cycle with Queues Begins [2017-02-08 14:18:48] local.INFO: Request Cycle with Queues Begins [2017-02-08 14:18:55] local.INFO: Request Cycle with Queues Ends [2017-02-08 14:18:55] local.INFO: Request Cycle with Queues Ends [2017-02-08 14:18:55] local.INFO: Request Cycle with Queues Ends [2017-02-08 14:18:59] local.INFO: Request Cycle with Queues Ends [2017-02-08 14:19:00] local.INFO: Request Cycle with Queues Ends [2017-02-08 14:19:00] local.INFO: Request Cycle with Queues Ends [2017-02-08 14:19:00] local.INFO: Request Cycle with Queues Ends [2017-02-08 14:19:01] local.INFO: Request Cycle with Queues Ends [2017-02-08 14:19:01] local.INFO: Request Cycle with Queues Ends [2017-02-08 14:19:01] local.INFO: Request Cycle with Queues Ends [2017-02-08 14:19:01] local.INFO: Request Cycle with Queues Ends [2017-02-08 14:19:01] local.INFO: Request Cycle with Queues Ends ```
2017/02/09
[ "https://Stackoverflow.com/questions/42133628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6770506/" ]
I am seeing that you already have Queue table. Try running `php artisan queue:listen --tries=3` or `php artisan queue:work` etc. Queue work is for executing only one Job per command. So if there are 20 jobs in the table you might have to run queue work 20 times. That's why you can run `queue:listen` command. But it eats up a lot of CPU. In the server, you might want to run your queue listen with max 3 tries in the background. SSH to your server in the Terminal / Command Prompt. Then `CD` to your project directory where the artisan file lives. Run this command: `nohup php artisan queue:listen --tries=3 > /dev/null 2>&1 &` In this case jobs will automatically be processed in the background. You just have to dispatch the job. And I would recommend using failed-jobs table. If you are using background queue listner. Hope this helps.
All thing are set-up and still not work then make sure added schedule on crontab -e `* * * * * cd /var/www/html/<project_name> && php artisan schedule:run >> /dev/null 2>&1`
15,482
Nietzsche claims we must say "yes" to life, and be healthy and strong that way. But he also makes scathing remarks both in Zarathustra and in his late notebooks, about the Biblical maxim "thou shalt not kill". Is there anyway of reconciling the will to life with the first commandment?
2014/08/26
[ "https://philosophy.stackexchange.com/questions/15482", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/-1/" ]
You asked, "In Nietzsche is there any way of reconciling the 'will to life' with the first commandment?" Actually, the first four commandments (Exodus 20:1-11) refer to our duty toward God; the next six commandments (Exodus 20:12-17) outline our duty toward mankind. Your question regards the *sixth* commandment (Exodus 20:13): "Thou shalt not murder." In Nietzsche, you must understand, there is no way toward "reconciliation" of *religion* in any form, other than raw humanism, with *the* philosophy. The philosophy of the 'antichrist" (*the* philosophy) stands alone in its defiance to *anything* Christian. In Nietzsche, Christianity is the very definition of weakness. This is the most important thing to remember. Real strength (in Nietzsche) is to overcome all religious impulses (right brain stuff), including what I fondly call "Christian Truth and Knowing." However bleak this may seem (at first reading) in a post-modern world you cannot get by *not* knowing your Nietzsche. The "thou shalt not kill" reference seems more an irony than a meaning. The maxim, "Say yes to life" is not an irony. It *is* meaning. Say "yes" to the necessary remaking of the world by whatever means are available. Say "yes" because the greater tragedy is: "God has failed to show up." After the failure of Christianity (if there is such a failure), the *final* philosophy is Nietzsche. Beyond Nietzsche, consider who said this: **"To man *as* man, we readily say good riddance..."** and, **"We have not yet seen what man can make of man."** Certainly, Nietzsche opened the way, that is to say, he is the *precedent* for B.F. Skinner (behavioristic determinism), J. Derrida (antiphilosophy), with R. Dawkins, C. Hitchens and the aspiring world atheism movement; and perhaps, more significantly, the sociobiology of E.O. Wilson (directly inspired by James Watson) and its successor--evolutionary psychology. **Excellent secondary sources on Nietzsche include:** Walter Kaufmann: *Nietzsche: Philosopher, Psychologist, Anti-Christ* (1950; 1974) B3317.K29 1974 Harold Alderman: *Nietzsche's Gift* (1977) B3317 .A397 Janet I. Porter: *The Invention of Dionysus: Nietzsche and the Philology of the Future* (2000) B3313 G43 P67 2000 J.A. Bernstein: *Nietzsche's Moral Philosophy* (1987) B3318 E9 B47 1987
So it is "will to power" and not "will to life". To me the best way to avoid putting these directly at odds is to look at what "power" actually means from a perspective like post-Marxist-Feminism of Starhawk or some other position that deeply undercuts the power of both kings and martyrs. This is a vast oversimplification, stripped of all the feminism. (It is a little punchy, because Nietsche and Starhawk both seem to really like bad jokes.) The power to kill is a dumb power. Once you use it, the person you used it on is not going to do much for you. It is only power until you use it. Ultimately what you are really using is not the power of death, but the fear of death. This is the cocaine of power -- it makes you very effective, but then it is gone, and you immediately need more. It goes away not just when you kill people, but a little bit every time you use it as leverage. (So you never know exactly when you are running out.) It is a very contingent power. It depends on the target wanting life, which depends on the quality of their life, which you are actively degrading by threatening to kill them. At some point, they can face death to be rid of you. This is most tractable if they have already given up their life. But that is what martyr-religions do -- you give up your life to God, so that someone else cannot take it away from you. This is the heroin of power, it makes everything alright. But the downside of heroin is captured in the joke behind the name of the band 'Sublime', it feels heavenly, which is sublime the adjective. Sublime the verb means for something solid to basically disappear (untraceably into gas), which is what your life does ("All this love that I've found makes it hard to keep my soul on the ground" -- too hard. He did not succeed for very long.)... Nietsche's argument was that this was what is happening historically to the vitality of Europe, under the force of equality-based moralities, and what happens to the real soul of any good Christian, it evaporates, unnoticed. OK, well cocaine and heroin are stupid. They convey certain abilities and experiences to you, but they are likely to change who you are. Their corresponding versions of power are equally stupid, in the long run, in the ways that they overpower and degrade their wielder. If your own power overpowers you, who then has the power? -- The power has itself, and the holder loses. This explains why these forms of power are so persistent. Not that they are 'more real', but that they are addictive. It would be better if your menu of power looked less like the inside of Hunter S. Thompson's trunk, and more like the top of Martha Stewart's table. To remain vital, an individual, and a culture needs to develop a reflexive refusal to buy into the strong stuff and find subtler, more sustaining joys. So don't kill, in general. Not because someone said so, and *definitely* not because "everyone deserves to live", but because it is not sustainable. You don't want to be the master whose head got cut off by his slaves, or share even a part of his mindset -- he lost. But don't check out of material reality into some better place, either, or you will just evaporate. Instead, figure out what parts of power you can enjoy exceptionally well, that are unlikely to degrade your ability to continue to enjoy them for the long haul.
33,191,769
I've created a service (angular.js) that represents a model in my application: ``` angular.module("MyApp").factory('ItemService', function() { this.items = [1, 2, 3]; this.getItems = function() { return items; }; this.addItem = function(i) { ... }; this.deleteItem = function(i) { ... }; return this; }); ``` and my controller: ``` angular.module('ItemController', function($scope, ItemService) { $scope.getItems = function() { return ItemService.getItems(); }; }); ``` Now I want to wire up my service to a REST backend that retrieves, adds, deletes the items permanently. So I want to get rid of the initialization of the items array in my service and want to retrieve it from the server instead. Some things I came across: * The getItems function gets called from Angular multiple times (like 5-6 times when the page loads up and more often when page elements change). So I want to avoid to make each time a REST api call in the getItems function. * I could create an init() method in my service that initializes the items array using a REST request. But how can I ensure that this initialization is done before getItems gets called. * I could create a condition in getItems() that checks if items array is null. If so, initialize it from backend, if not return the saved array. * Note: getItems is not the only function that uses the items array. e.g. addItem, deleteItem etc. use it too. Many ways to do the same thing, but what is the correct/best way to do this using Angular.js?
2015/10/17
[ "https://Stackoverflow.com/questions/33191769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5458129/" ]
What worked for me ``` \ &nbsp; \ &nbsp; ``` [![enter image description here](https://i.stack.imgur.com/RozIQ.png)](https://i.stack.imgur.com/RozIQ.png)
You can also wrap it in a fenced code block. The advantage of this approach is you need not go for additional stuff for every line. However, the content shall be displayed as a highlighted block with a background, so it may not be apt for all use cases. ``` Lorem inmissa qui propinquas doleas Accipe fuerat accipiam ```
32,815
I am trying to clean up as much of the metadata as I can in my iTunes Library. One issue I came across is albums from a band, where the band releases multiple albums in a year. While this doesn't happen all that much, a good example is the Smashing Pumpkins, who released [Machina](http://en.wikipedia.org/wiki/Machina/The_Machines_of_God) in Feb. 2000, and then released [Machina II](http://en.wikipedia.org/wiki/Machina_II/The_Friends_&_Enemies_of_Modern_Music) later that year in Sept 2000. Live concerts are a great example as well, for example if you have recordings from different shows on a tour. In iTunes, currently Machina II is before Machina (Probably because in ASCII 'I' may come before '/'. This wouldn't matter much, except all the other albums from this artist are in order. Every once in a while, I am in the mood to listen to a particular artists set of albums over the years, and you can see then this won't work out. Is there a way to say either what Month the album was released, or another workaround (other than just saying the next year for example)? **Update:** I looked through the AppleScript dictionary, and it doesn't look like you can access anything except the year through AppleScript either.
2011/12/02
[ "https://apple.stackexchange.com/questions/32815", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/181/" ]
Hey I have this exact same problem, and I think I figured it out. 1. Right click on the selected album as a whole. 2. Go to the Sorting tab. 3. Under *Sorting Album*, for the album you would like to be second, type a number or any letter that is alphabetically before (if you want the album to be in front of another) then click *OK*. I did this with Syd Barrett's 2 solo albums that both came out in 1970. I didn't have to change anything on the first album he released, just on his second album, I typed the number 2 in the sorting album space and once I clicked *OK* it moved down below the 1st released album.
If put a letter or number in front of the album title in the "sort album" field, when you sync to your ipod the album will show up alphabetically on the ipod under that letter or number when you search by Album on the ipod. Still need a fix for this.
558,989
Assuming a poisson distribution, is there a way to solve for lambda in R? My inputs would be "x", and Pr(X<=x) ... and I would like R to tell me the lambda. Thanks
2022/01/02
[ "https://stats.stackexchange.com/questions/558989", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/345698/" ]
Let's call your original CI a 'probability-symmetric' confidence interval. For a symmetrical distribution, such an interval may be the narrowest one. However, the probability-symmetric 95% CI for normal $\sigma^2,$ based on pivoting $$\frac{(n-1)S^2}{\sigma^2}\sim\mathsf{Chisq}(\nu = n-1)$$ is not the shortest because chi-squared distributions are not symmetrical. For convenience, the probability-symmetric 95% CI is often used. (Also, 'minimum width' may not be the most important criterion, so the narrowest CI may not be the most useful.) *Example:* Suppose a random normal sample of size $n=50$ has $S^2 = 13.52.$ Then the probability-symmetric 95% CI $(9.43,20.99)$ has width $11.56,$ while the 95% CI $(9.28,20.61)$ has width $11.33.$ [Using R below.] ``` CI=49*(13.52)/qchisq(c(.975, .025), 49); CI [1] 9.434025 20.994510 diff(CI) [1] 11.56048 CI = 49*(13.52)/qchisq(c(.98, .03), 49); CI [1] 9.277642 20.611959 diff(CI) [1] 11.33432 CI = 49*(13.52)/qchisq(c(1, .05), 49); CI [1] 0.00000 19.52473 diff(CI) [1] 19.52473 # one-sided ``` In case width is especially important, one could search for the narrowest 95% CI.
### The symmetric interval minimises interval length in this case You can find a general exposition of optimal confidence intervals in this [related answer](https://stats.stackexchange.com/questions/477785/477861#477861). Here I will show you how to do the relevant optimisation for a confidence interval for the mean with known variance (via the normal approximation from the CLT). Let $0 \leqslant \theta \leqslant \alpha$ be the upper tail area for the interval and let $z\_a$ denote the quantile of the standard normal distribution with *upper* tail area $a$. The general interval form is: $$\text{CI}\_\mu (1-\alpha|\theta) = \Bigg[ \bar{x}\_n + \frac{z\_{1-\alpha+\theta}}{\sqrt{n}} \cdot \sigma, \bar{x}\_n + \frac{z\_{\theta}}{\sqrt{n}} \cdot \sigma \Bigg].$$ The length of this confidence interval is: $$\text{Length}(\theta) = (z\_{\theta} - z\_{1-\alpha+\theta}) \times \frac{\sigma}{\sqrt{n}}.$$ In order to obtain the optimal (minimum length) confidence interval of this form, we choose $\theta$ to minimise the length function. That is, we use the value: $$\hat{\theta} = \underset{0 \leqslant \theta \leqslant \alpha}{\text{arg min}} \ \text{Length}(\theta) = \underset{0 \leqslant \theta \leqslant \alpha}{\text{arg min}} \ (z\_{\theta} - z\_{1-\alpha+\theta}) = \frac{\alpha}{2}.$$ Using this optimisation result, we see that the length of the confidence interval is minimised using the equal tail (symmetric) interval. Using the fact that $z\_{1-\alpha/2} = - z\_{\alpha/2}$ we can write this optimal confidence interval in the standard form: $$\text{CI}\_\mu (1-\alpha) = \Bigg[ \bar{x}\_n - \frac{z\_{\alpha/2}}{\sqrt{n}} \cdot \sigma, \bar{x}\_n + \frac{z\_{\alpha/2}}{\sqrt{n}} \cdot \sigma \Bigg].$$
656,906
I am trying to make a web app print receipts for my customer (he asked me for it) I've placed a table and everything however when I print it I just can't get it to print correctly into the fields of the receipts. Let me explain, the receipts are already made so I am merely making a place where the user inputs all the required fields and then prints it as if printing a normal web page, being the output paper this receipt (that looks sort of like [this](http://www.monografias.com/trabajos55/documentos-comerciales/Image10677.gif)) anyway I've tried to move where the printer prints using a "print" css but it just won't obey...on top of that the text has gone wayyy small (I really don't know why) and honestly have no idea how to handle this anymore =/...does anyone out there knows? --- **Edit for Code** ``` * { /* old-style reset here :) */ border: 0px; padding: 0px; } table { left:0px; top:0px; } td, th { text-align: center; vertical-align: middle; color: #000; } input{ outline:none; } .borde{ background-color:#0FC; border: solid 2px #0FF; } ``` The HTML is a plain table...with input fields...
2009/03/18
[ "https://Stackoverflow.com/questions/656906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28586/" ]
Based on this link [here](http://forums.macrumors.com/archive/index.php/t-205556.html), it's possible that there's some optimization going on under the covers for common NSNumbers (which may not happen in all implementations hence a possible reason why @dizy's retainCount is 1). Basically, because NSNumbers are non-mutable, the underlying code is free to give you a second copy of the same number which would explain why the retain count is two. What is the address of n and n1? I suspect they're the same. ``` NSNumber* n = [[NSNumber alloc] initWithInt:100]; NSLog(@"Count of n : %i",[n retainCount]); NSNumber* n1 = n; NSLog(@"Count of n : %i",[n retainCount]); NSLog(@"Count of n1: %i",[n1 retainCount]); NSLog(@"Address of n : %p", n); NSLog(@"Address of n1: %p", n1); ``` Based on your update, that link I gave you is almost certainly the issue. Someone ran a test and found out that the NSNumbers from 0 to 12 will give you duplicates of those already created (they may in fact be created by the framework even before a user requests them). Others above 12 seemed to give a retain count of 1. Quoting: > > From the little bit of examination I've been able to do, it looks as if you will get "shared" versions of integer NSNumbers for values in the range [0-12]. Anything larger than 12 gets you a unique instance even if the values are equal. Why twelve? No clue. I don't even know if that's a hard number or circumstantial. > > > Try it with 11, 12 and 13 - I think you'll find 13 is the first to give you a non-shared NSNumber.
You should **never** rely on the `retainCount` of an object. You should **only** use it as a debugging aid, never for normal control flow. Why? Because it doesn't take into account `autorelease`s. If an object is `retain`ed and subequently `autorelease`d, its `retainCount` will increment, but as far as you're concerned, its *real* retain count hasn't been changed. The only way to get an object's real retain count is to also count how many times it's been added to any of the autorelease pools in the autorelease pool chain, and trying to do so is asking for trouble. In this case, the `retainCount` is 2 because somewhere inside `alloc` or `initWithInt:`, the object is being `retain`ed and `autorelease`d. But you shouldn't need to know or care about that, it's an implementation detail.
53,508,168
I'm attempting to create a JPA entity for a view. From the database layer, a table and a view should be the same. However, problems begin to arise and they are two fold: 1. When attempting to setup the correct annotations. A view does not have a primary key associated with it, yet without the proper `@javax.persistence.Id` annotated upon a field, you will get an `org.hibernate.AnnotationException: No identifier specified for entity` thrown at Runtime. 2. The Spring Boot `JpaRepository` interface definition requires that the `ID` type extends `Serializable`, which precludes utilizing `java.lang.Void` as a work-around for the lack of an id on an view entity. What is the proper JPA/SpringBoot/Hibernate way to interact with a view that lacks a primary key?
2018/11/27
[ "https://Stackoverflow.com/questions/53508168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1478636/" ]
**1. Create View with native SQL in the database,** ``` create or replace view hunters_summary as select em.id as emp_id, hh.id as hh_id from employee em inner join employee_type et on em.employee_type_id = et.id inner join head_hunter hh on hh.id = em.head_hunter_id; ``` **2. Map that, View to an 'Immutable Entity'** ``` package inc.manpower.domain; import org.hibernate.annotations.Immutable; import org.hibernate.annotations.Subselect; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.util.Date; @Entity @Immutable @Table(name = "`hunters_summary`") @Subselect("select uuid() as id, hs.* from hunters_summary hs") public class HuntersSummary implements Serializable { @Id private String id; private Long empId; private String hhId; ... } ``` **3. Now create the Repository with your desired methods,** ``` package inc.manpower.repository; import inc.manpower.domain.HuntersSummary; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import javax.transaction.Transactional; import java.util.Date; import java.util.List; @Repository @Transactional public interface HuntersSummaryRepository extends PagingAndSortingRepository<HuntersSummary, String> { List<HuntersSummary> findByEmpRecruitedDateBetweenAndHhId(Date startDate, Date endDate, String hhId); } ```
I hope this helps you, the id you can assign it to a united value in your view. We map the view to a JPA object as: ``` import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; @Entity @Table(name = "my_view") public class MyView implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "my_view_id") private Long myViewId; @NotNull @Column(name = "my_view_name") private String myViewName; } ``` We then create a repository: ``` import org.springframework.data.jpa.repository.JpaRepository; public interface MyViewRepository extends JpaRepository<View, Long> { } ```
847,153
I know that, for $|x|\leq 1$, $e^x$ can be bounded as follows: \begin{equation\*} 1+x \leq e^x \leq 1+x+x^2 \end{equation\*} Likewise, I want some *meaningful* lower-bound of $\sqrt{a^2+b}-a$ when $a \gg b > 0$. The first thing that comes to my mind is $\sqrt{a^2}-\sqrt{b} < \sqrt{a^2+b}$, but plugging this in ends up with a non-sense lower-bound of $-\sqrt{b}$ even though the target number is positive. \begin{equation\*} \big(\sqrt{a^2}-\sqrt{b} \big) - a < \sqrt{a^2+b}-a \end{equation\*} How can I obtain some positive lower-bound?
2014/06/25
[ "https://math.stackexchange.com/questions/847153", "https://math.stackexchange.com", "https://math.stackexchange.com/users/18526/" ]
Factor out an $a^2$ from the radical to get $a\sqrt{1+\frac{b}{a^2}}-a=a\left(\sqrt{1+\frac{b}{a^2}}-1\right)$ Which can then be expanded for $\left|\frac{b}{a^2}\right|<1$, which is true for $a \gg b > 0$. This expansion, to first order, is $a\left(1+\frac{b}{2a^2}-1\right)=\frac{b}{2a}$. EDIT: Forgot that you were looking for meaningful bounds. For a lower bound, you need to take the expansion to second order, so $a\left(1+\frac{b}{2a^2}-\frac{b^2}{8a^4}-1\right)=\frac{b}{2a}-\frac{b^2}{8a^3}$. For an upper bound, you need the third order expansion, so $a\left(1+\frac{b}{2a^2}-\frac{b^2}{8a^4}+\frac{b^3}{16a^6}-1\right)=\frac{b}{2a}-\frac{b^2}{8a^3}+\frac{b^3}{16a^5}$ So overall, we have $\frac{b}{2a}-\frac{b^2}{8a^3}<\sqrt{a^2+b}-a<\frac{b}{2a}-\frac{b^2}{8a^3}+\frac{b^3}{16a^5}$ These inequalities are true for $0<\frac{b}{a^2}<1$, which is true in this case.
By the mean value theorem, $$\sqrt{1 + x} - 1 = f(1 + x) - f(1) = x f'(c)$$ where $f$ is square root, $f'$ is its derivative, and $c$ is some point in $[1, 1+x]$. We need a lower bound and $f'$ is decreasing, so $c$ is at worst $1 + x$ and we obtain $$x f'(c) ≥ xf'(1 + x) = \frac{x}{2\sqrt{1 + x}}.$$ Backtrack: you want to underestimate $\sqrt{a^2 + b} - a$, which is $a(\sqrt{1 + b/a^2} - 1)$ and we can let $x$ be $b/a^2$: $$\sqrt{a^2 + b} - a ≥ a\frac{b/a^2}{2\sqrt{1 + b/a^2}} = \frac{b}{2\sqrt{a^2+b}}.$$ For an upper bound, $c$ is at best $1$ so $$\sqrt{a^2 + b} - a ≤ \frac{b}{2a}$$ which is trivial (cf. completing the square).
23,512,304
I've an array titled `$form_data` as follows: ``` Array ( [op] => preview [id] => [form_submitted] => yes [company_id] => 46 [1] => Array ( [pack] => 10 [quantity] => 20 [volume] => 30 [units] => 9 [amount] => 40 [rebate_start_date] => 2014-05-01 [rebate_expiry_date] => 2014-05-05 [applicable_states] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [rebate_total_count] => 5000 [products] => Array ( [1] => 9 [2] => 10 ) ) [2] => Array ( [pack] => 50 [quantity] => 60 [volume] => 70 [units] => 10 [amount] => 80 [rebate_start_date] => 2014-05-06 [rebate_expiry_date] => 2014-05-10 [applicable_states] => Array ( [0] => 14 [1] => 15 [2] => 16 ) [rebate_total_count] => 10000 [products] => Array ( [1] => 11 [2] => 8 ) ) [3] => Array ( [pack] => 100 [quantity] => 200 [volume] => 300 [units] => 7 [amount] => 400 [rebate_start_date] => 2014-05-21 [rebate_expiry_date] => 2014-05-30 [applicable_states] => Array ( [0] => 26 [1] => 33 [2] => 42 ) [rebate_total_count] => 9999 [products] => Array ( [1] => 9 [2] => 8 ) ) [multiselect] => 42 ) ``` I've written a function to validate the array entries. It is getting the parameters as `$form_data` array and `$error_msgs` array. Other objects are created in constructor of a class. So, please ignore those things and consider the error I'm getting in foreach loop. ``` function ValidateRebateByProductFormData($form_data, $errors_msgs) { if(!$this->mValidator->validate($form_data['company_id'], "required", "true")) $this->mValidator->push_error($errors_msgs['company_id'], 'company_id'); $product_ids = array(); // loop them, if its an array, loop inside it again /*for outer array $form_data*/ foreach($form_data as $index => $element) { /*check for each key of array $form_data whether it's an array or not*/ if(is_array($element)) { /*fo inner array having index [1], [2], [3],...*/ foreach($element as $key => $value) { /*check for each key of inner array [1], [2], [3],.. whether it's an array or not*/ if(is_array($value)) { if($key == 'products') { foreach($products as $k => $v) {//This is line 53 where I'm getting above warning if(!$this->mValidator->validate($v, "required", "true")) $this->mValidator->push_error($errors_msgs['product_id'], 'product_id'); //$product_ids = array_merge($product_ids, $value); } } else { //Validations for pack if(!$this->mValidator->validate($element['pack'], "numeric", "true")) $this->mValidator->push_error($errors_msgs['pack_invalid'], 'pack'); //Validations for quantity if(!$this->mValidator->validate($element['quantity'], "required", "true")) $this->mValidator->push_error($errors_msgs['quantity'], 'quantity'); elseif(!$this->mValidator->validate($element['quantity'], "numeric", "true")) $this->mValidator->push_error($errors_msgs['quantity_invalid'], 'quantity'); //Validations for volume if(!$this->mValidator->validate($element['volume'], "required", "true")) $this->mValidator->push_error($errors_msgs['volume'], 'volume'); elseif(!$this->mValidator->validate($element['volume'], "numeric", "true")) $this->mValidator->push_error($errors_msgs['volume_invalid'], 'volume'); //Validations for units if(!$this->mValidator->validate($element['units'], "required", "true")) $this->mValidator->push_error($errors_msgs['units'], 'units'); //Validations for amount if(!$this->mValidator->validate($element['amount'], "required", "true")) $this->mValidator->push_error($errors_msgs['amount'], 'amount'); elseif(!$this->mValidator->validate($element['amount'], "numeric", "true")) $this->mValidator->push_error($errors_msgs['amount_invalid'], 'amount'); //Validations for rebate start date if(!$this->mValidator->validate($element['rebate_start_date'], "required", "true")) $this->mValidator->push_error($errors_msgs['rebate_start_date'], 'rebate_start_date'); elseif(!$this->mValidator->validate($element['rebate_start_date'], "date", "true")) $this->mValidator->push_error($errors_msgs['rebate_start_date_invalid'], 'rebate_start_date'); //Validations for rebate expiry date if(!$this->mValidator->validate($element['rebate_expiry_date'], "required", "true")) $this->mValidator->push_error($errors_msgs['rebate_expiry_date'], 'rebate_expiry_date'); elseif(!$this->mValidator->validate($element['rebate_expiry_date'], "date", "true")) $this->mValidator->push_error($errors_msgs['rebate_expiry_date_invalid'], 'rebate_expiry_date'); //Validation for rebate start date and rebate expiry date if(change_date_format_to_db($element['rebate_expiry_date'], 'Y-m-d')<change_date_format_to_db($element['rebate_start_date'], 'Y-m-d')) $this->mValidator->push_error($errors_msgs['rebate_exp_date'], 'rebate_start_date'); if(clean($element['rebate_total_count'])!="") { if(!$this->mValidator->validate($element['rebate_total_count'], "integer", "true")) $this->mValidator->push_error($errors_msgs['rebate_total_count_invalid'], 'rebate_total_count'); } } } } } } } ``` In above code I've added a comment to indicate the line no.53 where I'm getting warning. If you find any other bugs in this loop iterations please let me know.
2014/05/07
[ "https://Stackoverflow.com/questions/23512304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1897974/" ]
`$products` doesn't appear to be defined. Did you mean: ``` foreach( $value as $k => $v) { ```
Looking again, it would rather be: ``` foreach($element as $key => $value) { /*check for each key of inner array [1], [2], [3],.. whether it's an array or not*/ if(is_array($value)) { foreach($value as $key1=>$value1){ if($key1 == 'products') { foreach($value['products'] as $k => $v) { ``` At the point where the loop reaches: ``` [1] => Array ( [pack] => 10 ``` You are checking with `is_array()` but you need to get into the nested level to have the *key* `products`.
1,725,856
Given the following table structure: ``` CREATE TABLE user ( uid INT(11) auto_increment, name VARCHAR(200), PRIMARY KEY(uid) ); CREATE TABLE user_profile( uid INT(11), address VARCHAR(200), PRIMARY KEY(uid), INDEX(address) ); ``` Which join query is more efficient: #1, ``` SELECT u.name FROM user u INNER JOIN user_profile p ON u.uid = p.uid WHERE p.address = 'some constant' ``` or #2: ``` SELECT u.name FROM user u INNER JOIN (SELECT uid FROM user_profile WHERE p.address = 'some constant') p ON u.uid = p.uid ``` How much is the difference in efficiency?
2009/11/12
[ "https://Stackoverflow.com/questions/1725856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207834/" ]
The first syntax is generally more efficient. `MySQL` buffers the derived queries so using the derived query robs the `user_profile` of possibility to be a driven table in the join. Even if the `user_profile` is leading, the subquery results should be buffered first which implies a memory and performance impact. A `LIMIT` applied to the queries will make the first query much faster which is not true for the second one. Here are the sample plans. There is an index on `(val, nid)` in the table `t_source`: First query: ``` EXPLAIN SELECT * FROM t_source s1 JOIN t_source s2 ON s2.nid = s1.id WHERE s2.val = 1 1, 'SIMPLE', 's1', 'ALL', 'PRIMARY', '', '', '', 1000000, '' 1, 'SIMPLE', 's2', 'ref', 'ix_source_val,ix_source_val_nid,ix_source_vald_nid', 'ix_source_val_nid', '8', 'const,test.s1.id', 1, 'Using where' ``` Second query: ``` EXPLAIN SELECT * FROM t_source s1 JOIN ( SELECT nid FROM t_source s2 WHERE val = 1 ) q ON q.nid = s1.id 1, 'PRIMARY', '<derived2>', 'ALL', '', '', '', '', 100000, '' 1, 'PRIMARY', 's1', 'ref', 'PRIMARY', 'PRIMARY', '4', 'q.nid', 10000, 'Using where' 2, 'DERIVED', 's2', 'ref', 'ix_source_val,ix_source_val_nid,ix_source_vald_nid', 'ix_source_vald_nid', '4', '', 91324, 'Using index' ``` As you can see, only a part of the index is used in the second case, and `q` is forced to be leading. **Update:** *Derived queries* (which is what this question concerns) are not to be confused with the *subqueries*. While `MySQL` is not able to optimize **derived queries** (those used in the `FROM` clause), the **subqueries** (those used with `IN` or `EXISTS`) are treated much better. See these articles in my blog for more detail: * [**Passing parameters in MySQL: IN list vs. temporary table**](http://explainextended.com/2009/08/18/passing-parameters-in-mysql-in-list-vs-temporary-table/) * [**NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: MySQL**](http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null-mysql/)
The answer usually depends on the statistics gathered by database. The first form seems to be easier for optimizer. As far as I remember, MySQL doesn't work well with IN... queries and subselects
13,760,844
I define below data type: ``` typedef int MyInt; ``` Then I hope to define a new data type based on size of MyInt, something like below code, but I can't find a solution for it. ``` #if sizeof(MyInt) == 2 typedef long MyLong; #else typedef short MyLong; #endif ``` Could anybody help?
2012/12/07
[ "https://Stackoverflow.com/questions/13760844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1877689/" ]
It's not the preprocessor's job to evaluate `sizeof`, that's done by the compiler which is a later stage in the process. Evaluating `sizeof` needs deep C knowledge that the preprocessor simply doesn't have. You could (in theory) consider the preprocessor as a separate step, that does *text only* transforms, in effect converting "foo.c" to "foo-preprocessed.c". The latter file won't have any `#include` or `#if`s left, they're all evaluated and replaced by the preprocessor. The actual compiler never sees them. You should consider using `<stdint.h>` and the known-precision types (`uint16_t` and friends).
You can use `UINT_MAX` - it can give you a clue about the size of integer. ``` #if (UINT_MAX <= 65536) typedef long MyLong; #else typedef short MyLong; #endif ```
16,344,683
I am creating a dictionary, that potentially has keys that are the same, but the values of each key are different. Here is the example dict: ``` y = {44:0, 55.4:1, 44:2, 5656:3} del y[44] print y {5656: 3, 55.399999999999999: 1} ``` I would like to be able to do something like: ``` del y[44:0] ``` Or something of that nature.
2013/05/02
[ "https://Stackoverflow.com/questions/16344683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/557695/" ]
Just an idea- instead of having scalar values, why not a collection of some kind? Perhaps even a set if they are unique values: ``` myDict = {44:set([1, 2, 3])} ``` So to add or remove an object: ``` myDict[44].add(1) myDict[44].remove(1) ``` For adding a new key: ``` if newKey not in myDict: myDict[newKey] = set() # new empty set ```
Your question is moot. In your `y` declaration, the `44:2` wouldn't go alongside `44:0`, it would overwrite it. You'd need to use a different key if you want both values in the dictionary.
3,544,221
I built a small cms for personal websites using Rails. Each site has a simple blog. I've been looking for a good third party comment system to add to the cms. Have you used (or know of) any "comment service" that I can seamlessly integrate via their API, and if they have a ruby gem even better. Thanks in advance Deb
2010/08/23
[ "https://Stackoverflow.com/questions/3544221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/226619/" ]
In addition to the two above, I've found this service (formerly called jskit) interesting, and it seems to have some great Twitter-integration features: <http://aboutecho.com/>
I have used [Intensedebate](http://intensedebate.com/) and [disqus](http://disqus.com/) I feel Intensedebate is better.
879,408
How can I write a wrapper that can wrap any function and can be called just like the function itself? The reason I need this: I want a Timer object that can wrap a function and behave just like the function itself, plus it logs the accumulated time of all its calls. The scenario would look like this: ``` // a function whose runtime should be logged double foo(int x) { // do something that takes some time ... } Timer timed_foo(&foo); // timed_foo is a wrapping fct obj double a = timed_foo(3); double b = timed_foo(2); double c = timed_foo(5); std::cout << "Elapsed: " << timed_foo.GetElapsedTime(); ``` How can I write this `Timer` class? I am trying something like this: ``` #include <tr1/functional> using std::tr1::function; template<class Function> class Timer { public: Timer(Function& fct) : fct_(fct) {} ??? operator()(???){ // call the fct_, // measure runtime and add to elapsed_time_ } long GetElapsedTime() { return elapsed_time_; } private: Function& fct_; long elapsed_time_; }; int main(int argc, char** argv){ typedef function<double(int)> MyFct; MyFct fct = &foo; Timer<MyFct> timed_foo(fct); double a = timed_foo(3); double b = timed_foo(2); double c = timed_foo(5); std::cout << "Elapsed: " << timed_foo.GetElapsedTime(); } ``` (BTW, I know of `gprof` and other tools for profiling runtime, but having such a `Timer` object to log the runtime of a few selected functions is more convenient for my purposes.)
2009/05/18
[ "https://Stackoverflow.com/questions/879408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60628/" ]
A solution using macros and templates: For example you want to wrap ``` double foo( double i ) { printf("foo %f\n",i); return i; } double r = WRAP( foo( 10.1 ) ); ``` Before and after calling foo() the wrapper functions beginWrap() and endWrap() should be called. (With endWrap() being a template function.) ``` void beginWrap() { printf("beginWrap()\n"); } template <class T> T endWrap(const T& t) { printf("endWrap()\n"); return t; } ``` The macro ``` #define WRAP(f) endWrap( (beginWrap(), f) ); ``` uses the precedence of the comma-operator to assure beginWrap() is called first. The result of f is passed to endWrap() which just returns it. So the output is: ``` beginWrap() foo 10.100000 endWrap() ``` And the result r contains 10.1.
If your compiler supports variadic macros, I'd try this: ``` class Timer { Timer();// when created notes start time ~ Timer();// when destroyed notes end time, computes elapsed time } #define TIME_MACRO(fn, ...) { Timer t; fn(_VA_ARGS_); } ``` So, to use it, you'd do this: ``` void test_me(int a, float b); TIME_MACRO(test_me(a,b)); ``` That's off the cuff, and you'd need to play around to get return types to work (I think you'd have to add a type name to the TIME\_MACRO call and then have it generate a temp variable).
18,863
In John Michael McDonagh's wonderful philosophical black comedy [Calvary](http://www.imdb.com/title/tt2234003/?ref_=fn_al_tt_1), a good priest receives a death threat during a confessional giving him a week to sort out his affairs. During the course of the week there are a lot of encounters between the priest and his parishioners, many acting as red herrings to distract the audience form the identity of the potential killer. Several threatening acts also take place: the church is burned and the priest's dog is killed. But in the final encounter between the priest and the mystery antagonist (I'm not saying who to avoid spoilers) the antagonist admits burning the church but claims not to have killed the priest's dog. Are they lying? Or is there a good reason that someone else might have killed the dog?
2014/04/21
[ "https://movies.stackexchange.com/questions/18863", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/134/" ]
I think it is intentionally left unclear so that you analyze everyone in the movie in retrospect and study each and every criticism of the church as presented by each character. It is a clever way to really force across the point.
Good Question! I agree with John Smith Optional that the film leaves this open-ended, but my sense after hearing the killer's denial was that killing the dog was a very personal attack in the sense that burning down the church and murdering Father James was not, and that as a result the suspicion falls on the one person who genuinely *does* have a profound personal grievance against him: **his daughter Fiona**, who left the village the morning after the dog was discovered. Rather than promoting the idea that there is another person aggrieved at "the Priest" for what the church as a whole has done, the reading I would propose is that James "the father" is being punished for making his aspiration to be a good priest rather than a good man. While she was visiting James, having come over from London following a suicide attempt, she discusses with him how he had left for the priesthood after his wife and her mother had died. Although James was leaving on a pursuit for the greater good, Fiona felt that she had been abandoned by both of her parents one after the other. Taking away the dog, one of James's few close companions in his work, would be fitting revenge, and "killing the dog" to send a message would appeal to a well-read sense of irony. James had tried to make up to her by telling her that he will always be there for her, but the scars of parental abandonment run very deep, as can be inferred from her failed relationships with men and her suicidal response to repeated rejection. They discuss the sad idea about cutting across, rather than down, early on in their interactions, and the method of the dog's execution (a horizontal slash across the neck) calls back to the slashed wrists referenced previously. Finally, of all of the characters other than Father James, Fiona is the only one that seems to be in any kind of regular contact with it. There are other readings, but this is the one that I think has the most interesting scope for analysis if we want to analyse the film in terms of the nature of faith and calling to do good. It also adds one extra layer of emotional complexity to the final scene, which is never a bad thing!
15,320
Qualifying offenses for the [sex offender registry](http://en.wikipedia.org/wiki/Sex_offender_registry#Application_to_offenses_other_than_felony_sexual_offenses) can [include public urination](http://freestudents.blogspot.com/2009/12/pee-nal-code-and-sex-crimes.html). Though the chance may be small, the potential consequences are severe. Unfortunately, bladders are apparently designed in ignorance of these laws. A few obvious solutions, such as intentionally becoming dehydrated or only riding in urban settings, are impractical. How can cyclists avoid becoming sex offenders when nature calls on long rides?
2013/04/16
[ "https://bicycles.stackexchange.com/questions/15320", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/3649/" ]
Plan your route accordingly. Make sure there's a couple gas stations or restaurants along the way that you could stop at if the need arises. It's probably a good idea to be somewhat close to civilization not only for urination purposes, but also in case you have some major mechanical problem with your bike, or you fall and get hurt. This doesn't mean your route has to be urban, but you should be able to plan a route such that you pass by some kind of civilization every 40-60 minutes. Alas, if you are that far out, you could always go off a side road or into the bush and relieve yourself there. If you're so far from civilization that you can't make it to a gas station, odds are that there won't be many cops around to prosecute you either.
I use an external catheter for on-the-road urination while riding the recumbent. For upright and other bikes you might make some changes. Here is what, how and why I do it. <http://psychling1.blogspot.com/2010/12/use-of-external-catheter-for-racing-or.html> I also use this device in work meetings, on long car trips or when I go to lectures or the symphony. In these situations I simply strap a very small Camelbak bladder to my calf, just under the knee. Discreet. Civilized.
271,518
Consider: ``` $ find . -name *.css ./style.css ./view/css/style.css $ ls view/css/ consultation.css jquery.scombobox.min.css page-content.css style.css ``` **Why might `find` have missed the files in `view/css`?** This is on Ubuntu 15.10, an obscure Debian derivative.
2016/03/22
[ "https://unix.stackexchange.com/questions/271518", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/9760/" ]
So while the answer by Thomas got me thinking along the right path, it was actually the comment on Thomas's answer by cas that solved my issue completely: Before cloning the partition, i edited `/etc/default/grub`, and uncommented the line that said `GRUB_DISABLE_LINUX_UUID=true` and ran `update-grub`. After cloning sda1 to sda3, Kali consistently boots into sda1, and gparted no longer shows sda3 as being mounted at `/`.
Yes, your root partition is mounted with the filesystem UUID and both, the original and the cloned one have the same UUID. To work around this, you could comment the corresponding line and mount it with the `/dev/sda1` path. ``` #UUID=20d4493c-5934-4633-998e-0c6dd970d4ad / ext4 errors=remount-ro 0 1 /dev/sda1 / ext4 errors=remount-ro 0 1 ``` You also should check the `grub` configuration, as sometimes the UUID is used there, too. There should be something like `root=` which either specifies a UUID or a full path to a device.
54,160,655
I am really trying very hard to figure out how to return string from a function to other. Please help me to solve this problem. Returning Password as String from this function: ``` char* password(void) { const maxPassword = 15; char password[maxPassword + 1]; int charPos = 0; char ch; printf( "\n\n\n\tPassword(max 15 Characters/no numeric value or special char is allowed):\t"); while (1) { ch = getch(); if (ch == 13) // Pressing ENTER break; else if (ch == 32 || ch == 9) //Pressing SPACE OR TAB continue; else if (ch == 8) { //Pressing BACKSPACE if (charPos > 0) { charPos--; password[charPos] = '\0'; printf("\b \b"); } } else { if (charPos < maxPassword) { password[charPos] = ch; charPos++; printf("*"); } else { printf( "You have entered more than 15 Characters First %d character will be considered", maxPassword); break; } } } //while block ends here password[charPos] = '\0'; return password; } ``` --- To this function (but its not printing) : ``` void newuser(void) { int i; FILE *sname, *sid; struct newuser u1; sname = fopen("susername.txt", "w"); if (sname == NULL) { printf("ERROR! TRY AGAIN"); exit(0); } printf("\n\n\n\tYourName:(Eg.Manas)\t"); //user name input program starts here scanf("%s", &u1.UserName); for (i = 0; i < strlen(u1.UserName); i++) putc(u1.UserName[i], sname); fclose(sname); //sid=fopen("sid.txt","w"); printf("\n\n\n\tUserId:(Eg.54321)\t"); //User Id input starts here scanf("%d", &u1.UserId); printf("%s", password()); } ```
2019/01/12
[ "https://Stackoverflow.com/questions/54160655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10375821/" ]
Because the lifetime of `char password[maxPassword+1];` is in `password` function after function finished automatic delete from ram. Variables defined inside a function, which are not declared static, are automatic. There is a keyword to explicitly declare such a variable – auto – but it is almost never used. Automatic variables (and function parameters) are usually stored on the stack. The stack is normally located using the linker. The end of the dynamic storage area is typically used for the stack. for solving this problem you have some choices 1. you can get this variable from argument of password function and then change it. `void password(char password*)` 2. C dynamic memory allocation with `malloc` `char *password = malloc(maxPassword+1)` If use this method with `printf("%s", password());` deliberately leaks memory by losing the pointer to the allocated memory. The leak can be said to occur as soon as the pointer 'a' goes out of scope, i.e. when function\_which\_allocates() returns without freeing 'a'. you should use `free()` to de-allocate the memory. `char* passwd = password(); printf("%s", passwd); free(passwd); passwd = NULL;`
`char password[maxPassword+1]` is local to the function, you need to allocate memory for it like that `char *password = malloc(maxPassword+1)` or use global variable. Also change `const maxPassword=15` to `int maxPassword=15`, and `ch=getch()` to `ch=getchar()`. Generally I recommend reading a book about C, because it seems that you're guessing and it won't get you anywhere with C.
57,412,942
I have an array [a0,a1,...., an] I want to calculate the sum of the distance between every pair of the same element. 1)First element of array will always be zero. 2)Second element of array will be greater than zero. 3) No two consecutive elements can be same. 4) Size of array can be upto 10^5+1 and elements of array can be from 0 to 10^7 For example, if array is [0,2,5 ,0,5,7,0] then distance between first 0 and second 0 is 2\*. distance between first 0 and third 0 is 5\* and distance between second 0 and third 0 is 2\*. distance between first 5 and second 5 is 1\*. Hence sum of distances between same element is 2\* + 5\* + 2\* + 1\* = 10; For this I tried to build a formula:- for every element having occurence more than 1 (0 based indexing and first element is always zero)--> sum = sum + (lastIndex - firstIndex - 1) \* (NumberOfOccurence - 1) if occurence of element is odd subtract -1 from sum else leave as it is. But this approach is not working in every case. ,,But this approach works if array is [0,5,7,0] or if array is [0,2,5,0,5,7,0,1,2,3,0] Can you suggest another efficient approach or formula? Edit :- This problem is not a part of any coding contest, it's just a little part of a bigger problem
2019/08/08
[ "https://Stackoverflow.com/questions/57412942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8090037/" ]
There is a gem for this [RailsCallbackLog](https://github.com/jaredbeck/rails-callback_log) Author already posted it here, in [this](https://stackoverflow.com/questions/13089936/tracking-logging-activerecord-callbacks) question (second answer) . An example: for this code `Mechanic.first.save` (`Mechanic` is just an ActiveRecord model) gem with default settings printed this ``` Callback: validate_associated_records_for_mechanics_games Callback: validate_associated_records_for_games Callback: _ensure_no_duplicate_errors Callback: before_save_collection_association Callback: #<ActiveSupport::Callbacks::Conditionals::Value:0x000000000b7736d8> Callback: autosave_associated_records_for_mechanics_games Callback: #<ActiveSupport::Callbacks::Conditionals::Value:0x000000000b6eba08> Callback: autosave_associated_records_for_games Callback: #<ActiveSupport::Callbacks::Conditionals::Value:0x000000000b6f1890> Callback: after_save_collection_association Callback: print_hello ``` Last callback `print_hello` was custom, defined for this test case, so gem shows both default and custom callbacks.
This callback works when using the upgrade method: ", on: :update"
2,184,763
Got Link error (Fatal: Access violation. Link terminated) in Borland 6.0. How do I know what is the cause of it ? Is there any output file that I can open and get more informative message ?
2010/02/02
[ "https://Stackoverflow.com/questions/2184763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264416/" ]
You should be able to use the command line that gets passed to the linker to determine which .obj files are being passed to the linker. You can then include/exclude files to see when the error occurs. A number of linker problems have been fixed since BCB6, you may want to try the linker from a demo of a newer version to see if that solves your problem.
Some files in the project had incorrect file path.
2,990,547
Consider a DB with a Client table and a Book table: Client: person\_id Book: book\_id Client\_Books: person\_id,book\_id How would you find all the Person ids which have no books? (without doing an outer join and looking for nulls)
2010/06/07
[ "https://Stackoverflow.com/questions/2990547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249571/" ]
``` select * from Client where person_id not in (select person_id from Client_Books) ```
``` SELECT * FROM Client WHERE person_id not in (SELECT person_id FROM Client_Books) ```
55,653,244
Here is the data ``` DPS Comodity Std Issue 111 Hard drive No Post 111 MBD NoBoot 111 LCD Flicker 222 MBD No Post 222 LCD No Post 333 MBD No power ``` I have to get in the below format ``` DPS Comodity Std Issue 111 Hard drive,MBD,LCD Hard drive-No Post,MBD-NoBoot,LCD-Flicker 222 MBD,LCD No Post 333 MBD No Power ``` I have tried `aggregate(Std Issue~DPS,df,function(x)toString(uniqe(x)))`, but it results Std Issue as ``` No Post,No Boot, Flicker No Post No Power ``` Which is not as per my requirement, any suggestion on it to solve this type of problem will be much helpful and appreciated. ``` aggregate(Std Issue~DPS,df,function(x)toString(uniqe(x))) ``` or Here is the expected result ``` DPS Comodity Std Issue 111 Hard drive,MBD,LCD Hard drive-No Post,MBD-NoBoot,LCD-Flicker 222 MBD,LCD No Post 333 MBD No Power ```
2019/04/12
[ "https://Stackoverflow.com/questions/55653244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10009769/" ]
You can do this by using `data.table` package- ``` > library(data.table) > setDT(dt)[,Std_Issue:=paste0(Comodity,"-",Std.Issue)] > setDT(dt)[, list(Comodity = paste(Comodity, collapse=","), `Std Issue` = paste(Std_Issue, collapse=",")), by = DPS] ``` **Output**- ``` DPS Comodity Std Issue 1: 111 Hard drive,MBD,LCD Hard drive-No Post,MBD-NoBoot,LCD-Flicker 2: 222 MBD,LCD MBD-No Post,LCD-No Post 3: 333 MBD MBD-No power ``` **Input data-** ``` dt <- read.table(text="DPS Comodity Std Issue 111 Hard drive No Post 111 MBD NoBoot 111 LCD Flicker 222 MBD No Post 222 LCD No Post 333 MBD No power",header=T,sep="\t") ``` **EDITED-** You can achieve this using without `for loop`- ``` > setDT(dt)[,Std_Issue:=paste0(Comodity,"-",Std.Issue)] > setDT(dt)[, list(Std_issue = ifelse(length(unlist(unique(lapply(str_split(Std_Issue,"-"),function(x)x[2]))))<3,paste(unique(`Std.Issue`), collapse=","),paste(Std_Issue, collapse=",")),Commodity=paste(Comodity, collapse=",")), by=DPS] DPS Std_issue Commodity 1: 111 Hard drive-No Post,MBD-NoBoot,LCD-Flicker Hard drive,MBD,LCD 2: 222 No Post MBD,LCD 3: 333 No power MBD ```
Finally I found the solution which worked : ``` test_df <- data.frame(DPS=c(111,111,111,222,222,333),comodity =c("HDD","MBD","LCD","MBD","LCD","MBD"),stdIss=c("No Post","No Boot","Flicker","No Post","No Post","No Power")) A <- data.frame(tapply(test_df$comodity,test_df$DPS,FUN = function(x){toString(x)})) B <- data.frame(tapply(test_df$stdIss,test_df$DPS,FUN=function(x{toString(unique(x))})) C <- data.frame(A,B) colnames(C)[1] <- "comodity" colnames(C)[2] <- "Std Issue" C$comodity <- strsplit(C$comodity, split = ",") C$`Std Issue` <- strsplit(C$`Std Issue`,split = ",") C$new <- NA D <- list() for(i in 1:nrow(C)){ if(length(C$`Std Issue`[[i]])>1){for(j in 1:length(C$`Std Issue`[[i]])) { D[j]<- paste(C$comodity[[i]][j],C$`Std Issue`[[i]][j],sep = "-") } C$new[i]<-paste(D,collapse = ",") } else { C$new[i] <-paste(C$`Std Issue`[i]) } } ```
34,545,875
I have created a bearer token using ASP.net Identity. In AngularJS I wrote this function to get authorized data. ``` $scope.GetAuthorizeData = function () { $http({ method: 'GET', url: "/api/Values", headers: { 'authorization': 'bearer <myTokenId>' }, }).success(function (data) { alert("Authorized :D"); $scope.values = data; }).error(function () { alert("Failed :("); }); }; ``` So **I want to store this token into Browser cookies**. If this token is present there , then take the token and get the data from IIS server Otherwise redirect to login page to login to get a new token. Similarly, if user click onto log out button, it should remove the token from browser cookie. **How to do this ? It it possible ? Is it proper way to authenticate and authorize a user ? What to do if there are multiple users token ?**
2015/12/31
[ "https://Stackoverflow.com/questions/34545875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4586387/" ]
There is a `$cookies` service available in the AngularJS API using the `ngCookies` module. It can be used like below: ``` function controller($cookies) { //set cookie $cookies.put('token', 'myBearerToken'); //get cookie var token=$cookies.get('token'); //remove token $cookies.remove('token'); } controller.$inject=['$cookies']; ``` For your case it would be: ``` //inject $cookies into controller $scope.GetAuthorizeData = function () { $http({ method: 'GET', url: "/api/Values", headers: { 'authorization': 'bearer <myTokenId>' }, }) .success(function (data) { $cookies.put('token', data); }).error(function () { alert("Failed :("); }); }; ``` You will also have to add the [angular-cookies module](https://www.npmjs.com/package/angular-cookies) code. And add it to your angular app: `angular.module('myApp', ['ngCookies']);`. [Docs for Angular Cookies.](https://docs.angularjs.org/api/ngCookies/service/$cookies) I would also like to suggest the usage of a `Http interceptor` which will set the bearer header for each request, rather than having to manually set it yourself for each request. ``` //Create a http interceptor factory function accessTokenHttpInterceptor($cookies) { return { //For each request the interceptor will set the bearer token header. request: function($config) { //Fetch token from cookie var token=$cookies.get['token']; //set authorization header $config.headers['Authorization'] = 'Bearer '+token; return $config; }, response: function(response) { //if you get a token back in your response you can use //the response interceptor to update the token in the //stored in the cookie if (response.config.headers.yourTokenProperty) { //fetch token var token=response.config.headers.yourTokenProperty; //set token $cookies.put('token', token); } return response; } }; } accessTokenHttpInterceptor.$inject=['$cookies']; //Register the http interceptor to angular config. function httpInterceptorRegistry($httpProvider) { $httpProvider.interceptors.push('accessTokenHttpInterceptor'); } httpInterceptorRegistry.$inject=['$httpProvider']; //Assign to module angular .module('myApp') .config(httpInterceptorRegistry) .factory('accessTokenHttpInterceptor', accessTokenHttpInterceptor) ``` Having the `http interceptor` in place you do not need to set the `Authorization header` for each request. ``` function service($http) { this.fetchToken=function() { //Authorization header will be set before sending request. return $http .get("/api/some/endpoint") .success(function(data) { console.log(data); return data; }) } } service.$inject=['$http'] ``` As stated by Boris: there are other ways to solve this. You could also use `localStorage` to store the token. This can also be used with the http interceptor. Just change the implementation from cookies to localStorage. ``` function controller($window) { //set token $window.localStorage['jwt']="myToken"; //get token var token=$window.localStorage['jwt']; } controller.$inject=['$window']; ```
I would advise against keeping the data in a cookie, for security purposes you should set the cookies to secure and HttpOnly (not accessible from javascript). If you're not using SSL, I would suggest moving to `https`. I would pass the token from the auth endpoint in a json response: ``` { tokenData: 'token' } ``` You can save the token data in `sessionStorage` by using the `$window` service: ``` $window.sessionStorage.setItem('userInfo-token', 'tokenData'); ``` It will be cleared once the user closes the page, and you can manually remove it by setting it to empty string: ``` $window.sessionStorage.setItem('userInfo-token', ''); ``` Edit: Interceptor implementation for catching data, adapted from cbass (not tested, you can inspect the objects for response/request to fiddle with the information): ``` //Create a http interceptor factory function accessTokenHttpInterceptor($window) { return { //For each request the interceptor will set the bearer token header. request: function($config) { //Fetch token from cookie var token=$window.sessionStorage.getItem('userInfo-token'); //set authorization header $config.headers['Authorization'] = 'Bearer '+token; return $config; }, response: function(response) { //if you get a token back in your response you can use //the response interceptor to update the token in the //stored in the cookie if (response.config.url === 'api/token' && response.config.data.tokenData) { //fetch token var token=response.config.data.tokenData; //set token $window.sessionStorage.setItem('userInfo-token', token); } return response; } }; } accessTokenHttpInterceptor.$inject=['$window']; ```
34,383,162
My table has these columns ``` [ID] [bigint] IDENTITY(1,1) NOT NULL, [PersonID] [bigint] NOT NULL, [B] [bit] NULL ``` Given a list of `PersonID` values, I would like to update the table, setting the value of `B` for the most recent entry for each `PersonID` to 1. The below script only updates a single record, but it seems something resembling it may work? ``` UPDATE table SET B = 1 WHERE PersonID in (<idlist>) AND ID IN (Select MAX(ID) FROM table WHERE PersonID in <idlist>) ```
2015/12/20
[ "https://Stackoverflow.com/questions/34383162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/426493/" ]
If am not wrong this is what you are trying to achieve ``` ;with cte as ( select row_number()over(partition by PersonID order by ID desc) as rn,* from yourtable Where PersonID in (<idlist>) ) update cte set B=1 where Rn=1 ``` Or use correlated sub-query ``` UPDATE A SET A.B = 1 from table A WHERE PersonID in (<idlist>) AND ID = (Select Top 1 ID FROM table B WHERE A.PersonID = B.PersonID order by id desc) ```
`IN (Select MAX(ID) FROM ...)` limits to a unique MAX(ID). Group by PersonID in order to get the MAX(ID) for each Person. ``` UPDATE table SET B = 1 WHERE ID IN (SELECT MAX(ID) FROM table WHERE PersonID in (<idlist>) GROUP BY PersonID) ```
3,723,044
If I input `5 5` at the terminal, press enter, and press enter again, I want to exit out of the loop. ``` int readCoefficents(double complex *c){ int i = 0; double real; double img; while(scanf("%f %f", &real, &img) == 2) c[i++] = real + img * I; c[i++] = 1 + 0*I; // most significant coefficient is assumed to be 1 return i; } ``` Obviously, that code isn't doing the job for me (and yes, I know there is a buffer overflow waiting to happen). `scanf` won't quit unless I type in a letter (or some non-numeric, not whitespace string). How do I get scanf to quit after reading an empty line?
2010/09/16
[ "https://Stackoverflow.com/questions/3723044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449021/" ]
The specific problem you're having is that a `scanf` format string of `%f` will skip white space (*including* newlines) until it finds an actual character to scan. From the c99 standard: > > A conversion specification is executed in the following steps: > >    -   Input white-space characters (as specified by the `isspace` function) are skipped, unless the specification includes a `'['`, `'c'`, or `'n'` specifier. > > > > and, elsewhere, describing `isspace()`: > > The standard white-space characters are the following: space `' '`, form feed `'\f'`, new-line `'\n'`, carriage return `'\r'`, horizontal tab `'\t'`, and vertical tab `'\v'`. > > > Your best bet is to use `fgets` to get the line (and this can be protected from buffer overflow very easily), then use `sscanf` on the resultant line. The `scanf` function is one of those ones you should look at very warily. The following piece of code is one I often use to handle line input: ``` #include <stdio.h> #include <string.h> #define OK 0 #define NO_INPUT 1 #define TOO_LONG 2 static int getLine (char *prmpt, char *buff, size_t sz) { int ch, extra; // Get line with buffer overrun protection. if (prmpt != NULL) { printf ("%s", prmpt); fflush (stdout); } if (fgets (buff, sz, stdin) == NULL) return NO_INPUT; // If it was too long, there'll be no newline. In that case, we flush // to end of line so that excess doesn't affect the next call. if (buff[strlen(buff)-1] != '\n') { extra = 0; while (((ch = getchar()) != '\n') && (ch != EOF)) extra = 1; return (extra == 1) ? TOO_LONG : OK; } // Otherwise remove newline and give string back to caller. buff[strlen(buff)-1] = '\0'; return OK; } ``` ``` // Test program for getLine(). int main (void) { int rc; char buff[10]; rc = getLine ("Enter string> ", buff, sizeof(buff)); if (rc == NO_INPUT) { // Extra NL since my system doesn't output that on EOF. printf ("\nNo input\n"); return 1; } if (rc == TOO_LONG) { printf ("Input too long [%s]\n", buff); return 1; } printf ("OK [%s]\n", buff); return 0; } ``` Testing it with various combinations: ``` pax> ./prog Enter string>[CTRL-D] No input pax> ./prog Enter string> a OK [a] pax> ./prog Enter string> hello OK [hello] pax> ./prog Enter string> hello there Input too long [hello the] pax> ./prog Enter string> i am pax OK [i am pax] ``` What I would do is to use this function to get a line safely, then simply use: ``` sscanf (buffer, "%f %f", &real, &img) ``` to get the actual values (and check the count). --- In fact, here's a complete program which is closer to what you want: ``` #include <stdio.h> #include <string.h> #define OK 0 #define NO_INPUT 1 #define TOO_LONG 2 static int getLine (char *prmpt, char *buff, size_t sz) { int ch, extra; // Get line with buffer overrun protection. if (prmpt != NULL) { printf ("%s", prmpt); fflush (stdout); } if (fgets (buff, sz, stdin) == NULL) return NO_INPUT; // If it was too long, there'll be no newline. In that case, we flush // to end of line so that excess doesn't affect the next call. if (buff[strlen(buff)-1] != '\n') { extra = 0; while (((ch = getchar()) != '\n') && (ch != EOF)) extra = 1; return (extra == 1) ? TOO_LONG : OK; } // Otherwise remove newline and give string back to caller. buff[strlen(buff)-1] = '\0'; return OK; } ``` ``` int main (void) { int i = 1, rc; char prompt[50], buff[50]; float real, imag; while (1) { sprintf (prompt, "\nEnter real and imaginary for #%3d: ", i); rc = getLine (prompt, buff, sizeof(buff)); if (rc == NO_INPUT) break; if (*buff == '\0') break; if (rc == TOO_LONG) { printf ("** Input too long [%s]...\n", buff); } if (sscanf (buff, "%f %f", &real, &imag) == 2) { printf ("Values were %f and %f\n", real, imag); i++; } else { printf ("** Invalid input [%s]\n", buff); } } return 0; } ``` along with a test run: ``` pax> ./testprog Enter real and imaginary for # 1: hello ** Invalid input [hello] Enter real and imaginary for # 1: hello there ** Invalid input [hello there] Enter real and imaginary for # 1: 1 ** Invalid input [1] Enter real and imaginary for # 1: 1.23 4.56 Values were 1.230000 and 4.560000 Enter real and imaginary for # 2: pax> _ ```
There's a way to do what you want using just scanf: ``` int readCoefficents(double complex *c) { int i = 0; double real; double img; char buf[2]; while (scanf("%1[\n]", buf) == 0) { // loop until a blank line or EOF if (scanf("%lf %lf", &real, &img) == 2) // read two floats c[i++] = real + img * I; scanf("%*[^\n]"); // skip the rest of the line scanf("%*1[\n]"); // and the newline } c[i++] = 1 + 0*I; // most significant coefficient is assumed to be 1 return i; } ``` If the user only enters 1 float on a line, it will read the next line for the second value. If any random garbage is entered, it will skip up to a newline and try again with the next line. Otherwise, it will just go on reading pairs of float values until the user enters a blank line or an EOF is reached.
2,354
So I was going to get a new acoustic. I really want to start getting into acoustics but I don't want to lose the ability to jam with friends who are on drums/bass, and have their own electrics plugged in. Does it make sense to get an acoustic/electric? I've never played one before plugged in. I know they sound okay unplugged but do they sound good plugged in as well? P.S. I was looking at this one: <http://guitars.musiciansfriend.com/product/Ibanez-Exotic-Wood-EW20QMEBBD-Cutaway-AcousticElectric-Guitar?sku=512210>
2011/02/07
[ "https://music.stackexchange.com/questions/2354", "https://music.stackexchange.com", "https://music.stackexchange.com/users/-1/" ]
IMHO, it's generally not a good idea to buy an acoustic/electric that lists for anything less than $1000. Why? Because no matter how much the guitar costs, some of what you're paying for in an acoustic/electric are the pickups and electronics. In other words, a $500 acoustic guitar is a $500 acoustic guitar, but a $500 acoustic/electric is really a $400 acoustic guitar with $100 or so worth of electronics. At that price point, there's a real difference in quality between a $500 acoustic and a $400 acoustic. At some price point, the guitars get good enough where the $100 or so dedicated to the electronics doesn't make a huge difference in the quality of the instrument. In other words, a $1000 acoustic guitar is still a $1000 acoustic guitar while a $1000 acoustic/electric might be a $900 acoustic + $100 of electronics. At that price point, though, the difference between a $1000 and a $900 guitar isn't too much---it's not as big a difference as between the $500 and the $400 guitars. Both the $1000 and the $900 guitars are decent quality, and so a $1000 acoustic/electric is probably a pretty good guitar. So my advice? **Buy the best-quality purely acoustic guitar you can afford.** If that's around $500, great---there are plenty of decent-quality acoustic guitars at that price. If later you decide that you want to plug it in, that's the time to buy a good acoustic pickup system. That way, you spread out the cost over a longer period of time, and you can always upgrade the pickup later without throwing away the guitar, and vice-versa. p.s. That Ibanez is pretty, but at $450 including the electronics, there's absolutely no way it's made of solid wood. That's a plywood instrument with quilted maple veneer. Don't get sucked in by its looks. For ~$500, you can get a well-made acoustic guitar with a solid-wood top from your choice of a variety of different builders. Update ------ It seems the argument I made above is more controversial than I had expected. Let me try to clarify it a bit. Suppose you're a guitar maker looking to introduce a new acoustic/electric model to your line. You pick one of your existing acoustic models and decide to add a pickup and electronics to it. The Stew Mac catalog [offers a variety](http://www.stewmac.com/shop/Electronics,_pickups/Pickups%3a_Guitar,_acoustic.html) of acoustic guitar pickups and electronics systems. The cheapest complete package (acoustic pickup, preamp, endpin jack, wiring) they offer is the [L.R. Baggs iBeam Active Pickup System](http://www.stewmac.com/shop/Electronics,_pickups/Pickups%3a_Guitar,_acoustic/L.R._Baggs_pickups/L_R_Baggs_iBeam_Active_Pickup_System.html), at $139. Add in the additional labor to install this system in your guitars, plus the markup, and it'll come to a $200 premium. Maybe $150 if you're a huge company and can buy enormous volumes. So now you have a choice: you can either add $150 to the cost of your guitar, or you can try to find $150 worth of corners to cut from your existing model. Well, if your existing model is around $1000, it's a lot easier to cut $150 worth of corners and still have a great instrument than it is if your existing model is $450. If you're looking to cut $150 off of a $1000 model, maybe you use A-grade solid wood instead of (prettier but sonically irrelevant) AA-grade. Maybe you stick with a AA-grade solid top, but go with plywood back and sides. Maybe you use cheaper tuners and abandon fancy binding. Either way, you'll cut some corners and still end up with a pretty good guitar. But if you're cutting $150 off of a $450 model, you were already using pretty cheap tuners, and now you're abandoning solid wood entirely and going with plywood throughout. So now imagine you're the customer, and you're looking at a $450 acoustic/electric. Of that $450, you know that $150 is electronics, so you're really looking at a $300 guitar with a pickup tacked on. The difference in quality between a $300 instrument and a $450 is way way bigger than the difference between a $900 instrument and a $1050 instrument. It's a 50% difference vs. a 15% difference. I'm emphatically *not* saying you've got to buy a $1000 guitar to be happy. I'm saying, if you've got $450 to spend on a guitar, buy a purely acoustic one with no electronics at all. Then you know all the money you'll spend has gone into making the best guitar $450 can make. Later, if you decide you simply need to plug it in, you can save up for a great acoustic pickup that you can use to amplify your $450 guitar.
Some of the low-end guitars can be surprising... Depends what you're looking for. I bought a decidedly-low-end Yamaha (APX500) for 300 bucks a couple of years ago. An inexpensive guitar to be sure, I bought it mostly because that's what I could afford and it had a small body so it didn't hurt my aging shoulders. Sound was surprisingly good. The Yamaha electrics in this APX line are pretty decent, more advanced than many you see in this price range. As for the guitar's acoustic sound... Not stellar but credible. I jam with a Folk-school sort of weekend jam group and this little instrument held up well both in terms of volume and tone. So don't be entirely dismissive of the under-a-grand models... Just have realistic expectations and make sure you play 'em first! Plugging in and modeling your volume and tone from the guitar is definitely handy. Of course, you can always buy a non-electrified acoustic and just add an after-market pickup....
1,250,892
I'm reading an algorithms book and I came across a code example for a primality test. The problem is that I couldn't understand the condition for the [for-loop](http://www.tutorialspoint.com/cprogramming/c_for_loop.htm): ``` public static boolean isPrime( int N ) { if (N < 2) return false; for ( int i = 2; i * i < N; i++ ) { if ( N % i == 0 ) return false; } return true; } ``` If we multiply `i` by itself we would miss a lot of numbers to check. So if we want to check if `n=10` is prime or not, then we would quickly end the loop by `i=3`. I know that the idea is finish the loop as early as possible, but how do we guarantee that by using that condition we are actually checking all possible divisors and the rest that we omitted are never going to be divisors? This condition seems quite common and popular but I really wasn't able to understand it or find an interpretation. I understood the condition `i < n/2` but not that one. I hope I'm not stupid!
2015/04/25
[ "https://math.stackexchange.com/questions/1250892", "https://math.stackexchange.com", "https://math.stackexchange.com/users/119055/" ]
If $n$ is not prime, then at least one of the factors of $n$ is at most as large as $\sqrt n$. To see why, let's suppose not. Since $n$ is not prime, $n = ab$ for some $a,b \neq 1$. If both $a$ and $b$ are larger than $\sqrt n$, then $a\cdot b > \sqrt n \cdot \sqrt n = n$. This clearly cannot be! So you only need to check for factors up to $\sqrt n$.
The trial division test, abstractly formulated, is this: for each number $i$ in some suitable set, check whether $i$ divides $n$. If one such number is found, output "$n$ is composite", else output "$n$ is prime". (Perhaps you need to special-case $n=1$; I'll leave that to the reader). Clearly no suitable set can contain $1$ or $n$, or we would report all numbers to be composite. No number is divisible by zero, and a number is divisible by $-x$ iff it is divisible by $x$, so we don't need to check numbers less than $1$. Also, if $m > n$ then $m$ does not divide $n$, so the set $\{2..n-1\}$ is definitely good enough: if we check all those numbers (and only those), then we are guaranteed to output the correct answer. It can be large, though, so we would like to thin it out if we can. > > How do we guarantee that by using that condition we are actually > checking all possible divisors and the rest that we omitted are never > going to be divisors? > > > If $n / i$ is an integer, let's call it $k$, then definitely $n / k = n / (n/i) = i$ is also an integer. In other words, if $n = ik$ with $i < k$, then when you check for $i$ you indirectly also check for $k$: if $n$ can be factored into two non-trivial factors, finding the smaller of the two is finding at least one such factor (from which you can conclude that it's composite), and if $n$ can't be factored so, no such smaller-of-the-two factor will exist. So, if instead of $\{2..n-1\}$ you only look at from 2 up to the largest of any possible smallest-factor-in-a-pair, you have still looked at enough possible candidates to be certain in your conclusion. Other people have already explained why $\sqrt{n}$ is the limit. There is some subtlety in why $\lfloor\sqrt{n}\rfloor$, which is really what is being checked, is also good enough: either $\lfloor\sqrt{n}\rfloor = \lceil(\sqrt{n})\rceil = \sqrt{n}$ or $\lceil(\sqrt{n})\rceil^2 > n$, so either you *have* checked $\lceil(\sqrt{n})\rceil$ also, *or* you don't need to.
220,520
[Related](https://codegolf.stackexchange.com/questions/126172/create-a-binary-ruler), [related](https://codegolf.stackexchange.com/questions/71833/how-even-is-a-number) Introduction ============ The [ruler sequence](https://oeis.org/A001511) is the sequence of the largest possible numbers \$a\_n\$ such that \$2^{a\_n}\mid n\$. It is so-called because its pin plot looks similar to a ruler's markings: ![Pin plot of ruler sequence](https://oeis.org/A001511/graph?png=1) However, with a slight modification, we can also get a similar sequence. This sequence is \$\{a\_1,a\_2,a\_3,…\}\$ where \$a\_n\$ is the largest **power of 2** such that \$a\_n\mid n\$ ([relevant OEIS](http://oeis.org/A006519)). The first 100 terms of this sequence are: ``` 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 32, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 64, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 32, 1, 2, 1, 4 ``` Challenge ========= Your challenge is to do one of these three things: * Take a positive integer \$n\$ as input and return the \$n\$th term of this sequence. * Take a positive integer \$n\$ as input and return the first \$n\$ terms of this sequence. * Output the sequence infinitely. Test Cases ========== ``` 12 -> 4 64 -> 64 93 -> 1 8 -> 8 0 -> (undefined behavior) ``` Rules ===== * You may output the sequence in any convenient format - e.g. as a list or some other iterable or separated by any non-digit separator, as long as it is constant between all terms. * You may output the term(s) in any convenient format - e.g. as an integer, as an integer string, as a float with the decimal part consisting of only zeros, ditto but as a string, or as a Boolean (`True`) if and only if the term is `1`. * You may choose to use either zero- or one-indexing. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Trailing whitespace is allowed. * If possible, please link to an online interpreter (e.g. [TIO](https://tio.run)) to run your program on. * Please explain your answer. This is not necessary, but it makes it easier for others to understand. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
2021/03/11
[ "https://codegolf.stackexchange.com/questions/220520", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/94066/" ]
[05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 6 bytes ============================================================= ``` ÝoʒÖ}θ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8Nz8U5MOT6s9t@P/fzMA "05AB1E – Try It Online") Turns out I'm way too used to Vyxal. -2 thanks to Makonede Explained --------- ```py ÝoʒÖ}θ Ýo # 2 ** range(0, input) // vectorised ʒÖ} # filter(lambda x: x % input == 0, ^) θ # ^[-1] ```
[APL (Dyalog Unicode)](https://www.dyalog.com/), 16 bytes ========================================================= Nth Term ```apl {2*(⊥⍨~)2⊥⍣¯1⊢⍵} 2* ⍝ exponentiation ⊥⍨~ ⍝ number of trailing zeros 2⊥⍣¯1⊢ ⍝ bit vector conversion ⍵ ⍝ argument ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqIy2NR11LH/WuqNM0AjMWH1pv@Khr0aPerbVAJQqGRlxpCmYmQMLSGEhYALEBAA "APL (Dyalog Unicode) – Try It Online") --- [APL (Dyalog Unicode)](https://www.dyalog.com/), 21 bytes ========================================================= First N Terms ```apl {2*(⊥⍨~)∘(2⊥⍣¯1⊢)¨⍳⍵} 2* ⍝ exponentiation ⊥⍨~ ⍝ number of trailing zeros ∘ ⍝ curry 2⊥⍣¯1⊢ ⍝ bit vector conversion ¨ ⍝ each ⍳⍵ ⍝ range of 1–n ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqIy2NR11LH/WuqNN81DFDwwjMWXxoveGjrkWah1Y86t38qHdrLVCxgqERV5qCmQmQsDQGEhZAbAAA "APL (Dyalog Unicode) – Try It Online")
21,780,252
I am creating an app where i need to find current location of user . So here I would like to do a task like when user returns from that System intent, my task should be done after that.(Displaying users current location) So i am planning to use `OnActivityResult()`. ``` protected void onActivityResult(int requestCode, int resultCode, Intent data) { } ``` But the problem is that I don't know how can I use that method in a class which is not extending Activity. Please some one give me idea how can i achieve this?
2014/02/14
[ "https://Stackoverflow.com/questions/21780252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3247551/" ]
You need an Activity on order to receive the result. If its just for organisation of code then call other class from Activty class. ``` public class Result { public static void activityResult(int requestCode, int resultCode, Intent data){ ... } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Result.activityResult(requestCode,resultCode,data); ... } ```
**You can't call this method out of his scope.** ``` protected void onActivityResult (int requestCode, int resultCode, Intent data) ``` If the method is **protected** like this case, you can see the table of **Access Levels** to know how to proceed. ``` |-----------------------------------------------------------| | ACCESS LEVELS | |------------------|---------|---------|----------|---------| | Modifier | Class | Package | Subclass | World | |------------------|---------|---------|----------|---------| | public | Y | Y | Y | Y | |------------------|---------|---------|----------|---------| | protected | Y | Y | Y | N | |------------------|---------|---------|----------|---------| | no modifier | Y | Y | N | N | |------------------|---------|---------|----------|---------| | private | Y | N | N | N | |------------------|---------|---------|----------|---------| ``` As you can see, this method only can be called from `android.app.*` package, `Activity` and their subclasses. --- **SOLUTION:** You need to do something like this: We have a class `ImagePicker` for selecting a image from **Gallery** or **Camera** or **Delete** it. This class need to call `onActivityResult` if user wants to delete image (We don't need to start an `Activity` for a result that we already know). ``` public class ImagePicker { private ImagePickerDelegate delegate; public ImagePicker (ImagePickerDelegate delegate) { this.delegate = delegate; } //Will explain this two methods later public void show() { //Some code to show AlertDialog } public void handleResponse(Intent data) { //Some code to handle onActivityResult } //Our interface to delegate some behavior public interface ImagePickerDelegate { void onImageHandled(Bitmap image); void onImageError(); void onImageDeleted(); } } ``` For using this class in our `Activity`, we need to implement the delegate methods and pass our activity as the delegate of `ImagePicker`: ``` public class MyActivity extends Activity implements ImagePicker.ImagePickerDelegate { ImagePicker imagePicker; @OnClick(R.id.image_edit) public void selectImage () { imagePicker = new ImagePicker(this); imagePicker.show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ImagePicker.REQUEST_IMAGE_PICKER && resultCode == RESULT_OK) { imagePicker.handleResponse(data); } super.onActivityResult(requestCode, resultCode, data); } @Override public void onImageHandled(Bitmap image) { //handle image resized imageView.setImageBitmap(image); } @Override public void onImageError() { //handle image error Toast.makeText(this, "Whoops - unexpected error!", Toast.LENGTH_SHORT).show(); } @Override public void onImageDeleted() { //handle image deleted groupImageView.setImageBitmap(null); groupImageView.setImageResource(R.drawable.ic_pick_picture); } } ``` Finally, we need to make thous delegate methods to be called, and that happen in `show()` and `handleResponse(Intent data)`: ``` //The show method create and dialog with 3 options, //the important thing here, is when an option is selected public void show() { //Inflating some views and creating dialog... NavigationView navView = (NavigationView)viewInflated.findViewById(R.id.navigation_menu); navView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.action_select_image: Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); activity.startActivityForResult(pickPhoto , REQUEST_IMAGE_PICKER); break; case R.id.action_take_picture: Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); activity.startActivityForResult(takePicture, REQUEST_IMAGE_PICKER); break; case R.id.action_delete_image: delegate.onImageDeleted(); //send response to activity break; } alertDialog.dismiss(); return true; } }); //Show dialog... } //this method is called from onActivityResult public void handleResponse(Intent data) { try { //Retrieve and resize image... delegate.onImageHandled(image); //send the image to activity } catch (Exception e) { e.printStackTrace(); delegate.onImageError(); //send error to activity } } ``` At the end, what we have, is a `class` that can call a method in your `Activity` instead of `onActivityResult`, but when you get a result in `onActivityResult`, you need to handle it in that `class`
37,422,781
I have been stuck with this exercise for way too long. I've been given some part of the code and i had to write the rest of it. First of all, i got a VolleyManager class that helps with some Volley tools (like adding to request queue). Then another Gson class that helps parsing the requested Json. This is the code for the UserListFragment, where there are two buttons. One for populating the list, one for clearing it, and the list itself below those two buttons. ``` public class UserListFragment extends Fragment { private static final String USERS_URL = "https://raw.githubusercontent.com/bengui/volleytest/master/json/users.json"; private static final String TAG = UserListFragment.class.getSimpleName(); private View view; private ListAdapter listAdapter; private Button requestButton; private Button cleanButton; private ListView listView; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_user_list, null); // UI Elements requestButton = (Button) view.findViewById(R.id.request_btn); listView = (ListView) view.findViewById(R.id.listview_users); requestButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listAdapter = new ListAdapter(view.getContext()); listView.setAdapter(listAdapter); } }); cleanButton = (Button) view.findViewById(R.id.clean_btn); cleanButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listView.setAdapter(null); } }); return view; } ``` This is the personalized adapter i made to fill the elements on the list. ``` public class ListAdapter extends ArrayAdapter { VolleyManager volleyManager; List<User> list; public ListAdapter(Context context){ super(context,0); volleyManager = VolleyManager.getInstance(getActivity()); requestButton.setEnabled(false); JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( USERS_URL, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { list = parseUserList(response.toString()); requestButton.setEnabled(true); notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error){ Log.d(TAG, "JSON response error : " + error.getMessage()); requestButton.setEnabled(true); } } ); volleyManager.addToRequestQueue(jsonArrayRequest); } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View listItemView = convertView; if (null == convertView) { listItemView = layoutInflater.inflate( R.layout.fragment_list_item, parent, false); } // Pick an element of the list and fill the UI textViews. User user = list.get(position); TextView nombre = (TextView) listItemView.findViewById(R.id.user_name); TextView apellido = (TextView) listItemView.findViewById(R.id.user_last_name); TextView edad = (TextView) listItemView.findViewById(R.id.user_age); // Update views nombre.setText(user.getName()); apellido.setText(user.getLastName()); edad.setText(user.getAge()); return listItemView; } } /** * Parses a users json array into a users list. * * @param jsonArray * * @return Users list */ private List<User> parseUserList(String jsonArray) { Gson gson = new Gson(); // Declares the list type Type listType = new TypeToken<List<User>>() {}.getType(); List<User> userList = gson.fromJson(jsonArray, listType); return userList; } } ``` I am not sure why this isn't working. Maybe i don't completely understand how Adapters work and i'm making a wrong call on the button click listener? I have been trying to figure this out for over a week. **Made some progress!** but still can't make it work. Any input is welcome. edit: Forgot the .xmls This is the layout for the fragment. ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fragment_user_list" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/request_btn" android:text="@string/request_btn" android:layout_width="match_parent" android:layout_height="wrap_content"/> <Button android:id="@+id/clean_btn" android:text="@string/clean_btn" android:layout_width="match_parent" android:layout_height="wrap_content"/> <ListView android:id="@+id/listview_users" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> ``` This is the layout for the listview items. ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/user_name" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:id="@+id/user_last_name" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:id="@+id/user_age" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> ```
2016/05/24
[ "https://Stackoverflow.com/questions/37422781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4808318/" ]
You could use a normal for loop iterating over the array elements or follow a [functional](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map) [approach](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). ```js var data = [ {item1: 123, item2: "name", item3: "id"}, {item1: 234, item2: "other"}, {item1: 456, item2: "another"}, {item1: 789, item2: "again"} ]; // 1. Using Array.foreach: data.forEach(function(element) { if (!element.hasOwnProperty('item3')) element.item3 = "default"; }); // 2. Using Array.map: data = data.map(function(element) { if (!element.hasOwnProperty('item3')) element.item3 = "default"; return element; }); // 3. Using a for-loop: for (var i = 0, length = data.length; i < length; ++i) { if (!data[i].hasOwnProperty('item3')) data[i].item3 = "default"; } console.log(data); ``` I recommend 1 or 2 if you don't want to keep the original data array. **Performance on Chrome 48 (similar in Firefox 44, 100000 runs):** * Array.foreach() 520ms * Array.map() 790ms * for-loop 2700ms Possible explanation: Since the Array.foreach() and Array.map() callbacks do not reference anything outside the passed parameters, modern JITs can cache the passed inline function and outperform the traditional for-loop.
You can use a for loop to iterate over each item, in order, in the array. ``` for(var i = 0; i < data.length; i++) { //check to see if item3 is NOT there if(typeof data[i].item3 === 'undefined') { data[i].item3 = 'default value'; } } ```
42,304,745
I have a JSONB column with JSON that looks like this: > > {"id" : "3", "username" : "abcdef"} > > > Is there way to update the JSON to : > > {"id" : 3, "username" : "abcdef"} > > >
2017/02/17
[ "https://Stackoverflow.com/questions/42304745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2069092/" ]
OK, that was my misunderstanding. <https://github.com/streamproc/MediaStreamRecorder> > > MediaStreamRecorder can record audio as WAV and video as either WebM or animated gif on Chrome > > > no mp4 possible.
Checkout [ffmpeg.wasm](https://ffmpegwasm.netlify.app/) You can install it via: ```sh # Use npm $ npm install @ffmpeg/ffmpeg @ffmpeg/core # Use yarn $ yarn add @ffmpeg/ffmpeg @ffmpeg/core ``` And then, you can convert your blobs into an mp4 file. Checkout the example that they provided in the link I shared.
39,093,941
What I want to do : ```css div#test { color: green;} div { color: blue; background-color:white;} ``` ```html <div id="test"> <span>Text</span> </div> <div> <span>Text2</span> </div> ``` I want to apply only `color:green`(not `background-color`) to `div` tag having `id="test"`. But as you can see here, `div` tag with `id="test"` also has `background-color`... How can I avoid this?
2016/08/23
[ "https://Stackoverflow.com/questions/39093941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3595632/" ]
You need to add background none property to id ```css div#test { color: green; background-color:none;} div { color: blue; background-color:white;} ``` ```html <div id="test"> <span>Text</span> </div> <div> <span>Text2</span> </div> ```
You should separate the style you want to apply into a class. Then add that class to an element you want apply the background style to, like so: ```css div#test { color: green;} div { color: blue;} .bg-white { background-color: white;} ``` ```html <div id="test"> <span>Text</span> </div> <div class="bg-white"> <span>Text2</span> </div> ```
1,311,713
Basically, I do not totally understand how GNOME the whole stuff works. As the title shows, I am currently working on using [TigerVNC](https://tigervnc.org/) to start a GNOME desktop, which is separate from the original GNOME when I use a physical screen to log in. [Here is my physical desktop appearance.](https://i.stack.imgur.com/LXFdv.png) Here is my `~/.vnc/xstartup` script (`xstartup`): And I ran it by `vncserver -verbose -localhost yes :2` ```sh #!/bin/sh # Change "GNOME" to "KDE" for a KDE desktop, or "" for a generic desktop MODE="GNOME" #Uncommment this line if using Gnome and your keyboard mappings are incorrect. # export XKL_XMODMAP_DISABLE=1 # Load X resources (if any) if [ -e "$HOME/.Xresources" ] then xrdb "$HOME/.Xresources" fi export GNOME_SHELL_SESSION_MODE=ubuntu # Try a GNOME session, or fall back to KDE if [ "GNOME" = "$MODE" ] then if which gnome-session >/dev/null then # see /usr/share/gnome-session/sessions/ubuntu.session for more info dbus-launch --exit-with-session gnome-session --session=ubuntu --debug & else MODE="KDE" fi fi # Try a KDE session, or fall back to generic if [ "KDE" = "$MODE" ] then if which startkde >/dev/null then startkde & else MODE="" fi fi # Run a generic session if [ -z "$MODE" ] then xsetroot -solid "#DAB082" x-terminal-emulator -geometry "80x24+10+10" -ls -title "$VNCDESKTOP Desktop" & x-window-manager & fi ``` [Notice there are two icons missing on the left (one is Terminal app)](https://i.stack.imgur.com/v4ChP.jpg) I am a newbie to the whole GNOME stuff. Hope someone can give me some suggestions! --- I have also tried replace `dbus-launch --exit-with-session gnome-session --session=ubuntu --debug &` with `dbus-launch --exit-with-session gnome-shell &`. It turned out the icons were back, but my `Settings` window was blank. [The left side icons were back but Settings' windows was blank](https://i.stack.imgur.com/lJudY.jpg) The error message from `tigervnc`: ``` Thu Jan 28 22:13:02 2021 vncext: VNC extension running! vncext: Listening for VNC connections on local interface(s), port 5902 vncext: created VNC server for screen 0 GNOME Shell-Message: 22:13:02.986: Telepathy is not available, chat integration will be disabled. Gjs-Message: 22:13:03.130: JS WARNING: [/usr/share/gnome-shell/extensions/ubuntu-dock@ubuntu.com/appIcons.js 1028]: unreachable code after return statement Gjs-Message: 22:13:03.159: JS WARNING: [resource:///org/gnome/shell/ui/workspaceThumbnail.js 891]: reference to undefined property "_switchWorkspaceNotifyId" (gnome-shell:15336): Bluetooth-WARNING **: 22:13:03.209: Could not create bluez object manager: GDBus.Error:org.freedesktop.DBus.Error.AccessDenied: Rejected send message, 2 matched rules; type="method_call", sender=":1.6794" (uid=1001 pid=15336 comm="gnome-shell " label="unconfined") interface="org.freedesktop.DBus.ObjectManager" member="GetManagedObjects" error name="(unset)" requested_reply="0" destination=":1.2" (uid=0 pid=1025 comm="/usr/lib/bluetooth/bluetoothd " label="unconfined") GNOME Shell-Message: 22:13:03.384: Error looking up permission: GDBus.Error:org.freedesktop.portal.Error.NotFound: No entry for geolocation (gnome-shell:15336): AccountsService-WARNING **: 22:13:03.577: Could not get current seat: No data available ``` --- I have also followed the instructions in [Arch Linux-TigerVNC](https://wiki.archlinux.org/index.php/TigerVNC) Namely, adding this file into `~/.vnc/config` and removing `xstartup` script. ``` session=ubuntu geometry=1920x1080 localhost alwaysshared ``` Unfortunately, my icons were still different from my original GNOME desktop :( --- Here is my current theme: ``` $ gsettings get org.gnome.desktop.interface icon-theme 'Adwaita' ``` I don't know if this was caused by `Adwaita` icons. For example, here is my `/usr/share/applications/org.gnome.Terminal.desktop` ``` [Desktop Entry] Name=Terminal Comment=Use the command line Keywords=shell;prompt;command;commandline;cmd; TryExec=gnome-terminal Exec=gnome-terminal Icon=utilities-terminal Type=Application X-GNOME-DocPath=gnome-terminal/index.html X-GNOME-Bugzilla-Bugzilla=GNOME X-GNOME-Bugzilla-Product=gnome-terminal X-GNOME-Bugzilla-Component=BugBuddyBugs X-GNOME-Bugzilla-Version=3.28.2 Categories=GNOME;GTK;System;TerminalEmulator; StartupNotify=true X-GNOME-SingleWindow=false OnlyShowIn=GNOME;Unity; Actions=new-window X-Ubuntu-Gettext-Domain=gnome-terminal NoDisplay=true [Desktop Action new-window] Name=New Terminal Exec=gnome-terminal ``` I found that `./Adwaita/scalable/apps/utilities-terminal-symbolic.svg` whose basename is not `utilities-terminal`
2021/01/28
[ "https://askubuntu.com/questions/1311713", "https://askubuntu.com", "https://askubuntu.com/users/1167241/" ]
AppImages have limited integration with your desktop environment. You can manually add a launcher to your menu, but there is also a tool in development that can integrate appimages **Manual approach** You can [manually add a launcher](https://askubuntu.com/a/95278/558158) for your AppImage in the dash. Once it is there, you optionally will be able to pin it to the Dash/Dock. Commonly, the AppImage provides an icon and a `.desktop` launcher file that you can use for a start. Retrieve it from within the AppImage file as follows: 1. Make sure the AppImage is running. 2. Using the command `mount` in a terminal, find out where the AppImage is mounted in your file system. For example, in my little test, I see an entry for an AppImage appearing as ``` LibreSprite-8ac9ab1-x86_64.AppImage on /tmp/.mount_LibreSyxGgsk type fuse.LibreSprite-8ac9ab1-x86_64.AppImage (ro,nosuid,nodev,relatime,user_id=1000,group_id=1000) ``` in the terminal output of `mount`. It reveals that the AppImage is mounted under `/tmp/.mount_LibreSyxGgs`. 3. Navigate to the folder where the AppImage is mounted using your file manager. In most cases, you will find icons there and a `.desktop` launcher, in the main folder or in a subfolder. 4. Copy the icon file to the folder `~/.local/share/icons` 5. Copy the `.desktop` file to `~/.local/share/applications` 6. Open the copy of the `.desktop` file you created, and edit the `Exec=` line (and also the `TryExec=`line if present) to include the full pathname of your AppImage. Check on the `Icon=` line if it corresponds with the basename of the icon file you copied (just the basename, no need for the extension). If needed, update. You can also provide a full path to the specific icon file. This will cause the `.desktop` file to be picked up in your application menu, i.e., the Application Overview in standard Ubuntu with Gnome Shell. **Automating using the tool AppImageLauncher** If you work frequently with AppImages, then you could explore the tool ["AppImageLauncher"](https://github.com/TheAssassin/AppImageLauncher). That tool is a regular application, designed to associate with .AppImage files. When you click an AppImage file, the tool will automatically copy it to a standard folder (by default `~/Applications`) and create a desktop launcher for it.
Use AppImageLauncher * <https://github.com/TheAssassin/AppImageLauncher> * <https://github.com/TheAssassin/AppImageLauncher/wiki/Install-on-Ubuntu-or-Debian> ``` sudo apt install software-properties-common sudo add-apt-repository ppa:appimagelauncher-team/stable sudo apt update sudo apt install appimagelauncher ```
44,007,693
this is what I need: from the saledate column I need to extract just the month and date and combine with the 2017 year in NewDate column, but I couldn't update. Any suggestions? [![enter image description here](https://i.stack.imgur.com/eLRQh.png)](https://i.stack.imgur.com/eLRQh.png) This is the Select statment, I'm trying to update with the alias NewDate and getting an error: The conversion of a varchar data type to a datetime data type resulted in an out of range value. This is the data in the saledate column: 1983-09-01 00:00:00.000, I'm trying to make to be the same, just the year to be 2017. SELECT saledate, renewaldate,CONVERT(date,saledate), ('2017'+ '-' + LTRIM(REVERSE(SUBSTRING(REVERSE(CONVERT(date,saledate)), 1, 5)))) AS NewDate FROM tprogram UPDATE tprogram SET renewaldate = ('2017'+ '-' + LTRIM(REVERSE(SUBSTRING(REVERSE(CONVERT(date,saledate)), 1, 5)))) FROM tprogram
2017/05/16
[ "https://Stackoverflow.com/questions/44007693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8021081/" ]
You could use `dateadd()` with the `day()` and `month()` functions like so: ``` select dateadd(day,day(saledate)-1,dateadd(month,month(saledate)-1,'20180101')) as NewDate ``` --- For example: ``` select dateadd(day,day(getdate())-1,dateadd(month,month(getdate())-1,'20180101')) ``` returns: `2018-05-16`
You say you need it with the 2017 year, but you're using a 2018 value. Here's something to get started. ``` SELECT CONVERT(DATE,'2017-'+CONVERT(VARCHAR(2),MONTH(SaleDate))+'-'+CONVERT(VARCHAR(2),DAY(SaleDate))) AS NewDate ```
39,695,542
I have three tables, `tbl_doctors_details`, `tbl_time` and `tbl_token`. I have to select the details from `tbl_time` or `tbl_token`. That is if for particular doctor in hospital have `t_type` is `time` then select from `tbl_time` else select from `tbl_token`. For example, for `doctor_id` is 100 and `hospital_id` 1, the `t_type` is `time`. So for this user, details should select from `tbl_time` table. Below is the sample structure and data of three tables: [![enter image description here](https://i.stack.imgur.com/xB2dd.png)](https://i.stack.imgur.com/xB2dd.png) [![enter image description here](https://i.stack.imgur.com/p5k5R.png)](https://i.stack.imgur.com/p5k5R.png) How can I use **CASE** condition in query here? I tried: ``` SELECT * FROM ( SELECT * CASE WHEN t_type= 'time' FROM dbname.tbl_doctors_details t1 THEN dbname.tbl_time t2 ELSE dbname.tbl_token t2 WHERE t1.hospital_id=t2.hospital_id AND t1.doctor_id=t2.doctor_id); ``` I know the query is not working, but how can I make the query working?
2016/09/26
[ "https://Stackoverflow.com/questions/39695542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3115085/" ]
Second function will be called in both the cases, as the your redefining the function definition. Also there is no function overloading in javascript, in the second case change function signature( i.e arguments it takes) will redefine the same A function (defined 1st).
In both cases the second function will be called because it overwrites the global variable `A` when declared. It's similar to writing: ``` var a = 1; var a = 2; a === 2; // true ```
16,703,886
Where are static local variables stored in memory? Local variables can be accessed only inside the function in which they are declared. Global static variables go into the .data segment. If both the name of the static global and static local variable are same, how does the compiler distinguish them?
2013/05/23
[ "https://Stackoverflow.com/questions/16703886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/713179/" ]
Static variables go into the same segment as global variables. The only thing that's different between the two is that the compiler "hides" all static variables from the linker: only the names of extern (global) variables get exposed. That is how compilers allow static variables with the same name to exist in different translation units. Names of static variables remain known during the compilation phase, but then their data is placed into the `.data` segment anonymously.
As mentioned by dasblinken, GCC 4.8 puts local statics on the same place as globals. More precisely: * `static int i = 0` goes on `.bss` * `static int i = 1` goes on `.data` Let's analyze one Linux x86-64 ELF example to see it ourselves: ``` #include <stdio.h> int f() { static int i = 1; i++; return i; } int main() { printf("%d\n", f()); printf("%d\n", f()); return 0; } ``` To reach conclusions, we need to understand the relocation information. If you've never touched that, consider [reading this post first](https://stackoverflow.com/a/30507725/895245). Compile it: ``` gcc -ggdb -c main.c ``` Decompile the code with: ``` objdump -S main.o ``` `f` contains: ``` int f() { 0: 55 push %rbp 1: 48 89 e5 mov %rsp,%rbp static int i = 1; i++; 4: 8b 05 00 00 00 00 mov 0x0(%rip),%eax # a <f+0xa> a: 83 c0 01 add $0x1,%eax d: 89 05 00 00 00 00 mov %eax,0x0(%rip) # 13 <f+0x13> return i; 13: 8b 05 00 00 00 00 mov 0x0(%rip),%eax # 19 <f+0x19> } 19: 5d pop %rbp 1a: c3 retq ``` Which does 3 accesses to `i`: * `4` moves to the `eax` to prepare for the increment * `d` moves the incremented value back to memory * `13` moves `i` to the `eax` for the return value. It is obviously unnecessary since `eax` already contains it, and `-O3` is able to remove that. So let's focus just on `4`: ``` 4: 8b 05 00 00 00 00 mov 0x0(%rip),%eax # a <f+0xa> ``` Let's look at the relocation data: ``` readelf -r main.o ``` which says how the text section addresses will be modified by the linker when it is making the executable. It contains: ``` Relocation section '.rela.text' at offset 0x660 contains 9 entries: Offset Info Type Sym. Value Sym. Name + Addend 000000000006 000300000002 R_X86_64_PC32 0000000000000000 .data - 4 ``` We look at `.rela.text` and not the others because we are interested in relocations of `.text`. `Offset 6` falls right into the instruction that starts at byte 4: ``` 4: 8b 05 00 00 00 00 mov 0x0(%rip),%eax # a <f+0xa> ^^ This is offset 6 ``` From our knowledge of x86-64 instruction encoding: * `8b 05` is the `mov` part * `00 00 00 00` is the address part, which starts at byte `6` [AMD64 System V ABI Update](http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-AMD64/LSB-Core-AMD64/elf-amd64.html) tells us that `R_X86_64_PC32` acts on 4 bytes (`00 00 00 00`) and calculates the address as: ``` S + A - P ``` which means: * `S`: the segment pointed to: `.data` * `A`: the `Added`: `-4` * `P`: the address of byte 6 when loaded `-P` is needed because GCC used `RIP` relative addressing, so we must discount the position in `.text` `-4` is needed because `RIP` points to the following instruction at byte `0xA` but `P` is byte `0x6`, so we need to discount 4. Conclusion: after linking it will point to the first byte of the `.data` segment.