prompt
stringlengths
48
2.37k
chosen
stringlengths
7
4.28k
rejected
stringlengths
11
4.44k
Question: How does a Stack Overflow moderator know about sock puppet accounts? How do they trap the user? Answer:
I am not going to answer this directly, for reasons that should be obvious. However; this isn't a "trap" - it is our attempt at *enforcing reasonable behaviour*; using a sock-puppet for *any purpose* (most commonly, but not exclusively: upvoting yourself) is unacceptable. If you want the vote of the masses; write good questions and answers.
They have ways of finding pretty much any kind of sock puppets using their sites... ![sock puppet](https://i.stack.imgur.com/UISly.jpg)
Question: How does a Stack Overflow moderator know about sock puppet accounts? How do they trap the user? Answer:
I am not going to answer this directly, for reasons that should be obvious. However; this isn't a "trap" - it is our attempt at *enforcing reasonable behaviour*; using a sock-puppet for *any purpose* (most commonly, but not exclusively: upvoting yourself) is unacceptable. If you want the vote of the masses; write good questions and answers.
Actions speak louder than IP address… Possibly even a “view” of a question is an action.
Question: How does a Stack Overflow moderator know about sock puppet accounts? How do they trap the user? Answer:
I am not going to answer this directly, for reasons that should be obvious. However; this isn't a "trap" - it is our attempt at *enforcing reasonable behaviour*; using a sock-puppet for *any purpose* (most commonly, but not exclusively: upvoting yourself) is unacceptable. If you want the vote of the masses; write good questions and answers.
You know, throughout your posts here, you keep referring to this as a "bug" or a "trap". It's not a bug at all; it's a *feature* designed to prevent people from abusing the site. **Which is exactly what you were doing.** In your comments on Marc's answer, you complain that your friend "Nahid" got her account merged due to suspicious behavior. If that's true, and Nahid actually exists and was playing by the rules, then what happened to her was because *your behavior* made her look like another one of your sock puppets. Why did this happen? Not because of "bugs" in Stack Overflow, or the malice of the evil moderators. It happened because you abused this site *so badly* that everyone around you was thrown into suspicion. If you hadn't tried so hard to make your fake accounts look like real ones, your friend's real account wouldn't have looked like another of your fakes. If "Nahid" is upset that her account got merged, she should be blaming you for that. If you're upset that you lost reputation, you should blame yourself. **You cheated. You got caught cheating. That's your fault, not Stack Overflow's.** You've suggested that SO might lose users due to features like this, but I think it'll *gain* users when they see that their reputation means something. People don't like being taken advantage of by others who don't play by the rules, and they don't like cheaters filling up their community space with garbage. Even in your imaginary "99 lost professional users" scenario, I suspect the number we'll gain far outweighs the number we'll lose due to accidental merges. To sum up, the solution isn't to ask how to cheat more effectively, and it's also not to blame others for noticing. The solution is to improve your behavior, start playing by the rules, and try to be valuable to the rest of this community.
Question: How does a Stack Overflow moderator know about sock puppet accounts? How do they trap the user? Answer:
They have ways of finding pretty much any kind of sock puppets using their sites... ![sock puppet](https://i.stack.imgur.com/UISly.jpg)
Actions speak louder than IP address… Possibly even a “view” of a question is an action.
Question: How does a Stack Overflow moderator know about sock puppet accounts? How do they trap the user? Answer:
You know, throughout your posts here, you keep referring to this as a "bug" or a "trap". It's not a bug at all; it's a *feature* designed to prevent people from abusing the site. **Which is exactly what you were doing.** In your comments on Marc's answer, you complain that your friend "Nahid" got her account merged due to suspicious behavior. If that's true, and Nahid actually exists and was playing by the rules, then what happened to her was because *your behavior* made her look like another one of your sock puppets. Why did this happen? Not because of "bugs" in Stack Overflow, or the malice of the evil moderators. It happened because you abused this site *so badly* that everyone around you was thrown into suspicion. If you hadn't tried so hard to make your fake accounts look like real ones, your friend's real account wouldn't have looked like another of your fakes. If "Nahid" is upset that her account got merged, she should be blaming you for that. If you're upset that you lost reputation, you should blame yourself. **You cheated. You got caught cheating. That's your fault, not Stack Overflow's.** You've suggested that SO might lose users due to features like this, but I think it'll *gain* users when they see that their reputation means something. People don't like being taken advantage of by others who don't play by the rules, and they don't like cheaters filling up their community space with garbage. Even in your imaginary "99 lost professional users" scenario, I suspect the number we'll gain far outweighs the number we'll lose due to accidental merges. To sum up, the solution isn't to ask how to cheat more effectively, and it's also not to blame others for noticing. The solution is to improve your behavior, start playing by the rules, and try to be valuable to the rest of this community.
Actions speak louder than IP address… Possibly even a “view” of a question is an action.
Question: I've got my first RoR app deployed to Dreamhost and it's using Passenger. The one note on Dreamhost's wiki about slow response mentioned changing a RewriteRules line in the public/.htaccess file to use FastCGI. But I assume this will have no effect if I'm using Passenger, is that right? I've looked at the logs and compared them to my local logs, and it looks like there is a wider range on Dreamhost. Some responses are comparable to the quick local ones, others can take a few seconds. I'm using a Flex front end with HTTPServices to the rails backend, and I think I also need to add logging around my services to see what kind of network delay I'm getting and try to isolate where the delays are. I should also add that there is probably plenty of room for improvement in the area of eager loading associations. I think I did that a little early on, but haven't done it thoroughly through all the associations. I have the local logs set to the default where I can see all the queries, and there are a lot of them. Answer:
You must be running in Development mode. Try running in Production mode to see if it is still slow. Post below may help: [Ruby On Rails is slow...?](https://stackoverflow.com/questions/566401/ruby-on-rails-is-slow)
[New Relic](http://www.newrelic.com/) is a Rails performance monitoring app. I haven't personally used it, but I hear their name a lot and it looks like they have a free lite version that you could try. From my experience profiling other applications, a tool like this is worth using because the slow parts of your application are often in areas where you didn't expect.
Question: I can't find a way to toggle mc internal editor in hex mode. [Here](http://www.tldp.org/LDP/LG/issue23/wkndmech_dec97/mc_article.html) it says to use F4 however it suggest to replace. How to do it? Answer:
You can open file with `F3`. Hex view - `F4`. Start edit - `F2`.
`F4` toggles hex mode in the Midnight Commander **viewer** (accessed using `F3`), not in the editor. Once in hex mode in the viewer, `F2` allows you to make changes to the file being viewed. As you discovered, `F4` in the editor starts a search.
Question: I'm getting crazy, cause I cannot find what are the "default" keys you would have in a PDF Document. For example, if I want to retrieve an hyperlink from a CGPDFDocument, I do this: ``` CGPDFStringRef uriStringRef; if(!CGPDFDictionaryGetString(aDict, "URI", &uriStringRef)) { break; } ``` In this case, the key is "URI". Is there a document explaining what are the keys of a CGPDFDictionary? Answer:
The [Adobe PDF Reference](http://www.adobe.com/devnet/pdf/pdf_reference_archive.html) describes all of the keys.
The keys in a dictionary depend on the actual object the dictionary represents (a page dictionary has other keys than an annotation dictionary). The Adobe PDF reference describes all these objects and their keys.
Question: I'm getting crazy, cause I cannot find what are the "default" keys you would have in a PDF Document. For example, if I want to retrieve an hyperlink from a CGPDFDocument, I do this: ``` CGPDFStringRef uriStringRef; if(!CGPDFDictionaryGetString(aDict, "URI", &uriStringRef)) { break; } ``` In this case, the key is "URI". Is there a document explaining what are the keys of a CGPDFDictionary? Answer:
It's absurd that you would have to go read 1300 page long specs just to find what keys a dictionary contains, a dictionary that could contain anything depending on what kind of annotation it is. To get a list of keys in a `CGPDFDictionaryRef` you do: ``` // temporary C function to print out keys void printPDFKeys(const char *key, CGPDFObjectRef ob, void *info) { NSLog(@"key = %s", key); } ``` In the place where you're trying to see the contents: ``` CGPDFDictionaryRef mysteriousDictionary; // this is your dictionary with keys CGPDFDictionaryApplyFunction(mysteriousDictionary, printPDFKeys, NULL); // break on or right after above, and you will have the list of keys NSLogged ```
The [Adobe PDF Reference](http://www.adobe.com/devnet/pdf/pdf_reference_archive.html) describes all of the keys.
Question: I'm getting crazy, cause I cannot find what are the "default" keys you would have in a PDF Document. For example, if I want to retrieve an hyperlink from a CGPDFDocument, I do this: ``` CGPDFStringRef uriStringRef; if(!CGPDFDictionaryGetString(aDict, "URI", &uriStringRef)) { break; } ``` In this case, the key is "URI". Is there a document explaining what are the keys of a CGPDFDictionary? Answer:
It's absurd that you would have to go read 1300 page long specs just to find what keys a dictionary contains, a dictionary that could contain anything depending on what kind of annotation it is. To get a list of keys in a `CGPDFDictionaryRef` you do: ``` // temporary C function to print out keys void printPDFKeys(const char *key, CGPDFObjectRef ob, void *info) { NSLog(@"key = %s", key); } ``` In the place where you're trying to see the contents: ``` CGPDFDictionaryRef mysteriousDictionary; // this is your dictionary with keys CGPDFDictionaryApplyFunction(mysteriousDictionary, printPDFKeys, NULL); // break on or right after above, and you will have the list of keys NSLogged ```
The keys in a dictionary depend on the actual object the dictionary represents (a page dictionary has other keys than an annotation dictionary). The Adobe PDF reference describes all these objects and their keys.
Question: This is the HTML I want to extract from. ``` <input type="hidden" id="continueTo" name="continueTo" value="/oauth2/authz/?response_type=code&client_id=localoauth20&redirect_uri=http%3A%2F%2Fbg-sip-activemq%3A8080%2Fjbpm-console%2Foauth20Callback&state=72a37ba7-2033-47f4-8e7e-69a207406dfb" /> ``` I need a Xpath to extract only state value i.e `72a37ba7-2033-47f4-8e7e-69a207406dfb` Answer:
The XPATH: ``` //input[@id="continueTo"]/@value ``` It will get the value of the node `input` with id `continueTo`. Then it will need to be processed with a Regex first to get a final result. The Regex: ``` `[^=]+$` ``` `$` means the end of the string. It will get everything on the end of the string which is not `=`.
Use below code:- ``` String val = driver.findElement(By.xpath("//input[@id='continueTo']/@value")).getText(); String [] myValue = val.split("&state="); System.out.println(myValue[1]); ``` Hope it will help you :)
Question: This is the HTML I want to extract from. ``` <input type="hidden" id="continueTo" name="continueTo" value="/oauth2/authz/?response_type=code&client_id=localoauth20&redirect_uri=http%3A%2F%2Fbg-sip-activemq%3A8080%2Fjbpm-console%2Foauth20Callback&state=72a37ba7-2033-47f4-8e7e-69a207406dfb" /> ``` I need a Xpath to extract only state value i.e `72a37ba7-2033-47f4-8e7e-69a207406dfb` Answer:
Hi you can only get value of a attribute using xpath not its sub-string but if you want to get sub-string then please do it like below ``` String AttributeValue = driver.findElement(By.id("continueTo")).getAttribute("value"); System.out.println("Value of the attribute value is : " + AttributeValue); // now as you want 72a37ba7-2033-47f4-8e7e-69a207406dfb this substring of the vale attribute // then plz apply java split as below String value = "/oauth2/authz/?response_type=code&client_id=localoauth20&redirect_uri=http%3A%2F%2Fbg-sip-activemq%3A8080%2Fjbpm-console%2Foauth20Callback&state=72a37ba7-2033-47f4-8e7e-69a207406dfb"; String [] myValue = value.split("="); System.out.println(myValue[0]); // will print /oauth2/authz/?response_type System.out.println(myValue[1]); // will print code&client_id System.out.println(myValue[2]); // will print localoauth20&redirect_uri System.out.println(myValue[3]); // will print http%3A%2F%2Fbg-sip-activemq%3A8080%2Fjbpm-console%2Foauth20Callback&state System.out.println(myValue[4]); // will print 72a37ba7-2033-47f4-8e7e-69a207406dfb ``` Hope this helps your query
Use below code:- ``` String val = driver.findElement(By.xpath("//input[@id='continueTo']/@value")).getText(); String [] myValue = val.split("&state="); System.out.println(myValue[1]); ``` Hope it will help you :)
Question: I am working on node.js where forever is installed. I am not sure where is intalled . when i go to project directory then type command `forever list` then it will display no forever Can any body tell me how to check and how to resart processes. My website is running. it means forever may be running Answer:
If `forever list` is empty, your nodeJS app is not running. You have to start it first by doing `forever start yourApp.js`
You have to install forever with sudo.
Question: I'm starting a VPN connection using Network Manager. Once the connection is established I have to change [MTU](http://en.wikipedia.org/wiki/Maximum_transmission_unit) in order it to work properly. For example: ``` sudo ifconfig ppp0 mtu 777 ``` It is very annoying to execute this command every time I open a VPN connection. Is there any idea to create a script that would execute this command automatically once the connection is established (ppp0 interface is up)? Answer:
Create a script in `/etc/network/if-up.d`, containing ``` #!/bin/sh if [ "$IFACE" = "ppp0" ]; then ifconfig ppp0 mtu 777 fi ``` and [make it executable](https://askubuntu.com/questions/122428/how-to-run-sh-file).
Here's a modernized (using `ip` instead of `ifconfig`) and generic (`openconnect` on the command-line uses `tun0`, Network Manager uses `vpn0` through the network applet; the numbers may vary if another network is already active) variant of @enzotib's excellent answer, tested on Ubuntu 20.04: ``` #!/bin/bash if [[ "$IFACE" =~ ^(tun|vpn)[0-9] ]]; then ip link set "$IFACE" mtu 777 fi ```
Question: Sorry for the very noob question. Let's suppose I have an enum like so ``` public enum MyElementType { TYPE_ONE, TYPE_TWO, TYPE_THREE; } ``` When I want to loop over this enum, I always see this solution: ``` for(MyElementType type: MyElementType.values()) { //do things } ``` I wonder if there exist a viable solution with the while loop. Seraching around I see that Enumeration interface exposes the method hasMoreElements() but I don't know how to link the things together. Any advice? Answer:
Why do you want to use a while loop rather than the for-each you more typically see? In any case, it's pretty simple ``` Set<MyElementType> elements = EnumSet.allOf(MyElementType.class); Iterator<MyElementType> it = elements.iterator(); while (it.hasNext()) { MyElementType el = it.next(); // etc } // or Iterator<MyElementType> it = Arrays.asList(MyElementType.values()).iterator(); ```
Take a look @ <http://www.javaspecialists.eu/archive/Issue107.html>
Question: Consider an application that currently uses a combination of license file and/or subscription to verify which features to activate. I can use a smart contract instead of the license file, and potentially the subscription. But today, the subscription check requires an online validation and associated credential check. With the Ethereum blockchain, is it possible to check state while offline? I'd like to implement a system where people are not required to be online to use the software. I can imagine having contracts that return themselves as valid while offline, but will nodes provide access to data if they are not sync'd up? I'd be ok using out of date data for up to a month or more, but I'd need the local client to respond. Alternatively, I could create local license files from the node when the node is online, but I could almost as easily email license files. But by using the blockchain, the licenses and other assets could be traded and available should the company fold. Answer:
When your app is able to sync with the blockchain (network connection available), the check the blockchain and update your app settings file to allow use for up to e.g. 1 week after the blockchain subscription check. Just tell the user that they have to sync before the period is up. One extra feature you can add: * Your app has a unique public and private Ethereum key embedded in it and has to send a small amount of ethers back to your account on a periodic basis. * If you get sent more ether transactions from your app than expected, your customer is running more than one copy of your app.
If you want to get up-to-date information from the Ethereum blockchain then you'll need a node somewhere that's synced up. However, in theory you could do this with either a trusted server or a more lightweight proof so you wouldn't necessarily need the whole chain to be downloaded to the client. If you can tolerate partially out-of-date licensing information then you could certainly cache it locally as you suggest. > > Alternatively, I could create local license files from the node when the node is online, but I could almost as easily email license files. > > > Right, if the goal is just that you want to be able to issue license files based on some information you already have then the Ethereum blockchain probably isn't suitable. Just issue that information on a server of your own and have the client software contact that server. However, there are a couple of interesting things you get from using Ethereum for something like this. For example, you can make software licenses tradeable by arbitrary exchanges that you don't have to create yourself, and licenses bought in this way will work even if you go out of business.
Question: I ask this as someone who loves maths but has no ability. So 2 axioms & a question. Axiom 1 - a digital processor exists that can find the n'th prime number of any size instantly. Axiom 2 - all natural numbers can be expressed as the sum of 2 primes. Would it take more/less/same amount of bits to define a natural number exactly as the sum of primes or as traditional POW2 digital format and will that fact apply to all natural numbers whatever their size? I presume a +/- wouldn't be needed because if it's a - then the larger prime is given first. I'm also interested to know if it's ALWAYS more/less efficient or is their a numerical point at which the optimal solution alters. Maybe it's a very badly written question. If so, I can only apologise. I have wondered this for 20 years but never had anywhere to ask. Thanks. Answer:
The ordinary way of storing natural numbers by means of bits is already optimal. This can easily be seen: Each of the $2^n$ combinations of assignments of $n$ bits represents exactly one distinct natural number between $0$ and $2^n-1$. If there was a way of storing more numbers with the same amount of bits, and we would try to create the mapping between the combination of bits and the actual numbers, we would necessarily end up with a combination of bits that maps to more than one natural number, see [pigeonhole principle](https://en.wikipedia.org/wiki/Pigeonhole_principle). This obviously does not make sense, because we want each number to be unambiguously represented as a certain "bit pattern" in the memory. But it is even worse: We know for sure, that there are infinitely many numbers that can be represented as sum of two primes in more than one way (see [Infinitely many even numbers that can be expressed as the sum of $m$ primes in $n$ different ways](https://math.stackexchange.com/q/1443667/407833)). This means, that there will be definitely fewer natural numbers than unique combinations of two primes. Even if your axioms were true, you would have to represent the pairs of primes in such way that each sum appears only once, i.e. you need some magic that skips the combinations that map to natural numbers that are already covered by other prime pairs.
In this reference, <https://en.m.wikipedia.org/wiki/Goldbach%27s_conjecture> they give a nineteen digit number whose lower prime must be at least 9781. The $n$th prime is about $n\ln n$ so you save a factor of 42, or about six bits, by storing the index of the larger prime. But 9781 is about the 1000th prime, so you need ten bits to store that one. That was a worst case. There will be best cases where the second prime is small. But for the first $2^{50}$ numbers you need at least $2^{50}$ different ways to store them which would mean an average of 50 bits, regardless.
Question: I'm working through Example 2.22 in Steward and Tall's Algebraic Number Theory book. The goal is to determine the ring of integers of $\mathbb Q(\sqrt[3]5)$. Let $\theta\in\mathbb R$ such that $\theta^3=5$. Let $\omega=e^{2\pi i/3}$. I'm at the point where I need to check whether $$ \alpha=\frac 13(1+\theta+\theta^2) $$ or $$ \beta=\frac 13(2+2\theta+2\theta^2) $$ are algebraic integers (I've checked the other cases). Let's start with $\alpha$. I can think of two ways to do this. The first would be to consider the norm $$ N(\alpha)=\frac 1{27}(1+\theta+\theta^2)(1+\omega\theta+\omega^2\theta^2)(1+\omega^2\theta+\omega\theta^2). $$ If $\alpha$ is an algebaric integer, then $N(\alpha)\in\mathbb Z$. However, the expression of $N(\alpha)$ is a bit complicated (unless I'm overlooking something). The second would be to determine the minimum polynomial $\mu$ of $\alpha$ over $\mathbb Q$, and then invoke that $\alpha$ is an algebraic integer iff $\mu\in\mathbb Z[X]$. In both cases I'm not too hopeful. Should I still proceed in this way, or is there something obvious I'm missing? Answer:
[![enter image description here](https://i.stack.imgur.com/7hWo2.png)](https://i.stack.imgur.com/7hWo2.png) As pointed out by dezdichado, the problem can be done by two applications of Cosine Formula. Refer to the figure, One such formula is: $$\cos \alpha=\frac{(c-x)^2+y^2-a^2}{2(c-x)y}$$ Applying Cosine Formula to the other triangle and combining the $2$ equations would yield the required answer.
I have an idea to start : In $\Bbb C, A=0, B=1, C=\xi +i\eta, D=x$ Unfortunately, none of my calculations succeed, although simplifications appear: I suspect that there is a sign error in the proposed equality.
Question: I want my marker to appear not in the center of the screen, but 25% of the way up to give extra room for the popup box. Although sticking an offset in is easy, the offset depends on the zoom level as if you're zoomed far out, you'll want to center the map quite far up (such as 50km). If you're really zoomed in, then you'll want to center it just a tiny amount like 10 meters. I'm not sure how to accomplish this. Any ideas? Answer:
Try this: Take the height of the plugin and get 25% of that. Then you need to multiply that by the degrees or kilometres per pixel scale at that height (if you can't get it straight from the plugin then I guess do the math), then centre the screen at that point on the globe.
I am not sure as it has been a while since I messed around with the API, but I think you can create a custom marker object with its own pixel based offset, and display that instead of the default marker. EDIT: Whoops read it again and realized you probably just wanted to move the whole map and not the marker.
Question: I know this is a very classical question which might be answered many times in this forum, however I could not find any clear answer which explains this clearly from scratch. Firstly, imgine that my dataset called my\_data has 4 variables such as my\_data = variable1, variable2, variable3, target\_variable So, let's come to my problem. I'll explain all my steps and ask your help for where I've been stuck: ``` # STEP1 : split my_data into [predictors] and [targets] predictors = my_data[[ 'variable1', 'variable2', 'variable3' ]] targets = my_data.target_variable # STEP2 : import the required libraries from sklearn import cross_validation from sklearn.ensemble import RandomForestRegressor #STEP3 : define a simple Random Forest model attirbutes model = RandomForestClassifier(n_estimators=100) #STEP4 : Simple K-Fold cross validation. 3 folds. cv = cross_validation.KFold(len(my_data), n_folds=3, random_state=30) # STEP 5 ``` At this step, I want to fit my model based on the training dataset, and then use that model on test dataset and predict test targets. I also want to calculate the required statistics such as MSE, r2 etc. for understanding the performance of my model. I'd appreciate if someone helps me woth some basic codelines for Step5. Answer:
First off, you are using the deprecated package `cross-validation` of scikit library. New package is named `model_selection`. So I am using that in this answer. Second, you are importing `RandomForestRegressor`, but defining `RandomForestClassifier` in the code. I am taking `RandomForestRegressor` here, because the metrics you want (MSE, R2 etc) are only defined for regression problems, not classification. There are multiple ways to do what you want. I assume that since you are trying to use the KFold cross-validation here, you want to use the left-out data of each fold as test fold. To accomplish this, we can do: ``` predictors = my_data[[ 'variable1', 'variable2', 'variable3' ]] targets = my_data.target_variable from sklearn import model_selection from sklearn.ensemble import RandomForestRegressor from sklearn import metrics model = RandomForestRegressor(n_estimators=100) cv = model_selection.KFold(n_splits=3) for train_index, test_index in kf.split(predictors): print("TRAIN:", train_index, "TEST:", test_index) X_train, X_test = predictors[train_index], predictors[test_index] y_train, y_test = targets[train_index], targets[test_index] # For training, fit() is used model.fit(X_train, y_train) # Default metric is R2 for regression, which can be accessed by score() model.score(X_test, y_test) # For other metrics, we need the predictions of the model y_pred = model.predict(X_test) metrics.mean_squared_error(y_test, y_pred) metrics.r2_score(y_test, y_pred) ``` For all this, documentation is your best friend. And scikit-learn documentation are one of the best I have ever seen. Following links may help you know more about them: * <http://scikit-learn.org/stable/modules/cross_validation.html#cross-validation-evaluating-estimator-performance> * <http://scikit-learn.org/stable/modules/model_evaluation.html#regression-metrics> * <http://scikit-learn.org/stable/user_guide.html>
Also in the for loop it should be: ``` model = RandomForestRegressor(n_estimators=100) for train_index, test_index in cv.split(X): ```
Question: Requirements for a TextBox control were to accept the following as valid inputs: 1. A sequence of numbers. 2. Literal string 'Number of rooms'. 3. No value at all (left blank). Not specifying a value at all should allow for the RegularExpressionValidator to pass. Following RegEx yielded the desired results (successfully validated the 3 types of inputs): ``` "Number of rooms|[0-9]*" ``` However, I couldn't come up with an explanation when a colleague asked why the following fails to validate when the string 'Number of rooms' is specified (requirement #2): ``` "[0-9]*|Number of rooms" ``` An explanation as to why the ordering of alternation matters in this case would be very insightful indeed. UPDATE: The second regex successfully matches the target string "Number of rooms" in console app as shown [here](http://pastebin.com/yzr6Bqcd). However, using the identical expression in aspx markup doesn't match when the input is "Number of rooms". Here's the relevant aspx markup: ``` <asp:TextBox runat="server" ID="textbox1" > </asp:TextBox> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" EnableClientScript="false" runat="server" ControlToValidate="textbox1" ValidationExpression="[0-9]*|Number of rooms" ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator> <asp:Button ID="Button1" runat="server" Text="Button" /> ``` Answer:
The order matters since that is the order which the Regex engine will try to match. Case 1: `Number of rooms|[0-9]*` In this case the regex engine will first try to match the text "Number of room". If this fails will then try to match numbers or nothing. Case 2: `[0-9]*|Number of rooms`: In this case the engine will first try to match number or nothing. But nothing will *always* match. In this case it never needs to try "Number of rooms" This is kind of like the || operator in C#. Once the left side matches the right side is ignored. **Update:** To answer your second question. It behaves differently with the RegularExpressionValidator because that is doing more than just checking for a match. ``` // ..... Match m = Regex.Match(controlValue, ValidationExpression); return(m.Success && m.Index == 0 && m.Length == controlValue.Length); // ..... ``` It is checking for a match as well as making sure the length of the match is the whole string. This rules out partial or empty matches.
The point is that the `[0-9]*` at the beginning is matching empty strings if you specify that first. If you specify that *the whole string* should be digits, then it should work: ``` ^[0-9]*$|Number of rooms ``` Unless you specify `^` and `$`, to indicate that *the whole string* must be a match, an empty string will be matched at the beginning of "Number of rooms", and at that point the second alternative will not be tried out. I hope this answers your question in the comment, I'm not sure if it's clear...
Question: Requirements for a TextBox control were to accept the following as valid inputs: 1. A sequence of numbers. 2. Literal string 'Number of rooms'. 3. No value at all (left blank). Not specifying a value at all should allow for the RegularExpressionValidator to pass. Following RegEx yielded the desired results (successfully validated the 3 types of inputs): ``` "Number of rooms|[0-9]*" ``` However, I couldn't come up with an explanation when a colleague asked why the following fails to validate when the string 'Number of rooms' is specified (requirement #2): ``` "[0-9]*|Number of rooms" ``` An explanation as to why the ordering of alternation matters in this case would be very insightful indeed. UPDATE: The second regex successfully matches the target string "Number of rooms" in console app as shown [here](http://pastebin.com/yzr6Bqcd). However, using the identical expression in aspx markup doesn't match when the input is "Number of rooms". Here's the relevant aspx markup: ``` <asp:TextBox runat="server" ID="textbox1" > </asp:TextBox> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" EnableClientScript="false" runat="server" ControlToValidate="textbox1" ValidationExpression="[0-9]*|Number of rooms" ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator> <asp:Button ID="Button1" runat="server" Text="Button" /> ``` Answer:
The order matters since that is the order which the Regex engine will try to match. Case 1: `Number of rooms|[0-9]*` In this case the regex engine will first try to match the text "Number of room". If this fails will then try to match numbers or nothing. Case 2: `[0-9]*|Number of rooms`: In this case the engine will first try to match number or nothing. But nothing will *always* match. In this case it never needs to try "Number of rooms" This is kind of like the || operator in C#. Once the left side matches the right side is ignored. **Update:** To answer your second question. It behaves differently with the RegularExpressionValidator because that is doing more than just checking for a match. ``` // ..... Match m = Regex.Match(controlValue, ValidationExpression); return(m.Success && m.Index == 0 && m.Length == controlValue.Length); // ..... ``` It is checking for a match as well as making sure the length of the match is the whole string. This rules out partial or empty matches.
You probably wanted to use regex `Number of rooms|[0-9]+` or `[0-9]+|Number of rooms`, because pattern `[0-9]*` (with star) will always match at least empty string (`*` means `{0,}`, so "zero or more...").
Question: I am trying to round the corners of a custom shape, but it is just straightening the original curves out. *Note: This is in Illustrator CS5* **Here is the shape before the effect:** [![enter image description here](https://i.stack.imgur.com/luohd.png)](https://i.stack.imgur.com/luohd.png) The 3 "corners should be rounded". **Here is what happens when I use the effect:** [![enter image description here](https://i.stack.imgur.com/3jyfQ.png)](https://i.stack.imgur.com/3jyfQ.png) **How can I preserve the curves, and just round the actual corners?** Answer:
I don't have CS5, but this should work: Select your path. With the pen tool selected, create points on each side of the anchor points, something like the following: [![Path with new anchor points added near the original cusp points.](https://i.stack.imgur.com/U3Mk7.png)](https://i.stack.imgur.com/U3Mk7.png) With the white arrow tool selected, click one of the original cusp points (i.e., corner points) and then `Shift`-click the other two to select all three. Then, click the `Convert selected anchor points to smooth` icon in the toolbar at the top of the screen (alternatively, with the pen tool selected you can `Alt` or `Option`-drag on a corner point to convert it to a smooth point): [![Convert selected anchor points to smooth icon](https://i.stack.imgur.com/mchHs.png)](https://i.stack.imgur.com/mchHs.png) You should end up with something similar to this: [![Path with bulging corners.](https://i.stack.imgur.com/zOo3s.png)](https://i.stack.imgur.com/zOo3s.png) With the white arrow tool, drag each of the bulging corner points inward until they look appropriate: [![Bulging corner points fixed.](https://i.stack.imgur.com/glD9N.png)](https://i.stack.imgur.com/glD9N.png) Here's the new path overlaying your original shape. [![Path with rounded corners.](https://i.stack.imgur.com/Mz93L.png)](https://i.stack.imgur.com/Mz93L.png) If you want the corners to be more rounded, make sure the anchor points you added in the first step are farther away from the corner points.
My way is easier if you have good experience with the pen tool. First, make your triangle. In my case, I just made a box, deleted 1 anchor point, joined the two points creating a segment opposite to the middle point and rotated about 45 degrees (please correct me if I'm wrong). [![enter image description here](https://i.stack.imgur.com/sXe3V.png)](https://i.stack.imgur.com/sXe3V.png) Next, hit the convert path to rounded corner button. I'm pretty sure this feature is already in CS5. Make sure you have the point selected when doing this. [![enter image description here](https://i.stack.imgur.com/ZjWmA.png)](https://i.stack.imgur.com/ZjWmA.png) Do this one by one for each of your points. The one in the middle should be the easiest one to convert. The one at the top and the bottom are a bit tricky but nothing a pen tool can't fix :) As you go each of the top and the bottom points, with your Direct Selection Tool active, grab the furthest to the left angle for the point being selected and while holding Shift, bring it to the center creating a nice straight side but still rounded corners. [![enter image description here](https://i.stack.imgur.com/Z6DvZ.png)](https://i.stack.imgur.com/Z6DvZ.png) It should look something like this: [![enter image description here](https://i.stack.imgur.com/Jj8Te.png)](https://i.stack.imgur.com/Jj8Te.png) Again, do the same thing for the bottom and you will get this: [![enter image description here](https://i.stack.imgur.com/WQiBV.png)](https://i.stack.imgur.com/WQiBV.png) I hope this helps! Please let me know if I confuse you. I'll be glad to clarify myself some more.
Question: I am trying to round the corners of a custom shape, but it is just straightening the original curves out. *Note: This is in Illustrator CS5* **Here is the shape before the effect:** [![enter image description here](https://i.stack.imgur.com/luohd.png)](https://i.stack.imgur.com/luohd.png) The 3 "corners should be rounded". **Here is what happens when I use the effect:** [![enter image description here](https://i.stack.imgur.com/3jyfQ.png)](https://i.stack.imgur.com/3jyfQ.png) **How can I preserve the curves, and just round the actual corners?** Answer:
I don't have CS5, but this should work: Select your path. With the pen tool selected, create points on each side of the anchor points, something like the following: [![Path with new anchor points added near the original cusp points.](https://i.stack.imgur.com/U3Mk7.png)](https://i.stack.imgur.com/U3Mk7.png) With the white arrow tool selected, click one of the original cusp points (i.e., corner points) and then `Shift`-click the other two to select all three. Then, click the `Convert selected anchor points to smooth` icon in the toolbar at the top of the screen (alternatively, with the pen tool selected you can `Alt` or `Option`-drag on a corner point to convert it to a smooth point): [![Convert selected anchor points to smooth icon](https://i.stack.imgur.com/mchHs.png)](https://i.stack.imgur.com/mchHs.png) You should end up with something similar to this: [![Path with bulging corners.](https://i.stack.imgur.com/zOo3s.png)](https://i.stack.imgur.com/zOo3s.png) With the white arrow tool, drag each of the bulging corner points inward until they look appropriate: [![Bulging corner points fixed.](https://i.stack.imgur.com/glD9N.png)](https://i.stack.imgur.com/glD9N.png) Here's the new path overlaying your original shape. [![Path with rounded corners.](https://i.stack.imgur.com/Mz93L.png)](https://i.stack.imgur.com/Mz93L.png) If you want the corners to be more rounded, make sure the anchor points you added in the first step are farther away from the corner points.
The simple way: Create additional anchor points around cornes (as it was mentioned at first answer), then apply Round Corner effect as usual.
Question: I am trying to round the corners of a custom shape, but it is just straightening the original curves out. *Note: This is in Illustrator CS5* **Here is the shape before the effect:** [![enter image description here](https://i.stack.imgur.com/luohd.png)](https://i.stack.imgur.com/luohd.png) The 3 "corners should be rounded". **Here is what happens when I use the effect:** [![enter image description here](https://i.stack.imgur.com/3jyfQ.png)](https://i.stack.imgur.com/3jyfQ.png) **How can I preserve the curves, and just round the actual corners?** Answer:
I don't have CS5, but this should work: Select your path. With the pen tool selected, create points on each side of the anchor points, something like the following: [![Path with new anchor points added near the original cusp points.](https://i.stack.imgur.com/U3Mk7.png)](https://i.stack.imgur.com/U3Mk7.png) With the white arrow tool selected, click one of the original cusp points (i.e., corner points) and then `Shift`-click the other two to select all three. Then, click the `Convert selected anchor points to smooth` icon in the toolbar at the top of the screen (alternatively, with the pen tool selected you can `Alt` or `Option`-drag on a corner point to convert it to a smooth point): [![Convert selected anchor points to smooth icon](https://i.stack.imgur.com/mchHs.png)](https://i.stack.imgur.com/mchHs.png) You should end up with something similar to this: [![Path with bulging corners.](https://i.stack.imgur.com/zOo3s.png)](https://i.stack.imgur.com/zOo3s.png) With the white arrow tool, drag each of the bulging corner points inward until they look appropriate: [![Bulging corner points fixed.](https://i.stack.imgur.com/glD9N.png)](https://i.stack.imgur.com/glD9N.png) Here's the new path overlaying your original shape. [![Path with rounded corners.](https://i.stack.imgur.com/Mz93L.png)](https://i.stack.imgur.com/Mz93L.png) If you want the corners to be more rounded, make sure the anchor points you added in the first step are farther away from the corner points.
**Purely for comparison’s sake**, I thought it would be good to show what Adobe Illustrator CC (in this case, I am using v2017) can do: [![enter image description here](https://i.stack.imgur.com/8d2hQ.gif)](https://i.stack.imgur.com/8d2hQ.gif) 1. With the selection tool, select your entire path 2. On a Mac, hold down `COMMAND` key (`CONTROL` on Win). 3. Click and drag on the corner radius circle icons that appear 4. You can optionally select a specific point and just round the corner for that part of your shape Double click one of the circles for corner options: [![](https://i.stack.imgur.com/3ci1E.png)](https://i.stack.imgur.com/3ci1E.png)
Question: I am trying to round the corners of a custom shape, but it is just straightening the original curves out. *Note: This is in Illustrator CS5* **Here is the shape before the effect:** [![enter image description here](https://i.stack.imgur.com/luohd.png)](https://i.stack.imgur.com/luohd.png) The 3 "corners should be rounded". **Here is what happens when I use the effect:** [![enter image description here](https://i.stack.imgur.com/3jyfQ.png)](https://i.stack.imgur.com/3jyfQ.png) **How can I preserve the curves, and just round the actual corners?** Answer:
**Purely for comparison’s sake**, I thought it would be good to show what Adobe Illustrator CC (in this case, I am using v2017) can do: [![enter image description here](https://i.stack.imgur.com/8d2hQ.gif)](https://i.stack.imgur.com/8d2hQ.gif) 1. With the selection tool, select your entire path 2. On a Mac, hold down `COMMAND` key (`CONTROL` on Win). 3. Click and drag on the corner radius circle icons that appear 4. You can optionally select a specific point and just round the corner for that part of your shape Double click one of the circles for corner options: [![](https://i.stack.imgur.com/3ci1E.png)](https://i.stack.imgur.com/3ci1E.png)
My way is easier if you have good experience with the pen tool. First, make your triangle. In my case, I just made a box, deleted 1 anchor point, joined the two points creating a segment opposite to the middle point and rotated about 45 degrees (please correct me if I'm wrong). [![enter image description here](https://i.stack.imgur.com/sXe3V.png)](https://i.stack.imgur.com/sXe3V.png) Next, hit the convert path to rounded corner button. I'm pretty sure this feature is already in CS5. Make sure you have the point selected when doing this. [![enter image description here](https://i.stack.imgur.com/ZjWmA.png)](https://i.stack.imgur.com/ZjWmA.png) Do this one by one for each of your points. The one in the middle should be the easiest one to convert. The one at the top and the bottom are a bit tricky but nothing a pen tool can't fix :) As you go each of the top and the bottom points, with your Direct Selection Tool active, grab the furthest to the left angle for the point being selected and while holding Shift, bring it to the center creating a nice straight side but still rounded corners. [![enter image description here](https://i.stack.imgur.com/Z6DvZ.png)](https://i.stack.imgur.com/Z6DvZ.png) It should look something like this: [![enter image description here](https://i.stack.imgur.com/Jj8Te.png)](https://i.stack.imgur.com/Jj8Te.png) Again, do the same thing for the bottom and you will get this: [![enter image description here](https://i.stack.imgur.com/WQiBV.png)](https://i.stack.imgur.com/WQiBV.png) I hope this helps! Please let me know if I confuse you. I'll be glad to clarify myself some more.
Question: I am trying to round the corners of a custom shape, but it is just straightening the original curves out. *Note: This is in Illustrator CS5* **Here is the shape before the effect:** [![enter image description here](https://i.stack.imgur.com/luohd.png)](https://i.stack.imgur.com/luohd.png) The 3 "corners should be rounded". **Here is what happens when I use the effect:** [![enter image description here](https://i.stack.imgur.com/3jyfQ.png)](https://i.stack.imgur.com/3jyfQ.png) **How can I preserve the curves, and just round the actual corners?** Answer:
**Purely for comparison’s sake**, I thought it would be good to show what Adobe Illustrator CC (in this case, I am using v2017) can do: [![enter image description here](https://i.stack.imgur.com/8d2hQ.gif)](https://i.stack.imgur.com/8d2hQ.gif) 1. With the selection tool, select your entire path 2. On a Mac, hold down `COMMAND` key (`CONTROL` on Win). 3. Click and drag on the corner radius circle icons that appear 4. You can optionally select a specific point and just round the corner for that part of your shape Double click one of the circles for corner options: [![](https://i.stack.imgur.com/3ci1E.png)](https://i.stack.imgur.com/3ci1E.png)
The simple way: Create additional anchor points around cornes (as it was mentioned at first answer), then apply Round Corner effect as usual.
Question: I use a custom hook to support dark mode with tailwindcss in my new react-native app, created with Expo CLI. The TailwindProvider with the dark mode logic looks like this: ```js const TailwindProvider: React.FC = ({ children }) => { const [currentColorScheme, setcurrentColorScheme] = useState(Appearance.getColorScheme()); console.log("CurrentColorScheme:", currentColorScheme); const isDarkMode = currentColorScheme == "dark"; const tw = (classes: string) => tailwind(handleThemeClasses(classes, isDarkMode)) return <TailwindContext.Provider value={{ currentColorScheme, setcurrentColorScheme, tw, isDarkMode }}>{children}</TailwindContext.Provider>; } ``` as you can see, i use the `Appearance.getColorScheme()` method from `react-native` to get the current ColorScheme. But both on iOS and Android, i always get `light` instead of `dark`, in debug as well as in production mode. How can I fix this? Answer:
Use `systimestamp` since that includes a time zone. ``` select systimestamp at time zone 'US/Eastern' from dual; ``` should return a timestamp in the Eastern time zone (assuming your database time zone files are up to date). Note that if you ask for a timestamp in EST, that should be an hour earlier than the current time in the Eastern time zone of the United States because the US is in Daylight Savings Time. So the Eastern time zone is in EDT currently not EST.
Use `systimestamp` rather than `sysdate`, because it is already timezone-aware; then `at time zone` to translate: ``` select systimestamp at time zone 'America/New_York' from dual ``` Using a region is better/safer than an abbreviation like 'EST", which might not be unique; and [gives you the wrong answer](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=8792c9f5fb967821b6c1406e8baca6d3) - this shows mine, Justin's alternative (and maybe better!) region, what you get with EST, and all the things EST is an abbreviation of. (You could use `EST5EDT`, but a region is still clearer.) You could also set your session to an East-coat region (if it isn't already) and then use `current_timestamp` instead of `systimestamp`: ``` alter session set time_zone = 'America/New_York'; select current_timestamp from dual; ``` [db<>fiddle](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=f3f5b5a55fe5f1f5a1ff50d1ad3213ab) Either way, how it is displayed is down to your client/application - e.g. the session `nls_timestamp_tz_format` - unless you convert it to a string with `to_char()`, supplying the format you want.
Question: I use a custom hook to support dark mode with tailwindcss in my new react-native app, created with Expo CLI. The TailwindProvider with the dark mode logic looks like this: ```js const TailwindProvider: React.FC = ({ children }) => { const [currentColorScheme, setcurrentColorScheme] = useState(Appearance.getColorScheme()); console.log("CurrentColorScheme:", currentColorScheme); const isDarkMode = currentColorScheme == "dark"; const tw = (classes: string) => tailwind(handleThemeClasses(classes, isDarkMode)) return <TailwindContext.Provider value={{ currentColorScheme, setcurrentColorScheme, tw, isDarkMode }}>{children}</TailwindContext.Provider>; } ``` as you can see, i use the `Appearance.getColorScheme()` method from `react-native` to get the current ColorScheme. But both on iOS and Android, i always get `light` instead of `dark`, in debug as well as in production mode. How can I fix this? Answer:
Use `systimestamp` rather than `sysdate`, because it is already timezone-aware; then `at time zone` to translate: ``` select systimestamp at time zone 'America/New_York' from dual ``` Using a region is better/safer than an abbreviation like 'EST", which might not be unique; and [gives you the wrong answer](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=8792c9f5fb967821b6c1406e8baca6d3) - this shows mine, Justin's alternative (and maybe better!) region, what you get with EST, and all the things EST is an abbreviation of. (You could use `EST5EDT`, but a region is still clearer.) You could also set your session to an East-coat region (if it isn't already) and then use `current_timestamp` instead of `systimestamp`: ``` alter session set time_zone = 'America/New_York'; select current_timestamp from dual; ``` [db<>fiddle](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=f3f5b5a55fe5f1f5a1ff50d1ad3213ab) Either way, how it is displayed is down to your client/application - e.g. the session `nls_timestamp_tz_format` - unless you convert it to a string with `to_char()`, supplying the format you want.
If you really want to use `SYSDATE` then you can use: ```sql SELECT from_tz(CAST(sysdate AS TIMESTAMP),'PST') AT TIME ZONE 'EST5EDT' FROM DUAL; ``` Which outputs: > > > ``` > > | FROM_TZ(CAST(SYSDATEASTIMESTAMP),'PST')ATTIMEZONE'EST5EDT' | > | :--------------------------------------------------------- | > | 02-APR-21 11.07.33.000000 PM EST5EDT | > > ``` > > or: ```sql SELECT from_tz(CAST(sysdate AS TIMESTAMP),'US/Pacific') AT TIME ZONE 'US/Eastern' FROM DUAL; ``` Which outputs: > > > ``` > > | FROM_TZ(CAST(SYSDATEASTIMESTAMP),'US/PACIFIC')ATTIMEZONE'US/EASTERN' | > | :------------------------------------------------------------------- | > | 02-APR-21 11.07.33.000000 PM US/EASTERN | > > ``` > > *db<>fiddle [here](https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=d5f2a83874b278412b0596443eb29d4c)*
Question: I use a custom hook to support dark mode with tailwindcss in my new react-native app, created with Expo CLI. The TailwindProvider with the dark mode logic looks like this: ```js const TailwindProvider: React.FC = ({ children }) => { const [currentColorScheme, setcurrentColorScheme] = useState(Appearance.getColorScheme()); console.log("CurrentColorScheme:", currentColorScheme); const isDarkMode = currentColorScheme == "dark"; const tw = (classes: string) => tailwind(handleThemeClasses(classes, isDarkMode)) return <TailwindContext.Provider value={{ currentColorScheme, setcurrentColorScheme, tw, isDarkMode }}>{children}</TailwindContext.Provider>; } ``` as you can see, i use the `Appearance.getColorScheme()` method from `react-native` to get the current ColorScheme. But both on iOS and Android, i always get `light` instead of `dark`, in debug as well as in production mode. How can I fix this? Answer:
Use `systimestamp` since that includes a time zone. ``` select systimestamp at time zone 'US/Eastern' from dual; ``` should return a timestamp in the Eastern time zone (assuming your database time zone files are up to date). Note that if you ask for a timestamp in EST, that should be an hour earlier than the current time in the Eastern time zone of the United States because the US is in Daylight Savings Time. So the Eastern time zone is in EDT currently not EST.
If you really want to use `SYSDATE` then you can use: ```sql SELECT from_tz(CAST(sysdate AS TIMESTAMP),'PST') AT TIME ZONE 'EST5EDT' FROM DUAL; ``` Which outputs: > > > ``` > > | FROM_TZ(CAST(SYSDATEASTIMESTAMP),'PST')ATTIMEZONE'EST5EDT' | > | :--------------------------------------------------------- | > | 02-APR-21 11.07.33.000000 PM EST5EDT | > > ``` > > or: ```sql SELECT from_tz(CAST(sysdate AS TIMESTAMP),'US/Pacific') AT TIME ZONE 'US/Eastern' FROM DUAL; ``` Which outputs: > > > ``` > > | FROM_TZ(CAST(SYSDATEASTIMESTAMP),'US/PACIFIC')ATTIMEZONE'US/EASTERN' | > | :------------------------------------------------------------------- | > | 02-APR-21 11.07.33.000000 PM US/EASTERN | > > ``` > > *db<>fiddle [here](https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=d5f2a83874b278412b0596443eb29d4c)*
Question: (<https://webapps.stackexchange.com/review/suggested-edits/111499> shows action by both.) [Edit: At first glance they both looked like special users. Not so.] Answer:
Community♦ is [a special user](https://meta.stackexchange.com/questions/19738/who-is-the-community-user). Community is credited for reviews when they are: * Done by deleted users * Improved, in which case Community is shown as having approved the edit * Rejected and edited, in which case Community is shown as having rejected the edit [user0](https://webapps.stackexchange.com/users/186471/user0) is a normal user who just happens to have "0" in the username. user0 approved the edit before it was improved by a different user.
A key difference is that their real user numbers, respectively, are -1 for Community♦ and 186471 for user0 (on webapps, and thus *not* 0), as can be seen in the URL (classically displayed in a browser's status bar when mousing over the usernames) that clicking on the name opens. [Community♦](https://stackexchange.com/users/-1) (/community is tacked on the end of the canonical URL) is [a special user](https://meta.stackexchange.com/questions/19738/who-is-the-community-user). But [user0](https://webapps.stackexchange.com/users/186471) (/user0 is tacked on the end of the canonical URL) is a normal user who just happens to have "0" in the username. user0 approved the edit before it was improved by a different user. [I found no true user 0 - no user with ID 0](https://stackexchange.com/users/0/anything) on any SE sites. [There is also no user with ID 1](https://webapps.stackexchange.com/users/1) on some SE sites, but [there IS a user with ID 1](https://stackexchange.com/users/1) on other SE sites.
Question: My project can switch between languages. The items are stored in a database, and using $\_GET['lang'] in the database gives back the correct items. For now, only English and French are in use, so it works with this code : ``` if ($_GET['lang'] == 'fr' OR ($_GET['lang'] == 'en')) { $header = getTranslation('header', $_GET['lang']); $footer = getTranslation('footer', $_GET['lang']); } else { header('Location: error.php'); } ``` What I'm looking for is some way to be prepared in case a language is added in the db. The code below approaches what I need (and obviously didn't work). ``` while ($translations = $languagesList->fetch()) { if ($_GET['lang'] == $translations['code']) { $header = getTranslation('header', $_GET['lang']); $footer = getTranslation('footer', $_GET['lang']); } else { header('Location: language.php'); } } ``` Is there any way to create a code that would generate multiple if conditions based on the number of languages in the db ? Answer:
You should move the else part outside of the loop, as otherwise you will always execute it at some point in the loop iterations. Only when you have iterated through *all* possibilities, and you still have no match, then you can be sure there to have to navigate to the language page: ``` $header = null; while ($translations = $languagesList->fetch()) { if ($_GET['lang'] == $translations['code']) { $header = getTranslation('header', $_GET['lang']); $footer = getTranslation('footer', $_GET['lang']); break; // No need to waste time to look further. } } if ($header === null) { header('Location: language.php'); } ``` But it would be smarter to [prepare an SQL statement](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) that gets you the result for the *particular* language only (with `where code = ?` and bind `$_GET['lang']` to it). Then you don't have to iterate in PHP, which will in general be slower than what the database can provide. Instead you can just see whether you had 0 or 1 records back (Or use `select count(*)` and check whether that is 0 or not).
Easiest is to have a mapping in an array, check if your language is present there, and if so, do stuff. Something like this; ``` $languages = array('en', 'fr', 'de', '...'); $default_language = 'en'; $language = in_array($_GET['lang'], $languages) ? $_GET['lang'] : $default_language; $header = getTranslation('header', $language); ``` As you can see I've set a default langauge which is used if the language in the query var cannot be found. How to create that array of languages is up to you (a simple query should suffice).
Question: I have a list of strings (see below) how do I concatenate these strings into one list containing one string. ``` ["hello","stack","overflow"] ``` to ``` ["hellostackoverflow"] ``` I am just allowed to import Data.Char and Data.List Answer:
Consider each string in a list as a list of characters ``` ["hello","stack","overflow"] :: [[Char]] ``` Concatenation is a process of connecting several lists into one. It must have a following type: ``` concat :: [[a]] -> [a] ``` If you will have such a function, you'll get a half of job done. You are looking for a way to get ``` ["hellostackoverflow"] ``` as a result of concatenation. Once again, look at it's type: ``` ["hellostackoverflow"] :: [[Char]] ``` It is the same type as you had at the beginning except that there is only one element in a list. So now you need a function which puts something into a list. It must have a type ``` putToList :: a -> [a] ``` Once you'll have both `concat` and `putToList` functions, your solution will be almost ready. Last thing you need to do is to compose it like that: ``` myConcatenation = putToList . concat ``` --- I suggest you to use [Hoogle](https://www.haskell.org/hoogle/) to search existing function by it's type.
You can also use the list monad to reduce the list to a single string, then re-wrap the result in a list. ``` > [["hello", "stack", "overflow"] >>= id] ["hellostackoverflow"] ``` The preceding avoids explicitly use of `Control.Monad.join`: ``` > import Control.Monad > [join ["hello", "stack", "overflow"] ["hellostackoverflow"] ```
Question: I have a list of strings (see below) how do I concatenate these strings into one list containing one string. ``` ["hello","stack","overflow"] ``` to ``` ["hellostackoverflow"] ``` I am just allowed to import Data.Char and Data.List Answer:
Consider each string in a list as a list of characters ``` ["hello","stack","overflow"] :: [[Char]] ``` Concatenation is a process of connecting several lists into one. It must have a following type: ``` concat :: [[a]] -> [a] ``` If you will have such a function, you'll get a half of job done. You are looking for a way to get ``` ["hellostackoverflow"] ``` as a result of concatenation. Once again, look at it's type: ``` ["hellostackoverflow"] :: [[Char]] ``` It is the same type as you had at the beginning except that there is only one element in a list. So now you need a function which puts something into a list. It must have a type ``` putToList :: a -> [a] ``` Once you'll have both `concat` and `putToList` functions, your solution will be almost ready. Last thing you need to do is to compose it like that: ``` myConcatenation = putToList . concat ``` --- I suggest you to use [Hoogle](https://www.haskell.org/hoogle/) to search existing function by it's type.
```hs concat ["hello","stack","overflow"] -- => "hellostackoverflow" ```
Question: I have a list of strings (see below) how do I concatenate these strings into one list containing one string. ``` ["hello","stack","overflow"] ``` to ``` ["hellostackoverflow"] ``` I am just allowed to import Data.Char and Data.List Answer:
```hs concat ["hello","stack","overflow"] -- => "hellostackoverflow" ```
You can also use the list monad to reduce the list to a single string, then re-wrap the result in a list. ``` > [["hello", "stack", "overflow"] >>= id] ["hellostackoverflow"] ``` The preceding avoids explicitly use of `Control.Monad.join`: ``` > import Control.Monad > [join ["hello", "stack", "overflow"] ["hellostackoverflow"] ```
Question: Here T could be an array or a single object. How can add the array to an arraylist or add a single object to the same arraylist. This gives me a build-time error that the overloaded match for `AddRange` has invalid arguments. ``` T loadedContent; if (typeof(T).IsArray) { contentArrayList.AddRange(loadedContent); } else { contentArrayList.Add(loadedContent); } ``` Answer:
Make sure you have set the correct editor associations and content types Go to settings (`Window -> preferences`) **Content Types** 1. Type in `Content Types` in the search box (should show under `General -> Types` 2. Click on the arrow next to `Text`, select `PHP Content Type` 3. Add `*.ctp` by clicking on the Add button on the right side **File Association** 1. Type in `File Associations` in the search box on the left 2. Add \*.ctp (click the Add button on the top right side) 3. Associate the proper editor for it by clicking Add (on the bottom right side) and selecting PHP Editor
You can change the extension that CakePHP uses for view files to an extension that Eclipse likes. In the controller (or app\_controller) add the following variable: ``` var $ext = '.tpl'; ``` If you change the extension to "PHP" you may have problems because CakePHP will try to load a class that matches the filename.
Question: I've tried connecting a camera to my Raspberry Pi and I've enabled it on `raspi-config` but `vcgencmd get_camera` still shows `supported=0` `detected=0`. Also, in my `boot/config.txt`, `start_x=1` is not even commented nor enabled upon enabling camera interface. Another thing to note is my Raspberry Pi constantly shows a low voltage warning but I am unsure whether this is related in any way. What might be the issue? Answer:
Thanks to the comments, I have rectified the issue. The issue was with the bullseye version of the os. I used a buster version and it worked just fine
1. [Check first if the camera is supported](http://elinux.org/RPi_VerifiedPeripherals#USB_Webcams) 2. Try a powered USB hub to plug in the camera / maybe it isnt getting enough power Then you can install this tool to test out the camera `sudo apt-get install luvcview`
Question: I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`? Here is the code: ``` public List<Bike> addBikes() throws ClassNotFoundException, SQLException{ List<Bike> bikeList = new ArrayList<Bike>(); Class.forName("com.mysql.jdbc.Driver"); Connection con = null; Statement stm = null; ResultSet rs = null; con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ; stm=con.createStatement(); String qry="Select * from bike"; rs=stm.executeQuery(qry); while(rs.next()) { /* I need to put * rs.getString("name"),rs.getString("model") * etc into any of the suitable collection objects * and then need to add those to the ArrayList - bikeList * */ } return bikeList; } ``` Answer:
For each result in the result set, create a `new Bike()` and copy the values from that result to the new bikes fields. At the end, add the bike to the list. ``` Bike bike = new Bike() bike.setName(rs.getString("name")); //... bikeList.add(bike); ```
you would instantiate a Bike object and set properties that you read from result set, then add the bike object to your arraylist, isnt it what you are looking for?
Question: I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`? Here is the code: ``` public List<Bike> addBikes() throws ClassNotFoundException, SQLException{ List<Bike> bikeList = new ArrayList<Bike>(); Class.forName("com.mysql.jdbc.Driver"); Connection con = null; Statement stm = null; ResultSet rs = null; con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ; stm=con.createStatement(); String qry="Select * from bike"; rs=stm.executeQuery(qry); while(rs.next()) { /* I need to put * rs.getString("name"),rs.getString("model") * etc into any of the suitable collection objects * and then need to add those to the ArrayList - bikeList * */ } return bikeList; } ``` Answer:
For each result in the result set, create a `new Bike()` and copy the values from that result to the new bikes fields. At the end, add the bike to the list. ``` Bike bike = new Bike() bike.setName(rs.getString("name")); //... bikeList.add(bike); ```
You have Banana in your hand..just eat it :) Create a empty list and in iteration Create new Bike and add into the List. ``` List<Bike> bikes = new ArrayList<Bikes>(); while(rs.next()) { Bike bike = new Bike(); bike.setname( rs.getString("name")); //other properties bikes.add(bike); } return bikes; ```
Question: I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`? Here is the code: ``` public List<Bike> addBikes() throws ClassNotFoundException, SQLException{ List<Bike> bikeList = new ArrayList<Bike>(); Class.forName("com.mysql.jdbc.Driver"); Connection con = null; Statement stm = null; ResultSet rs = null; con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ; stm=con.createStatement(); String qry="Select * from bike"; rs=stm.executeQuery(qry); while(rs.next()) { /* I need to put * rs.getString("name"),rs.getString("model") * etc into any of the suitable collection objects * and then need to add those to the ArrayList - bikeList * */ } return bikeList; } ``` Answer:
For each result in the result set, create a `new Bike()` and copy the values from that result to the new bikes fields. At the end, add the bike to the list. ``` Bike bike = new Bike() bike.setName(rs.getString("name")); //... bikeList.add(bike); ```
``` while (rs.next()) { Bike bike = new Bike(); bike.setName(rs.getString("name")); bike.setModel(rs.getString("model")); bikeList.add(bike); } ```
Question: I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`? Here is the code: ``` public List<Bike> addBikes() throws ClassNotFoundException, SQLException{ List<Bike> bikeList = new ArrayList<Bike>(); Class.forName("com.mysql.jdbc.Driver"); Connection con = null; Statement stm = null; ResultSet rs = null; con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ; stm=con.createStatement(); String qry="Select * from bike"; rs=stm.executeQuery(qry); while(rs.next()) { /* I need to put * rs.getString("name"),rs.getString("model") * etc into any of the suitable collection objects * and then need to add those to the ArrayList - bikeList * */ } return bikeList; } ``` Answer:
For each result in the result set, create a `new Bike()` and copy the values from that result to the new bikes fields. At the end, add the bike to the list. ``` Bike bike = new Bike() bike.setName(rs.getString("name")); //... bikeList.add(bike); ```
I don't know how Your Bike class look like, but you should do it like this way: ``` while(rs.next()) { String column1 = rs.getString("column1_name"); .... and the others columns Bike bike = new Bike(); bike.setColumn1(column1); .... and others... bikeList.add(bike) } ```
Question: I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`? Here is the code: ``` public List<Bike> addBikes() throws ClassNotFoundException, SQLException{ List<Bike> bikeList = new ArrayList<Bike>(); Class.forName("com.mysql.jdbc.Driver"); Connection con = null; Statement stm = null; ResultSet rs = null; con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ; stm=con.createStatement(); String qry="Select * from bike"; rs=stm.executeQuery(qry); while(rs.next()) { /* I need to put * rs.getString("name"),rs.getString("model") * etc into any of the suitable collection objects * and then need to add those to the ArrayList - bikeList * */ } return bikeList; } ``` Answer:
For each result in the result set, create a `new Bike()` and copy the values from that result to the new bikes fields. At the end, add the bike to the list. ``` Bike bike = new Bike() bike.setName(rs.getString("name")); //... bikeList.add(bike); ```
You need to instantiate Bike in while loop and add to `List`. ``` List<Bike> bikes = new ArrayList<>(); while(rs.next()) { Bike bike = new Bike(); bike.setname( rs.getString("name")); //other properties bikes.add(bike); } return bikes; ```
Question: I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`? Here is the code: ``` public List<Bike> addBikes() throws ClassNotFoundException, SQLException{ List<Bike> bikeList = new ArrayList<Bike>(); Class.forName("com.mysql.jdbc.Driver"); Connection con = null; Statement stm = null; ResultSet rs = null; con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ; stm=con.createStatement(); String qry="Select * from bike"; rs=stm.executeQuery(qry); while(rs.next()) { /* I need to put * rs.getString("name"),rs.getString("model") * etc into any of the suitable collection objects * and then need to add those to the ArrayList - bikeList * */ } return bikeList; } ``` Answer:
you would instantiate a Bike object and set properties that you read from result set, then add the bike object to your arraylist, isnt it what you are looking for?
You need to instantiate Bike in while loop and add to `List`. ``` List<Bike> bikes = new ArrayList<>(); while(rs.next()) { Bike bike = new Bike(); bike.setname( rs.getString("name")); //other properties bikes.add(bike); } return bikes; ```
Question: I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`? Here is the code: ``` public List<Bike> addBikes() throws ClassNotFoundException, SQLException{ List<Bike> bikeList = new ArrayList<Bike>(); Class.forName("com.mysql.jdbc.Driver"); Connection con = null; Statement stm = null; ResultSet rs = null; con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ; stm=con.createStatement(); String qry="Select * from bike"; rs=stm.executeQuery(qry); while(rs.next()) { /* I need to put * rs.getString("name"),rs.getString("model") * etc into any of the suitable collection objects * and then need to add those to the ArrayList - bikeList * */ } return bikeList; } ``` Answer:
You have Banana in your hand..just eat it :) Create a empty list and in iteration Create new Bike and add into the List. ``` List<Bike> bikes = new ArrayList<Bikes>(); while(rs.next()) { Bike bike = new Bike(); bike.setname( rs.getString("name")); //other properties bikes.add(bike); } return bikes; ```
You need to instantiate Bike in while loop and add to `List`. ``` List<Bike> bikes = new ArrayList<>(); while(rs.next()) { Bike bike = new Bike(); bike.setname( rs.getString("name")); //other properties bikes.add(bike); } return bikes; ```
Question: I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`? Here is the code: ``` public List<Bike> addBikes() throws ClassNotFoundException, SQLException{ List<Bike> bikeList = new ArrayList<Bike>(); Class.forName("com.mysql.jdbc.Driver"); Connection con = null; Statement stm = null; ResultSet rs = null; con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ; stm=con.createStatement(); String qry="Select * from bike"; rs=stm.executeQuery(qry); while(rs.next()) { /* I need to put * rs.getString("name"),rs.getString("model") * etc into any of the suitable collection objects * and then need to add those to the ArrayList - bikeList * */ } return bikeList; } ``` Answer:
``` while (rs.next()) { Bike bike = new Bike(); bike.setName(rs.getString("name")); bike.setModel(rs.getString("model")); bikeList.add(bike); } ```
You need to instantiate Bike in while loop and add to `List`. ``` List<Bike> bikes = new ArrayList<>(); while(rs.next()) { Bike bike = new Bike(); bike.setname( rs.getString("name")); //other properties bikes.add(bike); } return bikes; ```
Question: I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`? Here is the code: ``` public List<Bike> addBikes() throws ClassNotFoundException, SQLException{ List<Bike> bikeList = new ArrayList<Bike>(); Class.forName("com.mysql.jdbc.Driver"); Connection con = null; Statement stm = null; ResultSet rs = null; con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ; stm=con.createStatement(); String qry="Select * from bike"; rs=stm.executeQuery(qry); while(rs.next()) { /* I need to put * rs.getString("name"),rs.getString("model") * etc into any of the suitable collection objects * and then need to add those to the ArrayList - bikeList * */ } return bikeList; } ``` Answer:
I don't know how Your Bike class look like, but you should do it like this way: ``` while(rs.next()) { String column1 = rs.getString("column1_name"); .... and the others columns Bike bike = new Bike(); bike.setColumn1(column1); .... and others... bikeList.add(bike) } ```
You need to instantiate Bike in while loop and add to `List`. ``` List<Bike> bikes = new ArrayList<>(); while(rs.next()) { Bike bike = new Bike(); bike.setname( rs.getString("name")); //other properties bikes.add(bike); } return bikes; ```
Question: What is the best and/or fastest to learn Java API for consuming XML feeds like this: ``` <body copyright="Company"> <student id="1" fname="Anthony" lname="Hopkins"/> <student id="2" fname="John" lname="Anderson"/> <student id="3" fname="Will" lname="Smitherman"/> </body> ``` As you can see it provides all the data with attributes. Also, XML Feed data will be accessed using URLs with parameters specified in the query string. Thanks in advance guys. Answer:
Easiest way is to use JaxB to generate the Java classes for you. If you have a schema you use xjb tool that will create the classes and can let java do all the parsing without you needing to do anything. Look at <http://www.javaworld.com/javaworld/jw-06-2006/jw-0626-jaxb.html>
It depends on what you want to do with it but XStream might be the easiest way to import data from XML. This can produce a data structure to match your data.
Question: I'm trying to make a Greasemonkey script to hide a really annoying div, on a website, that pops up after a few seconds. Neither of these works: ``` $("#flyin").hide(); $(document).ready(function(){ $("#flyin").hide(); }); ``` I assume it's because the `#flyin` div is not created, yet. How do I tell jQuery to keep on looking for this div, maybe every n seconds, so I can hide it? When I try to hide a non js, regular old div that is always present on the page, it works. Answer:
There's [a utility for that (waitForKeyElements)](https://gist.github.com/2625891). Your **whole script** would simply be: ``` // ==UserScript== // @name _YOUR_SCRIPT_NAME // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js // @require https://gist.github.com/raw/2625891/waitForKeyElements.js // @grant GM_addStyle // ==/UserScript== /*- The @grant directive is needed to work around a design change introduced in GM 1.0. It restores the sandbox. */ waitForKeyElements ("#flyin", hideFlyin); function hideFlyin (jNode) { jNode.hide (); } ``` Or, if the node only appears once per page load and the pages are not wholly changed via AJAX, use: ``` //-- Unload after one run. waitForKeyElements ("#flyin", hideFlyin, true); ```
Try ``` (function () { var $el = $("#flyin").hide(); //the element is not already created if (!$el.length) { //create an interval to keep checking for the presents of the element var timer = setInterval(function () { var $el = $("#flyin").hide(); //if the element is already created, there is no need to keep running the timer so clear it if ($el.length) { clearInterval(timer); } }, 500); } })(); ```
Question: I'm a complete cooking newb. I saw on youtube the other day that you should cook steak in an oven before frying it. I think it makes it softer (not sure, please let me know). But anyway, I never used an oven in my entire life. And I looked inside the oven and there are no trays in there. So I went to the store and the only trays I saw in the cooking section were meant for "cookies" that you cook in the oven, and other things like that, muffins etc. But they never mentioned steak. So can I cook my steak on trays meant for deserts, or do I need to look for a tray meant for steaks? and should I even cook my steak in the oven in the first place? Answer:
To answer your question directly, if the method of cooking is what I think it is, the pan you use should be fine, even if it has a nonstick coating on it. You can read the second section to see if my assumption about your cooking method is correct. It's important that you don't use nonstick cookware for extremely high heat cooking. If the nonstick coating gets to the smoking point, it releases gases that are toxic enough (as a friend tragically learned) to kill pets. This includes pans that go in the oven, and on the stovetop. Since the temperature at which you're cooking the steak isn't that much hotter than you'd use baking cookies, it should be fine. If it does have a nonstick coating, you should not use it under a broiler, which is much hotter than just sitting in the oven while it bakes. --- Even though it's not exactly what you asked, since you don't seem to be super confident in what you're doing, I'll give you a little more info on what I believe is the technique you're trying to pull off. I think what you're referring to is the method of cooking where you cook a steak slowly in the oven until the internal doneness (rare, medium rare, etc.) is just how you like it, and then you give it a good hot sear in a pan so you form a flavorful crust on the outside. It's pretty intuitive when you consider the following: * Making sure steak (or chicken, or pork chops, or other quick-cooking cuts of meat) is cooked through simply involves getting it to the desired internal temperature. The more consistent the internal temperature throughout the meat, the more consistent the texture and juiciness. + The best way to control the overall internal temperature of the meat is to use gentler lower temperature methods of cooking so the inside has time to warm up before the outside gets overcooked. * Getting optimum flavor in a steak requires a nice sear/crust on the meat. + The best way to get a nice crust on your steak is to add a decent amount of salt, and use a high-heat cooking method to trigger the Maillard reaction (what's happening chemically when browning occurs) and perhaps some charring. You can see where the conflict lies between these two needs. Using the method you read about, you can use the oven to gently bring it up to temperature so it's consistently cooked inside, and then you can use a pan (which does not have a nonstick coating) to give it a nice hot sear after it comes out of the oven. It is easy to overcook steak if you're not particularly experienced, especially using more complicated dual-cook methods. Nobody wants to eat a tough, dry mess. Though it's tempting to rely on cooking times you find on the internet, **time is usually the least precise method to determine how cooked something is.** I highly recommend using an instant-read thermometer to check the actual temperature inside.
The method I think you are referring to is called "reverse sear". When I do a reverse sear, I use a standard [wire rack](http://dailydecor.foodiefriendsfridaydailydish.com/wp-content/uploads/2015/04/30b0052baa76.jpg) on top of a foil covered baking sheet. I'm not sure precisely what you mean by a dessert tray - but you probably want something (like a wire rack) that allows airflow on all sides, including the bottom. IMO the [Serious Eats guide](https://www.seriouseats.com/2017/03/how-to-reverse-sear-best-way-to-cook-steak.html) is great, it got me started using this method. Edit(3) to add: the big advantage of the reverse sear is that you can control the cooking process more precisely and get a steak that's seared on the outside, but not overcooked on the inside. Similar to Cooking Sous Vide then searing, but without the expense/clutter of a SV cooker. As SomeInterwebDev points out, you definitely want to be cooking to an internal temp, not by time to get a good result here.
Question: I have two strings. ``` str_a = "the_quick_brown_fox" str_b = "the_quick_red_fox" ``` I want to find the first index at which the two strings differ (i.e. `str_a[i] != str_b[i]`). I know I could solve this with something like the following: ``` def diff_char_index(str_a, str_b) arr_a, arr_b = str_a.split(""), str_b.split("") return -1 unless valid_string?(str_a) && valid_string?(str_b) arr_a.each_index do |i| return i unless arr_a[i] == arr_b[i] end end def valid_string?(str) return false unless str.is_a?(String) return false unless str.size > 0 true end diff_char_index(str_a, str_b) # => 10 ``` Is there a better way to do this? Answer:
Something like this ought to work: ``` str_a.each_char.with_index .find_index {|char, idx| char != str_b[idx] } || str_a.size ``` **Edit:** It works: <http://ideone.com/Ttwu1x> **Edit 2:** My original code returned `nil` if `str_a` was shorter than `str_b`. I've updated it to work correctly (it will return `str_a.size`, so if e.g. the last index in `str_a` is 3, it will return 4). Here's another method that may strike some as slightly simpler: ``` (0...str_a.size).find {|i| str_a[i] != str_b[i] } || str_a.size ``` <http://ideone.com/275cEU>
``` i = 0 i += 1 while str_a[i] and str_a[i] == str_b[i] i ```
Question: I have two strings. ``` str_a = "the_quick_brown_fox" str_b = "the_quick_red_fox" ``` I want to find the first index at which the two strings differ (i.e. `str_a[i] != str_b[i]`). I know I could solve this with something like the following: ``` def diff_char_index(str_a, str_b) arr_a, arr_b = str_a.split(""), str_b.split("") return -1 unless valid_string?(str_a) && valid_string?(str_b) arr_a.each_index do |i| return i unless arr_a[i] == arr_b[i] end end def valid_string?(str) return false unless str.is_a?(String) return false unless str.size > 0 true end diff_char_index(str_a, str_b) # => 10 ``` Is there a better way to do this? Answer:
Something like this ought to work: ``` str_a.each_char.with_index .find_index {|char, idx| char != str_b[idx] } || str_a.size ``` **Edit:** It works: <http://ideone.com/Ttwu1x> **Edit 2:** My original code returned `nil` if `str_a` was shorter than `str_b`. I've updated it to work correctly (it will return `str_a.size`, so if e.g. the last index in `str_a` is 3, it will return 4). Here's another method that may strike some as slightly simpler: ``` (0...str_a.size).find {|i| str_a[i] != str_b[i] } || str_a.size ``` <http://ideone.com/275cEU>
This uses a binary search to find the index where a slice of `str_a` no longer occurs at the beginning of `str_b`: ``` (0..str_a.length).bsearch { |i| str_b.rindex(str_a[0..i]) != 0 } ```
Question: I have two strings. ``` str_a = "the_quick_brown_fox" str_b = "the_quick_red_fox" ``` I want to find the first index at which the two strings differ (i.e. `str_a[i] != str_b[i]`). I know I could solve this with something like the following: ``` def diff_char_index(str_a, str_b) arr_a, arr_b = str_a.split(""), str_b.split("") return -1 unless valid_string?(str_a) && valid_string?(str_b) arr_a.each_index do |i| return i unless arr_a[i] == arr_b[i] end end def valid_string?(str) return false unless str.is_a?(String) return false unless str.size > 0 true end diff_char_index(str_a, str_b) # => 10 ``` Is there a better way to do this? Answer:
Something like this ought to work: ``` str_a.each_char.with_index .find_index {|char, idx| char != str_b[idx] } || str_a.size ``` **Edit:** It works: <http://ideone.com/Ttwu1x> **Edit 2:** My original code returned `nil` if `str_a` was shorter than `str_b`. I've updated it to work correctly (it will return `str_a.size`, so if e.g. the last index in `str_a` is 3, it will return 4). Here's another method that may strike some as slightly simpler: ``` (0...str_a.size).find {|i| str_a[i] != str_b[i] } || str_a.size ``` <http://ideone.com/275cEU>
``` str_a = "the_quick_brown_dog" str_b = "the_quick_red_dog" (0..(1.0)/0).find { |i| (str_a[i] != str_b[i]) || str_a[i].nil? } #=> 10 str_a = "the_quick_brown_dog" str_b = "the_quick_brown_dog" (0..(1.0)/0).find { |i| (str_a[i] != str_b[i]) || str_a[i].nil? } #=> 19 str_a.size #=> 19 ```
Question: I have two strings. ``` str_a = "the_quick_brown_fox" str_b = "the_quick_red_fox" ``` I want to find the first index at which the two strings differ (i.e. `str_a[i] != str_b[i]`). I know I could solve this with something like the following: ``` def diff_char_index(str_a, str_b) arr_a, arr_b = str_a.split(""), str_b.split("") return -1 unless valid_string?(str_a) && valid_string?(str_b) arr_a.each_index do |i| return i unless arr_a[i] == arr_b[i] end end def valid_string?(str) return false unless str.is_a?(String) return false unless str.size > 0 true end diff_char_index(str_a, str_b) # => 10 ``` Is there a better way to do this? Answer:
``` i = 0 i += 1 while str_a[i] and str_a[i] == str_b[i] i ```
This uses a binary search to find the index where a slice of `str_a` no longer occurs at the beginning of `str_b`: ``` (0..str_a.length).bsearch { |i| str_b.rindex(str_a[0..i]) != 0 } ```
Question: I have two strings. ``` str_a = "the_quick_brown_fox" str_b = "the_quick_red_fox" ``` I want to find the first index at which the two strings differ (i.e. `str_a[i] != str_b[i]`). I know I could solve this with something like the following: ``` def diff_char_index(str_a, str_b) arr_a, arr_b = str_a.split(""), str_b.split("") return -1 unless valid_string?(str_a) && valid_string?(str_b) arr_a.each_index do |i| return i unless arr_a[i] == arr_b[i] end end def valid_string?(str) return false unless str.is_a?(String) return false unless str.size > 0 true end diff_char_index(str_a, str_b) # => 10 ``` Is there a better way to do this? Answer:
``` str_a = "the_quick_brown_dog" str_b = "the_quick_red_dog" (0..(1.0)/0).find { |i| (str_a[i] != str_b[i]) || str_a[i].nil? } #=> 10 str_a = "the_quick_brown_dog" str_b = "the_quick_brown_dog" (0..(1.0)/0).find { |i| (str_a[i] != str_b[i]) || str_a[i].nil? } #=> 19 str_a.size #=> 19 ```
This uses a binary search to find the index where a slice of `str_a` no longer occurs at the beginning of `str_b`: ``` (0..str_a.length).bsearch { |i| str_b.rindex(str_a[0..i]) != 0 } ```
Question: So this question... <https://serverfault.com/questions/45734/the-coolest-server-names> It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community). I understand that it's being kept around for its historical significance, but it's not this site's history. It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots. Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end? The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. Answer:
I've certainly done my bit to try and get rid of that question, as well as similar ones, but the system is against us. If Jeff brought it back from the dead I'd love to hear his reasoning for doing so. The only reasoning I can think of is that it brings traffic due to Google and traffic translates to revenue and revenue is the reason Stack Exchange exists. That question is part of the history of SF only in the sense of being a great example of what NOT to post. Rather than adding value it merely detracts from SF and on at least one occasion I've seen it referenced as an excuse to post an off-topic question ("if they can do it why can't I?").
Send it back from whence it came.
Question: So this question... <https://serverfault.com/questions/45734/the-coolest-server-names> It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community). I understand that it's being kept around for its historical significance, but it's not this site's history. It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots. Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end? The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. Answer:
Hear ye, hear ye, hear ye, -------------------------- Three days have passed. Since then: * 30% of our >10K users have voted to delete that question, independent of the vote going on here. * 22 upvotes for sun-based disposal * 4 upvotes for 'send it back from whence it came' * Showers of hate upon 'Leave it'. Based upon this, the question will be ritually tossed into the sun. Which is cranky today, so it is fitting. It is gone. ![Record of destruction](https://i.stack.imgur.com/3jY0B.png)
Leave it, just keep it locked down.
Question: So this question... <https://serverfault.com/questions/45734/the-coolest-server-names> It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community). I understand that it's being kept around for its historical significance, but it's not this site's history. It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots. Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end? The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. Answer:
Throw this question into the sun.
Hear ye, hear ye, hear ye, -------------------------- Three days have passed. Since then: * 30% of our >10K users have voted to delete that question, independent of the vote going on here. * 22 upvotes for sun-based disposal * 4 upvotes for 'send it back from whence it came' * Showers of hate upon 'Leave it'. Based upon this, the question will be ritually tossed into the sun. Which is cranky today, so it is fitting. It is gone. ![Record of destruction](https://i.stack.imgur.com/3jY0B.png)
Question: So this question... <https://serverfault.com/questions/45734/the-coolest-server-names> It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community). I understand that it's being kept around for its historical significance, but it's not this site's history. It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots. Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end? The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. Answer:
It needs to be burniated. It adds nothing to the site. It was a "fun" question once upon a time *maybe* but we've moved on from that. Perhaps it should be locked while its fate is being debated?
Send it back from whence it came.
Question: So this question... <https://serverfault.com/questions/45734/the-coolest-server-names> It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community). I understand that it's being kept around for its historical significance, but it's not this site's history. It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots. Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end? The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. Answer:
Throw this question into the sun.
If it were my choice, I'd just hit the delete button on it here and be done with it. Yes, by today's rules it is off topic both here and on Stack Overflow. I don't feel it adds *any* useful information to this site, or any on the Stack Exchange network. It goes no way towards the Stack Exchange mission of "make the internet better" and as such should simply be obliterated. I'd like to think we've all become much less tolerant of crap since December '10 when it was resurrected, and I'd hope everyone else would also agree. There has been a very visible onslaught against bad questions that don't add value to the internet, and to me this is one of them. Hey, it was practically Christmas - maybe Jeff had a few drinks and was feeling generous? :-)
Question: So this question... <https://serverfault.com/questions/45734/the-coolest-server-names> It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community). I understand that it's being kept around for its historical significance, but it's not this site's history. It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots. Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end? The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. Answer:
Throw this question into the sun.
I've certainly done my bit to try and get rid of that question, as well as similar ones, but the system is against us. If Jeff brought it back from the dead I'd love to hear his reasoning for doing so. The only reasoning I can think of is that it brings traffic due to Google and traffic translates to revenue and revenue is the reason Stack Exchange exists. That question is part of the history of SF only in the sense of being a great example of what NOT to post. Rather than adding value it merely detracts from SF and on at least one occasion I've seen it referenced as an excuse to post an off-topic question ("if they can do it why can't I?").
Question: So this question... <https://serverfault.com/questions/45734/the-coolest-server-names> It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community). I understand that it's being kept around for its historical significance, but it's not this site's history. It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots. Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end? The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. Answer:
Send it back from whence it came.
Leave it, just keep it locked down.
Question: So this question... <https://serverfault.com/questions/45734/the-coolest-server-names> It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community). I understand that it's being kept around for its historical significance, but it's not this site's history. It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots. Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end? The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. Answer:
Hear ye, hear ye, hear ye, -------------------------- Three days have passed. Since then: * 30% of our >10K users have voted to delete that question, independent of the vote going on here. * 22 upvotes for sun-based disposal * 4 upvotes for 'send it back from whence it came' * Showers of hate upon 'Leave it'. Based upon this, the question will be ritually tossed into the sun. Which is cranky today, so it is fitting. It is gone. ![Record of destruction](https://i.stack.imgur.com/3jY0B.png)
It needs to be burniated. It adds nothing to the site. It was a "fun" question once upon a time *maybe* but we've moved on from that. Perhaps it should be locked while its fate is being debated?
Question: So this question... <https://serverfault.com/questions/45734/the-coolest-server-names> It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community). I understand that it's being kept around for its historical significance, but it's not this site's history. It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots. Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end? The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. Answer:
Hear ye, hear ye, hear ye, -------------------------- Three days have passed. Since then: * 30% of our >10K users have voted to delete that question, independent of the vote going on here. * 22 upvotes for sun-based disposal * 4 upvotes for 'send it back from whence it came' * Showers of hate upon 'Leave it'. Based upon this, the question will be ritually tossed into the sun. Which is cranky today, so it is fitting. It is gone. ![Record of destruction](https://i.stack.imgur.com/3jY0B.png)
I've certainly done my bit to try and get rid of that question, as well as similar ones, but the system is against us. If Jeff brought it back from the dead I'd love to hear his reasoning for doing so. The only reasoning I can think of is that it brings traffic due to Google and traffic translates to revenue and revenue is the reason Stack Exchange exists. That question is part of the history of SF only in the sense of being a great example of what NOT to post. Rather than adding value it merely detracts from SF and on at least one occasion I've seen it referenced as an excuse to post an off-topic question ("if they can do it why can't I?").
Question: So this question... <https://serverfault.com/questions/45734/the-coolest-server-names> It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community). I understand that it's being kept around for its historical significance, but it's not this site's history. It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots. Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end? The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. Answer:
It needs to be burniated. It adds nothing to the site. It was a "fun" question once upon a time *maybe* but we've moved on from that. Perhaps it should be locked while its fate is being debated?
Leave it, just keep it locked down.
Question: I have a 40 gallon (bladdered) pressure tank in the basement which keeps pressure to my office building, and a 2-inch 2 horsepower submersible pump in a dug well 450 feet away. The pump is cycling waaay too fast, and the tank will hold pressure at 41 pounds to 43 pounds but not at 60 pounds at shut-off pressure. (The pump comes on at 40 and shuts off at 60). It only takes 6 seconds for the pump to come on and shut off and I fear I will cook the pump if this keeps up. I have recently tested the pressure in the tank and it is 50 pounds. Does this mean the bladder leaked and caused pressure to increase in the tank? I know the tank pressure should be set at around 39, or a little below the 'turn-on' pressure. Could this be the cause of the short cycle? Answer:
The bladder is there to flatten the pressure/volume curve so pressure doesn't change rapidly as water is pumped. This allows for a longer duty cycle. The expected symptom of a burst bladder is just as you describe.
It needs air. Get hold of an air compressor and give it a charge. Be sure to be running water while charging, and the pump is off. Easy. If you need to do this more than once a year there might be a problem with the bladder.
Question: I am creating a BitSet with a fixed number of bits. In this case the length of my String holding the binary representation is 508 characters long. So I create BitSet the following way: ``` BitSet bs = new BitSet(binary.length()); // binary.length() = 508 ``` But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end. Maybe there is some misunderstanding of the following documentation: > > **BitSet(int nbits)** > > > Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. > > > Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger? Answer:
The number of bits in the constructor is a sizing hint, not a limit on the number of bits allowed. The `size()` of a Bitset is effectively its current *capacity*, though the specification is rather more rubbery than that. > > So I can't rely on the size if I get passed another bitset? There may also be some bits appended or it can be longer than "expected" ? > > > Correct, and yes. If you want the logical size (i.e. the highest bit index that is set) use the `length()` method, not the `size()` method. > > If length() gives me the highest bit set, this can't help in every situation. Because "my" highest bit on position 508 can also be 0. > > > In this case "set" means "set to 1 / true". So if your highest bit (at position 508) is a zero, the `length()` will be less than 508. I'm not sure if that will help. But if you have a concept of a highest bit position that is defined then you need to represent that position as a separate value. A Bitset is actually modelled as a potentially infinite array of bits which is default initialized to all zeros. (That's why there is no "flip the entire Bitset" operation. It would use a huge amount of storage.)
According to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html), the actual size in memory is implementation dependent, so you can't really know for sure what `size()` you're going to get. You as a user shouldn't have to worry about it, though, because the `length()` of the BitSet is always accurate - even if the size in memory is larger, it returns the number of bits actually in use. Since the BitSet can automatically grow to accomodate any data added to it, I wouldn't be surprised if it uses a growth strategy that's similar to lists, which tend to use increasing powers of two. But as said, that fact is an implementation detail, and it might not be the same everywhere and every time.
Question: I am creating a BitSet with a fixed number of bits. In this case the length of my String holding the binary representation is 508 characters long. So I create BitSet the following way: ``` BitSet bs = new BitSet(binary.length()); // binary.length() = 508 ``` But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end. Maybe there is some misunderstanding of the following documentation: > > **BitSet(int nbits)** > > > Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. > > > Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger? Answer:
The number of bits in the constructor is a sizing hint, not a limit on the number of bits allowed. The `size()` of a Bitset is effectively its current *capacity*, though the specification is rather more rubbery than that. > > So I can't rely on the size if I get passed another bitset? There may also be some bits appended or it can be longer than "expected" ? > > > Correct, and yes. If you want the logical size (i.e. the highest bit index that is set) use the `length()` method, not the `size()` method. > > If length() gives me the highest bit set, this can't help in every situation. Because "my" highest bit on position 508 can also be 0. > > > In this case "set" means "set to 1 / true". So if your highest bit (at position 508) is a zero, the `length()` will be less than 508. I'm not sure if that will help. But if you have a concept of a highest bit position that is defined then you need to represent that position as a separate value. A Bitset is actually modelled as a potentially infinite array of bits which is default initialized to all zeros. (That's why there is no "flip the entire Bitset" operation. It would use a huge amount of storage.)
That's just a hint for a collection (this applies to all collections I think) so it don't have to resize itself after adding elements. For instance, if you know that your collection will hold 100 elements at maximum, you can set it's size to 100 and no resize will be made which is better for performance.
Question: I am creating a BitSet with a fixed number of bits. In this case the length of my String holding the binary representation is 508 characters long. So I create BitSet the following way: ``` BitSet bs = new BitSet(binary.length()); // binary.length() = 508 ``` But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end. Maybe there is some misunderstanding of the following documentation: > > **BitSet(int nbits)** > > > Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. > > > Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger? Answer:
The number of bits in the constructor is a sizing hint, not a limit on the number of bits allowed. The `size()` of a Bitset is effectively its current *capacity*, though the specification is rather more rubbery than that. > > So I can't rely on the size if I get passed another bitset? There may also be some bits appended or it can be longer than "expected" ? > > > Correct, and yes. If you want the logical size (i.e. the highest bit index that is set) use the `length()` method, not the `size()` method. > > If length() gives me the highest bit set, this can't help in every situation. Because "my" highest bit on position 508 can also be 0. > > > In this case "set" means "set to 1 / true". So if your highest bit (at position 508) is a zero, the `length()` will be less than 508. I'm not sure if that will help. But if you have a concept of a highest bit position that is defined then you need to represent that position as a separate value. A Bitset is actually modelled as a potentially infinite array of bits which is default initialized to all zeros. (That's why there is no "flip the entire Bitset" operation. It would use a huge amount of storage.)
The BitSet size will be set to the first multiple of 64 that is equal to or greater than the number you use for 'size'. If you specify a 'size' of 508, you will get a BitSet with an actual size of 512, which is the next highest multiple of 64.
Question: I am creating a BitSet with a fixed number of bits. In this case the length of my String holding the binary representation is 508 characters long. So I create BitSet the following way: ``` BitSet bs = new BitSet(binary.length()); // binary.length() = 508 ``` But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end. Maybe there is some misunderstanding of the following documentation: > > **BitSet(int nbits)** > > > Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. > > > Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger? Answer:
According to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html), the actual size in memory is implementation dependent, so you can't really know for sure what `size()` you're going to get. You as a user shouldn't have to worry about it, though, because the `length()` of the BitSet is always accurate - even if the size in memory is larger, it returns the number of bits actually in use. Since the BitSet can automatically grow to accomodate any data added to it, I wouldn't be surprised if it uses a growth strategy that's similar to lists, which tend to use increasing powers of two. But as said, that fact is an implementation detail, and it might not be the same everywhere and every time.
That's just a hint for a collection (this applies to all collections I think) so it don't have to resize itself after adding elements. For instance, if you know that your collection will hold 100 elements at maximum, you can set it's size to 100 and no resize will be made which is better for performance.
Question: I am creating a BitSet with a fixed number of bits. In this case the length of my String holding the binary representation is 508 characters long. So I create BitSet the following way: ``` BitSet bs = new BitSet(binary.length()); // binary.length() = 508 ``` But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end. Maybe there is some misunderstanding of the following documentation: > > **BitSet(int nbits)** > > > Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. > > > Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger? Answer:
According to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html), the actual size in memory is implementation dependent, so you can't really know for sure what `size()` you're going to get. You as a user shouldn't have to worry about it, though, because the `length()` of the BitSet is always accurate - even if the size in memory is larger, it returns the number of bits actually in use. Since the BitSet can automatically grow to accomodate any data added to it, I wouldn't be surprised if it uses a growth strategy that's similar to lists, which tend to use increasing powers of two. But as said, that fact is an implementation detail, and it might not be the same everywhere and every time.
The BitSet size will be set to the first multiple of 64 that is equal to or greater than the number you use for 'size'. If you specify a 'size' of 508, you will get a BitSet with an actual size of 512, which is the next highest multiple of 64.
Question: I tried to look in other solutions. But it didn't help me out. Kindly look into this. my html code. ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %} <form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` my views.py and urls.py code ``` def delete_data(request,id): if request.method == 'POST': pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') urlpatterns=[ re_path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ``` Answer:
You are using `re_path` like it is `path`. `re_path` expects regex, it does not have path converters like `path`. You can either write a regex or switch to `path`. Regex solution: ``` urlpatterns=[ re_path(r'delete/(?P<pk>\d+)/',views.delete_data,name="deletedata") ] ``` path solution: ``` from django.urls import path urlpatterns=[ path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ``` **Edit:** Also in your view you have named your parameter as **id**, all captured arguments from the url pattern are passed as keyword arguments, ensure that your naming is **consistent** in your pattern, view, template. Change your view definition (and all usages of the variable in the view function to **pk**) to: ``` def delete_data(request, pk): ```
Try this In the template, you have used pk change in the template or in view and url ``` urlpatterns=[ re_path('<int:pk>/',views.update_data,name="deletedata") ] ``` Or ``` <form action="{% url 'deletedata' id = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> ```
Question: I tried to look in other solutions. But it didn't help me out. Kindly look into this. my html code. ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %} <form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` my views.py and urls.py code ``` def delete_data(request,id): if request.method == 'POST': pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') urlpatterns=[ re_path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ``` Answer:
Try this In the template, you have used pk change in the template or in view and url ``` urlpatterns=[ re_path('<int:pk>/',views.update_data,name="deletedata") ] ``` Or ``` <form action="{% url 'deletedata' id = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> ```
{% url 'deletedata' pk = st.id %} in thr URL just remove the spaces, bellow code it should work ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> <form action="{% url 'deletedata' pk=st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ```
Question: I tried to look in other solutions. But it didn't help me out. Kindly look into this. my html code. ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %} <form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` my views.py and urls.py code ``` def delete_data(request,id): if request.method == 'POST': pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') urlpatterns=[ re_path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ``` Answer:
Try this In the template, you have used pk change in the template or in view and url ``` urlpatterns=[ re_path('<int:pk>/',views.update_data,name="deletedata") ] ``` Or ``` <form action="{% url 'deletedata' id = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> ```
You can also write it with one a tag ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> <a href="{% url 'deletedata' pk=st.id %}" class="d-inline">Delete</a> <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` and then your views.py ``` def delete_data(request,id): pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') ``` Urls.py ``` urlpatterns=[ path('<int:pk>/',views.delete_data,name="deletedata") ] ```
Question: I tried to look in other solutions. But it didn't help me out. Kindly look into this. my html code. ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %} <form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` my views.py and urls.py code ``` def delete_data(request,id): if request.method == 'POST': pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') urlpatterns=[ re_path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ``` Answer:
You are using `re_path` like it is `path`. `re_path` expects regex, it does not have path converters like `path`. You can either write a regex or switch to `path`. Regex solution: ``` urlpatterns=[ re_path(r'delete/(?P<pk>\d+)/',views.delete_data,name="deletedata") ] ``` path solution: ``` from django.urls import path urlpatterns=[ path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ``` **Edit:** Also in your view you have named your parameter as **id**, all captured arguments from the url pattern are passed as keyword arguments, ensure that your naming is **consistent** in your pattern, view, template. Change your view definition (and all usages of the variable in the view function to **pk**) to: ``` def delete_data(request, pk): ```
{% url 'deletedata' pk = st.id %} in thr URL just remove the spaces, bellow code it should work ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> <form action="{% url 'deletedata' pk=st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ```
Question: I tried to look in other solutions. But it didn't help me out. Kindly look into this. my html code. ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %} <form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` my views.py and urls.py code ``` def delete_data(request,id): if request.method == 'POST': pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') urlpatterns=[ re_path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ``` Answer:
You are using `re_path` like it is `path`. `re_path` expects regex, it does not have path converters like `path`. You can either write a regex or switch to `path`. Regex solution: ``` urlpatterns=[ re_path(r'delete/(?P<pk>\d+)/',views.delete_data,name="deletedata") ] ``` path solution: ``` from django.urls import path urlpatterns=[ path('delete/<int:pk>/',views.delete_data,name="deletedata") ] ``` **Edit:** Also in your view you have named your parameter as **id**, all captured arguments from the url pattern are passed as keyword arguments, ensure that your naming is **consistent** in your pattern, view, template. Change your view definition (and all usages of the variable in the view function to **pk**) to: ``` def delete_data(request, pk): ```
You can also write it with one a tag ``` <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> <a href="{% url 'deletedata' pk=st.id %}" class="d-inline">Delete</a> <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> ``` and then your views.py ``` def delete_data(request,id): pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') ``` Urls.py ``` urlpatterns=[ path('<int:pk>/',views.delete_data,name="deletedata") ] ```
Question: You know how PHP's `isset()` can accept multiple (no limit either) arguments? Like I can do: ``` isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc ``` How would I be able to do that in my own function? How would I be able to work with infinity arguments passed? How do they do it? Answer:
You can use `func_get_args()`, it will return an array of arguments. ``` function work_with_arguments() { echo implode(", ", func_get_args()); } work_with_arguments("Hello", "World"); //Outputs: Hello, World ```
Calling `[func\_get\_args()](http://php.net/manual/en/function.func-get-args.php)` inside of your function will return an array of the arguments passed to PHP.
Question: You know how PHP's `isset()` can accept multiple (no limit either) arguments? Like I can do: ``` isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc ``` How would I be able to do that in my own function? How would I be able to work with infinity arguments passed? How do they do it? Answer:
[`func_get_args`](http://php.net/manual/en/function.func-get-args.php) will do what you want: ``` function infinite_parameters() { foreach (func_get_args() as $param) { echo "Param is $param" . PHP_EOL; } } ``` You can also use `func_get_arg` to get a specific parameter (it's zero-indexed): ``` function infinite_parameters() { echo func_get_arg(2); } ``` But be careful to check that you have that parameter: ``` function infinite_parameters() { if (func_num_args() < 3) { throw new BadFunctionCallException("Not enough parameters!"); } } ``` You can even mix together `func_*_arg` and regular parameters: ``` function foo($param1, $param2) { echo $param1; // Works as normal echo func_get_arg(0); // Gets $param1 if (func_num_args() >= 3) { echo func_get_arg(2); } } ``` But before using it, think about whether you *really* want to have indefinite parameters. Would an array not suffice?
You can use `func_get_args()`, it will return an array of arguments. ``` function work_with_arguments() { echo implode(", ", func_get_args()); } work_with_arguments("Hello", "World"); //Outputs: Hello, World ```
Question: You know how PHP's `isset()` can accept multiple (no limit either) arguments? Like I can do: ``` isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc ``` How would I be able to do that in my own function? How would I be able to work with infinity arguments passed? How do they do it? Answer:
Starting with PHP 5.6 you can use the token "**...**" Example: ``` <?php function sum(...$numbers) { $acc = 0; foreach ($numbers as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4); ?> ``` Source: <http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list>
You can use `func_get_args()`, it will return an array of arguments. ``` function work_with_arguments() { echo implode(", ", func_get_args()); } work_with_arguments("Hello", "World"); //Outputs: Hello, World ```
Question: You know how PHP's `isset()` can accept multiple (no limit either) arguments? Like I can do: ``` isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc ``` How would I be able to do that in my own function? How would I be able to work with infinity arguments passed? How do they do it? Answer:
[`func_get_args`](http://php.net/manual/en/function.func-get-args.php) will do what you want: ``` function infinite_parameters() { foreach (func_get_args() as $param) { echo "Param is $param" . PHP_EOL; } } ``` You can also use `func_get_arg` to get a specific parameter (it's zero-indexed): ``` function infinite_parameters() { echo func_get_arg(2); } ``` But be careful to check that you have that parameter: ``` function infinite_parameters() { if (func_num_args() < 3) { throw new BadFunctionCallException("Not enough parameters!"); } } ``` You can even mix together `func_*_arg` and regular parameters: ``` function foo($param1, $param2) { echo $param1; // Works as normal echo func_get_arg(0); // Gets $param1 if (func_num_args() >= 3) { echo func_get_arg(2); } } ``` But before using it, think about whether you *really* want to have indefinite parameters. Would an array not suffice?
Calling `[func\_get\_args()](http://php.net/manual/en/function.func-get-args.php)` inside of your function will return an array of the arguments passed to PHP.
Question: You know how PHP's `isset()` can accept multiple (no limit either) arguments? Like I can do: ``` isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc ``` How would I be able to do that in my own function? How would I be able to work with infinity arguments passed? How do they do it? Answer:
Starting with PHP 5.6 you can use the token "**...**" Example: ``` <?php function sum(...$numbers) { $acc = 0; foreach ($numbers as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4); ?> ``` Source: <http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list>
Calling `[func\_get\_args()](http://php.net/manual/en/function.func-get-args.php)` inside of your function will return an array of the arguments passed to PHP.
Question: You know how PHP's `isset()` can accept multiple (no limit either) arguments? Like I can do: ``` isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11); //etc etc ``` How would I be able to do that in my own function? How would I be able to work with infinity arguments passed? How do they do it? Answer:
[`func_get_args`](http://php.net/manual/en/function.func-get-args.php) will do what you want: ``` function infinite_parameters() { foreach (func_get_args() as $param) { echo "Param is $param" . PHP_EOL; } } ``` You can also use `func_get_arg` to get a specific parameter (it's zero-indexed): ``` function infinite_parameters() { echo func_get_arg(2); } ``` But be careful to check that you have that parameter: ``` function infinite_parameters() { if (func_num_args() < 3) { throw new BadFunctionCallException("Not enough parameters!"); } } ``` You can even mix together `func_*_arg` and regular parameters: ``` function foo($param1, $param2) { echo $param1; // Works as normal echo func_get_arg(0); // Gets $param1 if (func_num_args() >= 3) { echo func_get_arg(2); } } ``` But before using it, think about whether you *really* want to have indefinite parameters. Would an array not suffice?
Starting with PHP 5.6 you can use the token "**...**" Example: ``` <?php function sum(...$numbers) { $acc = 0; foreach ($numbers as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4); ?> ``` Source: <http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list>
Question: I've seen quite a few security camera examples and many have options for a duty schedule that activates the camera during certain specified days/hours to set up a routine. However I have fairly dynamic schedule and would like for my security cameras to turn on when our phones are not on the WiFi network. This would be an easy shortcut to "on when we're not home" and prevents it from taking intrusive pictures when we are. Is there a way to configure OpenCV or Motion, or to run a python script to activate a camera when our phones are off the WiFi network? I would like to take advantage of some features of the above software to email or stream footage, so I would like to avoid redesigning a system from the ground up to do this. Any advice? Thanks! Answer:
You'd need to know either the MAC or IP address of the phones you want to monitor but you could just `ping` or `arping` each one in turn and if none reply start your recording otherwise stop recording. Calling something like this from `cron` might do the trick: ``` #!/bin/bash # # Determine if we should be recording or not by pinging each phone in the list # and setting the variable to "NO" if any reply. If the variable is still "YES" # at the end we check if the recording process is running and start it if not. # LIST="192.168.123.25 192.168.123.56 192.168.123.13 MyPhone.local 192.168.123.78" RECORD_CMD="RecordingCommand" RECORD="YES" for HOST in $LIST; do ping -c1 "$HOST" &> /dev/null && RECORD="NO" done if [ "$RECORD" == "YES" ]; then # Start or continue recording? if [ $(pgrep -c "$RECORD_CMD") -eq 0 ]; then # Not currently recording so we need to start... "$RECORD_CMD" fi else # Stop recording... killall "$RECORD_CMD" fi exit 0 ```
Your question appears to be about ***activating*** and ***disabling*** the cameras when you are not able to connect to them directly when your phones are not on the same local subnet. So it seems to be about ***networking*** and access to control them, rather than the phones themselves that you reference. That's what I *believe* that I see here. Since the cameras are on an RFC 1918 non-routable address, when you're away from home you can't connect to 192.168.1.1 for example as it's *not routable across the Internet*. The solution is a VPN. Many routers now have this functionality as standard and make it easy to set up a VPN connection back to your home network just by adding a username and password for the VPN account and off you go. Once you connect to your home router via that VPN connection, you can now be connect to the cameras, switch, etc on their non-public IP addresses. With a VPN you'd just ssh into the Pi-Cam via it's local address and execute `sudo systemctl stop/start motion` and directly issue commands to control it. Further, with a VPN connection back to your home network, you will be able to view streams from the cameras directly on a web browser on your phone.
Question: I did some changes at my CoreData Model. So far, I added a attribute called 'language'. When my application is launched and I click on "Create new Customer" a instance variable Customer is created. This variable is created by: ``` Customer *newCustomer = [NSEntityDescription insertNewObjectForEntityForName:@"Customer" inManagedObjectContext:appDelegate.managedObjectContext]; ``` Before I did these changes everything worked fine and as planned. But now i get a dump with this error message:`reason = "The model used to open the store is incompatible with the one used to create the store";` What do I have to do to solve this? reseting the persistence store didn't help so far. Answer:
What I did to get around this problem was to add this > > [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]; > > > to my appDelegate in the persistentStoreCoordinator before adding the persistent store. This deletes the existing store that no longer is compatible with your data model. Remember to comment this line before you run the application the next time if you want to keep what is stored. My implementation of the persistentStoreCoordinator looks like this when I have to remove an old store. ``` - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (persistentStoreCoordinator_ != nil) { return persistentStoreCoordinator_; } NSError *error = nil; NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"MyPinballScore.sqlite"]]; //The following line removes your current store so that you can create a new one that is compatible with your new model [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]; persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return persistentStoreCoordinator_; ``` }
The answer is a bit tricky but this always works for me. This is for a **clean** installation of a new compatible .sqlite file, **not a migration**! launch simulator, delete the app and the data (the popup after you delete the app). quit simulator open X-Code, after making any edits to your data model delete the `{*appname*}.sqlite` file (or back it up, remove it from project folder, and delete reference) clean the app (`Product > Clean`) Run the app in a simulator (for this tutorial I will assume 4.2) While the simulator is running, in a Finder window, navigate to: `{*home*} > Library > Application Support > iPhone Simulator > 4.2 > Applications > {*random identifier*} > Documents > {*appname*}.sqlite` **Copy** this file to another location Stop running your app in X-Code Drag and drop the {*appname*}.sqlite file into the files list in X-Code. In the dialog that pops up, make sure the `copy to folder` checkbox, is checked. `Product > Clean` Then run the app in the simulator again Now you should have a working sqlite file! Cheers, Robert
Question: I have problem with dll file and have project which need this file System.Windows.Controls.dll for ``` listBox1.ItemsSource ``` error fix , and add reference with this dll to fix error. Where i can find this dll file? Is there any download link ? Share please ! Thanks ! In "Add Reference" it doesn't exist ! Solution: <http://download.microsoft.com/download/7/7/6/776875B7-AD81-44D4-AA47-648D1BCB097E/silverlight_sdk.exe> Answer:
Here are the steps: 1. Right click on `References` in the `Solutions Explorer` (Solutions explorer is on the right of your IDE) 2. Select `Add Reference` 3. In the window that opens, Select `Assemblies > Framework` 4. Check the `PresentationFramework` component box and click ok
This should be in the PresentationFramework.dll but that control is in the System.Windows.Controls namespace. <http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.aspx> You can add it by going to your project, Right clicking on References > Add Reference > .Net Tab > And selecting this DLL
Question: I have problem with dll file and have project which need this file System.Windows.Controls.dll for ``` listBox1.ItemsSource ``` error fix , and add reference with this dll to fix error. Where i can find this dll file? Is there any download link ? Share please ! Thanks ! In "Add Reference" it doesn't exist ! Solution: <http://download.microsoft.com/download/7/7/6/776875B7-AD81-44D4-AA47-648D1BCB097E/silverlight_sdk.exe> Answer:
This should be in the PresentationFramework.dll but that control is in the System.Windows.Controls namespace. <http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.aspx> You can add it by going to your project, Right clicking on References > Add Reference > .Net Tab > And selecting this DLL
I was able to find the dll file by searching my computer for "System.Windows.Controls.dll". I found it under the following file location... "C:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\System.Windows.Controls.dll" Hope this helps!
Question: I have problem with dll file and have project which need this file System.Windows.Controls.dll for ``` listBox1.ItemsSource ``` error fix , and add reference with this dll to fix error. Where i can find this dll file? Is there any download link ? Share please ! Thanks ! In "Add Reference" it doesn't exist ! Solution: <http://download.microsoft.com/download/7/7/6/776875B7-AD81-44D4-AA47-648D1BCB097E/silverlight_sdk.exe> Answer:
Here are the steps: 1. Right click on `References` in the `Solutions Explorer` (Solutions explorer is on the right of your IDE) 2. Select `Add Reference` 3. In the window that opens, Select `Assemblies > Framework` 4. Check the `PresentationFramework` component box and click ok
I was able to find the dll file by searching my computer for "System.Windows.Controls.dll". I found it under the following file location... "C:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\System.Windows.Controls.dll" Hope this helps!
Question: I am very new to CSS and javascript, so take it easy on me. I am trying to remove the class `disable-stream` from each of the div elements under the div class="stream-notifications". (See image, below) I have tried the following in Tampermonkey, but it doesn't seem to work: ``` (function() { 'use strict'; disable-stream.classList.remove("disable-stream");})(); ``` [![screen shot of page structure](https://i.stack.imgur.com/FNFGz.jpg)](https://i.stack.imgur.com/FNFGz.jpg) Answer:
``` var divs =document.getElementsByClassName("stream-notifications"); divs=Array.from(divs); divs.forEach(function(div){ div.classList.remove('disable-stream'); }); ```
Use something like this using jQuery ``` $(".disable-stream div").removeClass("disable-stream"); ``` [Plunker demo](https://plnkr.co/edit/hP4IyF64trUEjTmZpwBK?p=preview)
Question: I am very new to CSS and javascript, so take it easy on me. I am trying to remove the class `disable-stream` from each of the div elements under the div class="stream-notifications". (See image, below) I have tried the following in Tampermonkey, but it doesn't seem to work: ``` (function() { 'use strict'; disable-stream.classList.remove("disable-stream");})(); ``` [![screen shot of page structure](https://i.stack.imgur.com/FNFGz.jpg)](https://i.stack.imgur.com/FNFGz.jpg) Answer:
That looks to be an AJAX-driven web page, so you need to use AJAX-aware techniques to deal with it. EG [waitForKeyElements](https://gist.github.com/2625891), or `MutationObserver`, or similar. Here's **a complete script** that should work: ``` // ==UserScript== // @name _Remove a select class from nodes // @match *://app.hubspot.com/reports-dashboard/* // @match *://app.hubspot.com/sales-notifications-embedded/* // @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js // @require https://gist.github.com/raw/2625891/waitForKeyElements.js // @grant GM_addStyle // ==/UserScript== //- The @grant directive is needed to restore the proper sandbox. console.log ("Do you see this?"); waitForKeyElements (".disable-stream", removeDSclass); function removeDSclass (jNode) { console.log ("Cleaned node: ", jNode); jNode.removeClass ("disable-stream"); } ``` --- Note that there are two `@match` statements because the nodes, that the OP cared about, turned out to be in an iframe.
Use something like this using jQuery ``` $(".disable-stream div").removeClass("disable-stream"); ``` [Plunker demo](https://plnkr.co/edit/hP4IyF64trUEjTmZpwBK?p=preview)
Question: I am very new to CSS and javascript, so take it easy on me. I am trying to remove the class `disable-stream` from each of the div elements under the div class="stream-notifications". (See image, below) I have tried the following in Tampermonkey, but it doesn't seem to work: ``` (function() { 'use strict'; disable-stream.classList.remove("disable-stream");})(); ``` [![screen shot of page structure](https://i.stack.imgur.com/FNFGz.jpg)](https://i.stack.imgur.com/FNFGz.jpg) Answer:
That looks to be an AJAX-driven web page, so you need to use AJAX-aware techniques to deal with it. EG [waitForKeyElements](https://gist.github.com/2625891), or `MutationObserver`, or similar. Here's **a complete script** that should work: ``` // ==UserScript== // @name _Remove a select class from nodes // @match *://app.hubspot.com/reports-dashboard/* // @match *://app.hubspot.com/sales-notifications-embedded/* // @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js // @require https://gist.github.com/raw/2625891/waitForKeyElements.js // @grant GM_addStyle // ==/UserScript== //- The @grant directive is needed to restore the proper sandbox. console.log ("Do you see this?"); waitForKeyElements (".disable-stream", removeDSclass); function removeDSclass (jNode) { console.log ("Cleaned node: ", jNode); jNode.removeClass ("disable-stream"); } ``` --- Note that there are two `@match` statements because the nodes, that the OP cared about, turned out to be in an iframe.
``` var divs =document.getElementsByClassName("stream-notifications"); divs=Array.from(divs); divs.forEach(function(div){ div.classList.remove('disable-stream'); }); ```
Question: Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected? Answer:
It's very hacky, but I've done this by having an item selected, but making it look like it's not selected, by making the background temporarily transparent. When an item is then selected by the user, the secretly-selected item is deselected and the background restored to normal. Or, if it's the secretly-selected item which is selected (thus deselecting it), I reselect it, then set a boolean to stop it happening again. I also had to use a counter in onItemCheckedStateChanged, as I was changing the checked state of the secret item from within that callback, resulting in a loop. Probably not an ideal solution for all cases, but I don't think there's another way to do it at the moment, since [AbsListView can't easily be extended.](https://stackoverflow.com/questions/9637759/is-it-possible-to-extend-abslistview-to-make-new-listview-implementations) Edit: if the screen orientation changes while the selected state of the selected item is hidden, it will suddenly be shown as being selected, so you have to make sure to save the fact that it should be hidden, and restore it after the listview is recreated. I had to use the View post() method to ensure the restoration happened after the listview had finished redrawing all its child items after the configuration change. Edit: another potential issue is if the user tries to carry out an action while there are supposedly no items selected. As far as the application knows there *is* an item selected so it will carry out the action on that item, unless you make sure it doesn't.
You just have to use : ``` listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
Question: Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected? Answer:
Just call: ``` mListView.setItemChecked(-1, true); ``` ListView's actionMode will be started without selecting any list element. Make sure you've properly set your ListView before call: ``` mListView.setMultiChoiceModeListener( ... ) mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); or mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
You just have to use : ``` listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
Question: Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected? Answer:
It's very hacky, but I've done this by having an item selected, but making it look like it's not selected, by making the background temporarily transparent. When an item is then selected by the user, the secretly-selected item is deselected and the background restored to normal. Or, if it's the secretly-selected item which is selected (thus deselecting it), I reselect it, then set a boolean to stop it happening again. I also had to use a counter in onItemCheckedStateChanged, as I was changing the checked state of the secret item from within that callback, resulting in a loop. Probably not an ideal solution for all cases, but I don't think there's another way to do it at the moment, since [AbsListView can't easily be extended.](https://stackoverflow.com/questions/9637759/is-it-possible-to-extend-abslistview-to-make-new-listview-implementations) Edit: if the screen orientation changes while the selected state of the selected item is hidden, it will suddenly be shown as being selected, so you have to make sure to save the fact that it should be hidden, and restore it after the listview is recreated. I had to use the View post() method to ensure the restoration happened after the listview had finished redrawing all its child items after the configuration change. Edit: another potential issue is if the user tries to carry out an action while there are supposedly no items selected. As far as the application knows there *is* an item selected so it will carry out the action on that item, unless you make sure it doesn't.
If you want to change the action bar, call this from your activity: > > startActionMode(new ActionMode.Callback { > > > > ``` > @Override > public boolean onCreateActionMode(ActionMode mode, Menu menu) { > return false; > } > > @Override > public boolean onPrepareActionMode(ActionMode mode, Menu menu) { > return false; > } > > @Override > public void onDestroyActionMode(ActionMode mode) { > > } > > @Override > public boolean onActionItemClicked(ActionMode mode, MenuItem item) { > return false; > } > }); > > ``` > >
Question: Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected? Answer:
Just call: ``` mListView.setItemChecked(-1, true); ``` ListView's actionMode will be started without selecting any list element. Make sure you've properly set your ListView before call: ``` mListView.setMultiChoiceModeListener( ... ) mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); or mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
If you want to change the action bar, call this from your activity: > > startActionMode(new ActionMode.Callback { > > > > ``` > @Override > public boolean onCreateActionMode(ActionMode mode, Menu menu) { > return false; > } > > @Override > public boolean onPrepareActionMode(ActionMode mode, Menu menu) { > return false; > } > > @Override > public void onDestroyActionMode(ActionMode mode) { > > } > > @Override > public boolean onActionItemClicked(ActionMode mode, MenuItem item) { > return false; > } > }); > > ``` > >
Question: Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially. What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes). I've also tried this in other apps (gmail), and it works the same way. Is there a way to be in multi-select mode, with no items selected? Answer:
It's very hacky, but I've done this by having an item selected, but making it look like it's not selected, by making the background temporarily transparent. When an item is then selected by the user, the secretly-selected item is deselected and the background restored to normal. Or, if it's the secretly-selected item which is selected (thus deselecting it), I reselect it, then set a boolean to stop it happening again. I also had to use a counter in onItemCheckedStateChanged, as I was changing the checked state of the secret item from within that callback, resulting in a loop. Probably not an ideal solution for all cases, but I don't think there's another way to do it at the moment, since [AbsListView can't easily be extended.](https://stackoverflow.com/questions/9637759/is-it-possible-to-extend-abslistview-to-make-new-listview-implementations) Edit: if the screen orientation changes while the selected state of the selected item is hidden, it will suddenly be shown as being selected, so you have to make sure to save the fact that it should be hidden, and restore it after the listview is recreated. I had to use the View post() method to ensure the restoration happened after the listview had finished redrawing all its child items after the configuration change. Edit: another potential issue is if the user tries to carry out an action while there are supposedly no items selected. As far as the application knows there *is* an item selected so it will carry out the action on that item, unless you make sure it doesn't.
Just call: ``` mListView.setItemChecked(-1, true); ``` ListView's actionMode will be started without selecting any list element. Make sure you've properly set your ListView before call: ``` mListView.setMultiChoiceModeListener( ... ) mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); or mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); ```
Question: I have a solution with a C# project of 'library' and a project 'JavaScript' after that compiled it generates a .winmd file being taken to another project. But this project is built on x86 and I need to compile for x64, to run the application in order x64 get the following error: ``` 'WWAHost.exe' (Script): Loaded 'Script Code (MSAppHost/2.0)'. Unhandled exception at line 25, column 13 in ms-appx://2c341884-5957-41b1-bb32-10e13dd434ba/js/default.js 0x8007000b - JavaScript runtime error: An attempt was made to load a program with an incorrect format. System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance() WinRT information: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance() The program '[5776] WWAHost.exe' has exited with code -1 (0xffffffff). ``` Answer:
It looks like you were making calls with no Access Token at all, to data that's publicly visible on Facebook.com v1.0 of Facebook's Graph API was deprecated in April 2014 and scheduled for removal after 2015-04-30 - one of the changes between v1.0 and v2.0 was that in v2.0 all calls require an Access Token - the deprecation of v1.0 was phased and one of the last things to be removed was the ability to make tokenless calls - it's possible that's why you didn't notice this until recently More info on the changelog here: <https://developers.facebook.com/docs/apps/changelog#v2_0> - under "Changes from v1.0 to v2.0" You'll need to rewrite your app to make its API calls using an access token from a user who can see the content you're trying to create, or (possibly) using your app's access token (and given you had no token at all, you may also need to create an app ID for that purpose)
I finally realized that since May 1, it is **necessary** to create an app and then generate a token and use it in my JSON call URL. So this: ``` $.getJSON('https://graph.facebook.com/616894958361877/photos?limit=100&callback=? ``` Became this: ``` $.getJSON('https://graph.facebook.com/616894958361877/photos?access_token=123456789123456789|ajdkajdlajfldkeieflejejf&limit=100&callback=? ``` I've replaced my actual token with random numbers, but it's basically a giant string of numbers and letters with a pipe in the middle. For me the confusing part was needing an "app" when I'm not using a mobile device. I also didn't realize that Facebook had actually deprecated the old methond. Creating an app is simple... go here and follow the steps: <https://developers.facebook.com/apps/> Leave the "NameSpace" field blank... not sure what that is exactly and it's not required. Generating the token string took a few more steps which a friend from work walked me through... I can't remember off the top of my head, but once you get the string and insert it into your JSON call, it will definitely work. The REASON for this is so when Facebook receives a data request from some random website, the request comes with a built-in ID so Facebook knows who is asking for the data.
Question: I have a solution with a C# project of 'library' and a project 'JavaScript' after that compiled it generates a .winmd file being taken to another project. But this project is built on x86 and I need to compile for x64, to run the application in order x64 get the following error: ``` 'WWAHost.exe' (Script): Loaded 'Script Code (MSAppHost/2.0)'. Unhandled exception at line 25, column 13 in ms-appx://2c341884-5957-41b1-bb32-10e13dd434ba/js/default.js 0x8007000b - JavaScript runtime error: An attempt was made to load a program with an incorrect format. System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance() WinRT information: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance() The program '[5776] WWAHost.exe' has exited with code -1 (0xffffffff). ``` Answer:
It looks like you were making calls with no Access Token at all, to data that's publicly visible on Facebook.com v1.0 of Facebook's Graph API was deprecated in April 2014 and scheduled for removal after 2015-04-30 - one of the changes between v1.0 and v2.0 was that in v2.0 all calls require an Access Token - the deprecation of v1.0 was phased and one of the last things to be removed was the ability to make tokenless calls - it's possible that's why you didn't notice this until recently More info on the changelog here: <https://developers.facebook.com/docs/apps/changelog#v2_0> - under "Changes from v1.0 to v2.0" You'll need to rewrite your app to make its API calls using an access token from a user who can see the content you're trying to create, or (possibly) using your app's access token (and given you had no token at all, you may also need to create an app ID for that purpose)
You need an App Access Token. Go to <http://developers.facebook.com/apps/> and create an app for the client's Facebook page. When you're presented with the options, select the "Website" type of app. You can skip the configuration option using the "Skip and Create App ID" button in the top right corner. Give it a Display Name, don't worry about the Namespace, and give it a applicable category. Once the app is created, go to "Tools & Support" > "Access Token Tool" in the top menu. You should see an App Token listed in green text. Copy that into your JSON call, and it should work. ``` $.getJSON('https://graph.facebook.com/616894958361877/photos?access_token=PASTE_APP_TOKEN_HERE&limit=100&callback=?', function(json) { $.each(json.data, function(i, photo) { $('<li></li>').append('<span class="thumb" style="background: url(' + ((photo.images[1]) ? photo.images[1].source : '') + ') center center no-repeat; background-size: cover;"><a href=' + ((photo.images[0]) ? photo.images[0].source : '') + ' rel="gallery"></a></span>').appendTo('#timeline'); }); ``` });
Question: I am late game Alien Crossfire, attacking with gravitons aremed with [string disruptor](https://strategywiki.org/wiki/Sid_Meier%27s_Alpha_Centauri/Weapon#String_Disruptor). Unfortunately, the others have gotten wise and are building everything [AAA](https://strategywiki.org/wiki/Sid_Meier%27s_Alpha_Centauri/Special_Ability#AAA_Tracking). In a way, that's good, as it is expensive, and diverts their resources. However, I can no longer "one hit kill", and am losing gravitons. Should I replace the weapons with [Psi attack](https://strategywiki.org/wiki/Sid_Meier%27s_Alpha_Centauri/Weapon#Psi_Attack)? Answer:
Psi attack/defense is orthogonal to conventional weapons. Its result depends on *Morale* levels of attacking/defending units. If an attacker/defender is a *Mind Worm*, they have their own class, plus both faction's *Planet (Green)* scores/attitudes largely affect the outcome of the fight. **Answer:** see what's your faction's Morale and/or Green score. You may also trick the system by changing your *Government/Economy* type before the attack. Say, if you possess some *Mind Worms* and you are planning to give them a victorious ride, switch to *Green* several turns before the planned invasion. Or to *Fundamentalist + Power* if you are planning Psi attacks with conventional units. --- Personally, I *love* Green because if you are lucky enough, you can capture native life forms, making a considerable amount of your units Mind Worms **(Independent)** which means it requires no support from a home base, still performing as police in "at least one unit defending each Base" paradigm.
If you have dominant weapons, mixing in hovertanks and even air-dropped infantry will let you continue leveraging those dominant weapons. Psi-combat is mostly useful when facing technologically superior enemies that your weapons cannot defeat. Switching from overwhelming firepower to psi-attack will make you lose as many (if not more) units, since psi-combat is less lopsided in general. I'd say consider changing your gravs to transports and using their mobility to deploy slower, ground-based units that ignore AAA. At least until your opponents stop putting all of their eggs in one basket.
Question: **Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this? Answer:
From the author himself (<https://lvdmaaten.github.io/tsne/>): > > Once I have a t-SNE map, how can I embed incoming test points in that > map? > > > t-SNE learns a non-parametric mapping, which means that it does not > learn an explicit function that maps data from the input space to the > map. Therefore, it is not possible to embed test points in an existing > map (although you could re-run t-SNE on the full dataset). A potential > approach to deal with this would be to train a multivariate regressor > to predict the map location from the input data. Alternatively, you > could also make such a regressor minimize the t-SNE loss directly, > which is what I did in this paper (<https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf>). > > > So you can't directly apply new data points. However, you can fit a multivariate regression model between your data and the embedded dimensions. The author recognizes that it's a limitation of the method and suggests this way to get around it.
t-SNE fundamentally does not do what you want. t-SNE is designed only for visualizing a dataset in a low (2 or 3) dimension space. You give it all the data you want to visualize all at once. It is not a general purpose dimensionality reduction tool. If you are trying to apply t-SNE to "new" data, you are probably not thinking about your problem correctly, or perhaps simply did not understand the purpose of t-SNE.
Question: **Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this? Answer:
t-SNE does not really work this way: The following is an expert from the t-SNE author's website (<https://lvdmaaten.github.io/tsne/>): > > Once I have a t-SNE map, how can I embed incoming test points in that > map? > > > t-SNE learns a non-parametric mapping, which means that it does not > learn an explicit function that maps data from the input space to the > map. Therefore, it is not possible to embed test points in an existing > map (although you could re-run t-SNE on the full dataset). A potential > approach to deal with this would be to train a multivariate regressor > to predict the map location from the input data. Alternatively, you > could also make such a regressor minimize the t-SNE loss directly, > which is what I did in this paper. > > > You may be interested in his paper: <https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf> This website in addition to being really cool offers a wealth of info about t-SNE: <http://distill.pub/2016/misread-tsne/> On Kaggle I have also seen people do things like this which may also be of intrest: <https://www.kaggle.com/cherzy/d/dalpozz/creditcardfraud/visualization-on-a-2d-map-with-t-sne>
t-SNE fundamentally does not do what you want. t-SNE is designed only for visualizing a dataset in a low (2 or 3) dimension space. You give it all the data you want to visualize all at once. It is not a general purpose dimensionality reduction tool. If you are trying to apply t-SNE to "new" data, you are probably not thinking about your problem correctly, or perhaps simply did not understand the purpose of t-SNE.
Question: **Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this? Answer:
This the mail answer from the author (Jesse Krijthe) of the Rtsne package: > > Thank you for the very specific question. I had an earlier request for > this and it is noted as an open issue on GitHub > (<https://github.com/jkrijthe/Rtsne/issues/6>). The main reason I am > hesitant to implement something like this is that, in a sense, there > is no 'natural' way explain what a prediction means in terms of tsne. > To me, tsne is a way to visualize a distance matrix. As such, a new > sample would lead to a new distance matrix and hence a new > visualization. So, my current thinking is that the only sensible way > would be to rerun the tsne procedure on the train and test set > combined. > > > Having said that, other people do think it makes sense to define > predictions, for instance by keeping the train objects fixed in the > map and finding good locations for the test objects (as was suggested > in the issue). An approach I would personally prefer over this would > be something like parametric tsne, which Laurens van der Maaten (the > author of the tsne paper) explored a paper. However, this would best > be implemented using something else than my package, because the > parametric model is likely most effective if it is selected by the > user. > > > So my suggestion would be to 1) refit the mapping using all data or 2) > see if you can find an implementation of parametric tsne, the only one > I know of would be Laurens's Matlab implementation. > > > Sorry I can not be of more help. If you come up with any other/better > solutions, please let me know. > > >
t-SNE fundamentally does not do what you want. t-SNE is designed only for visualizing a dataset in a low (2 or 3) dimension space. You give it all the data you want to visualize all at once. It is not a general purpose dimensionality reduction tool. If you are trying to apply t-SNE to "new" data, you are probably not thinking about your problem correctly, or perhaps simply did not understand the purpose of t-SNE.