text
stringlengths
175
47.7k
meta
dict
Q: tooltip background color change and font styles of tooltip text in primefaces I am trying to see some features availability in prime-faces..... I wanted to know if there are any font styles and background color change functionality available in tool-tip in prime-faces... Please let me know. here is the sample code: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui"> <h:head> <title>Tool Tip Customization</title> </h:head> <h:body> <h:panelGrid columns="3" cellpadding="5"> <h:outputText value="Focus/Blur: " /> <p:inputText id="focus" title="This tooltip is displayed when input gets the focus"/> <p:tooltip for="focus" showEvent="focus" hideEvent="blur" /> <h:outputText value="Fade: " /> <h:outputLink id="fade" value="#"> <h:outputText value="Fade Effect" /> </h:outputLink> <p:tooltip for="fade" value="Fade effect is used by default" showEffect="fade" hideEffect="fade" /> <h:outputText value="Slide: " /> <h:outputLink id="slide" value="#"> <h:outputText value="Slide Effect" /> </h:outputLink> <p:tooltip for="slide" value="This tooltip uses slide effect for the animation" showEffect="slide" hideEffect="slide" /> <h:outputText value="Clip/Explode: " /> <h:outputLink id="grow" value="#"> <h:outputText value="Clip/Explode Effects" /> </h:outputLink> <p:tooltip for="grow" value="This tooltip uses clip/explode effects for the animation" showEffect="clip" hideEffect="explode" /> <h:outputText value="Content: " /> <h:outputLink id="lnk" value="#"> <h:outputText value="PrimeFaces Users" /> </h:outputLink> <p:tooltip for="lnk"> <p:graphicImage value="C:\raman\AMAP\POC\primefaces\JSF2.0HelloWorld\WebContent\images\Users.gif" /> </p:tooltip> </h:panelGrid> </h:body> </html> A: If you want to set styles for all tooltips globally you can use class ui-tooltip. For example like this: .ui-tooltip { border: 1px solid #ccc; box-shadow: 0 0 10px 0 #ddd; -moz-box-shadow: 0 0 10px 0 #ddd; -webkit-box-shadow: 0 0 10px 0 #ddd; color: #666; background: #f8f8f8; } As written in PrimeFaces Userʼs Guide: Tooltip has only .ui-tooltip as a style class and is styled with global skinning selectors, see main skinning section for more information. A: The Primefaces tooltip component has styleand styleClass attributes: Quick example to change font color: <p:tooltip for="slide" value="Text" style="color : red; background-color : yellow"/>
{ "pile_set_name": "StackExchange" }
Q: Convert from and to messagepack So I'm trying to get the string representation of a JSON message in Golang. I just want to receive the messagepack encoded JSON, modify some values and send it back. I haven't found an easy way to do it. Most of the times, I can't know in advance what is the structure of the JSON (apart from having JSON structure), so want I want to do is to receive the binary message. Decode it as a JSON, print it as a string to the standard output, modify the content, convert it to MessagePack again and send it back. I've been looking at these two packages, but I don't know how to properly use them for a simple task like that: https://godoc.org/github.com/vmihailenco/msgpack https://godoc.org/github.com/ugorji/go/codec So I will receive something like this: DF 00 00 00 01 A7 6D 65 73 73 61 67 65 A3 48 69 21 I want to print this: {"message": "Hi!"} Modify the "Hi!": {"message": "Hello Sir!"} Send it as messagepack: DF 00 00 00 01 A7 6D 65 73 73 61 67 65 AA 48 65 6C 6C 6F 20 53 69 72 21 Current Python code I'm trying to port to Golang: def decode_msgpack(jsonData): packedStuff = 0 for key in jsonData.keys(): if type(jsonData[key]) is bytes: packedStuff += 1 try: jsonData[key] = umsgpack.unpackb(jsonData[key]) except umsgpack.InvalidStringException: try: jsonData[key] = umsgpack.unpackb(jsonData[key], allow_invalid_utf8=True) except umsgpack.InsufficientDataException: print("[!] InsufficientDataException") jsonData[key] = base64.b64encode(jsonData[key]).decode('utf-8') else: jsonData[key] = base64.b64encode(jsonData[key]).decode('utf-8') if packedStuff > 0: return decode_msgpack(jsonData) else: return jsonData A: Using the codec library and assuming that {"message": "Hi"} is a map, the code would look something like this. package main import ( "fmt" "github.com/ugorji/go/codec" ) func main() { var data []byte original := map[string]string{"message": "Hi!"} enc := codec.NewEncoderBytes(&data, new(codec.MsgpackHandle)) if err := enc.Encode(&original); err != nil { panic(err) } fmt.Printf("Encoded: ") for _, b := range data { fmt.Printf("%X ", b) } fmt.Printf("\n") decoded := make(map[string]string) dec := codec.NewDecoderBytes(data, new(codec.MsgpackHandle)) if err := dec.Decode(&decoded); err != nil { panic(err) } fmt.Printf("Decoded: %v\n", decoded) decoded["message"] = "Hello Sir!" /* reinitialize the encoder */ enc = codec.NewEncoderBytes(&data, new(codec.MsgpackHandle)) if err := enc.Encode(&decoded); err != nil { panic(err) } fmt.Printf("Encoded: ") for _, b := range data { fmt.Printf("%X ", b) } fmt.Printf("\n") } That said, if you get {"message": "Hi"} as a JSON string, you can use codec to decode the JSON into a map, update the map and then re-encode it as msgpack.
{ "pile_set_name": "StackExchange" }
Q: Json Data in int format I am parsing json and the url is returning an integer value. (e.g. 278) -(void) connectionDidFinishLoading: (NSURLConnection *) connection{ [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; NSString *responseString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"JSON Response = %@",responseString);} when I am printing response in NSLog, it gives out something like this 2012-09-15 18:02:02.091 Web Service[5190:f803] JSON Response = "278" I don't want the output in quotes. I want it like 2012-09-15 18:02:02.091 Web Service[5190:f803] JSON Response = 278 how can i achieve this? JSON NSString *urlString = [NSString stringWithFormat:@"http://10.5.6.105/ARAPPWS/Service1/InsertEmp/name=%@,phone=%@",name.text,number.text]; NSURL *addUrl = [NSURL URLWithString:urlString]; NSURLRequest *addRequest = [NSURLRequest requestWithURL:addUrl]; (void)[NSURLConnection connectionWithRequest:addRequest delegate:self]; -(void) connection: (NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response { jsonData = [[NSMutableData alloc]init]; } -(void) connection: (NSURLConnection *) connection didReceiveData:(NSData *)data { [jsonData appendData:data]; } -(void) connectionDidFinishLoading: (NSURLConnection *) connection { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; responseString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; [self performSelector:@selector(uploadEmpImg:) withObject:nil afterDelay:1]; } Thanks in advance. A: You can use - [NSString integerValue] to obtain the actual numerical representation of the string: NSLog(@"JSON response = %d", [responseString integerValue]); Edit: the problem is that it returns a JSON fragment - strictly speaking it's not valid JSON. You can then use [responseString substringWithRange:NSMakeRange(1, responseString.length - 2)] to get the actual string value without the quotes and [[responseString substringWithRange:NSMakeRange(1, responseString.length - 2)] intValue] to get it as an integer.
{ "pile_set_name": "StackExchange" }
Q: how to keep the first string per line I have a data like this df1 <- structure(list(V1 = structure(c(1L, 2L, 3L, 5L, 4L), .Label = c("A0A061ACH4;Q95Q10;Q9U1W6", "A0A061ACL3;Q965I6;O76618", "A0A061ACR1;Q2XN02;F5GUA3;Q22498", "A0A061AL01", "H2FLH3;H2FLH2;A0A061ACT3;A0A061AE24;Q23551-2;Q23551;Q23551-4;Q23551-3;Q23551-5" ), class = "factor"), V2 = c(1L, 5L, 100L, 645L, 11L), V3 = c(67L, 10L, 33L, 99L, 10L), V4 = c(7L, 16L, 0L, 1L, 5L)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c(NA, -5L )) What i want is to keep put all the strings under each other and copy the value in front of each line , in front of each string in that line An expected output should like this output <- structure(list(V1 = structure(c(1L, 18L, 20L, 2L, 19L, 19L, 10L, 3L, 17L, 7L, 11L, 9L, 8L, 4L, 5L, 13L, 12L, 15L, 14L, 16L, 6L ), .Label = c("A0A061ACH4", "A0A061ACL3", "A0A061ACR1", "A0A061ACT3", "A0A061AE24", "A0A061AL01", "F5GUA3", "H2FLH2", "H2FLH3", "O76618", "Q22498", "Q23551", "Q23551-2", "Q23551-3", "Q23551-4", "Q23551-5", "Q2XN02", "Q95Q10", "Q965I6", "Q9U1W6"), class = "factor"), V2 = c(1L, 1L, 1L, 5L, 5L, 5L, 5L, 100L, 100L, 100L, 100L, 645L, 645L, 645L, 645L, 645L, 645L, 645L, 645L, 645L, 11L), V3 = c(67L, 67L, 67L, 10L, 10L, 10L, 10L, 33L, 33L, 33L, 33L, 99L, 99L, 99L, 99L, 99L, 99L, 99L, 99L, 99L, 10L), V4 = c(7L, 7L, 7L, 16L, 16L, 16L, 16L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 5L)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c(NA, -21L )) For example, if we look at df1 first line, it looks like this A0A061ACH4;Q95Q10;Q9U1W6 1 67 7 Then I split the strings after ; and put them under each other and copy the values in front of them. so for the first line of the df1, I will have A0A061ACH4 1 67 7 Q95Q10 1 67 7 Q9U1W6 1 67 7 A: Here is a "base" way. # for each line... out <- do.call(rbind, apply(df1, MARGIN = 1, FUN = function(x) { # split by ; and... do.call(rbind, sapply(unlist(strsplit(x[1], ";")), FUN = function(y, y2) { # ... append the rest of the columns to individual element c(y, y2) }, simplify = FALSE, y2 = x[2:4])) })) rownames(out) <- NULL out <- as.data.frame(out) out V1 V2 V3 V4 1 A0A061ACH4 1 67 7 2 Q95Q10 1 67 7 3 Q9U1W6 1 67 7 4 A0A061ACL3 5 10 16 5 Q965I6 5 10 16 6 O76618 5 10 16 7 A0A061ACR1 100 33 0 8 Q2XN02 100 33 0 9 F5GUA3 100 33 0 10 Q22498 100 33 0 11 H2FLH3 645 99 1 12 H2FLH2 645 99 1 13 A0A061ACT3 645 99 1 14 A0A061AE24 645 99 1 15 Q23551-2 645 99 1 16 Q23551 645 99 1 17 Q23551-4 645 99 1 18 Q23551-3 645 99 1 19 Q23551-5 645 99 1 20 A0A061AL01 11 10 5
{ "pile_set_name": "StackExchange" }
Q: va_arg returns only parts of my integer I am trying to write my own va_args functions for the first time and I am having a problem that large integers (still within the range of int) are getting truncated to 3 digits, and out of order! Here is the implementation void __sprintf(char * _string, ...) { int i = a_sizeof(_string); char _arg; int j =0; int format = 0; va_list args; va_start (args,_string); for(; j < i; j++) { if(_string[j] == '\0') break; else if(_string[j] == '%') { format=1; continue; } else if(format==1) { switch(_string[j]) { case 'd': _arg = va_arg(args,int); printi(_arg); //Prints integers over serial by converting to ASCII break; default: continue; } format = 0; } else SerialPutChar(_string[j]); } va_end(args); } What I get when I try __sprintf("%d %d %d\n",32141,6400,919911); is 141 32 then it exits. I have set break points and sometimes it looks like Im getting total crap passed. Suspicions: IAR's implementation of stdarg complete bone-head miss-use of va_arg missing fine-print details (which are probably in bold 14pt but no one reads it anyway) Thanks in advance! A: You have declared char _arg instead of int _arg, therefore the "truncation" of the integer values.
{ "pile_set_name": "StackExchange" }
Q: I am not the first I am not the first. To some I am the second. To others I am the third. But I'm never the fourth. I am the first. I'm no help in "a way out." But I'm first in these words: "I", "don't", "know". I can't be left alone. If I'm alone, I will offend someone. You can't make peace if you cut me off. But on the other hand, you might. I was inspired by this riddle by Mello, so I wanna give him props. A: You are: my middle finger I am not the first. To some I am the second. To others I am the third. But I'm never the fourth. Counting from the index finger to pinky, the middle finger is the second. Counting from pinky to index, it is third. It will never be first or fourth (in a complete hand, anyway). I am the first. I'm no help in "a way out." But I'm first in these words: "I", "don't", "know". I missed this one entirely. See Matt's answer for the correct interpretation. I can't be left alone. If I'm alone, I will offend someone. The middle finger on its own is an insult. You can't make peace if you cut me off. The peace sign requires both the index and middle fingers. But on the other hand, you might. I believe this is just a pun on "hand". A: I think it's Your middle finger Reasoning: It's either second or third, depending on if you start with the thumb or not. The second clue is where the middle finger falls when typing. The third clue - a middle finger alone is offensive, and if you cut off the middle finger on one hand, you can't make a peace sign, but then you can always make a peace sign with the other hand
{ "pile_set_name": "StackExchange" }
Q: Issue while validating with PSR-2 on Prestashop Validator While validating my new module on Prestashop Validator, I am getting the following error in my main controller file (php file). End of line character is invalid; expected "\n" but found "\r\n" I am getting the error on the first line that only has the starting <?php tag. I have researched so much about it on the Internet but unable to find a solution for it. I am struck. What should I do? A: In Notepad++, first go to View --> Show Symbol --> Show All Characters All characters including spaces, tabs, and new lines (CR LF). Hit Ctrl + H for "Find and Replace." In "Find What," look for "\r\n" Replace with "\n". Click "Replace All" All CR's should now be removed and should fix the error.
{ "pile_set_name": "StackExchange" }
Q: multiselect table row checkbox using jquery I have a VF page with a datatable that is populated from a custom search. The datatable has a checkbox column so that the rows can be selected and processed. I'm trying to implement a way for the user to select multiple rows using either shift+click, ctrl+click, or ctrl+a on the rows that would also select the checkboxes so multiple rows can be easily selected and processed. I have jquery-3.3.1.min successfully loaded. I was trying to get the following plugin to work on the page: Multiselect Plugin I was unable to get the plugin to work. I tried using jquery 1.11.1 as indicated in the article as well because I was getting a type error with 3.3.1 version. When trying to debug, I'm not getting anything back in the browser debug log. Here is a portion of the VF page: <apex:page standardController="SalesOrder__c" extensions="EditAllLineItemsExt,SearchProducts" docType="html-5.0"> <apex:form > <apex:includeScript value="{!URLFOR($Resource.Jquery_3_3_1_min, '/jquery-3.3.1.min.js')}"/> <apex:includeScript value="{!$Resource.JqueryMultiselect}"/> <apex:includeScript value="{!$Resource.VF_EditAllLineItems}"/> // additional code moved for brevity.. // page block code below that displays the search results that I want to implement multi-select... <apex:pageBlock id="pbSearch"> <apex:pageBlockSection columns="1"> <apex:pageBlockTable value="{!results}" var="result" id="searchTable"> <apex:column headervalue="Action"> <apex:inputcheckbox value="{!result.selected}"> <apex:actionSupport event="onclick" action="{!getSelected}" reRender="btnAddProducts" /> </apex:inputcheckbox> </apex:column> <apex:column headerValue="Product SKU"> <apex:outputField value="{!result.product.Name}" /> </apex:column> <apex:column headerValue="{!dynamicColumnHeader1}"> <apex:outputPanel rendered="{!If(dynamicColumnHeader1 = 'Manufacturer', true, false)}"> <apex:outputField value="{!result.product.Manufacturer__c}" /> </apex:outputPanel> <apex:outputPanel rendered="{!If(dynamicColumnHeader1 = 'Description', true, false)}"> <apex:outputField value="{!result.product.Description}" /> </apex:outputPanel> </apex:column> <apex:column headerValue="{!dynamicColumnHeader2}"> <apex:outputPanel rendered="{!If(dynamicColumnHeader2 = 'Style Number', true, false)}"> <apex:outputField value="{!result.product.Style_Number__c}" /> </apex:outputPanel> <apex:outputPanel rendered="{!If(dynamicColumnHeader2 = 'Product Family', true, false)}"> <apex:outputField value="{!result.product.Family}" /> </apex:outputPanel> </apex:column> <apex:column headerValue="Color"> <apex:outputField value="{!result.product.Color__c}" /> </apex:column> <apex:column headerValue="Size"> <apex:outputField value="{!result.product.Size__c}" /> </apex:column> <apex:column headerValue="Product Name"> <apex:outputField value="{!result.product.Product_Name__c}" /> </apex:column> <apex:column headerValue="Tag Style"> <apex:outputField value="{!result.product.Tag_Style__c}" /> </apex:column> </apex:pageBlockTable> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page> script code: j$ = jQuery.noConflict(); j$(document).ready(function() { j$(function () { j$('[id*=searchTable]').multiSelect({ selector: 'tbody tr', except: ['tbody'] }); }) }); Does anyone know of a plugin to accomplish what I'm trying? Or, my error with the implementation of the above plugin? A: The Multiselect plugin which you are using seems to be deprecated. For example the plugin uses size() method which is deprecated in the latest versions of jQuery. I found a code in a fiddle which has a solution to your problem. It uses pure JS to select the rows without any plugin. I am including the Ctrl+A functionality to select the all rows in the table: document.onkeydown = function(){ if(window.event.ctrlKey && window.event.keyCode == 65){ for (var i = 0; i <= trs.length; i++) { trs[i].className = 'selected'; } } }
{ "pile_set_name": "StackExchange" }
Q: Line bundles and Cyclic Covers of Curves Let $X \to Y$ be a cyclic etale cover of smooth projective geometrically connected curves over some field $k$. Then the map is classified by an element of the cohomology group $H^1_{et}(Y_{k_s}, \mu_n)$; in other words the data of the covering is equivalent to giving a line bundle on $Y$ together with a trivialization of its $n$-th power. It follows that the induced map on Picard schemes given by pullback is not injective. My question is: what can be said about the kernel? I am especially interested in the special case of a degree $2$ cover; i.e are there are any other elements in the kernel besides the trivial bundle and the bundle classified by the covering. This one is given explicitly by pushing forward the structure sheaf on $X$ and modding out by the structure sheaf on $Y$. I tried asking this on MSE but got no answer. A: Let me give an answer when $\mathrm{char} \, k=0$. In this situation the double cover $f \colon X \to Y$ is defined by a line bundle $\mathcal{L}$ such that $\mathcal{L}^{\otimes 2} = \mathcal{O}_Y$ and the trace map provides a splitting $$f _* \mathcal{O}_X = \mathcal{O}_Y \oplus \mathcal{L}^{-1}.$$ Assume now that $\mathcal{M}$ belongs to the kernel of $$f^* \colon \mathrm{Pic} \, Y \to \mathrm{Pic} \, X.$$ Then $f^* \mathcal{M} = \mathcal{O}_X$ so, by applying the functor $f_*$ and the projection formula, we obtain $$f_* \mathcal{O}_X = f_* f^* \mathcal{M} = \mathcal{M} \otimes f_* \mathcal{O}_X = \mathcal{M} \oplus (\mathcal{M} \otimes \mathcal{L}^{-1}).$$ By the Krull-Schmidt theorem the decomposition of a vector bundle in a direct sum of indecomposable ones is unique up to permutation of the summands, so we get either $\mathcal{M} = \mathcal{O}_Y$ or $\mathcal{M}=\mathcal{L}$. Summing up, $\ker \, f^*$ is the subgroup of order $2$ generated by $\mathcal{L}$. Exactly the same argument shows that if the étale cover is cyclic of degree $n$, then $\ker f^*$ is cyclic of the same order. A: Theorem. Let $X \to Y$ be an étale Galois cover with group $G$ of proper geometrically integral schemes over any field $k$. Then we have an exact sequence $$0 \to \operatorname{Hom}(G,k^\times) \to \operatorname{Pic}(Y) \to \operatorname{Pic}(X)^G.$$ In particular, the kernel has size at most $n = |G^{\operatorname{ab}}|$, with equality if and only if $n$ is invertible in $k$ and $\mu_r \subseteq k$, where $r$ is the exponent of $G^{\operatorname{ab}}$. Proof. An étale Galois cover with group $G$ is the same thing as a $G$-torsor, and we have a Hochschild–Serre spectral sequence (see e.g. Milne's Étale cohomology notes, Thm 14.9) $$E_2^{pq} = H^p(G,H^q(X,\mathbb G_m)) \Rightarrow H^{p+q}(Y,\mathbb G_m).$$ The exact sequence of low degree terms is $$0 \to H^1(G,\mathbb G_m(X)) \to H^1(Y,\mathbb G_m) \to H^1(X,\mathbb G_m)^G \to H^2(G,\mathbb G_m(X)) \to \ldots .$$ Since $X$ is proper and geometrically integral, the global sections of $\mathcal O_X$ are just the constants $k$, hence the global sections of $\mathbb G_m$ are just $k^\times$. This clearly has the trivial $G$-action, so $$H^1(G,\mathbb G_m(X)) = \operatorname{Hom}(G,k^\times).$$ This proves the first statement. The second statement follows since $$\operatorname{Hom}(G,k^\times) = \operatorname{Hom}(G^{\operatorname{ab}},k^\times),$$ and for any finite abelian group $G$ there is a noncanonical isomorphism $G^{(p')} \cong \operatorname{Hom}(G,\bar k^\times)$, where $(-)^{(p')}$ denotes the prime to $p$-part if $\operatorname{char} k = p > 0$ (and the entire group if $\operatorname{char} k = 0$). Since the group generated by the images of homomorphisms $G \to \bar k^\times$ is the subgroup $\mu_r$ for $r$ the exponent of $G$, we conclude that they are all realised over $k$ if and only if $\mu_r \subseteq k$. $\square$
{ "pile_set_name": "StackExchange" }
Q: What's correct way to use default constructor for XmlSerializer? Could you help me to find an error please? I'm trying to use XmlSerialize: public static void ProcessLines(List<string> allLines, out pfm pfm) { ... pfm = newPfm; pfm forseril = new pfm(""); XmlSerializer mySerializer = new XmlSerializer(typeof(pfm)); StreamWriter myWriter = new StreamWriter("myFileName.xml"); mySerializer.Serialize(myWriter, forseril); myWriter.Close(); } And here is that thing that I think should be a default constructor: [Serializable] [XmlRoot(ElementName = "Pfm", Namespace = null)] public class pfm { public pfm(string data) { this.data = data; } public string data; public Ctl ctl { get; set; } [XmlAttribute(AttributeName = "Name")] public string Name { get; set; } } I used an istruction from Microsoft site: instruction A: What XmlSerializer requires is a parameterless constructor -- a constructor with no arguments. Thus your pfm needs a constructor as follows: public class pfm { pfm() : this("") { } public pfm(string data) { this.data = data; } } It doesn't need to be public. Sample fiddle.
{ "pile_set_name": "StackExchange" }
Q: How to solve $n^2-n<\lfloor\frac{n^2}{4}\rfloor$ ,$n \in \mathbb{N}$? How to solve this inequality? $$n^2-n<\lfloor\frac{n^2}{4}\rfloor \\ n \in \mathbb{N}$$ I can solve normal inequalities but this includes floor function with which I am not familiar. and because of that I could do nothing from the beginning. A: HINT: It's always true that $\left\lfloor\frac{n^2}4\right\rfloor\le\frac{n^2}4$, so if $n^2-n<\left\lfloor\frac{n^2}4\right\rfloor$, then certainly $n^2-n<\frac{n^2}4$. What solutions does this inequality have in $\Bbb N$? Are any of them solutions to the original inequality?
{ "pile_set_name": "StackExchange" }
Q: animateKeyframes with repeat and delay does not work as expected I'm creating a simple left to right animation for a label using key frames but when the animation repeats, the delay is ignored. The first time it executes, the delay of 3 seconds has an effect, but when the animation repeats, the delay is ignored. This causes the animation to re-start immediately after it ends. UIView.animateKeyframes(withDuration: 10, delay: 3, options: [.calculationModePaced, .repeat], animations: { let xDist = self.Label_ArtistAlbum2.frame.origin.x UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.1, animations: { self.Label_ArtistAlbum2.frame.origin.x = self.Label_ArtistAlbum2.frame.origin.x - (xDist * 0.1) }) UIView.addKeyframe(withRelativeStartTime: 0.9, relativeDuration: 0.1, animations: { self.Label_ArtistAlbum2.frame.origin.x = 0 }) }, completion: nil) I've tried adding an extra keyframe at the end however this has no effect even with the altered times: UIView.animateKeyframes(withDuration: 10, delay: 3, options: [.calculationModePaced, .repeat], animations: { let xDist = self.Label_ArtistAlbum2.frame.origin.x UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.1, animations: { self.Label_ArtistAlbum2.frame.origin.x = self.Label_ArtistAlbum2.frame.origin.x - (xDist * 0.1) }) UIView.addKeyframe(withRelativeStartTime: 0.1, relativeDuration: 0.7, animations: { self.Label_ArtistAlbum2.frame.origin.x = 0 }) //attempted pause - does not appear to work perhaps since the position is unchanged? UIView.addKeyframe(withRelativeStartTime: 0.8, relativeDuration: 0.2, animations: { self.Label_ArtistAlbum2.frame.origin.x = 0 }) }, completion: nil) If the delay will not be repeated along with the rest of the animation, how can I create a pause before the entire animation repeats? A: I've done a lot of testing on this issue and have found what I believe is the problem. I think that the animation option for the Curve is my issue. In my case choosing calculationModePaced has the effect of recalculating my keyframe parameters and not guaranteeing to hit any of them except the beginning and end. All intermediate keyframes become 'suggestions'. You can't create a pause at the end because the keyframe is 'consumed' when recalculating and does not stand on it's own. I changed to calculationModeLinear and got the keyframes I expected, and the pause too. However, it is as smooth as I would like so I'll have to keep tinkering... Apple's docs are here - they're descriptive but could really use some graphics and/or examples: https://developer.apple.com/reference/uikit/uiview?language=swift A good graph of the curves can be found here: https://www.shinobicontrols.com/blog/ios7-day-by-day-day-11-uiview-key-frame-animations
{ "pile_set_name": "StackExchange" }
Q: Problem adding image to UIView I'm making an app with a piano and each key will be it's own subclass. I tried making the keys a subclass of UIButton, but after having some problems getting the methods to be called, I checked online and found out that others were also having problems subclassing UIButtons. So then I tried subclassing a UIView. The problem was that I tried adding an image to it, but it showed up as a black box. Here is the code from the CustomView @implementation Keys - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"whitekey.gif"]]; } return self; (I've confirmed that the problem isn't whitekey.gif) Here is the code from the viewController - (void)viewDidLoad { [super viewDidLoad]; Keys *whiteKey = [[Keys alloc] initWithFrame:CGRectMake(0, 0, 100, 300)]; [self.view addSubview:whiteKey]; } Is it better if I subclass UIImageView? A: You should be using UIImageView. An image view object provides a view-based container for displaying either a single image or for animating a series of images. http://developer.apple.com/library/ios/#documentation/uikit/reference/UIImageView_Class/Reference/Reference.html Maybe a UIView as a container, with a UIImageView with the piano key image, with additional UIViews on top of that, depending on what you need to do?
{ "pile_set_name": "StackExchange" }
Q: Downloadable font on firefox: bad URI or cross-site access not allowed I'm a webmaster at http://www.beperk.com (I'm giving you the URL so you are able to check the problem) and I'm having lots of problems using @font-face in CSS. I want to use the foundicons from zurb dot com so I hosted them at Amazon S3. I set up the bucket to allow crossdomain access as specified here: http://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html#how-do-i-enable-cors And everything started to work seamless at webkit, trident and gecko... mostly: when browsing the web with firefox (version 17, 18 and 19 tested) all the icons fails randomly with this error: Timestamp: 22/02/13 13:18:01 Error: downloadable font: download failed (font-family: "GeneralFoundicons" style:normal weight:normal stretch:normal src index:1): bad URI or cross-site access not allowed And I say randomly since after a full reload of the page (with control/command + R) every single icon appears normally to fail again after some visits. Can anyone find the problem? A: On your server you will need to add: Access-Control-Allow-Origin To the header of the font files, so for example if you are using Apache you can add this to the .htaccess: <FilesMatch "\.(ttf|otf|eot|woff|woff2)$"> <IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule> </FilesMatch> A: If anyone are using local resource and facing this problem in firefox. You can go to about:config and change the security.fileuri.strict_origin_policy preference to false. see : https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs A: try to use implemented base64-encoded fonts like: @font-face { font-family:"font-name"; src:url(data:font/opentype;base64,[paste-64-code-here]); font-style:normal; font-weight:400; } see: http://sosweetcreative.com/2613/font-face-and-base64-data-uri it worked perfectly.
{ "pile_set_name": "StackExchange" }
Q: Use javascript/jquery to append URL? Is it possible to use javascript/jquery to append something on the end of a url when a link is clicked? For example, I have 5 tabs on a page (product.php), when I click a tab, then that tab opens. What I want to do is have the URL change to product.php#tab-3 (or whichever number tab is clicked) when you click on it. The reason I am doing this is so that users will be able to bookmark the page on a specific tab. Thanks A: No need to use JavaScript: <a href="#tab3">click</a> You can still use JavaScript if you need it though: location.hash = "tab3";
{ "pile_set_name": "StackExchange" }
Q: Что я делаю не так? Есть вот такая функция - function getauth(account_id,session,callback){ make_key(account_id,function(err,result){ if(result!=null){ session.auth_key=result.toString('hex'); session.account_id=account_id; findclient({name:account_id},function(err,result){ if(err!=null){ console.log(err); }else{ console.log('Findlcient on getauth: sid='+result.accounts[0].sid+',token='+result.accounts[0].auth_token); session.account_sid=result.accounts[0].sid; session.account_token=result.accounts[0].auth_token; console.log(session); } }); callback(null,session.auth_key); }else{ callback(err,null); } }); } В результате её выполнения почему-то console.log(session) отдает всё как надо: { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }, auth_key: 'c684c0bf8139fc3903ffcdb7b25180544f8f408a79aceeb4952d315a49627b80', account_id: 'ss', account_sid: 'ACba7f95311673301adf8203bda6ebd01f', account_token: '860c23f6afdb7e05163fe0374a94c55c' } но в Mongo я вижу только это - { cookie: {"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"}, "auth_key":"c684c0bf8139fc3903ffcdb7b25180544f8f408a79aceeb4952d315a49627b80", "account_id":"ss" } Как мне всё же заставить записаться недостающие два поля? PS: модули: var express = require('express'); var session = require('express-session'); var MongoStore = require('connect-mongo')(session); A: По какой-то причине express-session не замечает изменения объекта session. Попробуйте принудительное сохранение session.save().
{ "pile_set_name": "StackExchange" }
Q: OpenCV 3.0.0 with Xcode 6.3 I'm trying to compile a simple opencv code using Xcode but I'm getting a compilation error. The opencv version is 3.0.0 and Xcode version is 6.3 (OS X 10.10.3) In Xcode, Apple LLVM 6.1 Language C++ settings are: c++ Language Dialect : C++11[-std=c++11] c++ Standard Library : libc++ the error is: Undefined symbols for architecture x86_64: "cv::imread(cv::String const&, int)", referenced from: _main in main.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) When I change the c++ standard library to libstdc++, then the error was: /usr/local/include/opencv2/hal/defs.h:271:14: 'cstdint' file not found Can someone show me how to get opencv work with Xcode? I've already followed lot of forums and guides but still getting the same error. A: I had the same problem, either I got the "Undefined symbols x86_64" with libc++, or "cstdint file not found" with libstdc++. What finally made it work for me was that I needed to add a lot more libs than I'm used to, it wasn't enough to add just core, imgproc, and highgui for even a simple project. So I went to Build Settings, searched for Linking, and in Other Linker Flags I added the whole lot: -lopencv_calib3d -lopencv_core -lopencv_features2d -lopencv_flann -lopencv_highgui -lopencv_imgcodecs -lopencv_imgproc -lopencv_ml -lopencv_objdetect -lopencv_photo -lopencv_shape -lopencv_stitching -lopencv_superres -lopencv_ts -lopencv_video -lopencv_videoio -lopencv_videostab I'm using OpenCV 3.0.0 and Xcode 6.4. C++ Standard Library set to libc++ and C++ Language Dialect C++11. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Call the JFrame from another class i have simple JFRAME (create by Netbeans) and i want to call frame.setState(Frame.NORMAL) from another class. How to do call? public class Myclass{ public void Frame_normal{ ...? ???frame.setState(Frame.NORMAL); } } A: Basicaly you create an attribute in your class and you give it the reference to your JFrame. public class Myclass{ JFrame frame; public MyClass(JFrame aFrame){ this.frame = aFrame; } public void Frame_normal{ frame.setState(Frame.NORMAL); } } MyClass class = new Myclass(theJFrame); class.Frame_normal();
{ "pile_set_name": "StackExchange" }
Q: What is the cardinality of the set of all higher order functions mapping real functions to real functions? What is the cardinality of the set of all higher order functions mapping real functions to real functions? To be specific, this set includes all higher order functions with the type signature: $(\mathbb{R} \rightarrow \mathbb{R}) \rightarrow (\mathbb{R} \rightarrow \mathbb{R}) $, an example of which being the differential operator (i.e. taking the derivative of some function). Since the cardinality of the set of all functions $\mathbb{R} \rightarrow \mathbb{R} $ is $\aleph_2$, I'd assume it's $\aleph_3$, but I'm not sure. A: First, let me correct you. The cardinality of functions from $\Bbb R$ to itself is not $\aleph_2$ in general. This is a common mistake, but the aleph numbers are not defined by taking power sets, but rather by climbing up the ordinals until we increased the cardinality. So we can only prove that $\aleph_1\leq|\Bbb R|$, but we can't prove equality. To ease up on notation, we have the $\beth$ numbers which are defined using power sets, so $\beth_0=\aleph_0=|\Bbb N|$, and then we define $\beth_{n+1}=2^{\beth_n}$ (I'll spare you the full definition). So now we have that $|\Bbb R|=\beth_1$, and $|\Bbb{R^R}|=\beth_2$. But again, we can only prove that $\aleph_n\leq\beth_n$, and we cannot prove equality. The reason is that it is consistent that the inequality is strict. But let us not dwell on that, since it doesn't matter for the purpose of this question. What matters is that you can't claim the cardinality is $\aleph$ this or $\aleph$ that, but you can definitely say what it is in terms of $\beth$ numbers. What we can prove is this: If $X$ is infinite, then the set of all functions from $X$ to itself, denoted by $X^X$, has the same cardinality as $\mathcal P(X)$, namely $2^{|X|}$. The proof is simple if you are familiar with cardinal arithmetic (in particular exponentiation laws), but uses the axiom of choice. $$X<2^X\leq X^X\implies X^X\leq 2^{X^2}\leq X^{X^2}=X^X$$ The axiom of choice was used to have that $X^2$ and $X$ have the same cardinality. However in the case of $\Bbb R$ and the sets we are interested in, we can prove that this property is true without appealing to the axiom of choice. Therefore in the case of our interest, we can prove without the axiom of choice that: $$\Bbb{\left|\left(R^R\right)^{R^R}\right|}=|\cal P(P(P(\Bbb N)))|=\beth_3.$$
{ "pile_set_name": "StackExchange" }
Q: How to add data into List in ASP.NET MVC 4.0? I am new in MVC. I have a class in Models like below. public class UserInfo { public string Name{get;set;} public string Surname{get;set;} } And I have a controller like this. public class HomeController : Controller { // // GET: /Home/ List<UserInfo> Users = new List<UserInfo>(); public ActionResult Index() { return View(); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(UserInfo userInfo) { if (ModelState.IsValid) { Users.Add(userInfo); return RedirectToAction("Index"); } return View(); } } And every time when i press Create button in browser, it redirects to Index View. But List<UserInfo> is empty. Why it happens? How to save data into List and show from grid or table from that List? A: Controllers are stateless. A new instance is created each time you call an action, this is why your list is always empty. If you want to persist the list between controller actions, you will need some sort of persistence mechanism - database, caching, etc. A: Make your list static static List<UserInfo> Users = new List<UserInfo>();
{ "pile_set_name": "StackExchange" }
Q: Retrofit: How to get request properties in requestInterceptor I need to apply an Authorization header in a request interceptor, but I need to sign the request method, URI, and date. Inside the request interceptor I get a RequestInterceptor.RequestFacade, which only has "setter methods" Is there any way I can get request properties inside a request interceptor? A: Ah, did some more googling. The way to do this is to use a client wrapper. Observe... public class SigningClient implements Client { final Client wrapped; public SigningClient(Client client) { wrapped = client; } @Override public Response execute(Request request) { Request newRequest = sign(request); return wrapped.execute(newRequest); } private void sign(Request request) { // magic } } Found it here: https://github.com/square/retrofit/issues/185#issuecomment-17819547
{ "pile_set_name": "StackExchange" }
Q: Recursive mergeSort to Iterative in c++ using deque I'm trying to do the iterative version of this multiple recursive mergesort: I only need to make iterable this sort function: template<class T> deque<T> mergesort<T>::sort(deque<T> &right){ int size = right.size(); if (size <= 1){ return right; } int middle = size/2; deque<T> left; for(int i = 0; i < middle; i++){ left.push_back(right.front()); right.pop_front(); } left = sort(left); right = sort(right); return merge(left, right); } The merge function can be the same: template<class T> deque<T> mergesort<T>::merge(deque<T> &left, deque<T> &right){ deque<T> result; while(left.size() > 0 || right.size() > 0){ if (left.size() > 0 && right.size() > 0){ if (getOrder(left.front(),right.front())){ result.push_back(left.front()); left.pop_front(); } else{ result.push_back(right.front()); right.pop_front(); } } else if(left.size() > 0){ result.push_back(left.front()); left.pop_front(); } else if(right.size() > 0){ result.push_back(right.front()); right.pop_front(); } } return result; } It's hard for me to make the tranformation of multiple recursive function to iterative function. Thanks everyvody and kind regards. A: Do you have to use dequeue? The iterative version of merge sort is called a bottom-up merge sort. There's really no need to store extra information.
{ "pile_set_name": "StackExchange" }
Q: What is the difference between Jhana and Samadhi? In Sutta pitaka we find two Suttas namely Jhana sutta and Samadhi sutta. What is the difference? http://www.accesstoinsight.org/tipitaka/an/an04/an04.041.than.html http://www.accesstoinsight.org/tipitaka/an/an09/an09.036.than.html A: Samadhi is a general term for concentration. Jhanas are stages you achieve in Samatha meditation when your concentration reaches a certain level. To give an analogy, Samadhi is like the temperature of ice. When the temperature reaches a certain level, it becomes water. That's like reaching the first Jhana. If you keep heating, it will become steam. That is like reaching the second Jhana and so on.
{ "pile_set_name": "StackExchange" }
Q: Recieved String to useable variable in Arduino I'm trying to use data sent via Bluetooth from a mobile app to the Arduino. There will be 2 strings received dependent on the function required. First function: When the string "ledon" or "ledoff" received turn on or turn off an led. Second Function: from the app I get the data a user has typed into 2 boxes, one a text box the other a password box, this is received by the Arduino as one string with comma's as a delimiter so the string can be separated into it's component parts, which in this case are an "ssid name" and a "network key". These details I will be intending to write to an onboard sd card so that the wifi module will be able to logon to the network that the ssid and network key are relevant too. So far I can get the led light to do as it should, I can also get the string read, separated by the delimiter and printed out to the serial monitor. However when I try to combine the two codes the led function fails to turn on or off the led light although the correct command is printed into the serial monitor. I have researched how to solve this trying each requirement as a standalone function and calling them in the loop section, which individually they work but when called together again the led fails to come on. This is the code i'm presently using: const int ledPin = 11; String readString; void setup() { Serial.begin(9600); pinMode (ledPin, OUTPUT); } void loop() { while (Serial.available()) { delay(3); char c = Serial.read(); readString += c; } //turns led on or off if (readString.length() >0) { Serial.println(readString); if (readString == "ledon") { digitalWrite (ledPin, HIGH); } if (readString == "ledoff") { digitalWrite (ledPin, LOW); } readString=""; //seperates the string into 2 lines using the delimiter "," String first = Serial.readStringUntil(','); Serial.read(); //next character is comma, so skip it using this String second = Serial.readStringUntil(','); Serial.read(); Serial.println(first); Serial.println(second); readString=""; } } If I comment out the string part of the code the led turns on and off fine, if I try and run the code as is the code prints everything you would expect but the led doesn't come on. I'm pretty new to Arduino,c and c++ and I cannot seem to figure this out so any help would be great. The app I'm using to control this is being built in Mit's App Inventor 2 A: I have finally resolved this. I decided to look at other logical steps to find a solution. I considered the issue could be having different strings that did different things which may be conflicting in some way. In my research I found reference to the fact that the Bluetooth module HC-05 has 2 pins that in my case were not being utilised, the key pin and the state pin, in this stack overflow discussion Tell when Bluetooth module connects on Arduino and decided this logic of using the "State pin" to signify Bluetooth connection would negate the possibility of any conflicts within the String logic. Once I had figured out the best way to place and order the "where" statements I managed to get the functionality at this point in my project which then allows me to move on to the next step in the development. The code I have now arrived at: const int ledPin1 = 11; const int ledPin2 = 4; String readString; boolean BTconnected = false; void setup() { Serial.begin(9600); pinMode (ledPin1, OUTPUT); pinMode (ledPin2, INPUT); } void loop() { while (!BTconnected) { if ( digitalRead(ledPin2)==HIGH) { BTconnected = true;}; } digitalWrite(ledPin1, HIGH); Serial.println("HC-05 is now connected"); Serial.println(""); while (BTconnected) { if ( digitalRead(ledPin2)==LOW) { BTconnected = false; digitalWrite(ledPin1, LOW); Serial.println("HC-05 is now disconnected"); Serial.println(""); }; while (Serial.available()) { delay(3); char c = Serial.read(); readString += c; } if (readString.length() >0) { //Serial.println(readString); //readString=""; String first = Serial.readStringUntil(','); Serial.read(); //next character is comma, so skip it using this Serial.println(first); //readString=""; String second = Serial.readStringUntil(','); Serial.read(); Serial.println(second); Serial.println(""); //readString=""; } } }
{ "pile_set_name": "StackExchange" }
Q: VimL: Checking if function exists right now I'm cleaning up my .vimrc file to make sure it's compatible on most systems. In my statusline I use a function that another plugin sets, the GitBranchInfoString() function introduced by this plugin. What I wanna do is check if this function is set, and only then add it to the statusline. It would be in it's own line so I just need to check for it. What would be the simplest way to accomplish this? Thanks for all your help! EDIT: I have the following: if exists('*GitBranchInfoString') let &stl.='%{GitBranchInfoString()}' endif A: Use if exists("*GitBranchInfoString") " do stuff here endif A: The currently selected answer doesn't work for me (using Vim 7.4 / Ubuntu). I believe that's because: .vimrc is sourced before any plugins are loaded As @ZyX noted this in a comment. My preferred method is just to check for the existence of the plugin file. I find this cleaner than writing a separate function in an external file. if !empty(glob("path/to/plugin.vim")) echo "File exists." endif A: Just as an alternative you may also use a regexp to decide if the plugin at hand is in your runtimepath: if &rtp =~ 'plugin-name' ... endif This has the advantage that it works with plugins that only have vimscript code in the autoload directory, which in turn can't be detected when .vimrc is initially parsed since the autoload snippets are loaded at the time of a function call.
{ "pile_set_name": "StackExchange" }
Q: Direct3d 9 z-buffer fails drastically I have just completed my custom mesh class and my engine is very basic right now, but now I am facing this strange issue. I have posted the pictures bellow, it seems like z-buffer is not working properly. I am using the following for projection matrix D3DXMatrixPerspectiveFovLH((D3DXMATRIX*)&m_proj, toRad( 45.f ), aspect_ratio, 0.f, 100.0f ); and this is my clear call void Context::clear( Vec4& color ) { if( this->m_is_lost ) return; this->m_device->Clear(0, NULL , D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, D3DCOLOR_XRGB(0,0,50), 1.0, 0); } If I give anything other than 0 for near plane the model barely shows up and if camera is zoomed the geometry seems to be appearing partly and disappearing. I know that my view matrix is ok because if I use 0 near plane the geometry is rendered correctly but then the flickering happens. I used simple HLSL posted bellow. If someone faced the same situation please assist me.. EDIT : I used blender to export mesh to custom format, although unlikely but is there any winding order issue causing this problem?? void GameApp::renderScene() { LPDIRECT3DDEVICE9 dev = ((LPDIRECT3DDEVICE9)Engine::Context()->ptr()); HRESULT hr = 0; Matrix u; bool res; w = u; v = m_cam->view_copy(); p = *Engine::DefaultView()->fov(); Matrix wvp = w * v * p; hr = dev->SetRenderState(D3DRS_DITHERENABLE, TRUE); hr = dev->SetRenderState( D3DRS_LIGHTING, FALSE ); //dev->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); hr = dev->SetRenderState( D3DRS_ZENABLE, TRUE ); hr = dev->SetRenderState( D3DRS_STENCILENABLE, FALSE ); dev->SetTransform( D3DTS_PROJECTION, (D3DXMATRIX*)&p); res = this->sh->vs_wvp( wvp ); res = this->sh->tex0( m_tex ); res = this->sh->use(); this->m_mesh->test_draw(); dev->SetPixelShader(NULL); dev->SetVertexShader(NULL); } #include "constants.hlsl" struct VS_INPUT { float3 position : POSITION0; float3 normal : NORMAL0; float2 tex0 : TEXCOORD0; float4 color0 : COLOR0; }; /* vertex shader output */ struct VS_OUTPUT { float4 hposition : POSITION0; float4 color0 : COLOR0; float2 tex0 : TEXCOORD0; }; VS_OUTPUT main( VS_INPUT IN ) { VS_OUTPUT OUT = (VS_OUTPUT)0; OUT.hposition = mul( float4( IN.position, 1.0 ), gWVP ); OUT.tex0 = IN.tex0; return OUT; } /* The pixel shader */ #include "constants.hlsl" sampler gTEX0; /* primary texture */ struct VS_OUTPUT { float4 hposition : POSITION0; float4 color0 : COLOR0; float2 tex0 : TEXCOORD0; }; struct PS_OUTPUT { float4 color : COLOR; }; PS_OUTPUT main( VS_OUTPUT IN ) { PS_OUTPUT OUT; OUT.color = tex2D( gTEX0, IN.tex0 ); return OUT; } A: The near plane parameter shall be strictly larger than zero. The smaller it is the more precision you burn close to the camera, and with zero, the projection matrix degenerates into unusability. If your geometry isn't where you want it to be when you use a conformant projection matrix, address that problem instead.
{ "pile_set_name": "StackExchange" }
Q: Why can't I get netcat talking to my Rails server? I have a Thin server running locally, serving a Rails app. Following an example in the netcat man page, I'm trying to use nc to talk to my server: echo -n "GET / HTTP/1.1\r\n\r\n" | nc 0.0.0.0 3000 But I get a 400 response: HTTP/1.1 400 Bad Request Content-Type: text/plain Connection: close Server: thin 1.6.1 codename Death Proof What am I missing? A: HTTP 1.1 requires providing a Host: header. You also need to add the -e flag to the echo command to escape character sequences, so echo -en "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n" | nc 0.0.0.0 3000 would work, or alternatively you could use HTTP 1.0 which does not require the Host: header, so echo -en "GET / HTTP/1.0\r\n\r\n" | nc 0.0.0.0 3000
{ "pile_set_name": "StackExchange" }
Q: jQuery code works in jsFiddle, but not on my site I've written a script for a login that creates a username by concatenating first + last name (on blur), removing whitespaces and removing special characters. Everything works fine in jsFiddle, but not on my site - I get 3 times error '$str' is not defined - so my guess is that the replace function on line 5 + 10 isn't fired. Any ideas what's wrong? http://jsfiddle.net/Hxjyy/2/ The code: jQuery().ready(function() { jQuery('#firstname').blur(function() { var $login = jQuery('#firstname').val().toLowerCase()+jQuery('#firstname').val().toLowerCase(); $login = $login.replace(/\s/g, ""); $login = replaceChars($login); jQuery("#login").val($login); }); jQuery('#lastname').blur(function() { var $login = jQuery('#firstname').val().toLowerCase()+jQuery('#lastname').val().toLowerCase(); $login = $login.replace(/\s/g, ""); $login = replaceChars ($login); jQuery("#login").val($login); }); function replaceChars($str) { var charMap = { é:'e',è:'e',ë:'e',ê:'e',à:'a', ç:'c',á:'a',ö:'o' }; var str_array = $str.split(''); for( var i = 0, len = str_array.length; i < len; i++ ) { str_array[ i ] = charMap[ str_array[ i ] ] || str_array[ i ]; } $str= str_array.join(''); return($str); } }); A: I just discovered that the problem was caused by the special characters in the replaceChars function - if I replace them with the Javascript entities like \u00EB it works fine...
{ "pile_set_name": "StackExchange" }
Q: Integer number truncated when writing to text file in PHP? I wrote a download counter: $hit_count = @file_get_contents('download.txt'); $hit_count++; @file_put_contents('download.txt', $hit_count); header('Location: file/xxx.zip'); As simple as that. The problem is the stats number is truncated to 4 digits thus not showing the real count: http://www.converthub.com/batch-image-converter/download.txt The batch image converter program gets downloaded a couple hundred times per day and the PHP counter has been in place for months. The first time I found out about this was about 2 months ago when I was very happy that it hit 8000 mark after a few weeks yet a week after that it was 500 again. And it happened again and again. No idea why. Why? A: You're probably suffering a race condition in the filesystem, you're attempting to open and read a file, then open the same file and write to it. The operating system may not have fully released its original lock on the file when you close it for reading then open it for writing again straight away. If the site is as busy as you say, then you could even have issues of multiple instances of your script trying to access the file at the same time Failing that, do all your file operations in one go. If you use fopen (), flock (), fread (), rewind (), fwrite () and fclose () to handle the hit counter updating you can avoid having to close the file and open it again. If you use r+ mode, you'll be able to read the value, increment it, and write the result back in one go. None of this can completely guarantee that you won't hit issues with concurrent accesses though. I'd strongly recommend looking into a different approach to implementing your hit counter, such as a database driven counter.
{ "pile_set_name": "StackExchange" }
Q: Proving the set of all finite or countable unions of intervals is not a Sigma Algebra I would like to extend on a question I asked here Consider a set $J$ of all (open, closed, half-open, singleton, empty) intervals on $[0,1]$ Now consider further a set $B$ which is the set of all finite or countable unions of elements of $J$. According to the text I'm reading, $B$ is not a $\sigma$-algebra. I suspect that it is because it is not closed under countable intersections, however I can't understand why. Surely any countable intersection is simply an interval or the empty set? Can't come up with any sort of contradiction. A: The complement of the middle-thirds Cantor set is a countable union of (open) intervals. However, the Cantor set itself has uncountably many elements, and any two of them are separated by a point not in the Cantor set. So no countable union of intervals can produce it. Thus $B$ is not closed under complement and therefore it is not a $\sigma$-algebra.
{ "pile_set_name": "StackExchange" }
Q: How to save dynamic select list value into config table in Drupal 8? I wanted to show list of fields per content type in admin config form. After saving the form, selected list value should get save into config table. public function buildForm(array $form, FormStateInterface $form_state) { foreach (node_type_get_types() as $content_type) { $entity_type_id = 'node'; $fields = \Drupal::entityManager()->getFieldDefinitions('node', $content_type->get('type')); if ($fields) { $options = array(); foreach ($fields as $field_name => $field_definition) { if (!empty($field_definition->getTargetBundle())) { $options[$field_name] = $field_definition->getLabel(); } } $form['test']['test_' . $content_type->get('type') . '_field'] = array( '#type' => 'select', '#title' => $content_type->get('name'), '#options' => array_merge(array('0' => t('Auto')), $options), '#default_value' => $config->get('test_' . $content_type->get('type') . '_field') ? $config->get('test_' . $content_type->get('type') . '_field') : '', ); } } } Here is submit handler public function submitForm(array &$form, FormStateInterface $form_state) { foreach (node_type_get_types() as $content_type) { $this->config('test.settings') ->set('test_' . $content_type->get('type') . '_field', $form_state->getValue('test', 'test_' . $content_type->get('type') . '_field')) ->save(); } parent::submitForm($form, $form_state); } After saving admin form, test_article_field and test_page_field is getting saved instead of selected field. Any help would be appreciated? A: There is some problem in the submit handler. Replace $this->config('test.settings') ->set('test_' . $content_type->get('type') . '_field', $form_state->getValue('test', 'test_' . $content_type->get('type') . '_field')) ->save(); line with $this->config('test.settings') ->set('test_' . $content_type->get('type') . '_field', $form_state->getValues('test_' . $content_type->get('type') . '_field')) ->save(); Hope that this helps you.
{ "pile_set_name": "StackExchange" }
Q: Why direct communication between fragments is not recommended? while learning android fragments on developer.android.com it is specified that direct communication between two fragment is not recommended. I want to know what will be the consequences and the cases in which communication between two Fragments would fail? A: Well, with Fragments you aren't always sure if they will be alive and attached at the time of communication. Whether Fragments are attached and available or not might also depend on device layout or size. If you're absolutely sure that your Fragments will both be attached to your activity and available at the same time, then I suppose you can communicate directly. Having said that, Fragments are meant to be logical, standalone units. From the docs: You can think of a fragment as a modular section of an activity It kind of breaks the model if the fragments are affecting each other directly. Why not rather define an interface in your Activity and get Fragment A to call a method in the Activity? Then your Activity can check whether Fragment B is available and can then call the appropriate function in Fragment B. Here is the docs suggestion
{ "pile_set_name": "StackExchange" }
Q: SQL Multi line query in C# using SQLCommand I want to load specific data from different tables in SQL Server using C# But i got an error Incorrect syntax near the keyword 'as'. Incorrect syntax near 'EP'. Incorrect syntax near the keyword 'AND'. The code run well as i have put a messageBox to show the query, a messageBox popsup and show full query but after that i have got an error as i have mentioned above Here is the Code private void FillGridView() { CS = ConfigurationManager.ConnectionStrings["HRMSConnectionString"].ConnectionString; using (SqlConnection con = new SqlConnection(CS)) { SqlCommand cmd = new SqlCommand(query, con); con.Open(); SqlDataAdapter ad = new SqlDataAdapter(cmd); ad.Fill(dt); gvShowAllData.DataSource = dt; } } Here is the Query string query = @"Select 'ACTIVE POSTING' as POSTING,e.emp_id,e.emp_name,e.emp_fathername,e.emp_nic,e.emp_contact" + ",D.desig_id,D.desig_name" + "from EMP_Master as e,EMP_Posting_Log as p,EMP_Designation AS D" + "where e.emp_id=p.emp_id" + "AND P.desg_id=D.desig_id" + "and p.status='ACTIVE'" + "AND E.emp_name LIKE '%" + tbSearchName.Text + "%'" + "UNION" + "Select 'INACTIVE POSTING' as POSTING,e.emp_id,e.emp_name,e.emp_fathername,e.emp_nic,e.emp_contact" + ",NULL,NULL" + "from EMP_Master as e" + "WHERE E.emp_id IN (SELECT DISTINCT EP.emp_id FROM EMP_Posting_Log AS EP" + "WHERE EP.status='INACTIVE')" + "AND E.emp_name LIKE '%" + tbSearchName.Text + "%'" + "UNION" + "Select 'NOT POSTING' as POSTING,e.emp_id,e.emp_name,e.emp_fathername,e.emp_nic,e.emp_contact" + ",NULL,NULL" + "from EMP_Master as e" + "WHERE E.emp_id NOT IN (SELECT DISTINCT EP1.emp_id FROM EMP_Posting_Log AS EP1)" + "AND E.emp_name LIKE '%" + tbSearchName.Text + "%'"; A: You need spaces between your string parts. You are expecting the concatenation to create new lines but the reality is that is not how it works. If you want a new line or a space between strings you need to add that in the string. The more important issue is that your query is vulnerable to sql injection attacks. You should always use parameters for user input. string query = @"Select 'ACTIVE POSTING' as POSTING,e.emp_id,e.emp_name,e.emp_fathername,e.emp_nic,e.emp_contact,D.desig_id,D.desig_name from EMP_Master as e,EMP_Posting_Log as p,EMP_Designation AS D where e.emp_id=p.emp_id AND P.desg_id=D.desig_id and p.status='ACTIVE' AND E.emp_name LIKE @tbSearchName UNION Select 'INACTIVE POSTING' as POSTING,e.emp_id,e.emp_name,e.emp_fathername,e.emp_nic,e.emp_contact,NULL,NULL from EMP_Master as e WHERE E.emp_id IN (SELECT DISTINCT EP.emp_id FROM EMP_Posting_Log AS EP WHERE EP.status='INACTIVE') AND E.emp_name LIKE @tbSearchName UNION Select 'NOT POSTING' as POSTING,e.emp_id,e.emp_name,e.emp_fathername,e.emp_nic,e.emp_contact,NULL,NULL from EMP_Master as e WHERE E.emp_id NOT IN (SELECT DISTINCT EP1.emp_id FROM EMP_Posting_Log AS EP1) AND E.emp_name LIKE @tbSearchName"; as for adding a parameter: cmd.Parameters.Add(new SqlParameter("@tbSearchName", SqlDbType.VarChar) {Value = "%" + tbSearchName.Text + "%"}); A: although it appears 'in lines' in your code, you are just making one big line of SQL and your spaces are incorrect - you could try something like System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendLine(@"Select 'ACTIVE POSTING' as POSTING,e.emp_id,e.emp_name,e.emp_fathername,e.emp_nic,e.emp_contact"); sb.AppendLine(@",D.desig_id,D.desig_name"); sb.AppendLine(@"from EMP_Master as e,EMP_Posting_Log as p,EMP_Designation AS D"); sb.AppendLine(@"where e.emp_id=p.emp_id"); sb.AppendLine(@"AND P.desg_id=D.desig_id"); sb.AppendLine(@"and p.status='ACTIVE'"); sb.AppendLine("AND E.emp_name LIKE '%" + tbSearchName.Text.Replace(@"'",@"''") + "%'"); //escape single quote to avoid SQL injection attack //....and so on with the rest of your lines string query = sb.ToString(); //then as before
{ "pile_set_name": "StackExchange" }
Q: Processing ForeignSecurityPrincipal DomainA and DomainB trust each other. Some DomainB users are members of DomainA local domain groups. How can I get ForeignSecurityPrincipal in PowerShell and get list of its groups? A: That was surprisingly simple: Get-ADObject -Filter {ObjectClass -eq "foreignSecurityPrincipal"} -Properties msds-principalname,memberof where "msds-principalname" is sAMAccountName, so I can search now through FSPs by sAMAccountName and get its groups.
{ "pile_set_name": "StackExchange" }
Q: Django Order Ascending & Descending Let say, I want to order the Threads by total Votes, Views and Comments. But they order models is instanced from Thread model. here is my models.py class Thread(models.Model): .... rating = RatingField(can_change_vote=True) def get_comments(self): return Comment.objects.filter(thread__pk=self.pk) def get_visitors(self): return Visitor.objects.filter(thread__pk=self.pk) def get_rating_frequence(self): return self.rating.get_difference() class Comment(models.Model): thread = models.ForeignKey(Thread, ...) .... class Visitor(models.Model): thread = models.ForeignKey(Thread, ...) .... and the model of Vote using django updown For more: https://github.com/weluse/django-updown/blob/master/updown/models.py#L20 class Vote(models.Model): content_type = models.ForeignKey(ContentType, related_name="updown_votes") object_id = models.PositiveIntegerField() .... And here is my views.py def threads(request): .... template_name = 'foo/bar/threads.html' threads = Thread.objects.published() get_sorted_ratings = request.GET.get('sr', '') get_sorted_visitors = request.GET.get('sv', '') get_sorted_comments = request.GET.get('sc', '') context = { 'threads': threads, .... } return render(request, template_name, context) Question is, how i can order multiple models bassed on Thread model? In my test: >>> from django.db.models import (Q, Count, Sum) >>> from myapp.models import (Thread, Comment, Visitor) >>> t = Thread.objects.published() >>> Visitor.objects.filter(thread__in=t).values('thread').annotate(visit=Count('thread__id')).order_by('-visit') <QuerySet [{'thread': 3, 'visit': 8}, {'thread': 10, 'visit': 8}, {'thread': 9, 'visit': 7}, {'thread': 48, 'visit': 1}, {'thread': 57, 'visit': 1}, {'thread': 79, 'visit': 1}, {'thread': 103, 'visit': 1}, {'thread': 104, 'visit': 1}, {'thread': 132, 'visit': 1}, {'thread': 178, 'visit': 1}, {'thread': 216, 'visit': 1}, {'thread': 227, 'visit': 1}, {'thread': 267, 'visit': 1}, {'thread': 292, 'visit': 1}, {'thread': 300, 'visit': 1}, {'thread': 305, 'visit': 1}, {'thread': 1201, 'visit': 1}, {'thread': 1252, 'visit': 1}, {'thread': 1265, 'visit': 1}, {'thread': 1929, 'visit': 1}]> >>> >>> Comment.objects.filter(thread__in=t).values('thread').annotate(total=Count('thread__id')).order_by('-total') <QuerySet [{'total': 9, 'thread': 10}, {'total': 7, 'thread': 9}, {'total': 3, 'thread': 3}, {'total': 3, 'thread': 213}, {'total': 2, 'thread': 35}, {'total': 2, 'thread': 47}, {'total': 2, 'thread': 104}, {'total': 2, 'thread': 187}, {'total': 2, 'thread': 233}, {'total': 2, 'thread': 235}, {'total': 2, 'thread': 304}, {'total': 1, 'thread': 34}, {'total': 1, 'thread': 68}, {'total': 1, 'thread': 82}, {'total': 1, 'thread': 95}, {'total': 1, 'thread': 137}, {'total': 1, 'thread': 216}, {'total': 1, 'thread': 231}, {'total': 1, 'thread': 244}, {'total': 1, 'thread': 253}, '...(remaining elements truncated)...']> >>> >>> # rating likes, id=thread.id, total=total rating >>> t.values('id').annotate(total=Sum('rating_likes')).order_by('-total') <QuerySet [{'total': 3, 'id': 10}, {'total': 2, 'id': 104}, {'total': 2, 'id': 233}, {'total': 2, 'id': 235}, {'total': 2, 'id': 304}, {'total': 1, 'id': 3}, {'total': 1, 'id': 9}, {'total': 1, 'id': 34}, {'total': 1, 'id': 35}, {'total': 1, 'id': 47}, {'total': 1, 'id': 68}, {'total': 1, 'id': 82}, {'total': 1, 'id': 95}, {'total': 1, 'id': 137}, {'total': 1, 'id': 187}, {'total': 1, 'id': 213}, {'total': 1, 'id': 216}, {'total': 1, 'id': 231}, {'total': 1, 'id': 244}, {'total': 1, 'id': 253}, '...(remaining elements truncated)...']> >>> >>> # rating dislikes, id=thread.id, total=total rating >>> t.values('id').annotate(total=Sum('rating_dislikes')).order_by('-total') <QuerySet [{'total': 2, 'id': 3}, {'total': 1, 'id': 9}, {'total': 1, 'id': 10}, {'total': 1, 'id': 35}, {'total': 1, 'id': 47}, {'total': 1, 'id': 187}, {'total': 0, 'id': 29}, {'total': 0, 'id': 34}, {'total': 0, 'id': 42}, {'total': 0, 'id': 45}, {'total': 0, 'id': 48}, {'total': 0, 'id': 51}, {'total': 0, 'id': 53}, {'total': 0, 'id': 57}, {'total': 0, 'id': 68}, {'total': 0, 'id': 72}, {'total': 0, 'id': 75}, {'total': 0, 'id': 76}, {'total': 0, 'id': 77}, {'total': 0, 'id': 79}, '...(remaining elements truncated)...']> >>> >>> Thread.objects.get(pk=3).rating.dislikes 2 >>> Thread.objects.get(pk=9).rating.dislikes 1 >>> Finally, I updated it: and my code is worked well as what already suggested by @prakhar-trivedi at https://stackoverflow.com/a/41775990/6396981 threads = Thread.objects.published() def sorted_threads(values, order_by='-total', next_order=None): """ return sorted threads from values by `order_by` :param `values`, an example: values = Comment.objects.filter(thread__in=threads) .values('thread').annotate(total=Count('thread__id')) """ if next_order is not None: top_values = values.order_by(order_by).order_by(next_order) else: top_values = values.order_by(order_by) list_pk_threads = [pk['thread'] for pk in top_values] filter_threads = list(threads.filter(pk__in=list_pk_threads)) return sorted(filter_threads, key=lambda i: list_pk_threads.index(i.pk)) For complete stuff found at this gist. But, I just don't know how to combine it at all. For example: ordering from votes=1, views=1, comments=1. And the result of it is; the Thread Objects that ordered from popular by votes, popular by views and also from popular by comments. Another example: ordering from votes=1 views=1. The output of this condition should return the Thread Objects that ordered only from popular by votes, and popular by views. 1 as True and -1 as False A: You can use order_by('-thread'), like this : Comment.objects.filter(thread__in=t).values('thread').annotate(total=Count('thread__id')).order_by('-thread') And if you want to order records by rating of thread model,You can use double underscore "__" on thread key for foreign key lookup, like this : # rating likes Comment.objects.filter(thread__in=t).values('thread').annotate(total=Count('thread__id')).order_by('thread__rating_likes') Use this in all your queries as per the requirements.
{ "pile_set_name": "StackExchange" }
Q: Git clone remote repo into another remote repo Cloning git repo from remote server to local computer is rather easily done the standard way, but I need to clone a remote repo into another remote repo, is it possible? P.S. I come up with this problem because I just can't fork my own project on GitHub to create a child project, I can fork the projects of other users only. This is about cloning to make a whole child project from parent project, not just a submodule. A: Cloning git repo from remote server to local computer is rather easily done the standard way, but I need to clone a remote repo into another remote repo, is it possible? In git you can't have .git folder inside another git folder What can you do? Clone the original repo Add new remote git remote add <origin2> <url2> Use the code from both the repositories inside a single repo Now you can pull and merge the branches from the 2 remotes and have the code of both of them in a single repository. As you can see in the image below you will have 2 repositories which builds up your big repository. # clone first repository git clone <repo1> # add remote git remote add <remote2> <url2> # display the list of all the remotes git remote -v
{ "pile_set_name": "StackExchange" }
Q: JSpinner Arrows in odd positioning when used with JLabel Hello So i have created a JFrame with a JSpinner inside (as you can see in the picture). Right now, the BorderLabel is showing in the Jspinner (as it should) but the arrows on the JSpinner are there as a part of the entire thing instead of just the JSpinner field. I would like help to find out how to put the JSpinner arrows on the bar. Thank you. For you who asked for code, Also I miss stated JLabel Earlier. I meant TitledBorder import java.awt.ComponentOrientation; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; public class ex extends JFrame{ public static void main(String[] args){ new ex(); } ex(){ super("test"); setSize(200,100); SpinnerModel sm = new SpinnerNumberModel(3,1,25,1); JSpinner shiftIn = new JSpinner(sm); JPanel p = new JPanel(); shiftIn.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); shiftIn.setBorder(new CompoundBorder(new TitledBorder(new EmptyBorder(0, 0, 0, 0), "Shift Key"), shiftIn .getBorder())); p.add(shiftIn); add(p); setVisible(true); } } A: shiftIn.setBorder(new CompoundBorder( new TitledBorder(new EmptyBorder(0, 0, 0, 0), "Shift Key"), shiftIn.getBorder())); This is not the sort of thing that a titled border was made for! Use a JLabel and put it in the PAGE_START of a BorderLayout, put the JSpinner in the PAGE_END. Add that container (the panel) where the spinner is currently added. (Then add a mnemonic for the label and make it the 'label for' the spinner.) This is how to use that idea inside another layout (GridLayout in this example).. import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class ex extends JFrame { public static void main(String[] args) { new ex(); } ex() { super("test"); // imagine this is actually using GridBagLayout JPanel ui = new JPanel(new GridLayout(0, 3,4,4)); ui.setBorder(new EmptyBorder(4, 4, 4, 4)); SpinnerModel sm = new SpinnerNumberModel(3, 1, 25, 1); JSpinner shiftIn = new JSpinner(sm); JLabel l = new JLabel("Shift Key"); JPanel p = new JPanel(new BorderLayout()); p.add(l, BorderLayout.PAGE_START); p.add(shiftIn, BorderLayout.PAGE_END); add(ui); for (int ii=0; ii<9; ii++) { if (ii==4) { ui.add(p); } else { ui.add(new JButton("Button")); } } pack(); setVisible(true); } } A: You appear to be running into risk by messing with the JSpinner's border. Myself, I would wrap my JSpinner in a JPanel and then give that wrapper JPanel the desired border. For example: import java.awt.BorderLayout; import java.awt.ComponentOrientation; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; @SuppressWarnings("serial") public class Ex extends JFrame { public static void main(String[] args) { new Ex(); } Ex() { super("test"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); SpinnerModel sm = new SpinnerNumberModel(3, 1, 25, 1); JSpinner shiftIn = new JSpinner(sm); JPanel spinnerWrapper = new JPanel(new BorderLayout()); spinnerWrapper.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEmptyBorder(0, 0, 0, 0), "Shift Key")); spinnerWrapper.add(shiftIn); shiftIn.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); add(spinnerWrapper); pack(); setVisible(true); } }
{ "pile_set_name": "StackExchange" }
Q: Why exactly did Cartman let Kyle in on his voting scandal in Obama Wins? South Park season 16 finale episode "Obama Wins" starts off with Cartman calling Kyle over to look at the boxes of stolen ballots- to which of course, Kyle vows to not let Cartman get away with it. Cartman had planned to get Kyle to try and stop him- but how exactly did this contribute to his plan? His rival even ends up ultimately ruining his scheme in the end. So what exactly was the point of this, and how did it benefit his scheme? A: Cartman was letting Kyle to get external help only to get him fooled. Similar to Cow boy and the Tiger story. From what happens in the episode, we can assume that Cartman had two plans to execute. Call a friend and ask them to help him in the plan. Take a promise not to spill the secret to anyone. If they don't agree with him, let them go call the police or other external help. Then he hides all the ballots. He convinces them that he is innocent. That is what he did in the case in Kyle when he brought cops for raiding his home. By doing this, no one would suspect that he is involved in the voting fraud. But the plan backfired because Kyle also informed it to his friends where he finds out that Butters was also part of Cartman's plan in hiding the ballots. This was not expected by Cartman. It is highly possible Cartman took a promise from Butters not to spill this secret to anyone. He asked Kyle too but Kyle didn't promise. When Cartman visits Butters in the hospital, Butters: Please, Eric! I tried to be quiet, I swear! Cartman: Shhhh, it's okay, Butters. Nobody's going to find the election ballots. I have them hidden away, somewhere nobody would ever look. A place in town people barely even know exists. Obama Wins episode Script
{ "pile_set_name": "StackExchange" }
Q: static variable thread_local with open_MP I tried to use open_MP and use omp prallel for, but I ran into a problem. I use a lot of different static class members like class A { public: static std::vector<double> v; } which I initialize with an empty vector in my .cpp file. After some time I make some calculations and finally fill the vector v with my initial values: A::v = {1,2,3}; after some time I have a big for loop which could (but must not) change the value of v again. Now I tried to use open_MP to speed things up: #pragma omp parallel for for (int i = 0; i < nsched; ++i) { ... } because I want each loop to have its own instance of the static vector I simply tried to make it thread_local. class A { public: static thread_local std::vector<double> v; } My problem is now, as soon as I get into the parallel for loop my vector v is no longer {1,2,3}, it is simply empty. How can I change this? I assume that at the beginning v is thread local for the "main-thread" and the newly created "child-threads" don't get the Information about v. Is there a way to easily solve this problem? Or do I need to initialize v for each thread? (this would not be great, because the initialization takes quite some time and it is unlikely (but possible) that I need to change the parameters in each for loop) A: If you write an initialisation thread_local std::vector<double> A::v {1,2,3}; you will get a copy of v containing {1,2,3} in all threads. But if you write an assignment A::v = {1,2,3}; you will not. A::v will be initialised afresh for each thread and not copied from any other thread. If you need a thread local copy of an array initialised to some set of values, you will have to make sure the action (either initialisation or assignment) that puts the values there is performed in each thread.
{ "pile_set_name": "StackExchange" }
Q: How to work with null pointers in a std::vector Say I have a vector of null terminates strings some of which may be null pointers. I don't know even if this is legal. It is a learning exercise. Example code std::vector<char*> c_strings1; char* p1 = "Stack Over Flow"; c_strings1.push_back(p1); p1 = NULL; // I am puzzled you can do this and what exactly is stored at this memory location c_strings1.push_back(p1); p1 = "Answer"; c_strings1.push_back(p1); for(std::vector<char*>::size_type i = 0; i < c_strings1.size(); ++i) { if( c_strings1[i] != 0 ) { cout << c_strings1[i] << endl; } } Note that the size of vector is 3 even though I have a NULL at location c_strings1[1] Question. How can you re-write this code using std::vector<char> What exactly is stored in the vector when you push a null value? EDIT The first part of my question has been thoroughly answered but not the second. Not to my statisfaction at least. I do want to see usage of vector<char>; not some nested variant or std::vector<std::string> Those are familiar. So here is what I tried ( hint: it does not work) std::vector<char> c_strings2; string s = "Stack Over Flow"; c_strings2.insert(c_strings2.end(), s.begin(), s.end() ); // char* p = NULL; s = ""; // this is not really NULL, But would want a NULL here c_strings2.insert(c_strings2.end(), s.begin(), s.end() ); s = "Answer"; c_strings2.insert(c_strings2.end(), s.begin(), s.end() ); const char *cs = &c_strings2[0]; while (cs <= &c_strings2[2]) { std::cout << cs << "\n"; cs += std::strlen(cs) + 1; } A: You don't have a vector of strings -- you have a vector of pointer-to-char. NULL is a perfectly valid pointer-to-char which happens to not point to anything, so it is stored in the vector. Note that the pointers you are actually storing are pointers to char literals. The strings are not copied. It doesn't make a lot of sense to mix the C++ style vector with the C-style char pointers. Its not illegal to do so, but mixing paradigms like this often results in confused & busted code. Instead of using a vector<char*> or a vector<char>, why not use a vector<string> ? EDIT Based on your edit, it seems like what your'e trying to do is flatten several strings in to a single vector<char>, with a NULL-terminator between each of the flattened strings. Here's a simple way to accomplish this: #include <algorithm> #include <vector> #include <string> #include <iterator> using namespace std; int main() { // create a vector of strings... typedef vector<string> Strings; Strings c_strings; c_strings.push_back("Stack Over Flow"); c_strings.push_back(""); c_strings.push_back("Answer"); /* Flatten the strings in to a vector of char, with a NULL terminator between each string So the vector will end up looking like this: S t a c k _ O v e r _ F l o w \0 \0 A n s w e r \0 ***********************************************************/ vector<char> chars; for( Strings::const_iterator s = c_strings.begin(); s != c_strings.end(); ++s ) { // append this string to the vector<char> copy( s->begin(), s->end(), back_inserter(chars) ); // append a null-terminator chars.push_back('\0'); } } A: I have a funny feeling that what you would really want is to have the vector contain something like "Stack Over Flow Answer" (possibly without space before "Answer"). In this case, you can use a std::vector<char>, you just have to push the whole arrays, not just pointers to them. This cannot be accomplished with push_back, however vector have an insert method that accept ranges. /// Maintain the invariant that the vector shall be null terminated /// p shall be either null or point to a null terminated string void push_back(std::vector<char>& v, char const* p) { if (p) { v.insert(v.end(), p, p + strlen(p)); } v.push_back('\0'); } // push_back int main() { std::vector<char> v; push_back(v, "Stack Over Flow"); push_back(v, 0); push_back(v, "Answer"); for (size_t i = 0, max = v.size(); i < max; i += strlen(&v[i]) + 1) { std::cout << &v[i] << "\n"; } } This uses a single contiguous buffer to store multiple null-terminated strings. Passing a null string to push_back results in an empty string being displayed.
{ "pile_set_name": "StackExchange" }
Q: UNIQUE Column with multiple NULL values in visual studio I want to have a UNIQUE constraint on my Barcode column which may contain null values. How do I create the constraint that allows multiple null values? I use a local Database.sdf file (Microsoft SQL Server Compact 4.0 with the .NET Framework Data Provider for Microsoft SQL Server Compact 4.0). I tried this : SqlCeConnection con = null; con = new SqlCeConnection(@"Data Source=|DataDirectory|\Database.sdf"); con.Open(); try { SqlCeCommand cmd = con.CreateCommand(); cmd.CommandText = "CREATE UNIQUE NONCLUSTERED INDEX Barcodex ON Products(Barcode) WHERE Barcode IS NOT NULL"; cmd.ExecuteReader(); } catch (Exception ex) { MessageBox.Show(ex.Message); } but it is not working. The error I got : There was an error parsing the query,[Token line number =1,Token line offset =64,Token in error = WHERE] Any help? A: Update: Filtered Indexes are NOT supported in SQL Server Compact 4.0 Ref: Differences Between SQL Server Compact and SQL Server The TSQL syntax is correct. (Assuming you have SQL Server 2008+. Filtered Indexes were introduced in SQL Server 2008) Change this: cmd.ExecuteReader(); to this cmd.ExecutNonQuery(); Also, you should wrap your connection in a using block.
{ "pile_set_name": "StackExchange" }
Q: What is LINQ hosting and should I care? In terms of ISPs and webhosting, what is LINQ hosting? What does it give me as a developer or a site admin? I've looked around and all the sites I found fail to explain what LINQ hosting is. They explain what LINQ is but fall short on the hosting part. What are you using LINQ hositng for? EDIT 1: I know what LINQ is and love it! Why are ISPs offering something inherent in the framework? Edit 2: Examples include: http://winhost.com/ http://www.arvixe.com/linq_hosting http://www.windowshostingasp.net/Hosting_ASP.NET_plans/Hosting_ASP_NET_LINQ.aspx - from their website, "The ASP.NET LINQ Hosting plan means that the Windows hosting provider support MS LINQ (Language Integrated Query) hosting." A: It's a cheap trick for advertising. Linq is getting to be a hot subject and they try to score easy contracts with managers that have no clue except that the tech people said they used linq for the new project ;) I mean "Fully adheres to all LINQ hosting system requirements", what requirements? Does that mean that if I need a linq provider for an old Paradox database they do that :D
{ "pile_set_name": "StackExchange" }
Q: Changing background color of a bootstrap panel I am trying to change the background color of a panel using javascript to emulate "selected" functionality. So, on click I get hold of the div by ID and change its background color. It works fine but only momentarily and again resets the background color, and I have no idea why? DJANGO HTML Template <div class="panel-group"> {% if articles %} {% for article in articles %} <div class="panel panel-success" id="aid_{{ article.articleId }}"> <div class="panel-body"> <a href="" onclick="populateArticle({{ article.articleId }})" style="font-size: 1.2em"><b>{{ article.title }}</b></a><br/> <span style="color:darkgrey; font-size:.9em; font-family:sans-serif; font-style:italic">{{ article.source }} - {{ article.date }}</span><br/> {{ article.sentences }} </div> </div> {% endfor %} {% else %} NO ARTICLES PRESENT {% endif %} </div> Javascript function populateArticle(aid) { document.getElementById('aid_'+aid).style.backgroundColor="#DEF1DE"; } Also here is a link to a gif I recorded that shows the behavior: http://g.recordit.co/fSoTieo5Qn.gif (copy-paste the link in a new tab in case if it gives error). Any ideas why this is happening? A: You are not preventing default <a> tag behavior, so Your page refreshes. onclick="populateArticle({{ article.articleId }});return false;" Should fix it.
{ "pile_set_name": "StackExchange" }
Q: Css transition on element that changes position on mousehover I have a Box that elevates when the user has his mouse hovering this box, and I do this with : .box:hover { position: relative; top: -10px; } I would like to know if it possible to make a smooth transition with the transition property ? If not, How should i go about getting this smooth effect ? A: You can use the CSS transition property. Read more here: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions Here is an example: .box { background: red; height: 50px; position: relative; top: 50px; transition: top 1000ms ease-in; width: 50px; } .box:hover { position: relative; top: 0; } <div class="box">Hey</div>
{ "pile_set_name": "StackExchange" }
Q: Why isnt node checked for nil value in start when transplanting binary tree Whilst I was reading CLRS I came across this: When TRANSPLANT replaces the subtree rooted at node u with the subtree rooted at node v, node u’s parent becomes node v’s parent, and u’s parent ends up having v as its appropriate child. TRANSPLANT(T, u, v) 1 if u.p == NIL 2 T.root = v 3 elseif u == u.p.left 4 u.p.left = v 5 else u.p.right = v 6 if v != NIL 7 v.p = u.p Lines 1–2 handle the case in which u is the root of T . Otherwise, u is either a left child or a right child of its parent. Lines 3–4 take care of updating u.p.left if u is a left child, and line 5 updates u.p.right if u is a right child. We allow v to be NIL, and lines 6–7 update v.p if v is non-NIL. Why wasn't v was checked for nil value in the starting of the procedure and if it was not checked then why was it checked in line 6. If v is nil then its parent will be its original parent and u's parent will reference to v - wouldn't this cause inconsistency in tree ? Context Transplant is the sub-procedure used in deletion of a node from a binary search tree. It is used in binary search tree not in RB Trees or B-Trees. Details about the book Edition - 3rd Print - 2nd PageNo - 296 A: If $v$ is NIL then transplanting $v$ just transplants an empty tree. This is fine. It is handled in the exact same way as transplanting an actual tree, the only difference being that we don't need to update $v$'s parent pointer. Could the code be structured differently? Probably. Why, then, did the authors choose this particular implementation? No deep reason. They programmed the algorithm, and that's the code they came up with. You might have come up with a different code. There's no one right answer in programming.
{ "pile_set_name": "StackExchange" }
Q: Absolute value of a number I want to take the absolute of a number by the following code in bash: #!/bin/bash echo "Enter the first file name: " read first echo "Enter the second file name: " read second s1=$(stat --format=%s "$first") s2=$(stat -c '%s' "$second") res= expr $s2 - $s1 if [ "$res" -lt 0 ] then res=$res \* -1 fi echo $res Now the problem I am facing is in the if statement, no matter what I changes it always goes in the if, I tried to put [[ ]] around the statement but nothing. Here is the error: ./p6.sh: line 13: [: : integer expression expected A: You might just take ${var#-}. ${var#Pattern} Remove from $var the shortest part of $Pattern that matches the front end of $var. tdlp Example: s2=5; s1=4 s3=$((s1-s2)) echo $s3 -1 echo ${s3#-} 1 A: I know this thread is WAY old at this point, but I wanted to share a function I wrote that could help with this: abs() { [[ $[ $@ ] -lt 0 ]] && echo "$[ ($@) * -1 ]" || echo "$[ $@ ]" } This will take any mathematical/numeric expression as an argument and return the absolute value. For instance: abs -4 => 4 or abs 5-8 => 3 A: $ s2=5 s1=4 $ echo $s2 $s1 5 4 $ res= expr $s2 - $s1 1 $ echo $res What's actually happening on the fourth line is that res is being set to nothing and exported for the expr command. Thus, when you run [ "$res" -lt 0 ] res is expanding to nothing and you see the error. You could just use an arithmetic expression: $ (( res=s2-s1 )) $ echo $res 1 Arithmetic context guarantees the result will be an integer, so even if all your terms are undefined to begin with, you will get an integer result (namely zero). $ (( res = whoknows - whocares )); echo $res 0 Alternatively, you can tell the shell that res is an integer by declaring it as such: $ declare -i res $ res=s2-s1 The interesting thing here is that the right hand side of an assignment is treated in arithmetic context, so you don't need the $ for the expansions.
{ "pile_set_name": "StackExchange" }
Q: Index page in Joomla I have a problem, wich I cant figure out ;( I have made a homepage in Joomla 2.5, and I need my front page to be different then the page made in Joomla. My best solution then, is to make the front page in pure HMTL, and then redirect to the site made in Joomla. Is this posible? or is there an easier way to do it? for example whit a plugin or something :S I hope you understand my quistion. Thanks in advance! A: Create a custom html page and create it an article and then assign this article to front page. In this way you can display your custom html page to hope page of joomla. Further if you want to remove even the headers and footers of the joomla page for home page this can be done in various ways Make module positions and display the header and footer in it an then in admin do not publish these modules for home page We have variable in template index.php which give us flags weather this is home page you can use this flag and put a condition like if this is home page dont display the header and footer. Hope it will help you.
{ "pile_set_name": "StackExchange" }
Q: SQL Server - export data using regular expression? I have a table I'm trying to export out of a SQL Server database. One of the columns is giving me a hard time and the Import and Export Wizard is throwing all kinds of errors. As soon as you remove this column, the export runs flawlessly. The column in the database is storing a full HTML document as a text data type. I want to export just the text out of each field from this column between the DIV tags without the HTML. For example: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <STYLE type=text/css> P, UL, OL, DL, DIR, MENU, PRE { margin: 0 auto;}</STYLE> <META content="MSHTML 6.00.2900.3429" name=GENERATOR> </HEAD> <BODY leftMargin=1 topMargin=1 rightMargin=1> <FONT face=Tahoma size=2> <DIV>[REDACTED TEXT THAT I WANT TO EXPORT]</DIV> </FONT> </BODY> </HTML> That is copy pasted out of one of the records. Every row has the same HTML in the record but I just want to export the redacted text. Putting aside that the guy who designed this database/application was a moron, how do I grab that data? I'd even settle for pulling the full record with HTML if I could get the export wizard to work. Edit: Here is the Import and Export Wizard report errors: Operation stopped... - Initializing Data Flow Task (Success) - Initializing Connections (Success) - Setting SQL Command (Success) - Setting Source Connection (Success) - Setting Destination Connection (Success) - Validating (Success) - Prepare for Execute (Success) - Pre-execute (Success) - Executing (Warning) Messages * Warning: Preparation SQL Task 1: Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done. (SQL Server Import and Export Wizard) * Warning: Preparation SQL Task 1: Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done. (SQL Server Import and Export Wizard) Copying to Query (Error) Messages Error 0xc0202009: Data Flow Task 1: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x00040EDA. Error 0xc0209029: Data Flow Task 1: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR. The "input "Destination Input" (45)" failed because error code 0xC020907B occurred, and the error row disposition on "input "Destination Input" (45)" specifies failure on error. An error occurred on the specified object of the specified component. There may be error messages posted before this with more information about the failure. Error 0xc0047022: Data Flow Task 1: SSIS Error Code DTS_E_PROCESSINPUTFAILED. The ProcessInput method on component "Destination - Query" (34) failed with error code 0xC0209029 while processing input "Destination Input" (45). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running. There may be error messages posted before this with more information about the failure. Error 0xc02020c4: Data Flow Task 1: The attempt to add a row to the Data Flow task buffer failed with error code 0xC0047020. Error 0xc0047038: Data Flow Task 1: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED. The PrimeOutput method on component "Source Query" (1) returned error code 0xC02020C4. The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing. There may be error messages posted before this with more information about the failure. Post-execute (Success) Messages Information 0x4004300b: Data Flow Task 1: "component "Destination - Query" (34)" wrote 7465 rows. A: In your select statement for that field, extract only the part that you want using SUBSTRING and CHARINDEX to cut out the parts between the tags, assuming you really only have one such tag per field. Below, [HTML] is actually a cast of your field into a VARCHAR, so where you see [HTML] you'll put this: CAST([YourHTMLFieldName] AS VARCHAR(MAX)) And this essentially says "give me the text between and : SELECT SUBSTRING([HTML], CHARINDEX('<DIV>', [HTML]), CHARINDEX([HTML], '</DIV>') - CHARINDEX([HTML], '<DIV>')) You'll probably need to play with it a bit, like if the output erroneously includes the "" tag you can change it to "CHARINDEX('') + 5".
{ "pile_set_name": "StackExchange" }
Q: Azure autoscale metricname values I need to define scale rule for my virtual machine I have read the following The MetricName and MetricNamespace are not values I just made up. These have to be precise. You can get these values from the MetricsClient API and there is some sample code in this link to show how to get the values. http://rickrainey.com/2013/12/15/auto-scaling-cloud-services-on-cpu-percentage-with-the-windows-azure-monitoring-services-management-library/ But its still not clear ho do I get a MetricName list of possible values as I didn't found any sample code for it A: Here is the code I used to get the available MetricNames for the cloud service. It was part of a unit test project, hence the [TestMethod] attribute. [TestMethod] public async Task GetMetricDefinitions() { // Build the resource ID string. string resourceId = ResourceIdBuilder.BuildCloudServiceResourceId( cloudServiceName, deploymentName, roleName ); Console.WriteLine("Resource Id: {0}", resourceId); //Get the metric definitions. var retrieveMetricsTask = metricsClient.MetricDefinitions.ListAsync(resourceId, null, null, CancellationToken.None); var metricListResponse = await retrieveMetricsTask; MetricDefinitionCollection metricDefinitions = metricListResponse.MetricDefinitionCollection; // Make sure something was returned. Assert.IsTrue(metricDefinitions.Value.Count > 0); // Display the metric definitions. int count = 0; foreach (MetricDefinition metricDefinition in metricDefinitions.Value) { Console.WriteLine("MetricDefinitio: " + count++); Console.WriteLine("Display Name: " + metricDefinition.DisplayName); Console.WriteLine("Metric Name: " + metricDefinition.Name); Console.WriteLine("Metric Namespace: " + metricDefinition.Namespace); Console.WriteLine("Is Altertable: " + metricDefinition.IsAlertable); Console.WriteLine("Min. Altertable Time Window: " + metricDefinition.MinimumAlertableTimeWindow); Console.WriteLine(); } } Here is the output of the test for my cloud service:
{ "pile_set_name": "StackExchange" }
Q: Can someone help fix my opacity scrolling effect When i place my div id tag #fading everything seems to fade at once. I want my parts to fade one by one; individually. I'm not so skilled at jquery, so some assistance would be great. Part 1 Part 2 Part 3 Part 4 Part 5 </div> </div> </nav> </div> <div style="background:white;"> <div class="row" id="fading" style="padding-left:15%; padding-right:15%;margin-top:100px;"> <div class="col-xs-8"> <p><b><em>Part 1:</b></em> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> <div class="col-xs-4"> <img src="./photo1.jfif" class="img-responsive "> </div> </div> <div class="row" style="padding-left:15%; padding-right:15%;margin-top:150px;"> <div class="col-xs-8"> <p><b><em>Part 2:</b></em> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> <div class="col-xs-4"> <img src="./photo2.jpg" class="img-responsive "> </div> </div> <div class="row" style="padding-left:15%; padding-right:15%;margin-top:200px;"> <div class="col-xs-8"> <p><b><em>Part 3:</b></em> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> <div class="col-xs-4"> <img src="./photo3.jfif" class="img-responsive "> </div> </div> <div class="row" style="padding-left:15%; padding-right:15%;margin-top:250px;"> <div class="col-xs-8"> <p><b><em>Part 4:</b></em> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> <div class="col-xs-4"> <img src="./photo4.jfif" class="img-responsive "> </div> </div> <div class="row" style="padding-left:15%; padding-right:15%;margin-top:300px;"> <div class="col-xs-8"> <p><b><em>Part 5:</b></em> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> <div class="col-xs-4"> <img src="./photo5.jfif" class="img-responsive "> </div> </div> </body> Here is the script that needs to be fixed or changed. <script> var target = $('#fading'); var targetHeight = target.outerHeight(); $(document).scroll(function(e){ var scrollPercent = (targetHeight - window.scrollY) / targetHeight; if(scrollPercent >= 0){ target.css('opacity', scrollPercent); } }); </script> A: I think this is what you might be after? http://codepen.io/anon/pen/pJomJY?editors=001 The script is now accounting for the scroll percentage on each .row element : $(window).scroll(function() { var posY = window.scrollY; $('.row').each(function(key, item) { var target = $(item); var topMargin = parseInt(target.css('margin-top')); var targetHeight = target.outerHeight(true); var targetStart = target.position().top; var targetEnd = targetStart+targetHeight; var scrollPercent = (targetEnd-posY)/targetHeight; scrollPercent = Math.max(0, Math.min(scrollPercent, 1)); if (posY > targetStart-topMargin) { target.css('opacity', scrollPercent); } }); });
{ "pile_set_name": "StackExchange" }
Q: How to create inner children without creating another class? I need to generate an XML like this: <Root> <Children> <InnerChildren>SomethingM</InnerChildren> </Children> </Root> The simplest solution is creating an inner class on the Root class: @Root class Root{ @Element Children element; @Root private static class Children{ @Element String innerChildren; } } But I want to avoid that inner class creation, since it will make things look strange while using Root objects. Is there anyway I can achieve that result without using inner classes? Expected way to create Root objects: Root root = new Root("Something"); What I want to avoid: Children child = new Children("Something"); Root root = new Root(child); // this could be achieve by injecting some annotations // in the constructor, but it's awful A: Just use a normal class instead of an inner class. It should still work: @org.simpleframework.xml.Root public class Root{ @Element Children children; public Root(){ children = new Children("Something"); } } @org.simpleframework.xml.Root public class Children{ @Element String innerChildren; public Children(String inner){ innerChildren = inner; } } Update: If you do not want to create another class, you can use the Path annotation by specifying an XPath expression for the innerChildren field. For example: @org.simpleframework.xml.Root class Root { @Element @Path("children") private final String innerChildren; public Root(String name){ innerChildren = name; } } Produces: <root> <children> <innerChildren>Something</innerChildren> </children> </root> Use the Namespace annotation to add name spaces. For example: @org.simpleframework.xml.Root @Namespace(reference="http://domain/parent", prefix="bla") class Root { @Element @Path("bla:children") @Namespace(reference="http://domain/parent", prefix="bla") private final String innerChildren; public Root(String name){ innerChildren = name; } } Produces: <bla:root xmlns:bla="http://domain/parent"> <bla:children> <bla:innerChildren>Something</bla:innerChildren> </bla:children> </bla:root> If using Styles to format the XML, it's necessary to do some modifications since they remove the : from the Element. The result using styles is: <bla:root xmlns:bla="http://domain/parent"> <blachildren> <bla:innerChildren>Something</bla:innerChildren> </blachildren> </bla:root> This is what I did: public class MyStyle extends CamelCaseStyle{ @Override public String getElement(String name) { if( name == null ){ return null; } int index = name.indexOf(':'); if( index != -1 ){ String theRest = super.getElement(name.substring(index+1)); return name.substring(0, index+1)+theRest; } return super.getElement(name); } } And now the result is the expected one: <bla:Root xmlns:bla="http://domain/parent"> <bla:Children> <bla:InnerChildren>Something</bla:InnerChildren> </bla:Children> </bla:Root>
{ "pile_set_name": "StackExchange" }
Q: stacking subsets of data.frame in R I have a dataset with one (or more) id variables and many subsets of variables which have the same structure. I would like to stack these subsets, in a long format : I have three subsets in my example, so the final table must have three times more rows, and the id variable has to be triplicated. The foo_data table is an example of my data in R : individuals <-c("individual1","individual2","individual3") subset1.var1 <- c("value1","value2","value3") subset1.var2 <- c("value4","value5","value6") subset1.var3 <- c("value7","value8","value9") subset2.var1 <- c("value10","value11","value12") subset2.var2 <- c("value13","value14","value15") subset2.var3 <- c("value16","value17","value18") subset3.var1 <- c("value19","value20","value21") subset3.var2 <- c("value22","value23","value24") subset3.var3 <- c("value25","value26","value27") foo_data <-data.frame(individuals,subset1.var1,subset1.var2,subset1.var3,subset2.var1, subset2.var2,subset2.var3,subset3.var1,subset3.var2,subset3.var3) foo_data And this is what I would like to have : structure(list(id = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("individual1", "individual2", "individual3"), class = "factor"), var1 = structure(1:9, .Label = c("value1", "value2", "value3", "value10", "value11", "value12", "value19", "value20", "value21" ), class = "factor"), var2 = structure(1:9, .Label = c("value4", "value5", "value6", "value13", "value14", "value15", "value22", "value23", "value24"), class = "factor"), var3 = structure(1:9, .Label = c("value7", "value8", "value9", "value16", "value17", "value18", "value25", "value26", "value27"), class = "factor")), .Names = c("id", "var1", "var2", "var3"), row.names = c(NA, 9L), class = "data.frame") # individuals time var1 var2 var3 # individual1.subset1 individual1 subset1 value1 value4 value7 # individual2.subset1 individual2 subset1 value2 value5 value8 # individual3.subset1 individual3 subset1 value3 value6 value9 # individual1.subset2 individual1 subset2 value10 value13 value16 # individual2.subset2 individual2 subset2 value11 value14 value17 # individual3.subset2 individual3 subset2 value12 value15 value18 # individual1.subset3 individual1 subset3 value19 value22 value25 # individual2.subset3 individual2 subset3 value20 value23 value26 # individual3.subset3 individual3 subset3 value21 value24 value27 The most obvious solution would be to compute a loop, like this one : stacked_foo <- foo_data[,c(1:4)] noms <- c("id","var1","var2","var3") names(stacked_foo) <- noms for (i in 2:3){ c(1,(3*i-1):(3*(i+1)-2)) temp <- foo_data[,c(1,(3*i-1):(3*(i+1)-2))] names(temp) <- noms stacked_foo <- rbind(stacked_foo,temp) print(i) } But isn't there something more fast, more concise, with a built in function like melt or stack ? A: Option 1: Base R's reshape function This is a task for reshape (from base R), but it wants your data.frame names to be in a slightly different format. Try this: names(foo_data) <- gsub("(.*)\\.(.*)", "\\2.\\1", names(foo_data)) names(foo_data) # [1] "individuals" "var1.subset1" "var2.subset1" "var3.subset1" "var1.subset2" # [6] "var2.subset2" "var3.subset2" "var1.subset3" "var2.subset3" "var3.subset3" If your names are in this format, you can just do: reshape(foo_data, direction = "long", idvar = "individuals", varying = 2:ncol(foo_data)) # individuals time var1 var2 var3 # individual1.subset1 individual1 subset1 value1 value4 value7 # individual2.subset1 individual2 subset1 value2 value5 value8 # individual3.subset1 individual3 subset1 value3 value6 value9 # individual1.subset2 individual1 subset2 value10 value13 value16 # individual2.subset2 individual2 subset2 value11 value14 value17 # individual3.subset2 individual3 subset2 value12 value15 value18 # individual1.subset3 individual1 subset3 value19 value22 value25 # individual2.subset3 individual2 subset3 value20 value23 value26 # individual3.subset3 individual3 subset3 value21 value24 value27 You can remove the funky rownames with rownames(your-new-df-name) <- NULL. Option 2: melt and dcast from "reshape2" If you wanted to go the reshape2 route, you can try (this is assuming the column names have not been changed): library(reshape2) dfL <- melt(foo_data, id.vars = "individuals") ## Warning ahead, but OK # Warning message: # attributes are not identical across measure variables; they will be dropped X <- colsplit(dfL$variable, c("SUB", "VAR"), pattern = "\\.") dcast(dfL, individuals + X$SUB ~ X$VAR, value.var = "value") # individuals X$SUB var1 var2 var3 # 1 individual1 subset1 value1 value4 value7 # 2 individual1 subset2 value10 value13 value16 # 3 individual1 subset3 value19 value22 value25 # 4 individual2 subset1 value2 value5 value8 # 5 individual2 subset2 value11 value14 value17 # 6 individual2 subset3 value20 value23 value26 # 7 individual3 subset1 value3 value6 value9 # 8 individual3 subset2 value12 value15 value18 # 9 individual3 subset3 value21 value24 value27 Option 3: "tidyr" + "dplyr" However, it seems like people are starting to look at tidyr + dplyr as the next big thing for reshaping data. I'm not sold yet on all the piping stuff, but the approach would be: library(dplyr) # devtools::install_github("hadley/tidyr") library(tidyr) foo_data %>% gather(vars, vals, subset1.var1:subset3.var3) %>% separate(vars, into = c("subset", "var")) %>% spread(var, vals) # individuals subset var1 var2 var3 # 1 individual1 subset1 value1 value4 value7 # 2 individual1 subset2 value10 value13 value16 # 3 individual1 subset3 value19 value22 value25 # 4 individual2 subset1 value2 value5 value8 # 5 individual2 subset2 value11 value14 value17 # 6 individual2 subset3 value20 value23 value26 # 7 individual3 subset1 value3 value6 value9 # 8 individual3 subset2 value12 value15 value18 # 9 individual3 subset3 value21 value24 value27 # Warning message: # attributes are not identical across measure variables; they will be dropped
{ "pile_set_name": "StackExchange" }
Q: Really Frustrating CSS Stepdown in IE In my site, I have two divs - right and left. Both are contained within a wrapper div. Here is my code: #wrapper{ width:1000px; height:750px; margin:auto; } #left{ width:500px; height:750px; float:left; position:relative; } #right{ width:500px; height:750px; float:right; position:relative; } In Chrome, no problem. In Firefox, no problem. In Safari, no problem. In Opera, no problem In IE, the #right div is in the same location horizontally, but vertically it's below the #left div. I've tried a few different techniques to remedy this. Setting the wrapper line height to 0, setting the right display to inline, reducing the size of the right and left divs (I thought maybe there was a margin/padding issue). I've run out of ideas now, can anybody offer any help of the issue? In All Browsers (except IE): In IE: A: There's nothing wrong with the CSS you've posted. It will work in all browsers as expected (I've decreased the widths in my example). What's happening is that you've got an element in one of your columns that's forcing the width of either #left or #right to be greater than 500px. The easiest way to fix this is to start removing elements until the float drop disappears. Then you can figure out if there's a solution for the offending element (i.e. set its width or set overflow: hidden or scroll).
{ "pile_set_name": "StackExchange" }
Q: How to redirect to another action in Struts in given time? For example, once an action has been called I want it to redirect to another action in 5 seconds. Is it possible? <action name="proceedupdateaccount" class="accountAction" method="updateAccount"> <result name="success" type="redirectAction">update-message</result> <result name="input">/accountupdateform.jsp</result> </action> <action name="update-message"> <result>/message.jsp</result> <!-- in 5 seconds this action should redirect to logout action --> </action> <action name="logout"> <result type="redirect">/j_spring_security_logout</result> </action> A: You can simply redirect them from the first action to another action using the <meta http-equiv="refresh" > code on the first action's result, like this: In the message.jsp: <meta http-equiv="refresh" content="5;url=logout">
{ "pile_set_name": "StackExchange" }
Q: How do I auto-login as root into the TTY upon boot? I am working on creating a real time kernel with RT-PREEMPT patch. I have created this kernel without graphic desktop. It comes up in the terminal mode with login prompt. The requirement is, it should boot and directly go to the shell prompt with root permission, without asking for login. How can this be done? Can you help me? A: source: http://linux.koolsolutions.com/2009/04/30/autologin-linux-console-mode. I have gotten it to work, but it is slightly different on Ubuntu. First install mingetty: sudo apt-get install mingetty Edit /etc/init/tty1.conf: Change: exec /sbin/getty -8 38400 tty1 To: exec /sbin/mingetty --autologin root --noclear tty1 Reboot and test. This worked for me on Ubuntu 12.04, if this works for you and you need more tty's to autologin start changing tty2.conf - tty6.conf and you should be good to go.
{ "pile_set_name": "StackExchange" }
Q: Why can I not successively increment a variable within a function? I'm trying to add 10 over and over for every invocation of d. It stays 20 every time, why? function d() { var c = [10]; c[0] += 10; alert(c[0]); // always 20 } d(); d(); d(); // supposed to be 20, 30, 40... A: You create a new array and assign it to c each time the function is called. That resets it. Move the assignment so it is outside the function (so it only runs once). var c = [10]; function d() { c[0] += 10; alert(c[0]); } d(); d(); d(); // will be 20, 30, 40... But globals are good source of bugs, so it is considered good style to wrap such things in closures to minimise the use of globals. var d =(function () { var c = [10]; function d() { c[0] += 10; alert(c[0]); }; return d; })(); d(); d(); d();
{ "pile_set_name": "StackExchange" }
Q: What is the meaning of ${arg##/*/} and {} \; in shell scripting Please find the code below for displaying the directories in the current folder. What is the meaning of ${arg##/*/} in shell scripting. (Both arg#* and arg##/*/ gives the same output. ) What is the meaning of {} \; in for loop statement. for arg in `find . -type d -exec ls -d {} \;` do echo "Output 1" ${arg##/*/} echo "Output 2" ${arg#*} done A: Adding to @JoSo's helpful answer: ${arg#*} is a fundamentally pointless expansion, as its result is always identical to $arg itself, since it strips the shortest prefix matching any character (*) and the shortest prefix matching any character is the empty string. ${arg##/*/} - stripping the longest prefix matching pattern /*/ - is useless in this context, because the output paths will be ./-prefixed due to use of find ., so there will be no prefix starting with /. By contrast, ${arg##*/} will work and strip the parent path (leaving the folder-name component only). Aside from it being ill-advised to parse command output in a for loop, as @JoSo points out, the find command in the OP is overly complicated and inefficient (as an aside, just to clarify, the find command lists all folders in the current folder's subtree, not just immediate subfolders): find . -type d -exec ls -d {} \; can be simplified to: find . -type d The two commands do the same: -exec ls -d {} \; simply does what find does by default anyway (an implied -print). If we put it all together, we get: find . -mindepth 1 -type d | while read -r arg do echo "Folder name: ${arg##*/}" echo "Parent path: ${arg%/*}" done Note that I've used ${arg%/*} as the second output item, which strips the shortest suffix matching /* and thus returns the parent path; furthermore, I've added -mindepth 1 so that find doesn't also match . @JoSo, in a comment, demonstrates a solution that's both simpler and more efficient; it uses -exec to process a shell command in-line and + to pass as many paths as possible at once: find . -mindepth 1 -type d -exec /bin/sh -c \ 'for arg; do echo "Folder name: ${arg##*/}"; echo "Parent: ${arg%/*}"; done' \ -- {} + Finally, if you have GNU find, things get even easier, as you can take advantage of the -printf primary, which supports placeholders for things like filenames and parent paths: find . -type d -printf 'Folder name: %f\nParen path: %h\n' Here's a bash-only solution based on globbing (pathname expansion), courtesy of @Adrian Frühwirth: Caveat: This requires bash 4+, with the shell option globstar turned ON (shopt -s globstar) - it is OFF by default. shopt -s globstar # bash 4+ only: turn on support for ** for arg in **/ # process all directories in the entire subtree do echo "Folder name: $(basename "$arg")" echo "Parent path: $(dirname "$arg")" done Note that I'm using basename and dirname here for parsing, as they conveniently ignore the terminating / that the glob **/ invariably adds to its matches. Afterthought re processing find's output in a while loop: on the off chance that your filenames contain embedded \n chars, you can parse as follows, using a null char. to separate items (see comments for why -d $'\0' rather than -d '' is used): find . -type d -print0 | while read -d $'\0' -r arg; ...
{ "pile_set_name": "StackExchange" }
Q: "dir"-Input RTL but with LTR measurement data | "فثسف 3 cm فثسف" should be (فثسفy 3 cm فثسف) Do someone know if this is an issue of the browser, the windows language or something in general? I installed on my computer a second language called "Arabic (Saudi Arabia) Arabic (101) keyboard". And if I enter a text like "test 3cm test" (for "3cm" I switch to German keyboard) its more or less correct. - with dir="rtl". When I'm using ltr as dir it looks like when I'm copy&pasting it here. فثسف 3cm فثسف And now the (main) question. When I add a space between 3 and cm it will be vice versa. Do you know if it's possible to handle it with JavaScript or HTML like my picture modification below? Or is it a language behaviour? Thanks in Advance! :-) What did I tried? Using auto in dir <html dir="rtl" lang="ar"> <body> <input type="text" dir="auto" style="text-align: left;" value="فثسف 3 cm فثسف" /> </body> </html> And this. <html dir="rtl" lang="ar"> <body> <input type="text" dir="auto" style="text-align: right;" value="فثسف 3 cm فثسف" /> </body> </html> The value comes from this workflow. Switch to Arabic (RTL language) Write "test " Switch to German (LTR language) Write "3 cm " Switch to Arabic (RTL language) Write "test" Strg + A in the Input and put it into value="STRG + V" A: I used @alex-cohn idea with &lrm; and &rlm; tags and developed something what I need var ltrMarkThere = false; document.getElementById("test").addEventListener("keydown", function testKey(e) { if(e.key.match(/[0-9]/)) { document.getElementById("test").value += "\u202a"; ltrMarkThere = true; } else if(ltrMarkThere && e.key.charCodeAt(0) > 127) { document.getElementById("test").value = document.getElementById("test").value.replace(/( ?)$/, "\u202c$1"); ltrMarkThere = false; } }); <html dir="rtl" lang="ar"> <head> </head> <body> <input id="test" type="text" style="direction: rtl; text-align: right;" autocomplete="off" autofocus="true" value="فثسف ‪3 cm‬ فثسف" /> <!-- There is a hidden UTF8 Right-to-left-mark and hidden UTF8 Left-to-right-mark which allows to have it like this --> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: website not centered in firefox/chrome i am having a problem with my website on Widescreens on Firefox/Chrome. It's not centred for some reason, margin: 0 auto; is not working either. The website looks fine on normal screens or even wide screens with lower res but on 1900x1200 the content is not centered for some reason. However the website looks fine on IE 9 at 1900x1200. Here is the code: jsfiddle.net/hXskH/ Any clues? A: For it to be centered you need to add a width along with that margin: 0 auto; Most common width is 960px; #main { padding-bottom: 300px; margin:0 auto; position: relative; width: 960px; }
{ "pile_set_name": "StackExchange" }
Q: Plotting of for loop values (array) As I'm completely new to Mathematica I'm stuck at the following problem: I'm supposed to "fly" a drone in y-direction (upwards) and before it hits an "obstacle" which is placed at {0,5}, it should move out of the way in x-direction. This works out, however now I'm supposed to plot the "flightpath" of the drone. I tried this with an array but I was not able to plot it. Could someone help me out? Reap[For[it = 1, it < 11, it++, drone = {0, it}; Sow[drone] If[obstacle == drone + {0, 1}, For[i = 1, i < 11, i++, drone = {i, it}; Sow[drone]]]]] `{Null, {{{0, 1}, {0, 2}, {0, 3}, {0, 4}, {1, 4}, {2, 4}, {3, 4}, {4, 4}, {5, 4}, {6, 4}, {7, 4}, {8, 4}, {9, 4}, {10, 4}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, {0, 9}, {0, 10}}}}` I know that "For" isn't the best way to do this in Mathematica but I'm used to it from other program languages. I googled a lot of different approaches for this, (tables, lists etc.) but none worked out and this is the closest I got to a solution that works out for me (if I'm just able to plot it). Edit: Thanks for your solution. Got it to work! A: You should have a semicolon between Sow[drone] and If[obstacle == drone + {0, 1} although in this instance it still works. Here are some plotting suggestions. obstacles = {{0, 5}, {3, 12}}; i = 0; path = Reap[For[it = 1, it < 21, it++, drone = {i, it}; Sow[drone]; If[MemberQ[obstacles, drone + {0, 1}], Do[drone = {i++, it}; Sow[drone], 3]]]][[2, 1]]; plot = Show[ListLinePlot[path, PlotMarkers -> Automatic], ListPlot[obstacles, PlotStyle -> Red, PlotMarkers -> {Automatic, 12}], Frame -> True, PlotRangePadding -> {0.6, {1, 2}}, Axes -> False]
{ "pile_set_name": "StackExchange" }
Q: Get content between 2 words I wanna get the contents (text) between two words(word1 and word2), for example : word1blablabla Poetry can be divided into several genres, or categories. word2 blablabla so the contents = blablabla Poetry can be divided into several genres, or categories. but, the problems sometimes the word1 and word2 can be in upper-case letter or in lower-case letter. And the other problem is the word1 still be printed in the result. It should be printed. How to handle that problem? thank you :) here's the code : $file = 'word1 blablabla word1 Poetry can be divided into several genres, or categories. word2 blablabla '; $word1='word1'; $word2='word2'; $between = substr($file, strpos($file, $word1), strpos($file, $word2) - strpos($file, $word1)); A: You can use stripos instead of strpos: stripos — Find the position of the first occurrence of a case-insensitive substring in a string
{ "pile_set_name": "StackExchange" }
Q: Closing Parenthesis Beep in XCode 4 this is really getting on my nerves and, after too much Googling, I haven't found a satisfactory fix for it. If I begin to type in code using XCode 4.6, for instance: float x = y + z (my caret is just after the z) and then decide that what I really want is float x = ceilf(y + z); and I begin the modification by typing the closing parenthesis, XCode 4 beeps at me. The parentheses aren't balanced, but I'm well aware of that. I want to turn off this annoying beep, without making it system-wide. Any solutions? A: There does not seem to be any way to edit this from within Xcode. It is registered as an alert sound. It works just like if you tried to close out of Finder with cmd + q. It is handled on a system level. You can, however, disable all of these alert sounds. Step 1: Go to system preferences. Step 2: Open up the Sound menu. Step 3: Drag the little arrow of Alert Volume to 0. That is all that is technically necessary to disable the alert you hear when you type }, ), or ] without a prior opening brace/bracket. Some others also like to uncheck Play user interface sound effects because it removes some other annoying beeps and buzzes. It is on the same page as the alert volume:
{ "pile_set_name": "StackExchange" }
Q: How do I get the number of subunits from a PDB file with awk , python or biopython? I have PDB(text) files which are in a directory. I would like to print the number of subunits from each PDB file. Read all lines in a pdb file that start with ATOM The fifth column of the ATOM line contains A, B, C, D etc. If it contains only A the number of subunit is 1. If it contains A and B, the number of subunits are 2. If it contains A, B, and C the number of subunits are 3. 1kg2.pdb file ATOM 1363 N ASN A 258 82.149 -23.468 9.733 1.00 57.80 N ATOM 1364 CA ASN A 258 82.494 -22.084 9.356 1.00 62.98 C ATOM 1395 C MET B 196 34.816 -51.911 11.750 1.00 49.79 C ATOM 1396 O MET B 196 35.611 -52.439 10.963 1.00 47.65 O 1uz3.pdb file ATOM 1384 O ARG A 260 80.505 -20.450 15.420 1.00 22.10 O ATOM 1385 CB ARG A 260 78.980 -18.077 15.207 1.00 36.88 C ATOM 1399 SD MET B 196 34.003 -52.544 16.664 1.00 57.16 S ATOM 1401 N ASP C 197 34.781 -50.611 12.007 1.00 44.30 N 2b69.pdb file ATOM 1393 N MET B 196 33.300 -54.017 12.033 1.00 46.46 N ATOM 1394 CA MET B 196 33.782 -52.714 12.566 1.00 49.99 C desired output pdb_id subunits 1kg2 2 1uz3 3 2b69 1 How can I do this with awk, python or Biopython? A: You can use an array to record all seen values for the fifth column. $ gawk '/^ATOM/ {seen[$5] = 1} END {print length(seen)}' 1kg2.pdb 2 Edit: Using gawk 4.x you can use ENDFILE to generate the required output: BEGIN { print "pdb_id\t\tsubunits" print } /^ATOM/ { seen[$5] = 1 } ENDFILE { print FILENAME, "\t", length(seen) delete seen } The result: $ gawk -f pdb.awk 1kg2.pdb 1uz3.pdb 2b69.pdb pdb_id subunits 1kg2.pdb 2 1uz3.pdb 3 2b69.pdb 1
{ "pile_set_name": "StackExchange" }
Q: Как получить гладкие кривые в Android при рисовании по касанию? Обработчик onTouchEvent в ACTION_MOVE рисует прямую линию к event.getX(), event.getY(). В итоге при рисовании пальцем по экрану линия получается рубленой. Как это можно исправить? A: Вместо event.getX(), event.getY() нужно использовать event.getHistoricalX(), event.getHistoricalY(), в цикле по i пробегая по всем точкам.
{ "pile_set_name": "StackExchange" }
Q: Why is this only fading In and not fading out I have an image on the UIButton that I wish to glow in when I click button and glow out when I click it again. Everytime I click, it doesn't glow out, it only glows in making it brighter . I have tried UIView animateWithDuration as well as CATransition and CABasicAnimation.. Something is wrong. Probably something basic that I should know about. I'd appreciate the help. Heres my code: -(void)didTapButton:(UIButton *)button { button.selected = !button.selected; UIColor *glowColor = [self.arrayOfGlowColor objectAtIndex:button.tag]; UIImageView *imageView = button.imageView; UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, [UIScreen mainScreen].scale); [imageView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0,0,imageView.bounds.size.width,imageView.bounds.size.height)]; [glowColor setFill]; [path fillWithBlendMode:kCGBlendModeSourceAtop alpha:1.0]; UIImage *imageContext_image = UIGraphicsGetImageFromCurrentImageContext(); UIView *glowView = [[UIImageView alloc] initWithImage:imageContext_image]; glowView.center = imageView.center; [imageView.superview insertSubview:glowView aboveSubview:imageView]; glowView.alpha = 0; glowView.layer.shadowColor = glowColor.CGColor; glowView.layer.shadowOffset = CGSizeZero; glowView.layer.shadowRadius = 10; glowView.layer.shadowOpacity = 1.0; /* [UIView animateWithDuration: 1.0 animations:^(void) { glowView.alpha = (button.selected) ? 1.0 : 0.0f; }]; NSLog(@"glowView.alpha:%f",glowView.alpha); NSLog(button.selected ? @"YES" : @"NO"); */ /* if (button.selected) { CATransition *fadeIn = [CATransition animation]; fadeIn.duration = 1.0; fadeIn.startProgress = 0.0f; fadeIn.endProgress = 1.0f; [fadeIn setType:kCATransitionFade]; fadeIn.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; [fadeIn setFillMode:@"extended"]; [glowView.layer addAnimation:fadeIn forKey:nil]; } if (!button.selected) { CATransition *fadeOut = [CATransition animation]; fadeOut.duration = 1.0; fadeOut.startProgress = 1.0f; fadeOut.endProgress = 0.0f; [fadeOut setType:kCATransitionFade]; fadeOut.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; [fadeOut setFillMode:@"extended"]; [glowView.layer addAnimation:fadeOut forKey:nil]; } */ if (button.selected) { //Create a one-way animation that fades in the glow. glowView.layer.opacity = 1.0; CABasicAnimation *glowFadeInAnim = [CABasicAnimation animationWithKeyPath:@"opacity"]; glowFadeInAnim.fromValue = [NSNumber numberWithDouble:0.0]; glowFadeInAnim.toValue = [NSNumber numberWithDouble:1.0]; glowFadeInAnim.repeatCount = 1; glowFadeInAnim.duration = 1.0; glowFadeInAnim.autoreverses = FALSE; glowFadeInAnim.fillMode = kCAFillModeForwards; glowFadeInAnim.removedOnCompletion = NO; glowFadeInAnim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; [glowView.layer addAnimation:glowFadeInAnim forKey:nil]; } if (!button.selected) { glowView.layer.opacity = 1.0; CABasicAnimation *glowFadeOutAnim = [CABasicAnimation animationWithKeyPath:@"opacity"]; glowFadeOutAnim.fromValue = [NSNumber numberWithDouble:1.0]; glowFadeOutAnim.toValue = [NSNumber numberWithDouble:0.0]; glowFadeOutAnim.repeatCount = 1; glowFadeOutAnim.beginTime = 2; glowFadeOutAnim.duration = 2.0; glowFadeOutAnim.autoreverses = FALSE; glowFadeOutAnim.fillMode = kCAFillModeForwards; glowFadeOutAnim.removedOnCompletion = NO; glowFadeOutAnim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; [glowView.layer addAnimation:glowFadeOutAnim forKey:nil]; glowView.layer.opacity = 0.0; } NSLog(@"glowView.opacity:%f",glowView.layer.opacity); NSLog(button.selected ? @"YES" : @"NO"); } A: If you create a new glowView every time the button is pressed and add it to the button, then obviously it will just keep getting brighter, as more and more of them are being added to the button. You need to create the glowView once, for example in your viewDidLoad method, and store it as an instance variable so you don't lose it: @interface MyViewController : UIViewController { UIView *_glowView; } ... - (void)viewDidLoad { [super viewDidLoad]; _glowView = ... // Initialise it here ... [imageView.superview insertSubview:_glowView aboveSubview:imageView]; } Then in your didTapButton: method, you handle the tap as you do (adding or removing the _glowView, but make sure you don't set it to nil so the reference to it is always retained). This way, you only create and add it once, and the problem should be solved.
{ "pile_set_name": "StackExchange" }
Q: Como mandar um string para um servidor web? Eu preciso mandar uma string para um servidor, que no caso será uma página do meu site. Eu preciso mandar um txt com a string para lá, apenas isso. Alguém sabe com fazer isso no Android do jeito mais simples possível? Agradeço desde já! A: Crie esta classe em seu projeto: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URLEncoder; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; public class RestClient { private ArrayList <NameValuePair> params; private ArrayList <NameValuePair> headers; private String url; private int responseCode; private String message; private String response; public String getResponse() { return response; } public String getErrorMessage() { return message; } public int getResponseCode() { return responseCode; } public RestClient(String url) { this.url = url; params = new ArrayList<NameValuePair>(); headers = new ArrayList<NameValuePair>(); } public void AddParam(String name, String value) { params.add(new BasicNameValuePair(name, value)); } public void AddHeader(String name, String value) { headers.add(new BasicNameValuePair(name, value)); } public void Execute(RequestMethod method) throws Exception { switch(method) { case GET: { //add parameters String combinedParams = ""; if(!params.isEmpty()){ combinedParams += "?"; for(NameValuePair p : params) { String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8"); if(combinedParams.length() > 1) { combinedParams += "&" + paramString; } else { combinedParams += paramString; } } } HttpGet request = new HttpGet(url + combinedParams); //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } executeRequest(request, url); break; } case POST: { HttpPost request = new HttpPost(url); //add headers for(NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } if(!params.isEmpty()){ request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); } executeRequest(request, url); break; } } } private void executeRequest(HttpUriRequest request, String url) { HttpClient client = new DefaultHttpClient(); HttpResponse httpResponse; try { httpResponse = client.execute(request); responseCode = httpResponse.getStatusLine().getStatusCode(); message = httpResponse.getStatusLine().getReasonPhrase(); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); response = convertStreamToString(instream); // Closing the input stream will trigger connection release instream.close(); } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } catch (IOException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public void AddParam(String name, long value) { params.add(new BasicNameValuePair(name, value + "")); } public enum RequestMethod { GET(1), POST(2); public int action; private RequestMethod(int action) { this.action = action; } } } Depois é só usar o seguinte código dentro de uma Thread: RestClient client = new RestClient("http://site"); client.AddParam("nome_parametro1", valor); client.AddParam("nome_parametro2", valor2); try { client.Execute(RestClient.RequestMethod.GET); String resposta = client.getResponse(); } catch (Exception e) { e.printStackTrace(); }
{ "pile_set_name": "StackExchange" }
Q: Summation by parts of $\sum_{k=1} ^n \frac{2k+1}{k(k+1)}$ Let $\{f_k\}$ and $\{g_k\}$ be sequences of real numbers. The formula for summation by parts is given by: $\sum_{k=m} ^n f_k \Delta g_k=(f_{n+1}g_{n+1}-f_mg_m)-\sum_{k=m} ^n g_{k+1}\Delta f_k$, where $\Delta f_k=f_{k+1}-f_k$. Letting $f_k=2k+1$ and $g_k=-\frac{1}{k}$. One then computes $\Delta f_k=2$ and $\Delta g_k=\frac{1}{k(k+1)}$. Therefore, using the partial summation formula, we have \begin{align*} \sum_{k=1} ^n f_k \Delta g_k=\sum_{k=1} ^n \frac{2k+1}{k(k+1)}&=-\frac{2n+3}{n+1}+3+\sum_{k=1} ^n \frac{2}{k+1} \\ &=\frac{n}{n+1}+2(H_n-1)\\ &=2H_n-\frac{n+2}{n+1}, \end{align*} where $H_n$ denotes the $n^{th}$ harmonic number. I have check my answer multiple times, but I am convinced it is incorrect. Could anyone point out a flaw in my reasoning? Here is the full solution: Let $f_k=2k+1$ and $g_k=-\frac{1}{k}$. One then computes $\Delta f_k=2$ and $\Delta g_k=\frac{1}{k(k+1)}$. Therefore, \begin{align*} \sum_{k=1} ^n f_k \Delta g_k=\sum_{k=1} ^n \frac{2k+1}{k(k+1)}&=-\frac{2n+3}{n+1}+3+\sum_{k=1} ^n \frac{2}{k+1} \\ &=\frac{n}{n+1}+2(H_{n+1}-1)\\ &=2H_n+\frac{n}{n+1}-2\frac{n}{n+1}\\ &=2H_n-\frac{n}{n+1}. \end{align*} A: It does look to be your final conversion to harmonic numbers is at fault. In particular, $$\begin{align*} \sum_{k=1}^n \frac1{k+1}&=\sum_{k-1=1}^n \frac1{k-1+1}\\ &=\sum_{k=2}^{n+1} \frac1{k}\\ &=H_{n+1}-1\\ &=H_n+\frac1{n+1}-1\\ &=H_n-\frac{n}{n+1} \end{align*}$$
{ "pile_set_name": "StackExchange" }
Q: Django + PostgreSQL: database representation of JSONField is changing PostgreSQL 9.4.12 Django 1.10.7 With this minimal class : from django.contrib.postgres.fields import JSONField class Foobar(models.Model): extra_data = JSONField(blank=True, default="") I run manage.py shell_plus : In [2]: a=Foobar.objects.create() In [3]: a.extra_data={} In [4]: a.save() In [6]: a.extra_data Out[6]: {} In [7]: a.refresh_from_db() In [8]: a.extra_data Out[8]: '{}' In [9]: a.save() In [10]: a.refresh_from_db() In [11]: a.extra_data Out[11]: '"{}"' What could be the reason the JSONField value is quoted at each database save? A: Found it. This is a known incompatibility between django-jsonfield and django.contrib.postgres.fields.JSONField that cannot be used in same project. cf https://bitbucket.org/schinckel/django-jsonfield/issues/57/cannot-use-in-the-same-project-as-djangos
{ "pile_set_name": "StackExchange" }
Q: Stack Overflow doesn't display correctly when using Tor Browser I use Tor browser for nearly all of my internet browsing, including Stack Overflow. This wasn't a problem for me until about a week or two ago, when Stack Overflow produced two different errors when using Tor Browser. One, it would sometimes display without using any styles. The pages displayed in a linear fashion, and there were no fonts other than Times New Roman, no pictures, and no color, just like in this question. The second problem happens 100% of the time when problem one happens, and sometimes it happens on its own. When I try to log into Stack Overflow, I enter my Stack Exchange account information, hit enter or click login, and nothing happens. These problems do not happen all of the time, but as I said, when problem one happens, problem two always follows it. I have tried accessing this from multiple machines, using multiple script settings, and the same problem happens. I am also a member of the Tor Stack Exchange, and sometimes, when I am logged into one Stack Exchange, and click over to the other in Tor Browser, the one will display with errors and the other will work perfectly. I believe this is a bug, but if anyone knows a solution on my end, please tell me. (And please don't just tell me to stop using Tor.) A: There are two problems here: Tor Browser is not officially supported; any breakage in styling and functionality is at your own risk. There has been a history of abusive users using Tor to bypass restrictions placed on their accounts. As a result of recent extreme misbehaviour, many Tor exit nodes have been IP blocked. If you cannot connect at all, your request most probably came through such an exit node. It is unlikely that the Stack Exchange team is going to ease up on these two restrictions.
{ "pile_set_name": "StackExchange" }
Q: White screen of death after server move I am moving my expression engine site and database to a new server. Everything seems to be directed correctly but when I access admin.php I get a blank page. Any thoughts? A: If you are seeing a white screen there's an error happening and you need to display that error to be able to know how to proceed. (See the EE user guide about Blank Pages.) To show that error, edit your folder's index.php file and replace $debug = 0 with $debug = 1. Revisit your site and you should see the error. If you see something like this: A Database Error Occurred Unable to connect to your database server using the provided settings. Then follow this answer on another question. If that doesn't help, try the solutions offered in this answer.
{ "pile_set_name": "StackExchange" }
Q: How can I identify and count unique pairs at every level in a list of lists in R? I have a list of lists that looks like this: > class(cladelist) [1] "list" cladelist <- list( `46` = scan(text=' "KbFk2" "PeHa3" "PeHa51" "EeBi27" "EeBi17" "PeHa23" "PeHa44" "EeBi4" "EeBi26" "PeHa8" "PeHa26" "EeBi24" "EeBi3" "EeBi20" "KbFk5" "PeHa15" "PeHa43" "PeHa11" "PeHa12" "PeHa49" "PeHa67" "PeHa17" "PeHa59" "KbFk4" "PeHa10" "PeHa55" "PeHa73" "EeBi23" "PeHa78" "PeHa81" "EeBi11" "PeHa45" "EeBi6" "EeBi34" "PeHa25" "PeHa52" "PeHa62" "PeHa31" "PeHa65" "PeHa47" "PeHa50" "PeHa34" "PeHa54" "PeHa22" "PeHa30"', what=""), `47`= scan(text=' "KbFk2" "EeBi27" "EeBi17" "EeBi4" "EeBi26" "EeBi3" "EeBi20" "KbFk5" "KbFk4" "EeBi6" "EeBi34"', what=""), `48`= scan(text=' "PeHa3" "PeHa51" "PeHa23" "PeHa44" "PeHa8" "PeHa26" "EeBi24" "PeHa15" "PeHa43" "PeHa11" "PeHa12" "PeHa49" "PeHa67" "PeHa17" "PeHa59" "PeHa10" "PeHa55" "PeHa73" "EeBi23" "PeHa78" "PeHa81" "EeBi11" "PeHa45" "PeHa25" "PeHa52" "PeHa62" "PeHa31" "PeHa65" "PeHa47" "PeHa50" "PeHa34" "PeHa54" "PeHa22" "PeHa30"', what=""), `49`= scan(text=' "PeHa51" "PeHa23" "PeHa44" "PeHa8" "PeHa26" "EeBi24" "PeHa15" "PeHa43" "PeHa11" "PeHa12" "PeHa49" "PeHa67" "PeHa17" "PeHa59" "PeHa10" "PeHa55" "PeHa73" "EeBi23" "PeHa78" "PeHa81" "EeBi11" "PeHa45" "PeHa25" "PeHa52" "PeHa62" "PeHa31" "PeHa65" "PeHa47" "PeHa50" "PeHa34" "PeHa54" "PeHa22" "PeHa30"', what=""), `50`= scan(text=' "EeBi27" "EeBi17" "EeBi4" "EeBi26" "EeBi3" "EeBi20" "KbFk5" "KbFk4" "EeBi6" "EeBi34"', what="") ) Each of these sublists (ie "46", "47" etc) represents a clade in a dendogram that I've extracted using: > cladelist <- clade.members.list(VB.phy, tips = FALSE, tip.labels = TRUE, include.nodes=FALSE) Im trying to find each unique pair found within each sublist, and calculate the sum of times it appears between all sublists (clades). The ideal output would be a dataframe that looks like this where the count is the number of times this pair was found between all sublists (clades): Pair Count Peha1/PeHa2 2 Peha1/PeHa3 4 PeHa1/PeHa4 7 PeHa1/PeHa5 3 What sort of formulas am I looking for? Background for the question (just for interest, doesnt add that much to question): The idea is that I have a data set of 121 of these elements (Peha1, KbFk3, etc). They are artifacts (I'm an archaeologist) that I'm evaluating using 3D geometric morphometrics. The problem is that these artifacts are not all complete; they are damaged or degraded and thus provide an inconsistent amount of data. So I've had to reduce what data I use per artifact to have a reasonable, yet still inconsistent, sample size. By selecting certain variables to evaluate, I can get useful information, but it requires that I test every combination of variables. One of my analyses gives me the dendograms using divisive hierarchical clustering. Counting the frequency of each pair as found between each clade should be the strength of the relationship of each pair of artifacts. That count I will then divide by total number of clades in order to standardize for the following step. Once I've done this for X number of dendograms, I will combine all these values for each pair, and divide them by the number representing whether that pair appeared in a dendogram (if it shows up in 2 dendograms, that I divide by 2), because each pair will not appear in each of my tests and I have to standardize it so that more complete artifacts that appear more often in my tests don't have too much more weight. This should allow me to evaluate which pairs have the strongest relationships. A: This falls into a set of association kind of problems for which I find the widyr package to be super useful, since it does pairwise counts and correlations. (The stack() function just converts into a dataframe for the rest to flow). I couldn't check against your sample output, but for an example like "PeHa23/PeHa51", the output shows they are paired together in 3 different clades. This currently doesn't include zero counts to exhaust all possible pairs, but that could be shown as well (using complete()). UPDATE: Made references clearer for packages like dplyr, and filtered so that counts are non-directional (item1-item2 is same as item2-item1 and can be filtered). library(tidyverse) library(widyr) df <- stack(cladelist) %>% dplyr::rename(clade = "ind", artifact = "values") df %>% widyr::pairwise_count(feature = clade, item = artifact) %>% filter(item1 > item2) %>% mutate(Pair = paste(item1, item2, sep = "/")) %>% dplyr::select(Pair, Count = n) #> # A tibble: 990 x 2 #> Pair Count #> <chr> <dbl> #> 1 PeHa3/KbFk2 1 #> 2 PeHa51/KbFk2 1 #> 3 PeHa23/KbFk2 1 #> 4 PeHa44/KbFk2 1 #> 5 PeHa8/KbFk2 1 #> 6 PeHa26/KbFk2 1 #> 7 KbFk5/KbFk2 2 #> 8 PeHa15/KbFk2 1 #> 9 PeHa43/KbFk2 1 #> 10 PeHa11/KbFk2 1 #> # … with 980 more rows
{ "pile_set_name": "StackExchange" }
Q: Form created with React doesn't update the backing state object I am trying to automate the login form of Instagram web app: https://instagram.com/accounts/login/ With the following code (you can run it on Chrome console): var frm = window.frames[1].document.forms[0]; frm.elements[0].value = 'qacitester'; frm.elements[1].value = 'qatester'; frm.elements[2].click(); Even though the inputs are populated, when I monitor the XHR request, I see this is posted: username=&password=&intent= rather than this: username=qacitester&password=qatester&intent= And causes web app to not authenticate. Do you have any idea why the input values are not transferred to the backing state (model?) object of React? A: Instagram is using the linkState method from ReactLink: http://facebook.github.io/react/docs/two-way-binding-helpers.html The login page links to a bundles/Login.js that contains compressed code like this: o.createElement("input", { className:"lfFieldInput", type:"text", name:"username", maxLength:30, autoCapitalize:!1, autoCorrect:!1, valueLink:this.linkState("username") })) If you look at the documentation for ReactLink, this means that the input field value only gets sent back to state when the change event fires on the input fields. However, it's not as simple as just firing the change event on the node in question - I think due to the way that React normalises browser events. The React docs specifically say that onChange in React isn't exactly the same as onChange in the browser for various reasons: http://facebook.github.io/react/docs/dom-differences.html Fortunately in your case Instagram are using React with Addons included which gives you access to React TestUtils, so you can do: var frm = window.frames[1].document.forms[0]; var fReact = window.frames[1].React; fReact.addons.TestUtils.Simulate.change(frm.elements[0], {target: {value: 'qacitester' }}); fReact.addons.TestUtils.Simulate.change(frm.elements[1], {target: {value: 'qatester' }}); frm.elements[2].click(); More documentation here: http://facebook.github.io/react/docs/test-utils.html Notice that since the login form itself is in an iframe, you must use the instance of React from that iframe otherwise the TestUtils won't be able to find the nodes correctly. This will only work in situations where React Addons are included on the page. The normal non-Addons build of React will require another solution. However, if you're specifically talking about ReactLink then that's an addon anyway, so it's not an issue. A: Answering my own question, the required event is input event it seems and this code works: var doc = window.frames[1].document; var frm = doc.forms[0]; frm.elements[0].value = 'qacitester'; var evt = doc.createEvent('UIEvent'); evt.initUIEvent('input', true, false); frm.elements[0].dispatchEvent(evt); frm.elements[1].value = 'qatester'; frm.elements[1].dispatchEvent(evt); frm.elements[2].click();
{ "pile_set_name": "StackExchange" }
Q: ASP.NET Website Administration Tool: Unable to connect to SQL Server database I am trying to get authentication and authorization working with my ASP MVC project. I've run the aspnet_regsql.exe tool without any problem and see the aspnetdb database on my server (using the Management Studio tool). my connection string in my web.config is: <connectionStrings> <add name="ApplicationServices" connectionString="data source=MYSERVERNAME;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" /> </connectionStrings> The error I get is: There is a problem with your selected data store. This can be caused by an invalid server name or credentials, or by insufficient permission. It can also be caused by the role manager feature not being enabled. Click the button below to be redirected to a page where you can choose a new data store. The following message may help in diagnosing the problem: Unable to connect to SQL Server database. In the past, I have had trouble connecting to my database because I've needed to add users. Do I have to do something similar here? Edit Changing the connection string ultimately solved the problem. For the records I am using VS2010, ASP MVC2, SServer 2008 <connectionStrings> <add name="ApplicationServices" connectionString="data source=MYSERVERNAME;Integrated Security=True;Initial Catalog=aspnetdb" providerName="System.Data.SqlClient" /> </connectionStrings> A: You are using a server name, "MYSERVER" as if this is a full SQl Server Default instance, not Sql Express. I don't think you can use the AttachDbFilename with a full blown sql server. Either add "\SQLEXPRESS" (instance name) to your server name or get rid of the AttachDbFileName and use Database="NAMEOFDATABASE"
{ "pile_set_name": "StackExchange" }
Q: A linear transformation that fixes a subspace I am struggling with the problem below: Let $V$ be a finite-dimensional vector space over a field $F$, and $L: V \longrightarrow V$ a linear transformation over $F$. Define a sequence of subspaces $V_0, V_1, V_2, ...$ of $V$ inductively by $V_0 = V$, and $V_{n+1} = L(V_n)$ for $n \geq 1$. Prove that there exists a positive integer $N$ such that $V_{N + 1} = V_N$. I observed that $V_0 = V$, $V_1 = L(V)$, $V_2 = L^2(V)$, ... That is, $V_K = L^K(V)$. Thus, to show $V_{N + 1} = V_N$, we need to show that $L^{N+1}(V) = L^N(V)$, which occurs if and only if $L^N(V) \cdot (L(V) -1) = 0$, which is true if and only if $L(V)$ is the identity operator or $L$ is nilpotent. Thus, I've reduced the question down to proving that $L$ is either the identity transformation or nilpotent. How can I proceed with the proof? I'm not sure where to go from here. Thanks! A: Your last claim is false. $L^N(V) \cdot (L(V) - 1) = 0$ does not imply that $L^N = 0$ or $L = 1$. The composition of nonzero linear transformations may be zero. Note that the statement you are trying to prove is stated for an arbitrary linear transformation $L \colon V \to V$, not just nilpotent ones or the identity. Instead, observe that $$V \supseteq L(V) \supseteq L^2(V) \supseteq \cdots,$$ thus $$\dim_F(V) \geq \dim_F(L(V)) \geq \dim_F(L^2(V)) \geq \cdots.$$ Can you see why there must exist $N$ such that $\dim_F(L^{N + 1}(V)) = \dim_F(L^N(V))$, which implies $L^{N + 1}(V) = L^N(V)$?
{ "pile_set_name": "StackExchange" }
Q: How to send a data from req.body using nodejs How can I send data from body using nodejs? I am writing a code in node.js in which the user inputs a data in the body. And based on that input, the program fetches the data from the database and displays it in JSON format. I have written the following code: app.post('/city', (req,res) => { var id = parseInt(req.body.id); pool.connect(function (err, client, done) { if (err) { console.log("Can not connect to the DB" + err); } client.query(`SELECT * FROM city WHERE state_id=${id}`, function (err, result) { done(); if (err) { console.log(err); res.status(400).send(err); } res.status(200).send(result.rows); }) }) }); I feel that something is wrong with var id = parseInt(req.body.id);. Because, when I am running the code, it says it is not able to recognize the id? Also, when I run this in Postman, I get the following error: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Error</title> </head> <body> <pre>TypeError: Cannot read property &#39;id&#39; of undefined <br> &nbsp; &nbsp;at app.post (F:\DatabaseProject15\routes\common.js:36:32) <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5) <br> &nbsp; &nbsp;at next (F:\DatabaseProject15\node_modules\express\lib\router\route.js:137:13) <br> &nbsp; &nbsp;at Route.dispatch (F:\DatabaseProject15\node_modules\express\lib\router\route.js:112:3) <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5) <br> &nbsp; &nbsp;at F:\DatabaseProject15\node_modules\express\lib\router\index.js:281:22 <br> &nbsp; &nbsp;at Function.process_params (F:\DatabaseProject15\node_modules\express\lib\router\index.js:335:12) <br> &nbsp; &nbsp;at next (F:\DatabaseProject15\node_modules\express\lib\router\index.js:275:10) <br> &nbsp; &nbsp;at expressInit (F:\DatabaseProject15\node_modules\express\lib\middleware\init.js:40:5) <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5) </pre> </body> </html> Details: var id = parseInt(req.body.id); is at F:\DatabaseProject15\routes\common.js:36:32 Error at console: TypeError: Cannot read property 'id' of undefined at app.post (F:\DatabaseProject15\routes\common.js:36:32) at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5) at next (F:\DatabaseProject15\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (F:\DatabaseProject15\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5) at F:\DatabaseProject15\node_modules\express\lib\router\index.js:281:22 at Function.process_params (F:\DatabaseProject15\node_modules\express\lib\router\index.js:335:12) at next (F:\DatabaseProject15\node_modules\express\lib\router\index.js:275:10) at expressInit (F:\DatabaseProject15\node_modules\express\lib\middleware\init.js:40:5) at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5) CODE: app.js const pg = require('pg'); const express = require('express'); const app = express(); var common = require('./routes/common') app.use('/common', common) app.listen(4600, function () { console.log('Server is running.. on Port 8000'); }); router/common.js const pg = require('pg'); const express = require('express'); const app = express(); const config = { user: 'postgres', database: 'mydb', host: '40.83.121.72', password: 'abc', port: 5432 }; const pool = new pg.Pool(config); app.post('/', (req, res, next) => { pool.connect(function (err, client, done) { if (err) { console.log("Can not connect to the DB" + err); } client.query('SELECT * FROM city', function (err, result) { done(); if (err) { console.log(err); res.status(400).send(err); } res.status(200).send(result.rows); }) }) }); app.post('/city', (req,res) => { //var id = parseInt(req.params.id); var id = parseInt(req.body.id); pool.connect(function (err, client, done) { if (err) { console.log("Can not connect to the DB" + err); } client.query(`SELECT * FROM city WHERE state_id=${id}`, function (err, result) { done(); if (err) { console.log(err); res.status(400).send(err); } res.status(200).send(result.rows); }) }) }); app.post('/app/state/:id', (req,res) => { var id = parseInt(req.params.id); pool.connect(function (err, client, done) { if (err) { console.log("Can not connect to the DB" + err); } client.query(`SELECT * FROM state WHERE id=${id}`, function (err, result) { done(); if (err) { console.log(err); res.status(400).send(err); } res.status(200).send(result.rows); }) }) }); module.exports = app A: In app.js above your routes add app.use(express.json()); this will let you parse application/json, if you need to parse application/x-www-form-urlencoded you need to add app.use(express.urlencoded({ extended: true }));
{ "pile_set_name": "StackExchange" }
Q: Call web API from client app I used to use ASMX web services, however have since read (and been told) that a better way to request data from a client etc is to use web API's with MVC. I have created an MVC 4 web api application and getting to grips with how it works. Currently I have a single public string in my valuesControllers - public class ValuesController : ApiController { // GET api/values/5 public string Get(int id) { return "value"; } } And I am currently trying to call this in my client like this - class Product { public string value { get; set; } } protected void Button2_Click(object sender, EventArgs e) { RunAsync().Wait(); } static async Task RunAsync() { using (var client = new HttpClient()) { try { client.BaseAddress = new Uri("http://localhost:12345/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // HTTP GET HttpResponseMessage response = await client.GetAsync("api/values/5"); if (response.IsSuccessStatusCode) { Product product = await response.Content.ReadAsAsync<Product>(); Console.WriteLine("{0}", product.value); } } catch(Exception ex) { Console.WriteLine(ex.Message.ToString()); } } } On debugging I can step through the request and enter the web API code successfully however on the line - Product product = await response.Content.ReadAsAsync<Product>(); This fails and enters my catch with the exception - Error converting value "value" to type 'myDemo.Home+Product'. Path '', line 1, position 7. Why is this? A: Why is this? Because from your controller action you are returning a string, not a Product which are 2 quite different types: public string Get(int id) { return "value"; } so make sure that you are consistently reading the value on the client: if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsAsync<string>(); Console.WriteLine("{0}", result); } Of course if you modified your API controller action to return a Product: public Product Get(int id) { Product product = ... go fetch the product from the identifier return product; } your client code would work as expected.
{ "pile_set_name": "StackExchange" }
Q: Visual Studio 2013 crash on start Yesterday I studied a little MVC5 before bed. Today, I open Visual Studio 2013 and while loading, the following exception occurs: Exception Details System.ArgumentNullException was unhandled Message: An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll Additional information: Buffer cannot be null. Parameter name: buffer I have already repaired Visual Studio and nothing has changed. Does anyone know what's going on? A: The Update 5 worked for me. However you need to be part of Dev Essentials in order to download this update. https://my.visualstudio.com/Downloads?q=Visual%20Studio%202013%20Update%205
{ "pile_set_name": "StackExchange" }
Q: How to set color of child QLabels while hover parent QFrame with QSS? I'm trying to set the hover state color of 2 labels inside a QFrame with a stylesheet, but the frame takes the hover states regardless if there is an actual hover: See screenshot: I've got a QFrame with QLabels. I set the default colors to green and purple. While i hover the QFrame, the color of both labels should go red. The exact same CSS does work with html, but i can't seem to get it to work with the QT stylesheets. div{background-color:black; width:200px; height:100px;} #label1{color: green;} #label2{color: purple;} div:hover #label1 {color: red;} div:hover #label2 {color:red;} A: You could not do it with QLabel. It's limitation of QSS. Try to use QToolButton instead of QLabel (and customize QToolButton to look like QLabel). Possible you shuld use QToolButton instead of QFrame too.
{ "pile_set_name": "StackExchange" }
Q: How to use find and exec to execute multiple commands I have such a need: In the directory video, I need to find ./video -type f | while read myfile; do tmp=`basename $myfile` #example.mp4 tmp="${tmp/.mp4/.html}" #example.html cp index.html "$tmp" sed -i '' "s#sceneFilePath:.*#sceneFilePath: \"$myfile\",#g" $tmp #done; Here is my directory: dir |--- video | |--- example.mp4 |--- index.html |--- generateHtml.sh generateHtml.sh is just like above. Here is what it does: find the example.mp4 file in video, then cp index.html example.html and change a string in the example.html. It works well. But now for some path and name of .mp4 files, there are some special characters, such as &, , -. It doesn't seem that while read works for these cases. I've heard that find -exec can handle all of special characters but I don't know how to use it for this case. A: See Using Find for detailed discussion. find ./video -type f -print0 | while IFS= read -r -d '' myfile; do tmp=$(basename "$myfile") #example.mp4 -- consider also tmp=${myfile##*/} tmp="${tmp%.mp4}.html" #example.html sed "s#sceneFilePath:.*#sceneFilePath: \"$myfile\",#g" \ <index.html >"$tmp" done Note: -print0 is used on the find end, and IFS= read -r -d '' is used on the read end; this ensures that all possible filenames (including names with newlines, including names with leading or trailing whitespace) are supported. The former substitution, which replaced the first instance of .mp4 anywhere in the filename with .html, has been replaced with one which strips .mp4 off the end of the filename, and appends .html. "$myfile" is quoted in invoking basename. This was your most substantial immediate bug in the original code, as previously a filename could be split into multiple separate arguments to basename. $() is used instead of backticks. This modern (and yes, POSIX-compliant) command substitution syntax can be easily nested and has much clearer semantics for backslash escapes within. sed -i, which is nonstandard and nonportable (the above was valid for MacOS but not for GNU), is unneeded here; one can skip the cp and do the transform in-line.
{ "pile_set_name": "StackExchange" }
Q: AngularJS execution order with `$q` -- Chaining Promises Following Approach works: $q.when() .then(checkCookieToken) // check if cookie already exists e.g. in cookie .then(setHeader) // set Header with REST-Token e.g from cookie .then(checkTokenOnline) // if not OK logout .then(getMenu) // if previous OK get navigation menu .then(getDataResource) // set ngResource .then(getData); // and query it 4 Questions: 1) If e.g. checkTokenOnline is not OK, I don't want to execute the rest functions, how can I quit (exit, break, whatever,..) at this point? 2) How can I set some of them parallel and some of them serial ? 3) How can I transfer data between them? 4) How can I make the following function dependend from its previous result? A: You are asking how to chain functions in promises. 3) How can I transfer data between them? 4) How can I make the following function depend on its previous result? Return data (or a promise) for the next function in the chain: var p2 = p1.then ( function (data) { var nextData = someFn(data); return nextData; }); var p3 = p2.then ( function (nextData) { var nextData2 = someOtherFn(nextData); return nextData2; }); //return for further chaining return p3; 1) If e.g. checkTokenOnline is not OK, I don't want to execute the rest functions, how can I quit (exit, break, whatever,..) at this point? To reject a promise, have your function throw an error. The chain will skip all the .then methods until you supply an error handler. var p2 = p1.then ( function checkTokenOnline (response) { if ( isBadFn(response) { throw error; } else { return nextData; } }) .then ( someFn ) .then ( someOtherFn ) .catch ( function (error) { // someFn and someOtherFn skipped //log error throw error; }); //return for further chaining return p2; 2) How can I set some of them parallel and some of them serial ? To make two functions run in parallel, make two promises. Use $q.all to wait for them both to complete. var p1 = $q.when ( fn1() ); var p2 = $q.when ( fn2() ); var p3 = $q.all ( [p1, p2] ); var p4 = p3.then ( function (responseList) { var response1 = responseList[0]; var response2 = responseList[1]; return something; }). catch ( function (error) { //log error throw error; }); //return for further chaining return p4; Be aware that $q.all is not resilient. If any promise throws an error, the .then method will be skipped and only the first error will go to the .catch method. The rule of thumb for functional programming is always return something. Useful links AngularJS $q Reference - Chaining promises You're Missing the Point of Promises. Ninja Squad -- Traps, anti-patterns and tips about AngularJS promises
{ "pile_set_name": "StackExchange" }
Q: Name of the Minimum value in a named vector I have a named vector: v <- c("morning"=80, "noon"=20, "night"=40) printing min(v) gives [1] 20 I want to get this instead: noon     20 Is there a simple way? A: v[which.min(v)] will give you the output you listed. But if you just want the name, and not the value, then do names(v)[which.min(v)].
{ "pile_set_name": "StackExchange" }
Q: How can I change the height of mathematical equations in Microsoft Word 2013? How can I change the height of mathematical equations in Microsoft Word 2013? Example: I would like to change the height of the following selected equation: to have the same the height as the following selected equation: I use Microsoft Word 2013 on Windows 7 SP1 x64 Ultimate. I cannot use LaTeX (constrained by my editor). Here is the file from which I took the example (Google preview isn't able to show mathematical equations so it needs to be downloaded). A: Go to the end of the equation that has too large of a gap under it. Hit the "Delete" key to bring the equation below up and directly onto the end of it: Then to put it back on it's own line use Shift+Enter. Using Shift+Enter will force a "Line break", instead of the "Paragraph break" Word likes to use when you hit Enter, thus reducing the gap:
{ "pile_set_name": "StackExchange" }
Q: parse a ini like file with ruby I have a file in the following format: [X:10] [Y:20] # many of them, they are test parameters C = 1 A = 1234 B = 12345 .... # many of them, they are test cases # new test parameters [X:20] [Y:40] # new test cases C = 1 A = 1234 B = 12345 ... It is a test framework. The header (section on [] set the parameters and then the following fields are test cases) I parse them today in C. So basically i do the following (as usual in C): while(fgets(....) if(!strcmp(keyword,"[X")) x = atoi(value); however I would like to port it to ruby, in a ruby way: organizing it as classes. I would like to know if there is any framework (ini parses, doesnt help) to do it.. any idea, framework (treetop, citrus are kind of overkill) or snippet that could help me? I though something like: class TestFile attr_accessor :sections def parse end end # the test parameters value class Section attr_accessor :entries, foo,bar.. # all accessible fields end # the test cases class Entry attr_accessor #all accessible fields end then I could use it like: t = TestFile.new "mytests.txt" t.parse t.sections.first => <Section:0x000000014b6b70 @parameters={"X"=>"128", "Y"=>"96", "Z"=>"0"}, @cases=[{"A"=>"14", "B"=>"1", "C"=>"2598", "D"=>"93418"},{"A"=>"12", "B"=>"3", "C"=>"2198", "D"=>"93438"}] any help or direction? A: Here's what I came up with. First, the usage: t = Testfile.new('ini.txt') t.parse t.sections.count #=>2 t.sections.first #=> #<Section:0x00000002d74b30 @parameters={"X"=>"10", "Y"=>"20"}, @cases={"C"=>"1", "A"=>"1234", "B"=>"12345"}> As you can see, I made the Section contain both the parameters and the cases--just a judgement call, it could be done other ways. The implementation: class Testfile attr_accessor :filename, :sections def initialize(filename) @sections = [] @filename = filename end def parse @in_section = false File.open(filename).each_line do |line| next if line =~ /^#?\s*$/ #skip comments and blank lines if line.start_with? "[" if not @in_section @section = Section.new @sections << @section end @in_section = true key, value = line.match(/\[(.*?):(.*?)\]/).captures rescue nil @section.parameters.store(key, value) unless key.nil? else @in_section = false key, value = line.match(/(\w+) ?= ?(\d+)/).captures rescue nil @section.cases.store(key, value) unless key.nil? end end @sections << @section end end class Section attr_accessor :parameters, :cases def initialize @parameters = {} @cases = {} end end Most of this code is the parsing. It looks for a line beginning with [ and creates a new Section object (unless it is already parsing a section). Any other non-comment line is parsed as a test case.
{ "pile_set_name": "StackExchange" }
Q: Google Identity Toolkit returns error 2 when signing in with aol email Id I have been using Google Identity Toolkit for my GAE (Java) based app for couple years now. I have Google, Facebook and Microsoft federated logins enabled. However, when a user tries to "Sign In with Email" and uses an @aol.com account, it returns a 503 error, and Error code: Error code: 2. error message on the UI. In the console, the following errors appear: gitkit.js:242 POST https://www.googleapis.com/identitytoolkit/v3/relyingparty/createAuthUri?key=<key> 503 () lj.send @ gitkit.js:242 Mj @ gitkit.js:255 Lj.requestGitkitEndpoint @ gitkit.js:256 Oj.createAuthUri @ gitkit.js:258 N @ gitkit.js:190 Vm @ gitkit.js:337 (anonymous) @ gitkit.js:338 (anonymous) @ gitkit.js:79 (anonymous) @ gitkit.js:77 Yc @ gitkit.js:44 g.dispatchEvent @ gitkit.js:42 g.handleEvent @ gitkit.js:70 Mc.a.(anonymous function).a.(anonymous function) @ gitkit.js:41 Uc @ gitkit.js:39 Rc @ gitkit.js:41 Pc.b @ gitkit.js:37 gitkit.js:254 [ 40.291s] [identitytoolkit] createAuthUri: {"error":{"errors":[{"domain":"global","reason":"backendError","message":"Error code: 2"}],"code":503,"message":"Error code: 2"}} Is this a bug? A: It was related to AOL shutting down their OIDC service. Google Identity Toolkit team applied a fix to bypass it. The issue was resolved without any code change from my end. Thanks to @bojeil for help.
{ "pile_set_name": "StackExchange" }
Q: Remove an image using CSS attributes I have a set of identical images that I don't wish to display, I hope to do this with display:none; How can I target a src image url with CSS attributes? So far, I have: [src="mypic_68.png"] { display:none; } A: I think you have src like this: src="images/mypic_68.png" then your code won't work. You may use: [src$="mypic_68.png"] { //$ to indicate ending with display:none; } Here, you can find all attribute selectors.
{ "pile_set_name": "StackExchange" }
Q: Check if current date is between 2 dates in MySQL I have a contract table in my database and those contracts have a start date and an end date. How can I change their active state if the current date is after the end date? I already figured out that I'll do it with a stored procedure that gets executed every day or something like that. My Problem is, I don't know, how I can check each row in the table. It seems like something extremely basic yet I can't think of any solution. I found this Response and it looks very promising but I'm afraid I don't understand the way it's supposed to work. I'd highly appreciate any and all pointers. EDIT: I found the solution and my way of approaching the problem was way off. A: Thanks to @RiggsFolly I found the solution: UPDATE contract_conclusion SET is_active=0 WHERE CURDATE() > date_end_contract_conclusion;
{ "pile_set_name": "StackExchange" }
Q: UITableViewCell next to eachother How can i make a tableview where the cells are next to each other. Where there are 2 on each row. example like this? In the second row there are 2 images next to each other. Can this be done in a tableview by making custom tablevieCells? A: Yes this can be done in UItableViewCell But preferred to use collection view for this kind of view. Just subclass uitableviewcell, add new method -(void)setCellWithNumberOfImages:(NSInteger)images withImage1:(UIimage *)image1 withImage2:(UIImage *)image2; if(image2 ==nil) //add only one UIimageView with image1 else //add two imageviews.
{ "pile_set_name": "StackExchange" }
Q: Junit4 Android TestField text test My test is: @RunWith(AndroidJUnit4.class) @LargeTest public class TipActivityTests { @Rule public ActivityTestRule<TipActivity> mActivityRule = new ActivityTestRule<>(TipActivity.class); @Test public void initialValues() { onView(withId(R.id.tip_label_base_price)).check(matches(ViewMatchers.withText("45""))); } } But I get the error 'with text: is "45"' doesn't match the selected view. Expected: with text: is "45": android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with text: is "45"' doesn't match the selected view. Expected: with text: is "45" Got: "AppCompatTextView{id=2131689669, res-name=tip_label_base_price, visibility=VISIBLE, width=266, height=106, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=141.0, y=96.0, text=$ 45.00, input-type=0, ime-target=false, has-links=false}" It doesn't make sense to me, it should not print the actual value of the field vs the compared value? A: I had the same problem and spent quite some time trying to understand the root cause. It turned out the strings were not equals, that's why it was failing. The error message is not really explicit because it's printing the whole object properties etc instead of saying: expected: "foo", received: "bar". But the strings are actually compared.
{ "pile_set_name": "StackExchange" }
Q: What kind of Exception occurred? I tried to create a test ClassCastException: In line 1: it prints out class cast exception as I expected In line 2: it just prints exception.RuntimeExceptionTest$1B@7852e922 (RuntimeExceptionTest is my class name). I wonder what kind of exception here? try { class A { } class B extends A {} class C extends A {} A objA = new B(); System.out.println((C)objA); // Line 1 System.out.println((A)objA); // Line 2 } catch (Exception e) { e.printStackTrace(); } A: Line2 doesn't throw an exception. From the Oracle javadocs: The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of: getClass().getName() + '@' + Integer.toHexString(hashCode()) That means your Line2 just prints what objA.toString() returns, which is exception.RuntimeExceptionTest$1B@7852e922 since exception.RuntimeExceptionTest is your class name.
{ "pile_set_name": "StackExchange" }
Q: Implementing a "soft delete" system using sqlalchemy We are creating a service for an app using tornado and sqlalchemy. The application is written in django and uses a "soft delete mechanism". What that means is that there was no deletion in the underlying mysql tables. To mark a row as deleted we simply set the attributed "delete" as True. However, in the service we are using sqlalchemy. Initially, we started to add check for delete in the queries made through sqlalchemy itself like: customers = db.query(Customer).filter(not_(Customer.deleted)).all() However this leads to a lot of potential bugs because developers tend to miss the check for deleted in there queries. Hence we decided to override the default querying with our query class that does a "pre-filter": class SafeDeleteMixin(Query): def __iter__(self): return Query.__iter__(self.deleted_filter()) def from_self(self, *ent): # override from_self() to automatically apply # the criterion too. this works with count() and # others. return Query.from_self(self.deleted_filter(), *ent) def deleted_filter(self): mzero = self._mapper_zero() if mzero is not None: crit = mzero.class_.deleted == False return self.enable_assertions(False).filter(crit) else: return self This inspired from a solution on sqlalchemy docs here: https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/PreFilteredQuery However, we are still facing issues, like in cases where we are doing filter and update together and using this query class as defined above the update does not respect the criterion of delete=False when applying the filter for update. db = CustomSession(with_deleted=False)() result = db.query(Customer).filter(Customer.id == customer_id).update({Customer.last_active_time: last_active_time }) How can I implement the "soft-delete" feature in sqlalchemy A: I've done something similar here. We did it a bit differently, we made a service layer that all database access goes through, kind of like a controller, but only for db access, we called it a ResourceManager, and it's heavily inspired by "Domain Driven Design" (great book, invaluable for using SQLAlchemy well). A derived ResourceManager exists for each aggregate root, ie. each resource class you want to get at things through. (Though sometimes for really simple ResourceManagers, the derived manager class itself is generated dynamically) It has a method that gives out your base query, and that base query gets filtered for your soft delete before it's handed out. From then on, you can add to that query generatively for filtering, and finally call it with query.one() or first() or all() or count(). Note, there is one gotcha I encountered for this kind of generative query handling, you can hang yourself if you join a table too many times. In some cases for filtering we had to keep track of which tables had already been joined. If your delete filter is off the primary table, just filter that first, and you can join willy nilly after that. so something like this: class ResourceManager(object): # these will get filled in by the derived class # you could use ABC tools if you want, we don't bother model_class = None serializer_class = None # the resource manager gets instantiated once per request # and passed the current requests SQAlchemy session def __init__(self, dbsession): self.dbs = dbsession # hand out base query, assumes we have a boolean 'deleted' column @property def query(self): return self.dbs(self.model_class).filter( getattr(self.model_class, 'deleted')==False) class UserManager(ResourceManager): model_class = User # some client code might look this dbs = SomeSessionFactoryIHave() user_manager = UserManager(dbs) users = user_manager.query.filter_by(name_last="Duncan").first() Now as long as I always start off by going through a ResourceManager, which has other benefits too (see aforementioned book), I know my query is pre-filtered. This has worked very well for us on a current project that has soft-delete and quite an extensive and thorny db schema. hth!
{ "pile_set_name": "StackExchange" }
Q: How can I take multiple inputs from the same line? I can't figure out how to take multiple inputs from one line. Here is an example: p=gets.chomp().to_i q=gets.chomp().to_i puts"#{p} #{q}" When I run this and take inputs, I have to take it from a new line. E.g., 3 4 output: 3 4 If I type 3 4 it is not taking 4 as input and is waiting for another input from the next line. What should be done? A: gets reads in the whole line. If you want to process multiple elements from it, you need to split on that line, or perform regex matches on it, etc. In your case: p, q = gets.split.map(&:to_i) BTW, in your code, the chomp calls are superfluous, since to_i will work correctly whether the string ends with a newline or not.
{ "pile_set_name": "StackExchange" }
Q: Simple Clarification Objects Swift Language I have a very simple question on something that I may have misunderstood. I have two UIViews "A" and "B". If I write : let A = UIView() // Or something else let B = A and then I change properties of B (for exemple the frame), will the properties of A change too ? I though not, but I was animating a view, so I had the initial view and the final view. I created a transition view like this : let transitionView = finalView and then I changed the properties of transitionView, the position of a label for exemple. When I added the final view at the end of the animation, the label was at the new position. Why ? Thanks A: In swift types are split in 2 main categories: reference types value types Classes are reference types; structs (which include arrays and dictionaries), basic data types (int, float, string, etc.), and enums are all value types. A value type is always passed by value, which means when assigning to a variable or passing to a function/method, a copy of the original data is created. There's an exception to this rule: a function/method can use the inout modifier on a value type parameter to have it passed by reference. Note that the compiler and the runtime usually do optimizations, so a copy is not always created unless strictly needed - what's important is that we, as developer, know that we are working on a copy and not on the original data. A reference type is always passed by reference, which means when assigning it to a variable or passing it to a function/method, a reference to the data and not the data itself is assigned/passed. UIView is a class, so when you create an instance, assign it to a variable, then assign that variable to another variable, the reference to the instance and not the instance itself is assigned. Both variables point to the same UIView instance. Any change made to the instance is visible to all variables referencing that instance. Suggested reading: Classes and Structures
{ "pile_set_name": "StackExchange" }
Q: What does 4X, 5X, 6X VALUE! mean in Special Offers in CoC? In clash of clans, there are some special offers, with 4X, 5X, 6X VALUE! in top as you can see in the picture. Does this mean for example if we took Builder Potion we can gain 6 x 5 hours which mean 30 hours instead of just 6 hours? or what does mean exactly. A: It's just a marketing thing to motivate players to buy the bundle. You will get what's inside the bundle once. The 'value' is just saying that it's a limited offer that's way more valuable than a regular offer for the same amount of money.
{ "pile_set_name": "StackExchange" }
Q: How to remove the text "undefined" that is appearing in the autocomplete search field? I have a autocomplete search. If there are no results that corresponds to the search it appears the message "No results.". And its working the message "No results" if the user introduce 3 letters that don't correspond to any result. However it appears "undefiend" above the message "No results". Do you know how to remove that "undefiend" text? $.widget( "custom.catcomplete", $.ui.autocomplete, { _create: function() { this._super(); this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" ); }, _renderMenu: function( ul, items ) { var that = this, currentCategory = ""; $.each( items, function( index, item ) { var li; if ( item.category != currentCategory ) { ul.append( "<li>" + item.category + "</li>" ); currentCategory = item.category; } li = that._renderItemData( ul, item ); if ( item.category ) { li.attr( "aria-label", item.category + " : " + item.label ); } }); } }); $("#search").catcomplete({ source: "{{ URL::to('autocomplete-search') }}", minLength: 3, response: function(event, ui){ if (!ui.content.length) { var noResult = { value:"", label:"No results." }; ui.content.push(noResult); } }, select: function(event, ui) { if(ui.item.category=="Conferences"){ window.location.href = ui.item.url; } else{ $.get(ui.item.url, function(result) { var newConferences = ''; var placeholder = "{{route('conferences.show', ['id' => '1', 'slug' => 'demo-slug'])}}"; $.each(result, function(index, conference) { var url = placeholder.replace(1, conference.id).replace('demo-slug', conference.slug); newConferences += '<div>\n' + ' <div class="card box-shaddow">\n' + ' <div class="card-body">\n' + ' <h5>'+conference.name+'</h5>\n' + ' </div>\n' + ' </div></div>'; }); $('#conferences').html(newConferences); }, 'json'); } } }); A: You may replace the condition if ( item.category != currentCategory ) with the condition if ( item.category && item.category != currentCategory ) So that when the item doesn't have any category (which is your case : 'undefined') it doesn't append a useless line to your html.
{ "pile_set_name": "StackExchange" }
Q: What happened to the opera-next package? A week ago I noticed opera-next package in New in repository Synaptics' filter. So I installed it to test some HTML. Today I noticed that it has replaced x-www-browser alternative and tried to reproduce it but it was no longer in the repository. I don't remember enabling/disabling PPAs so it could be from official partner repository. And now it's gone. Was there some announcement about why was it removed? A: opera-next was never an Ubuntu package. You got it from http://deb.opera.com (FWIW, the partner repository isn't part of Ubuntu, either, it's an add-on repository from Canonical, that doesn't obey Ubuntu's rules)
{ "pile_set_name": "StackExchange" }
Q: How should I binding value to make the labelView in CustomItemView show the text info in the listController? I try to design a custom view inside a listView. The code looks like the following: Myapp.listView=SC.ScrollView.design({ layout: { centerX: 0, width:100, top: 70, bottom:36}, contentView: SC.ListView.design({ contentBinding: SC.Binding.oneWay('Myapp.listController'), rowHeight: 36, exampleView:Myapp.CustomItemView.design({ }) }) }); MyApp.CustomItemView = SC.View.design({ childViews:['imageView','labelView'], imageView: ...., labelView:SC.LabelView.design({ }) }); My question is: How should I binding value to make the labelView in CustomItemView show the text info in the listController? A: Like Ramesh say, your customItemView should be like this: MyApp.CustomItemView = SC.View.design({ childViews:['imageView','labelView'], imageView: ... labelView: SC.LabelView.design({ valueBinding: ".parentView.content.textInfo" })
{ "pile_set_name": "StackExchange" }
Q: How can I add a custom button by using a custom module in Magento 2.3? I wanted to add my own button in the Shopping Cart as I tried to show you in the screenshot. But I didn't find a tutorial that worked for me. Do you have any idea how I can do this? (I want to make my own extension) (EDIT) This is what I have done so far: In the registration.php file: <?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Vendor_ModuleName', __DIR__ ); In the module.xml file: <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Vendor_ModuleName" setup_version="1.0.0"></module> </config> In the Button.php file: <?php namespace Vendor\ModuleName\Block; class Button extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Backend\Block\Template\Context $context, array $data = [] ) { parent::__construct($context, $data); } } In the checkout_cart_index.xml file: <?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <referenceContainer name="cart.summary"> <block class="Vendor\Module\Block\Button" after="-" name="custom_button" template="Vendor_ModuleName::button.phtml" /> </referenceContainer> </page> In the button.phtml file: <button>Your Button</button> I also ran all commands you have told me. A: Create a Custom Module as Follows Vendor\ModuleName\registration.php <?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Vendor_ModuleName', __DIR__ ); then Vendor\ModuleName\etc\module.xml <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Vendor_ModuleName" setup_version="1.0.0"> <sequence> <module name="Magento_Checkout"/> </sequence> </module> </config> After that run following Command php bin/magento setup:upgrade php bin/magento setup:di:compile php bin/magento setup:static-content:deploy -f chmod -R 777 var/ pub/ generated/ Add this is Your Vendor\ModuleName\view\frontend\layout\checkout_cart_index.xml <?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <referenceContainer name="cart.summary"> <block class="Vendor\Module\Block\Button" after="-" name="custom_button" template="Vendor_ModuleName::button.phtml" /> </referenceContainer> </page> Now in Vendor\ModuleName\Block\Button.php namespace Vendor\ModuleName\Block; class Button extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Backend\Block\Template\Context $context, array $data = [] ) { parent::__construct($context, $data); } } then in Vendor\ModuleName\view\frontend\templates\button.phtml <button>Your Button</button>
{ "pile_set_name": "StackExchange" }
Q: How to define only 4 characters input by user in C I want to make program that allow user input only 4 characters. After that, the system should prompt appropriate error message to the users. How look syntax should be? Here , i am stuck on this,doesnt know how to continue. #include<stdio.h> #include<conio.h> #include <string.h> int main(int argc,char **argv) { int i; char cTransID[4]; printf("Enter 4 characters of your name: "); gets(cTransID); printf("Length of string c=%d \n",strlen(cTransID)); } A: If it's a case where the user absolutely must enter 4 characters, then you can try utilizing "getch()" along with a for loop. #include<stdio.h> #include<conio.h> #include <string.h> int main(int argc,char **argv) { int i; char cTransID[5]; printf("Enter 4 characters of your name: "); for (i = 0; i <= 3 ;i++) { cTransID[i] = getch(); printf("%c",cTransID[i]); } printf("\n\n%s",cTransID); getch(); return 0; }
{ "pile_set_name": "StackExchange" }
Q: Swift 4 Conversion error - NSAttributedStringKey: Any I converted my app recently and I keep getting the error "Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedStringKey: Any]?' barButtonItem.setTitleTextAttributes(attributes, for: .normal) Whole code: class func getBarButtonItem(title:String) -> UIBarButtonItem { let barButtonItem = UIBarButtonItem.init(title: title, style: .plain, target: nil, action: nil) let attributes = [NSAttributedStringKey.font.rawValue: UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor: UIColor.white] as! [String : Any] barButtonItem.setTitleTextAttributes(attributes, for: .normal) return barButtonItem } A: Why you got this error Previously, your attributes is defined as [String: Any], where the key comes from NSAttributedStringKey as a string or NSAttributedString.Key in Swift 4.2 During the migration, the compiler tries to keep the [String: Any] type. However, NSAttributedStringKey becomes a struct in swift 4. So the compiler tries to change that to string by getting its raw value. In this case, setTitleTextAttributes is looking for [NSAttributedStringKey: Any] but you provided [String: Any] To fix this error: Remove .rawValue and cast your attributes as [NSAttributedStringKey: Any] Namely, change this following line let attributes = [NSAttributedStringKey.font.rawValue: UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor: UIColor.white] as! [String : Any] to let attributes = [NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor: UIColor.white] as! [NSAttributedStringKey: Any] And in Swift 4.2, let attributes = [NSAttributedString.Key.font: UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedString.Key.foregroundColor: UIColor.white] as! [NSAttributedStringKey: Any] A: Its expecting NSAttributedStringKey(NSAttributedStringKey.font) and you are sending String(NSAttributedStringKey.font.rawValue). So please replace NSAttributedStringKey.font.rawValue with NSAttributedStringKey.font like below : let attributes = [NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor: UIColor.white] A: As noted in previous answers, NSAttributedStringKey was changed to a struct in Swift 4. However, other objects that use NSAttributedStringKey apparently didn't get updated at the same time. The easiest fix, without having to change any of your other code, is to append .rawValue to all your occurrences of NSAttributedStringKey setters - turning the key names into Strings: let attributes = [ NSAttributedStringKey.font.rawValue: UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor.rawValue: UIColor.white ] as [String : Any] Note that you won't need the ! at the as now, either. Alternatively, you can skip the as cast at the end by declaring the array to be [String : Any] upfront: let attributes: [String : Any] = [ NSAttributedStringKey.font.rawValue: UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor.rawValue: UIColor.white ] Of course, you still need to append the .rawValue for each NSAttributedStringKey item you set.
{ "pile_set_name": "StackExchange" }
Q: Why does array allocation with a variable work? This code: int main() { int size; scanf("%d", &size); int array[size]; } works fine with GCC, but VC expects a constant expression for the size of the array so does not compile it (which makes more sense to me). Any idea why it works with GCC? A: Yes, because gcc supports variable length arrays. It was added as a part of C99 standard, however, in the later standards (C11 and C18), it's an optional feature.
{ "pile_set_name": "StackExchange" }