text
stringlengths
64
89.7k
meta
dict
Q: practical applications of eigenvalues and eigenvectors We're making a video presentation on the topic of eigenvectors and eigenvalues. Unfortunately we have only reached the theoretical part of the discussion. Any comments on practical applications would be appreciated. A: The problem of ranking the outcomes of a search engine like Google is solved in terms of an invariant measure on the net, seen as a Markov chain. Finding the invariant measure requires the spectral analysis of the associated matrix. A: I would comment on Peitro's answer, but I don't have enough reputation; for a marvelously-titled explanation of Google's Pagerank, see The $25,000,000,000 Eigenvector. A: Google's pagerank system is most likely the most canonical example, however others include, -Dynamical System If you are able to express a model in terms of a matrix acting on vectors, one can look at the iterations and ask what occurs? This can be done to model the life cycle of some species in an environment (bacteria on a petri dish, wolf/sheep interaction, fibonacci sequence as the spread of a population of bunnies, etc...). These examples are fairly small, however you can certainly have massive systems to model, and if your matrix is diagonalizable, the iterations of this map correspond to iterations of a diagonal matrix (very easy to do!) instead of the standard $m^{2}$ operations to multiply out an $m\times m$ matrix. Think about a $1 000 000 \times 1 000 000$ matrix $M$, where you're looking at whether a certain species will die out (i.e., itererating $M^{n}$ and checking as $n\to\infty$. Quite the time saver!) -Graph theory As an undergrad one of my summer research projects looked into special graphs called (3,6)-fullerenes, where we were finding that, looking at the adjacency matrix of the graph, one could pick 3 well chosen eigenvalues and their corresponding eigenvetors, and generate nice 3d plots of the graphs, whereas other choices would produce degenerate images, involving some twisted 2d surface. -Differential equations One can use eigenvalues and eigenvectors to express the solutions to certain differential equations, which is one of the main reasons theory was developed in the first place! I would highly recommend reading the wikipedia article, as it covers many more examples than any one reply here will likely contain, with examples along to way! (Schrödinger equation, Molecular Orbitals, Geology and Glaciology, Factor Analysis, Vibration Analysis, Eigenfaces, Tensor of Inertia, Stress Tensor, Eigenvalues of a Graph)
{ "pile_set_name": "StackExchange" }
Q: Is it appropriate for assistant professors to supervise PhD students? As pointed out in another question, the general tendency today as compared from classical times is to make junior professors (at assistant level) more and more independent. However, I wonder that assistant professors (common in the US university) supervise PhD students. The philosophy of academic ranking is to prepare academics for academic/scientific tasks. Although, academics normally have postdoc experience before their appointment as assistant professors, it is not mandatory. Moreover, postdoc experience is not experience conducive for the supervising of students. In relation to the above is it wrong that an inexperienced assistant professor (who is not far from his PhD studentship days) can take control of one or several PhD students? Does it reduce the quality of the education/research? A: Isn't it wrong that an inexperienced assistant professor (who is not far from his PhD studentship days) can take control of one or several PhD students? Don't it reduce the education/research quality? For certain institutes I've been in, I would find myself asking the opposite question: isn't it wrong for senior professors to supervise students when they have little time for them? Of course it is not always the case that full professors have no time for their students, but I have seen it happen many times: I've seen cases where students were meeting their official full professor supervisors once a month (or less frequently) and putting names of supervisors on papers that the supervisors had never read. This seems to me to be prevalent in research institutes where the hierarchy tree has a high branching factor to get value out of available funds (few Full Professors, lots of PostDocs / Assistant Professors, even more PhD students and Research Assistants, etc.); in such cases, the priority for senior professors is getting funding for and managing projects. In my case, when I was a PostDoc in such an institute, I was doing the day-to-day supervision of a number of students whose supervisor(s) had no time for them. Of course it varies from place to place. But my hypothesis is that by the time you reach the Assistant Professor level, either you will have the necessary skills and personality to be a good supervisor, or you will probably never have those skills. In summary: I don't believe that seniority amongst professors is a good predictor for quality of supervision. A: Isn't it wrong that an inexperienced assistant professor (who is not far from his PhD studentship days) can take control of one or several PhD students? No, it is not wrong. Don't it reduce the education/research quality? Well, maybe. Supervising PhD students is a learning activity like most anything else. As such, it is to be expected that maybe when an assistant professor supervises her/his first student, s/he may do things that should would handle differently later on. But this is not tied to the status of the person, but to her/his experience in advising. So if you don't let assistant professors advise PhD students, they would start doing it later on and be equally bad in it, because when would they have learned how to do it? An additional concern is that there are only so many full professors to go around. While I concede that working with a more senior professor may have advantages, these advantages would likely disappear if every senior professor has to handle significantly more students (as the entire 'advising force' of assistant professors falls away). I should also add that, in general, assistant professors are not nearly as inexperienced as you seem to assume. Today, at least in my field (CS), there is hardly any assistant professor that did not have multiple years of postdoc experience, which also includes co-supervising master and PhD students. As such, I am not sure if the problem you seem to consider even exists. Edit based on ff524's comment: I think the question intends to ask, "Is it appropriate for assistant professors to supervise PhD students alone?" In some places, PhD students working with an inexperienced advisor are also co-advised by another (more experienced) advisor. Yes, this is actually the case in many well-respected university (dutch universities come to mind right now). I think this is great if the main responsibility / load is still on the junior professor, with the senior person being more an advisor to the advisor than to the student. If the model degenerates into the junior professor basically being a proxy for the senior person, this seems counter-productive. A: Of course it's appropriate. In many research-intensive academic departments it's the assistant professors (the younger researchers) that are doing the innovative research. I had several friends who worked with an assistant professor years ago. That professor later won a Nobel Prize for the work being done in his assistant professor days, with the help of those students.
{ "pile_set_name": "StackExchange" }
Q: xcode - Capitalise Label Output I'm pretty new to xcode - so please bear with me! I'm outputting information from a database to UILabels with information like Name, Region, etc (all good, so far). However - there is a column of text in the database which is all in lowercase (ie flat area to the left)... The lowercase text looks pretty sucky when it's loaded into the app - so without going into the database and changing all 5000 entries, is there a way to force capitalization programmatically (as is possible in CSS, for example)? For reference, I'm using the following code in the header file: IBOutlet UILabel *lblfeatures; Then in the implementation file: lblfeatures.text = [self.passedDict objectForKey:@"Feature"]; And linked up through the connections inspector. Thanks so much :) A: You might want to do something like: lblfeatures.text = [[self.passedDict objectForKey:@"Feature"] capitalizedString]; There are more methods for capitalization described in https://developer.apple.com/library/Mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/capitalizedString.
{ "pile_set_name": "StackExchange" }
Q: Drop Down list Issue in IOS I have made a drop down having a button and under it is a table view in which i show list in it. There are three drop down with this respective order, but1 with table1 , but2 with table2 and but3 with table3.when we click but1 it shows list of country in table1. when we click but2 it shows the cities name of the country we selected in but1 in table2 and when we click but3 it shows same country names in table3 and when i select country from but3 and table3 it shows country code in a textfield. The issue i'm facing is that , when i select country fro but3, but2 city name changes to country name that i have selected in but3. I'm finding this issue about more than 6 hours but i'm failed , kindly please help me where i'm doing mistake. my code is, - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if ([ImageViewC isEqualToString:@"1"]) return [data count]; else if ([ImageViewC isEqualToString:@"2"]){ return [data1 count]; }else{ return [data3 count]; } } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } if ([ImageViewC isEqualToString:@"1"]) { cell.textLabel.text = [data objectAtIndex:indexPath.row]; }else if([ImageViewC isEqualToString:@"2"]){ cell.textLabel.text = [data1 objectAtIndex:indexPath.row]; } else if([ImageViewC isEqualToString:@"3"]){ cell.textLabel.text = [data3 objectAtIndex:indexPath.row]; } return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath]; NSLog(@"%@",selectedCell.textLabel.text); if ([ImageViewC isEqualToString:@"1"]) { [self.but1 setTitle:[NSString stringWithFormat:@"%@",selectedCell.textLabel.text] forState:UIControlStateNormal]; if ([selectedCell.textLabel.text isEqualToString:@"Pakistan"]) { data1=[[NSArray alloc]initWithArray:Pak_city]; }else if ([selectedCell.textLabel.text isEqualToString:@"UAE"]){ data1=[[NSArray alloc]initWithArray:UAE_city]; }else{ data1=[[NSArray alloc]initWithArray:Oman_city]; } } else{ [self.but2 setTitle:[NSString stringWithFormat:@"%@",selectedCell.textLabel.text] forState:UIControlStateNormal]; } if ([ImageViewC isEqualToString:@"3"]) { [self.Country setTitle:[NSString stringWithFormat:@"%@",selectedCell.textLabel.text] forState:UIControlStateNormal]; if ([selectedCell.textLabel.text isEqualToString:@"PAKISTAN"]){ _code.text=pakCode; }else if ([selectedCell.textLabel.text isEqualToString:@"UAE"]){ _code.text=uaeCode; }else { _code.text=omanCode; } } table1.hidden=YES; table2.hidden=YES; table3.hidden=YES; } A: Change your condition as below : - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (tableView == table1) return [data count]; else if (tableView == table2){ return [data1 count]; }else{ return [data3 count]; } } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } if (tableView == table1) { cell.textLabel.text = [data objectAtIndex:indexPath.row]; }else if(tableView == table2){ cell.textLabel.text = [data1 objectAtIndex:indexPath.row]; } else if(tableView == table3){ cell.textLabel.text = [data3 objectAtIndex:indexPath.row]; } return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *selectedCell=[tableView cellForRowAtIndexPath:indexPath]; NSLog(@"%@",selectedCell.textLabel.text); if (tableview == table1) { [self.but1 setTitle:[NSString stringWithFormat:@"%@",selectedCell.textLabel.text] forState:UIControlStateNormal]; if ([selectedCell.textLabel.text isEqualToString:@"Pakistan"]) { data1=[[NSArray alloc]initWithArray:Pak_city]; }else if ([selectedCell.textLabel.text isEqualToString:@"UAE"]){ data1=[[NSArray alloc]initWithArray:UAE_city]; }else{ data1=[[NSArray alloc]initWithArray:Oman_city]; } } else if (tableview == table2){ [self.but2 setTitle:[NSString stringWithFormat:@"%@",selectedCell.textLabel.text] forState:UIControlStateNormal]; } else if (tableview == table3){ { [self.Country setTitle:[NSString stringWithFormat:@"%@",selectedCell.textLabel.text] forState:UIControlStateNormal]; if ([selectedCell.textLabel.text isEqualToString:@"PAKISTAN"]){ _code.text=pakCode; }else if ([selectedCell.textLabel.text isEqualToString:@"UAE"]){ _code.text=uaeCode; }else { _code.text=omanCode; } } table1.hidden=YES; table2.hidden=YES; table3.hidden=YES; }
{ "pile_set_name": "StackExchange" }
Q: Issue with multiple Switches, NullPointerException I am running into an issue that is causing a null pointer exception. The issue is because of the way I have my OnCheckedChanged() method structured. Currently, a different Dialog view is inflated based on a string that is passed on creation. Based on this view, there are different Switches that are presented to the user. I am looking for a way to reconfigure the following code so that it does run through all the "if statements" and crash. I would like it to do something similar to a switch(v.getId()) + switch structure. I am trying to avoid implementing seperate OnCheckedChange listeners for my app. Anyone know how I could restructure this to avoid the NullPointerException? @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (alertDelete.isChecked()) { // The toggle is enabled permSet.add("alert_delete"); Log.e("ALERTDELETE", "CHECKED"); } else { // The toggle is disabled permSet.remove("alert_delete"); Log.e("ALERTDELETE", "UNCHECKED"); } if (autoCreate.isChecked()) { // The toggle is enabled permSet.add("auto_create"); Log.e("ALERTDELETE", "CHECKED"); } else { // The toggle is disabled permSet.remove("auto_create"); Log.e("ALERTDELETE", "UNCHECKED"); } if (autoDelete.isChecked()) { // The toggle is enabled permSet.add("auto_delete"); Log.e("ALERTDELETE", "CHECKED"); } else { // The toggle is disabled permSet.remove("auto_delete"); Log.e("ALERTDELETE", "UNCHECKED"); } if (autoEdit.isChecked()) { // The toggle is enabled permSet.add("auto_edit"); Log.e("ALERTDELETE", "CHECKED"); } else { // The toggle is disabled permSet.remove("auto_edit"); Log.e("ALERTDELETE", "UNCHECKED"); } } A: you could also have a simple method to avoid replications private void checkAndSet(Checkable checkable, String param) { if (checkable.isChecked()) { // The toggle is enabled permSet.add(param); Log.e("ALERTDELETE", "CHECKED"); } else { // The toggle is disabled permSet.remove(param); Log.e("ALERTDELETE", "UNCHECKED"); } } and in each case you can call: checkAndSet(autoDelete, "auto_delete");
{ "pile_set_name": "StackExchange" }
Q: Scale down a larger number from 0 - 1 - 0 I'm not math savvy - but what I want to do seems to be math heavy. I'm looking to scale down a number which ranges from 0-800 so that it is within a range of 0-1-0 (so 1 being 400). Not sure if this is possible, but my attempts at a solution have not been fruitful. Any indication as to where to look for a solution would be of great benefit! It's so I can change the alpha of images depending on the screen location - the centre-most images should be 100% visible, whilst as it get's further to the edge of the screen, the images should become more transparent. The range for alpha is 0-1. Kind regards, and thanks in advance! A: Here is the graph of 1-abs(1-2x/a) where a=800: Here is sin(pi*x/a):
{ "pile_set_name": "StackExchange" }
Q: how to change nested if-else to when statements using Kotlin? I have the following block of code and want to reduce it using Kotlin. How can I do that? if (name == nameArray[0]) { // The statement } else if(name == nameArray[1]) { // The statement } else if(name == nameArray[2]) { // The statement } else if(name == nameArray[3]) { // The statement } else { // The statement } A: If the array is small and you want to map an action to each index: You could use indexOfFirst to determine the smallest index which meats your condition. Then you can use a when statement to decide what to do. when(nameArray.indexOfFirst{ it == name }) { 0 -> // do something 1 -> // do something else //... else -> // do something different } In case you might want to do the same thing for multiple indices you can use comma separated values. In case the indices are consecutive, you can use ranges: when(nameArray.indexOfFirst{ it == name }) { 0 -> // do something 1, 2 -> // do the same thing for 1 and 2 in 3..6 -> // do the same thing for 3, 4, 5 and 6 //... else -> // do something different } In order to use this syntax it is a good idea to do index retrieval (like shown) first. If the array is big and you really only want to check for specific elements: when(name) { nameArray[0] -> // do something nameArray[1] -> // do something nameArray[2] -> // do something nameArray[3] -> // do something else -> // other action }
{ "pile_set_name": "StackExchange" }
Q: Using threads to update UI with Swift I'm developing a software with Xcode 6 using Swift. When I press a button, my code takes some informations from the web and writes them on my NSWindow. So imagine something like this: @IBAction func buttonPressed(sender: AnyObject) { for page in listOfPages //Number of pages is 40. { var label: NSTextField = NSTextField(); label.stringValue = getInformetionsFromPage(page) /* some code to add label in the window here */ } } The problem is that once I click the button, it takes a while before I see the list of results, in the main time the app is frozen. That's because I'm not using any threads to handle this problem. How could I implement threads to see every label updated every step of the loop? I'm new with threads and Swift, so I would need some help! Thank you guys. A: Swift 3.0 + version DispatchQueue.main.async() { // your UI update code } Posted this because XCode cannot suggest the correct syntax from swift 2.0 version A: There is GCD. Here is a basic usage: for page in listOfPages { var label = NSTextField() dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let result = getInformationFromPage(page) dispatch_async(dispatch_get_main_queue()) { label.stringValue = result } } } dispatch_async function asynchronously runs the block of code on the given queue. In first dispatch_async call we dispatch the code to run on background queue. After we get result we update label on main queue with that result
{ "pile_set_name": "StackExchange" }
Q: How to set univeral timezone for entire application in winforms How can I set Universal timezone for entire application. So that even if the timezone is changed, the application should show time as per universal timezone. So is it possible to set entire application timezone? A: Unfortunately you cannot (You could look at Jon Skeet response in following thread: Setting/Changing an .NET application's TimeZone). So you have two options: Everywhwer use DateTime.ToUniversalTime (MSDN description) Create your own class which represents DateTime and use it instead You can use one more trick. You can mock DateTime with for example Microsoft Fakes. Look more here: Using shims to isolate your application from other assemblies for unit testing
{ "pile_set_name": "StackExchange" }
Q: Ontological status of variables Background This question has its origin in this post. More specifically, in giving answers to the following questions, In what way does the collection of all sets consist of sets? What are collections of sets actually? It was written here that, The answers to 1. and 2. is that you have to set up some theory that allows you to talk about collections. The standard theory do this with is first-order logic, in which every formula with free variables is a description of a collection (aka a class), and these collections may also be described by auxillary functions and relations. answer it has been commented that, The point is that you can view first-order logic itself as a primitive "Theory of Collections", hence avoiding infinite regress. We are not describing or postulating how actual collections behave, but we are describing the language by which we express or refer to the collections. The potential for regress lies in disagreeing on what it takes to specify a formal language (since of course, we never actually have access to ALL formulas unless there were only finitely many), but certainly specifying the rules for producing well-formed statements and the rules for judging them justified is considered sufficient description: most humans seem to be expected to apply some sort of "pattern-matching" to the rules and to comprehend from them how to form well-formed statements (i.e. how to speak) and how to judge whether a statement is justified (what a proof is). So you don't to actually go ahead and develop a formal theory of languages before you can specify a formal language, but there is an important philosophical shift from mental to social activity in the level of justification required. However when I asked my teacher the same question (the question linked above) he replied that, We actually even don't need to worry about a Theory of Collection at all. When you learn a language, say English, do you ever worry whether the alphabets a,b,c,... belong to some collection or not? Surely not. But I think that we do not worry about that mainly because we have an explicit list of what my alphabets are and also we have a precise criteria (so, we are inclined to believe) to determine whether a particular symbol is our alphabet or not. My teacher also said that the correct way to view the situation is, "We have some symbols, whose meaning we don't know and we don't need to know. We also don't know and neither need to know where the symbols exist, whether in a collection or not." But when I asked him what he exactly meant when he said that we "have some symbols", he said that it is simply a variant of saying that the symbols exist. The Question If the symbols exist, then they exist where? (In case of alphabets, if I want to be painfully philosophical, I may be tempted to say that the alphabets exist in some "imaginative world" of my mind - which will in this case be "collection".) Is it even meaningful to ask 'where the symbols exist'? I think that it is necessary to have a Theory of Collection because the phrase "[w]e have some symbols" is very much vague. Consider the following question for example, Does the meaning (or sense) of "have" in "have some symbols" the same as that of "have" in "have a doll"? How can you say that? A: What is a variable ? A variable is a "syntactical" object: it lives in formalized languages. In the formalized language of logic and mathematics, it "works" like a pronoun. When we have a propositional function like "x is a red" or "x is odd" we have a statement like "it is red" or "it is odd". What is the meaning of the statement "it is red" ? It depends on the context: if I utter it pointing at my (red) book on my desk, I'm uttering a true sentence, that someone being present to my utterance can verify. The same for a mathematical propositional function: if I assert "x is odd", its meaning (its truth value) depends on the context. In this case, a context is specified by an interpretation: if I focus on the domain N of natural numbers and I assign to the variable x (a term of the language) as "temporary" denotation the number 3, then my assertion become meaningful (in this case, a true one). A variable is part of the language; specifically: of the formalized language of mathematics. Thus, a variable is a symbol. Symbols are everywhere in "our world": they are in the language we use to "speak of" the world: the world of everyday experience as well as the world of more abstract objects, like black holes, quarks, GDP, numbers, mathematical structures. And symbols are the "stuff" of our social life: when we drive a car and we stop at the crossroad seeing the traffic light blinking red, we do that because we interpret a symbol: the color of the traffic light. When we play chess, the pieces we are playing with, no matter of their color, or the fact that they are made of wood or chalk, are symbols; we can play with them also if they have different shapes from usual, provided that we can recognize the different "roles". And we can play without physicals pieces at all, on a TV screen or by mail. We can do it because the pieces of chess are symbols that receive their "meaning" in a certain context: the players share the rules of the game. When we communicate, we are playing a game with "linguistic pieces" (symbols) according to the shared rules we have learned when we learned how to speak and write... and count. Symbolic manipulation is there from the beginning: we learn counting quite early, and then we learn playing with geometrical shapes, and then we go on, until derivatives, tensors and more. If we can play with them, they exist... Someone can bet on a chess play: he can bet "real" money (and also bitcoins...) and loose it: he can do all thorugh the web. So what ? the chess pieces do not exist ? neither the web? not the money (it is only a string of bit on our banck account..). If no "not-physical" objects exist, why care about money, Brexit, -10% of stock markets... So, symbols exist, period. If so, they exist where? In our "world", made of individuals, physical objects and social life: without language and symbols no social life is possible, and without a social reality no language is needed. Maybe relevant: John Searle, The Construction of Social Reality (1995). Regarding the question What are collections of sets ? (but what is the link with the title ?), it is a very complex question: we have to dig deep into Philosophy of mathematics, and I'm not able to do it. But in a nutshell, the "common view" is that mathematical theories speak about some abstract "furniture" of the world (our actual one or only a possible one ?). Arithmetic is about numbers: the theorems of arithmetic are true of all those structures (possibly: only one) that satisfy the arithmetical axioms. Set theory is about sets: the theorems of set theory (unfortunately, we have more than one set theory...) are true of all those domains that satisfy the axioms. Set theory is very very peculiar, due to the fact that the concept of set is quite basic : for mathematicians and philosophers of 19th Century (end of) to every concept we can define (imagine, conceive of) there must be the corresponding set of objects satisfying that concept. This philosophically natural point of view does not work mathematically [see: The Early Development of Set Theory]; thus, the need of a more rigorous set theory [see: Zermelo's Axiomatization of Set Theory]. According to the framework of modern set theory, a concept define a collection, but not every collection is an object existing in the domain (or universe) of set theory. The "safe" collections are those that the theory asserts (axioms) or proves (theorems) that exist; we call them : sets. Having said that, the collection of all sets consists of what? Every colelction is specified by a concept (expressible in the theory). If we consider the "usual" first-order language of set theory, the concept: x = x is the concept identifying the collection of all sets. See e.g. by Penelope Maddy: Realism in Mathematics (1992) Believing the Axioms, The Journal of Symbolic Logic, Vol.53, No.2. (Jun,1988), pp.481-511 Defending the Axioms: On the Philosophical Foundations of Set Theory (2011). A: I am going to give the overextended postmodernist view here, springing originally from Wittgenstein and psychoanalytic thinkers like Lacan. I am doing so just so that both ends of this range are pinned down. In some sense I think this is 'the truth', but it is far too difficult to actually use, and may not be worth considering in the context of teaching logic at all. If the symbols exist, then they exist where? (In case of alphabets, if I want to be painfully philosophical, I may be tempted to say that the alphabets exist in some "imaginative world" of my mind - which will in this case be "collection".) From that point of view the symbol is its intended effect upon people, so in that sense it exists. They exist in the realm of human intention or expectation and are backed up in the realm of the human imagination, including our simplified memories of the real past. The letters of the alphabet do not exist as physical or even mental 'objects', they take variant forms and can be substituted by any potential form, for instance in binary coding, without loss of their power to be the letters that they are. I cannot put that object into your mind, I can only intend to, and accept the degree to which I do or do not succeed. If you do not already have a sense of the intention behind 'A'-ness, I cannot show you an A. We learn this notion of 'A'-ness by playing out the effects by rote until they are natural to us: the notion is the collection of memories of its effects and imaginings about its potential deployments. So I can have a symbol in my mind only if I know it has an intended purpose, and I use that symbol to evoke a complex of memories and images in another person's imagination (or in my own). Is it even meaningful to ask 'where the symbols exist'? In order for the question to make sense, it has to be stripped of the basic assumptions we have about mental objects, or it becomes circular. Mental objects as real things are themselves simply symbolic and any realization of an idea is made up of symbols. Symbols are the things that symbolize, and that is not helpful. So the idea of a mental or symbolic realm becomes baseless and circular. One simply has to insist it into existence by fiat, which is unsatisfying. Instead, you need to back off from the situation within your mind into the social realm. Once you see symbols or thoughts in terms of their usage in communication, then it becomes clear that we abstract expected usages into symbolic representations using some kind of 'cleaning up' mechanism that is largely similar among human beings. That is how you the above positions ends up saying that symbols are 'expectations' and nothing more. I think that it is necessary to have a Theory of Collection because the phrase "[w]e have some symbols" is very much vague. Consider the following question for example, We have an intuition of collection that empowers us to span the gap between parts and wholes without thinking about it too much. We can take that as our basic 'Theory of Collections', but it is not very much of a theory. Attempting to express it logically turns out to be extremely difficult, and to lead into conflict with very basic concepts like universality or negation. All of this is tied up in one neat package by Russel's Paradox. Does the meaning (or sense) of "have" in "have some symbols" the same as that of "have" in "have a doll"? How can you say that? No, it is the same as that in "we have laws" or "we have nations". By the laws we do not mean their impressions upon paper, we mean the expectation they encode. Likewise, by a nation we do not mean its people. When all the Romans had passed away, there was still Rome as an exemplar 'nation' upon which other nations built their legal systems, and even their languages. These things are not physical objects, they are abstractions that hold our expectations of how things should happen -- they reify social processes. They are 'the content of language-games', which occupy one side of a natural duality between things and the rules we insist upon applying to them.
{ "pile_set_name": "StackExchange" }
Q: how to command line VLC to RTSP IPCAM I wish to use VLC to stream IPCAM(s) to UBUNTU. I found a way doing it using VLC: Stream Media as : rtsp://192.168.3.101:554, and I choose "8000ms" of cache, and take 1:4 zoom. How can it be done using a command line ? A: As part a bash script: cvlc -vvv --network-caching $cache rtsp://192.168.3.$port:554 --zoom $zoom While $cache is buffer size in ms. And $port define cam's port
{ "pile_set_name": "StackExchange" }
Q: How to get number of bytes read from QTextStream The following code I am using to find the number of read bytes from QFile. With some files it gives the correct file size, but with some files it gives me a value that is approximatively fileCSV.size()/2. I am sending two files that have same number of characters in it, but have different file sizes link text. Should i use some other objects for reading the QFile? QFile fileCSV("someFile.txt"); if ( !fileCSV.open(QIODevice::ReadOnly | QIODevice::Text)) emit errorOccurredReadingCSV(this); QTextStream textStreamCSV( &fileCSV ); // use a text stream int fileCSVSize = fileCSV.size()); qint64 reconstructedCSVFileSize = 0; while ( !textStreamCSV.atEnd() ) { QString line = textStreamCSV.readLine(); // line of text excluding '\n' if (!line.isEmpty()) { reconstructedCSVFileSize += line.size(); //this doesn't work always reconstructedCSVFileSize += 2; } else reconstructedCSVFileSize += 2; } I know that reading the size of QString is wrong, give me some other solutions if you can. Thank you. A: I guess it is because QString::size() returns the number of characters. If your text file is in UTF16 and , say, x bytes long, this will correspond with x/2 characters. Edit: If you want to know the exact size of a read line, you can just use QFile::readLine(). This returns a QByteArray of which the number of bytes can be queried using size().
{ "pile_set_name": "StackExchange" }
Q: Converting YUV to YUV420 Android onPreview a)I was wondering what is the difference between YUV and YUV420? b)I want to use the raw frames from Camera and convert them into YUV420 in real time. What is the fastest way to do this? I used bitmap factory to convert from yuv to jpg and I used onDraw() method to draw the bitmap. However, this takes some time to process. What is the best alternative to do the conversion if I want converting from YUV to YUV420? A: I found a very straight forward way to convert from NV12 to YV12/YUV 420. Two lines of code did the job for me: public void surfaceCreated(SurfaceHolder holder) { try { // set view of surface in cameraview Camera.Parameters p = mCamera.getParameters(); p.setPreviewFormat(ImageFormat.YV12); mCamera.setParameters(p); mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } }
{ "pile_set_name": "StackExchange" }
Q: Split string with plus sign as a delimiter I have an issue with a string containing the plus sign (+). I want to split that string (or if there is some other way to solve my problem) string ColumnPlusLevel = "+-J10+-J10+-J10+-J10+-J10"; string strpluslevel = ""; strpluslevel = ColumnPlusLevel; string[] strpluslevel_lines = Regex.Split(strpluslevel, "+"); foreach (string line in strpluslevel_lines) { MessageBox.Show(line); strpluslevel_summa = strpluslevel_summa + line; } MessageBox.Show(strpluslevel_summa, "summa sumarum"); The MessageBox is for my testing purpose. Now... The ColumnPlusLevel string can have very varied entry but it is always a repeated pattern starting with the plus sign. i.e. "+MJ+MJ+MJ" or "+PPL14.1+PPL14.1+PPL14.1" as examples. (It comes form Another software and I cant edit the output from that software) How can I find out what that pattern is that is being repeated? That in this exampels is the +-J10 or +MJ or +PPL14.1 In my case above I have tested it by using only a MessageBox to show the result but I want the repeated pattering stored in a string later on. Maybe im doing it wrong by using Split, maybe there is another solution. Maybe I use Split in the wrong way. Hope you understand my problem and the result I want. Thanks for any advice. /Tomas A: How can I find out what that pattern is that is being repeated? Maybe i didn't understand the requirement fully, but isn't it easy as: string[] tokens = ColumnPlusLevel.Split(new[]{'+'}, StringSplitOptions.RemoveEmptyEntries); string first = tokens[0]; bool repeatingPattern = tokens.Skip(1).All(s => s == first); If repeatingPattern is true you know that the pattern itself is first. Can you maybe explain how the logic works The line which contains tokens.Skip(1) is a LINQ query, so you need to add using System.Linq at the top of your code file. Since tokens is a string[] which implements IEnumerable<string> you can use any LINQ (extension-)method. Enumerable.Skip(1) will skip the first because i have already stored that in a variable and i want to know if all others are same. Therefore i use All which returns false as soon as one item doesn't match the condition(so one string is different to the first). If all are same you know that there is a repeating pattern which is already stored in the variable first.
{ "pile_set_name": "StackExchange" }
Q: Processing xml file I have the following xml file: row category="1" category_name="CatA" entry_id="1" entry_name="A1" row category="1" category_name="CatA" entry_id="2" entry_name="A2" row category="1" category_name="CatA" entry_id="3" entry_name="A3" row category="2" category_name="CatB" entry_id="4" entry_name="B1" row category="2" category_name="CatB" entry_id="5" entry_name="B2" row category="2" category_name="CatB" entry_id="6" entry_name="B3" row category="3" category_name="CatC" entry_id="7" entry_name="C1" row category="4" category_name="CatD" entry_id="8" entry_name="D1" and I want to produce below html: CatA ----A1 ----A2 ----A3 CatB ----B1 ----B2 ----B3 CatC ----C1 CatD ----D1 for this I am using below php xml parser: $ndeshjet=simplexml_load_file("xml_file.xml"); $new_category = 1; foreach ($ndeshjet->row as $entry) { $category = $entry['category']; if ($category <> $new_category){ $category_name = $entry['category_name']; echo $category_name."</br>"; $new_category = $category; } else { $entry_name = $entry['entry_name']; echo "----".$entry_name."</br>"; } } ?> but the result is : ----A1 ----A2 ----A3 CatB CatB CatB CatC CatD Thanks in advance A: As an alternative, you could gather all the values first inside an array and make the category name as key pushing same keys inside. After thats done and gathered, print them accordingly: $categories = array(); // gather inside container foreach ($ndeshjet->row as $entry) { $category_name = (string) $entry->attributes()->category_name; $entry_name = (string) $entry->attributes()->entry_name; $categories[$category_name][] = $entry_name; } // presentation foreach($categories as $category_name => $entries) { echo $category_name . '<br/>'; foreach($entries as $entry) { echo '----' . $entry . '<br/>'; } } Sample Output
{ "pile_set_name": "StackExchange" }
Q: new windows 08 server, can't download using browser by default it seems you can't download anything using the browser on the server when terminal server'ing into the box. I need to download the java sdk to install solr, and also need to install winrar since I can't even unzip a file I uploaded from my mapped drive. What setting do I have to change? A: By default on Windows 2008 servers the Internet Explorer Enhanced Security Configuration is enabled. You can either disable it, or add the site you are having with to the trusted/intranet zone.
{ "pile_set_name": "StackExchange" }
Q: setting specific interval time on python I'm currently working on a Python project. The code will refresh at a specific time and fetch new records and update the database. What I'm trying to achieve is to refresh every 15 minutes or 30 minutes. The below code is good but only fetches new records once per day at 00.00am. def check_schedule_task(self): # update group member list at 00:00 am every morning t = time.localtime() if t.tm_hour == 0 and t.tm_min <= 1: # update group member Log.debug('update group member list everyday') self.db.delete_table(Constant.TABLE_GROUP_LIST()) self.db.delete_table(Constant.TABLE_GROUP_USER_LIST()) self.db.create_table(Constant.TABLE_GROUP_LIST(), Constant.TABLE_GROUP_LIST_COL) self.db.create_table(Constant.TABLE_GROUP_USER_LIST(), Constant.TABLE_GROUP_USER_LIST_COL) self.wechat.fetch_group_contacts() I tried the below but it's refreshing every second def check_schedule_task(self): # update group member list at 00:00 am every morning t = time.localtime() if t.tm_min == 15 or 30 or 45 or 00: # update group member Log.debug('update group member list everyday') self.db.delete_table(Constant.TABLE_GROUP_LIST()) self.db.delete_table(Constant.TABLE_GROUP_USER_LIST()) self.db.create_table(Constant.TABLE_GROUP_LIST(), Constant.TABLE_GROUP_LIST_COL) self.db.create_table(Constant.TABLE_GROUP_USER_LIST(), Constant.TABLE_GROUP_USER_LIST_COL) self.wechat.fetch_group_contacts() A: The line if t.tm_min == 15 or 30 or 45 or 00: is incorrect. What you want to write instead is if t.tm_min in (15,30,45,00): Despite what you may think, your version is not how comparing to multiple values works in Python. The comparison will always evaluate to true since even if the first comparison is false, the rest of the values are truthy. You instead want to check if that list of number contains your variable.
{ "pile_set_name": "StackExchange" }
Q: Deserialize JSON object name-value pairs as elements of an array I'm trying to convert following string to an object, { "base":"TRY", "date":"2017-01-06", "rates":{ "EUR":0.37679, "USD":0.51059, "BRL":0.88513, "CAD":0.36651, ... } } I know, if I create an object containing all rates as Double attribute, I will be able to convert that object into an object. But I want rates to be in an array like below. How can I create convertedJsonObjectArrayList. Thanks in advance. List<Rate> rates = convertedJsonObjectArrayList; class Rate{ String name; //EUR Double value; //0.37679 } A: You can get fancy and write a custom deserializer. However, if you don't mind being a bit more quick-and-dirty, you can just deserialize to a Map, and convert to your preferred structure explicitly: String ratesAsJson = "{ \"EUR\" : 0.2, \"USD\":1.0 }"; ObjectMapper objectMapper = new ObjectMapper(); TypeReference<Map<String, Double>> typeRef = new TypeReference<Map<String, Double>>() {}; Map<String, Double> map = objectMapper.readValue(ratesAsJson, typeRef); List<Rate> list = map.entrySet().stream() .map(entry -> new Rate(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); (I've assumed a 2-arg constructor on the Rate class). If you write a custom deserializer, it will have very similar code to the above within it. I've used a stream and map(). You could use a for loop, but hey, it's 2017!
{ "pile_set_name": "StackExchange" }
Q: Using RequireJS with XRegExp: "XRegExp is not defined" I am using RequireJS with order.js and I need to use xregexp-all to include in RequireJS. Here is my code sample: require(["order!xregexp-all","order!../myscript"],function(XRegExp) {console.log(XRegExp.version)}); Here is the console log that returns me the version. But I could not able to use the XregExp in myscript.js it gives me following Error: "XRegExp is not defined" How can I use XRegExp in the rest of the code? A: the second argument of require is a function, with a parameter, that you named XRegExp. Outside this context it does not exist. What you can do is create a global variable, and assign it in that context to the XRegExp: var myRegExp; require(["order!xregexp-all","order!../myscript"],function(XRegExp) { myRegExp = XRegExp; console.log(XRegExp.version) }); //... rest of your coude...// console.log(myRegExp);
{ "pile_set_name": "StackExchange" }
Q: How does this syntax compile? I was messing around with lambdas. for those that don't know, they look like this: [] () { }; I removed the parentheses and it still compiles. [] {}; How is this so? A: Quoth the standard, If a lambda-expression does not include a lambda-declarator, it is as if the lambda-declarator were (). ([expr.prim.lambda]/4 in C++11) A: A lambda declarator is optional. §5.1.2 [expr.prim.lambda] lambda-expression:     lambda-introducer lambda-declaratoropt compound-statement Where a lambda-declarator is: lambda-declarator:     ( parameter-declaration-clause ) mutableopt     exception-specificationopt attribute-specifier-seqopt trailing-return-typeopt It also says in §5.1.2/4; If a lambda-expression does not include a lambda-declarator, it is as if the lambda-declarator were ().
{ "pile_set_name": "StackExchange" }
Q: Como ensino um usuário a votar e aceitar minha resposta? Eu queria mostrar a alguns usuários a evitar comentar, pois têm muitas respostas que vejo diariamente mas não recebe seu devido valor pelo \ seu esforço. Eu já passei por isso duas vezes, fiquei 1h investigando o problema e quando coloquei a resposta ele só disse "obrigado", achei muito ruim passar por essa situação. Eu quero ensinar a eles como dar votar adequadamente, mas não achei um lugar que ensina. A: Vou aproveitar e falar de uma forma geral de algumas coisas. Percebo uma visão equivocada sua do que é o Stack Overflow, alguns comentários seus tem sido sinalizados porque eles não são muito construtivos. Então evite comentar se não tiver certeza do que está falando. O SO deve ter pouco ruído, mu itos comentários seus são ruído e não ajudam o fluxo normal, pense duas vezes antes de comentar. Eu queria mostrar a alguns usuários a evitar comentar Mostre a si mesmo em primeiro lugar. pois têm muitas respostas que vejo diariamente mas não recebe seu devido valor pelo \ seu esforço Isso acontece, mas algumas eu não sei se devem ter esse "devido" valor reconhecido, porque elas talvez não tenham o valor que acha que tem. Posso dizer isto por ver algumas respostas e comentários seus que estão errados. Em resposta é bom porque pode-se negativar, em comentário não pode então as pessoas podem achar que aquilo é certo. Em alguns casos não é errado, só não fala nada do que é esperado ali, é algo quase aleatório. Eu já passei por isso duas vezes, fiquei 1h investigando o problema e quando coloquei a resposta ele só disse "obrigado" Pode ser que a pessoa só agradeceu por ter se esforçado, pode ser que nem resolveu a questão dela. Pode ser que respondeu e tenha outra que a pessoa gostou mais. Pode ser que a pessoa não saiba o que fazer. Essas coisas acontecem. achei muito ruim passar por essa situação. É ruim sim, muito eu não sei, mas só é ruim se a resposta é boa, é a única ou melhor e deveria ser aceita, nem sempre é o caso, não vou repetir o que disse antes. Eu quero ensinar a eles como dar votar adequadamente, mas não achei um lugar que ensina. Votar é diferente de aceitar. Eu tenho 3 comentários enlatados que uso para indicar para as pessoas que não aceitaram alguma resposta depois de um tempo, não falo logo em seguida que a pessoa perguntou e eu respondi, a não ser que ela diga obrigado e percebo que ela não entende, aí eu adapto um dos três. Obviamente só posto isto se nenhuma for aceita e tiver alguma chance da pessoa aceitar, se eu perceber que a pessoa nem sabe o que perguntou, não saberá escolher uma resposta, é preciso muito bom senso para fazer isto . Acha que tem esse bom senso? Se não tiver vai arrumar confusão. Quando a pessoa é experiente e só deve ter esquecido: A resposta resolveu o que estava em dúvida? Precisa que algo mais seja melhorado? Acha que é possível aceitá-la agora? Tem uma variação que o "A", vira "Alguma" para dar chance para a pessoa escolher uma outra resposta que não seja a minha. Quando tem algumas respostas de usuário iniciante no site: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver pontuação suficiente). Se a pessoa tiver pelo menos 15 pontos tiro os parenteses finais. Se a minha for a única resposta: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos). Também tiro o final se a pessoa já tiver a pontuação. É preciso tomar muito cuidado para não virar algo tendencioso ou até achaque. Se pedir uma aceitação em coisa errada pode gerar uma saia justa, poderá ser sinalizado, pode complicar a situação no site. Pode ocorrer com todo mundo, mas se acontecer com frequência isso é um problema. Estou reforçando isso pela observação do que responde e já vi pedindo aceitação em coisa errada. Pense bem se vai fazer isso. A: A princípio, aceitar a resposta como correta já é o correto de se agradecer, mas isso não impede que outras formas de gratidão sejam proibidas na comunidade, por mais que não sejam adequadas a nossa política. O intuito desta comunidade Q&A é simplesmente perguntar e responder, a reputação é apenas um número onde indica uma relação de como a comunidade recebeu suas publicações, seja perguntas ou respostas. Não somos obrigados a votar, mas é a nossa forma de expressar o que sentimos em relação a certa publicação. O voto é um tanto emotivo quanto racional. Não é errado apresentar aos usuários novos o Tour, é recomendado na verdade, e exibido quando um novo cadastro é apresentado ao site. Muitas vezes o Tour é introduzido por membros já estabelecidos que tentam ajudar perguntas que muitas vezes são fechadas por não seguir nossas políticas e regras. Nossos moderadores não podem aceitar respostas corretas, por mais que o OP (original poster) foi lá e comentou na sua resposta "Deu certo, obrigado!" e deixou ela ali, sem voto e sem reputação. Mas afinal, qual era a sua intenção ao responder? Se for considerar que você queria ajudar a pessoa, irá se contentar em receber um comentário do tipo. Qualquer sinal de que a sua resposta deu certo naquela situação irá te confortar, pois você concluiu o que queria. Agora se a intenção foi por reputação, em crescer seus números, dificilmente essa comunidade irá se adequar a você, não pela plataforma StackOverflow, mas pelos eventuais casos que ocorrem, como os que foram mencionados por você. Não é errado mencionar o comentário destas pessoas quando elas não aceitam suas respostas, pois assim, você irá instruir ela a como se adaptar a comunidade nas suas futuras perguntas, e assim, ela irá saber lidar com as respostas adequadamente. Portanto, o mais ideal a fazer, é apresentar a ela o Tour. O comentário indicado, é mostrar ao OP que ele pode aceitar a sua, como as demais respostas como correta. Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver pontuação suficiente). Maniero nesta resposta
{ "pile_set_name": "StackExchange" }
Q: Sheets IF Function setup and/or formatting errors Cell C5 on the Trip Assignment Form tab is a dropdown selection list of destinations. I am trying to make sheets automatically fill in the C6 cell with the matching address (coming from a tab called Schools). When I put the below formula in I get an error or FALSE but I cannot figure out why. =if(C5=Schools!A1, C6=Schools!B1, "Other Error") I need to make the formula work for any destination selected so that the appropriate address is inserted into the cell. Can I do this like the way I am thinking or would Apps Script be better and if so how would I go about that? "Trip Assignment Form" "Schools" data sheet Link to copy of my sheet: https://docs.google.com/spreadsheets/d/1Xkwxjtf6syEd-zGaPUVsyE2_6Kfczu8c-8W3RuRg9CY/edit?usp=sharing A: It is possible to do with Google Apps Script but it's probably not the easiest way to go You can use the onEdit trigger and this sort of code: function onEdit(e) { var sh=e.range.getSheet(); if(sh.getName()=='Sheet12' && e.range.columnStart==1 && e.range.rowStart==1 & e.value!='') { var ss=SpreadsheetApp.getActive(); var sh1=ss.getSheetByName('Sheet12'); var v1=sh1.getRange(1,1).getValue(); var sh2=ss.getSheetByName('Sheet13'); var v2=sh2.getRange(1,1,sh2.getLastRow(),2).getValues(); for(var i=0;i<v2.length;i++) { if(v2[i][0]==v1) { sh1.getRange(2,1).setValue(v2[i][1]); } } } } Animation: Your setup: function onEdit(e) { var sh=e.range.getSheet(); if(sh.getName()=='assignment sheet name' && e.range.columnStart==3 && e.range.rowStart==5 & e.value!='') { var ss=SpreadsheetApp.getActive(); var sh1=ss.getSheetByName('assignment sheet name');//assignment sheet name var v1=sh1.getRange(e.range.rowStart,e.range.columnStart).getValue(); var sh2=ss.getSheetByName('schools sheet name');//schools sheet name var v2=sh2.getRange(1,1,sh2.getLastRow(),2).getValues(); for(var i=0;i<v2.length;i++) { if(v2[i][0]==v1) { sh1.getRange(6,3).setValue(v2[i][1]); } } } }
{ "pile_set_name": "StackExchange" }
Q: What is the Time Complexity, Space complexity and Algorithm for strstr() function in C++? I was curious about the cost of using the default, old fashioned strstr() function in C++. What is its Time and Space complexity? Which algorithm does it use? We have other algorithms with below Worst Case Time and Space complexity : Let n = length of string, m = length of pattern Knuth-Morris-Pratt Algorithm : Time = O(n+m), Space = O(m) Rabin-Karp Algorithm : Time = O(n*m), Space = O(p) (p = p patterns of combined length m) Boyer-Moore Algorithm : Time = O(n*m), Space = O(S) (S = size of character set) In any way strstr() is better than above mentioned algorithms, in terms of Time and Space complexities? A: In the C standard it just says, in §7.24.5.7: Synopsis #include <string.h> char *strstr(const char *s1, const char *s2); Description The strstr function locates the first occurrence in the string pointed to by s1 of the sequence of characters (excluding the terminating null character) in the string pointed to by s2. Returns The strstr function returns a pointer to the located string, or a null pointer if the string is not found. If s2 points to a string with zero length, the function returns s1. So the complexity is unspecified. As far as I can tell, an implementation is allowed to use any of those algorithms.
{ "pile_set_name": "StackExchange" }
Q: iOS: how to serialize a non-NSCoding compliant object I already take a look around and found the closes answer here: Correct way to save/serialize custom objects in iOS But this is only applicable for custom objects that is user-created. My problem is serializing "SKProduct" which is a derived class that is non-NSCoding compliant. Specifically, the exact error I encountered: -[SKProduct encodeWithCoder:]: unrecognized selector sent to instance 0x4027160 Does anyone have similar experience? A: I'll preface this answer by saying there's probably an easier way; but class substitution during archiving and unarchiving is one approach you could take. During archiving, you have the option of setting a delegate that conforms to the NSKeyedArchiverDelegate protocol. All of the methods are optional. The delegate receives a message archiver:willEncodeObject: message during encoding. If you wish to substitute a class during archiving, you can create a substitute object and return it. Otherwise just return the original object. In your case, you could create a 'shadow object' for SKProduct that encapsulates whatever properties on the original class you are interested in serializing. Then substitute that class during archiving. During unarchiving, you could reverse the process and return SKProduct For illustrative purposes, here's an example. Mind you, I've left out the reverse substitution part - but if you read the docs on NSKeyedUnarchiverDelegate I think it would be clear. #import <Foundation/Foundation.h> @interface NoncompliantClass:NSObject @property (nonatomic,assign) NSInteger foo; @end @implementation NoncompliantClass @synthesize foo = _foo; @end @interface CompliantClass:NSObject <NSCoding> @property (nonatomic,assign) NSInteger foo; @end @implementation CompliantClass @synthesize foo = _foo; - (void)encodeWithCoder:(NSCoder *)coder { [coder encodeInteger:self.foo forKey:@"FooKey"]; } - (id)initWithCoder:(NSCoder *)coder { self = [super init]; if( !self ) { return nil; } _foo = [coder decodeIntegerForKey:@"FooKey"]; return self; } @end @interface ArchiverDelegate:NSObject <NSKeyedArchiverDelegate> @end @implementation ArchiverDelegate - (id)archiver:(NSKeyedArchiver *)archiver willEncodeObject:(id)object { NSString *objClassName = NSStringFromClass([object class]); NSLog(@"Encoding %@",objClassName); if( [object isMemberOfClass:[NoncompliantClass class]] ) { NSLog(@"Substituting"); CompliantClass *replacementObj = [CompliantClass new]; replacementObj.foo = [object foo]; return replacementObj; } return object; } @end int main(int argc, char *argv[]) { @autoreleasepool { NoncompliantClass *cat1 = [NoncompliantClass new]; NoncompliantClass *cat2 = [NoncompliantClass new]; NSArray *herdableCats = [NSArray arrayWithObjects:cat1,cat2,nil]; ArchiverDelegate *delegate = [ArchiverDelegate new]; NSMutableData *data = [NSMutableData data]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; [archiver setDelegate:delegate]; [archiver encodeObject:herdableCats forKey:@"badKitties"]; [archiver finishEncoding]; } } This logs: 2012-09-18 05:24:02.091 TestSerialization[10808:303] Encoding __NSArrayI 2012-09-18 05:24:02.093 TestSerialization[10808:303] Encoding NoncompliantClass 2012-09-18 05:24:02.093 TestSerialization[10808:303] Substituting 2012-09-18 05:24:02.094 TestSerialization[10808:303] Encoding NoncompliantClass 2012-09-18 05:24:02.094 TestSerialization[10808:303] Substituting
{ "pile_set_name": "StackExchange" }
Q: iOS UIDatePicker set max date I got an issue in trying to limit the date. With setting the date like that self.datePicker.maximumDate = [NSDate date]; it is only grey the date after now but enable the user to select a date after this maximum date. So When the picker value changed I compare the selected date if up than the current date I edit it. If I use both solutions I got weird behaviour, any idea ? - (IBAction)pickerValueChanged:(id)sender { dispatch_async(dispatch_get_main_queue(), ^{ UIDatePicker *datePicker = (UIDatePicker *)sender; if ([self.datePicker.date compare:[NSDate date]] == NSOrderedDescending) { datePicker.date = [NSDate date]; } }); } This function is triggered when the date value from the date picker did change. If I set a minimum and a maximum date I got a weird behaviour. Any idea? EDIT: http://youtu.be/GX0pbyjBC-U without setting self.datePicker.maximumDate = [NSDate date]; http://youtu.be/U8hYVSfKRZ4 with both A: Either you can set the maximum date in xcode or programatically. 1.Programatically you can set the picker maximum date by using the below line of code. [self.yourPickerView setMaximumDate: [NSDate date]]; This line of code will set the current date as maximum date that can select in picker.
{ "pile_set_name": "StackExchange" }
Q: Error in generating page number links using Codeigniter I am creating a pagination using Codeigniter and my problem is I have an error in displaying the page number links in my URL. example I go to page 2 my URL would be like this: http://localhost/my_project/inbound/listing/1 if page 3 http://localhost/my_project/inbound/listing/2 Here's my controller $config = array(); $config['base_url'] = base_url('inbound/listing'); $config['total_rows'] = $this->mod->countList(); $config['per_page'] = 1; $config['uri_segment'] = 3; //fd($config); $this->pagination->initialize($config); $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0; fp($page, 'pink'); //print out result $order = ($this->input->get('order'))? $this->input->get('order'): ''; $sort = ($this->input->get('sort'))? $this->input->get('sort'): ''; // Query data $data['data_list'] = $this->mod->listing($config['per_page'], $page); //where, limit, page, field, sort fP($data['data_list']); //print out result $data['pagination'] = $this->pagination->create_links(); Then my model for generating links: function listing($limit, $start) { //DATE_FORMAT(`post_date_added`, "%m/%d/%Y %H:%i") as `proper_post_date_added`, $this->db->select('*'); $this->db->from('inventory'); $this->db->limit($limit, $start); $query = $this->db->get(); //$rows = $query->result_array(); if($query->num_rows() > 0) { foreach($query->result() as $row) { $data[] = $row; } return $data; } return false; } Can you help me with this? A: If you want to go to page number based on your url, modify your listing function to be like this: function listing($limit, $start) { $offset_1 = $start - $limit; $offset_2 = $offset_1 < 0 ? 0 : $offset_1; //DATE_FORMAT(`post_date_added`, "%m/%d/%Y %H:%i") as `proper_post_date_added`, $this->db->select('*'); $this->db->from('inventory'); $this->db->limit($limit, $offset_2); $query = $this->db->get(); //$rows = $query->result_array(); if($query->num_rows() > 0) { foreach($query->result() as $row) { $data[] = $row; } return $data; } return false; }
{ "pile_set_name": "StackExchange" }
Q: Creating an archive - Save results or request them every time? I'm working on a project that allows users to enter SQL queries with parameters, that SQL query will be executed over a period of time they decide (say every 2 hours for 6 months) and then get the results back to their email address. They'll get it in the form of an HTML-email message, so what the system basically does is run the queries, and generate HTML that is then sent to the user. I also want to save those results, so that a user can go on our website and look at previous results. My question is - what data do I save? Do I save the SQL query with those parameters (i.e the date parameters, so he can see the results relevant to that specific date). This means that when the user clicks on this specific result, I need to execute the query again. Save the HTML that was generated back then, and simply display it when the user wishes to see this result? I'd appreciate it if somebody would explain the pros and cons of each solution, and which one is considered the best & the most efficient. The archive will probably be 1-2 months old, and I can't really predict the amount of rows each query will return. Thanks! A: Specifically regarding retrieving the results from queries that have been run previously I would suggest saving the results to be able to view later rather than running the queries again and again. The main benefits of this approach are: You save unnecessary computational work re-running the same queries; You guarantee that the result set will be the same as the original report. For example if you save just the SQL then the records queried may have changed since the query was last run or records may have been added / deleted. The disadvantage of this approach is that it will probably use more disk space, but this is unlikely to be an issue unless you have queries returning millions of rows (in which case html is probably not such a good idea anyway).
{ "pile_set_name": "StackExchange" }
Q: SQL Selecting from two tables I have the following two tables... I am trying to select all the cities belonging to a country using the country name, or using the country id but displaying only the city name and country name. I am using the following statement but is not working, this is my first time doing SQL SELECT CI.CITY_NAME, CO.COUNTRY_NAME FROM CITY CI INNER JOIN COUNTRY CO ON CI.CITY_ID = CO.COUNTRY_ID WHERE CO.COUNTRY_ID = 1; A: You're comparing a country id with a city id, seems like you'd really want to do; SELECT CI.CITY_NAME, CO.COUNTRY_NAME FROM CITY CI INNER JOIN COUNTRY CO ON CI.COUNTRY_ID = CO.COUNTRY_ID WHERE CO.COUNTRY_ID = 1;
{ "pile_set_name": "StackExchange" }
Q: Page Cycles - Right way to input data to database I have a page that has a few textboxes and a dropdownlist. When a logged in user opens this page the boxes are filled with data that he has input before, he can change the data and update it by pushing a update button. There is also that dropdownlist which has a dynamically populated data for him to choose from. What is the best way to make this page work. Where in the page cycles do I populate the forms and where do I input the data to the datatable. At the moment I'm populating the data on PreRender but the dropdownlist on the preinit. I have a button event handler to do the update on the datatable. The problem is that the autopostback messes up the data in the dropdownlist because its dynamically populated, how would I go by fixing this? A: Here is what I follow in most of my cases protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { InitDropdDownListes(); LoadDataFromDataBase(); } } void InitDropdDownListes() { // fill drop down boxes } void LoadDataFromDataBase() { // load from database } protected void OnDropdownListChanges(object sender, EventArgs e) { // reload the new data from database LoadDataFromDataBase(); } protected void btnSave_Click(object sender, EventArgs e) { // Save to database }
{ "pile_set_name": "StackExchange" }
Q: Контрольный знак Code 128 Возможно ли реализовать расчёт контрольного знака по стандарту для штрих-кода Code 128 (для некой последовательности цифр) при помощи библиотек Python? Вывод самого изображения штрих-кода не нужен - только контрольный знак для заданного числа. A: Используя 0.8b1 версию pyBarcode: >>> import barcode # $ pip install pybarcode --pre >>> from barcode.writer import ImageWriter >>> code = barcode.Code128('Stack Overflow', writer=ImageWriter()) >>> code.encoded [104, 51, 84, 65, 67, 75, 0, 47, 86, 69, 82, 70, 76, 79, 87] >>> code.build() ['110100100001101110100010011110100100101100001000010110011000010010110110011001000111011011110100100101100100001001001111010110000100110010100001000111101011110010100111011001001100011101011'] >>> code.to_ascii() 'XX X X XX XXX X X XXXX X X X XX X X XX XX X X XX XX XX X XXX XX XXXX X X X XX X X X XXXX X XX X XX X X X XXXX X XXXX X X XXX XX X XX XXX X XX' >>> code._calculate_checksum(code.encoded) 27 Модуль простой, но неотшлифованный -- версия 0.8 (с code128) и документация к ней не опубликованы и вычисление контрольной суммы почему-то в виде частного метода только доступно. >>> code.save('barcode-stackoverflow') 'barcode-stackoverflow.png' Если png картинка не нужна (по умолчанию svg генерится), то можно не передавать writer параметр при создании штрих-кода.
{ "pile_set_name": "StackExchange" }
Q: Bootstrap 4 Navs Drop Down List Issue I'm developing some Navs forms for my university projects, I used [email protected], This is my issue, I selected Book item, navs is working on it selected Child items and again click the Organais item after repeated Navs items details, you can check it. I attached my code in jsfiddle. please look at my code https://jsfiddle.net/9qsacmr4/4/ look at the image displayed some red color line in my issue Thanks A: Looks like your code has too many id repeated. id attribute must should be unique. I have rename some of your repeated id with number. and removed unwanted </div> inputState -> inputState2 and inputState3 Check updated jsfiddle EDIT: Replaced form content with Static text. EDIT 2: working with all 3 forms <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/> <div class="content-wrapper"> <div class="container-fluid"> <!-- section-two--> <div class="agrarian-section-addnewaccount" style="margin-top: -0.5rem;"> <div class="row"> <div class="col-md-12"> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> Select Your Account Type </a> <div class="dropdown-menu"> <a class="dropdown-item" id="pills-dropdown1-tab" href="#pills-dropdown1" role="tab" data-toggle="pill" aria-controls="pills-dropdown1">Book</a> <a class="dropdown-item" id="pills-dropdown2-tab" href="#pills-dropdown2" role="tab" data-toggle="pill" aria-controls="pills-dropdown2">Organais</a> <a class="dropdown-item" id="pills-dropdown3-tab" href="#pills-dropdown3" role="tab" data-toggle="pill" aria-controls="pills-dropdown3">Child</a> </div> </li> </ul> <!-- tab section--> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade" id="pills-dropdown1" role="tabpanel" aria-labelledby="pills-dropdown1-tab"> <!-- tab section head--> <div class="row"> <div class="col-sm-12"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <p class="WD-txt-hd">Individual Account</p> </li> </ol> </div> </div> <!-- tab section head--> <div class="row"> <div class="col-sm-12"> <div class="card"> <form> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputAccNum" class="col-form-label">Account Number</label> <input type="text" class="form-control" id="inputAccNum" placeholder="Account Number"> </div> <div class="form-group col-md-6"> <label for="inputGivName" class="col-form-label">Given Name</label> <input type="text" class="form-control" id="inputGivName" placeholder="Given Name"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputSurName" class="col-form-label">Sure Name</label> <input type="text" class="form-control" id="inputSurName" placeholder="Sure Name"> </div> <div class="form-group col-md-6"> <label for="inputOthName" class="col-form-label">Other Name</label> <input type="text" class="form-control" id="inputOthName" placeholder="Other Name"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputInd-DOB" class="col-form-label">Date of Birth</label> <div class="input-group input-append date" id="datePicker-IndDOB" > <input type="text" class="form-control" name="date" value="" placeholder="DOB" /> <span class="input-group-addon add-on"> <i class="fa fa-calendar" aria-hidden="true"></i> </span> </div> </div> <div class="form-group col-md-6"> <label for="inputGENDER" class="col-form-label">Gender</label> <br> <label class="custom-control custom-radio"> <input id="radio1" name="radio" type="radio" class="custom-control-input"> <span class="custom-control-indicator"></span> <span class="custom-control-description">Male</span> </label> <label class="custom-control custom-radio"> <input id="radio2" name="radio" type="radio" class="custom-control-input"> <span class="custom-control-indicator"></span> <span class="custom-control-description">Female</span> </label> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputNIC" class="col-form-label">NIC </label> <input type="text" class="form-control" id="inputNIC" placeholder="NIC"> </div> <div class="form-group col-md-6"> <label for="inputADD" class="col-form-label">Residential Address</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="1" placeholder="Address"></textarea> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputCity" class="col-form-label">City</label> <input type="text" class="form-control" id="inputCity"> </div> <div class="form-group col-md-4"> <label for="inputState" class="col-form-label">State</label> <select id="inputState" class="form-control"> <option selected>Select your state</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> <option value="7">Seven</option> <option value="8">Eight</option> <option value="9">Nine</option> <option value="10">Ten</option> </select> </div> <div class="form-group col-md-2"> <label for="inputZip" class="col-form-label">Zip</label> <input type="text" class="form-control" id="inputZip"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputMobile" class="col-form-label">Mobile</label> <input type="text" class="form-control" id="inputMobile" placeholder="Mobile"> </div> <div class="form-group col-md-6"> <label for="inputTeli" class="col-form-label">Teliphone</label> <input type="text" class="form-control" id="inputTeli" placeholder="Teliphone"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputSrvCentre" class="col-form-label">Services Centre</label> <select id="inputStatetwo" class="form-control"> <option selected>Select your Services Centre</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> <option value="7">Seven</option> <option value="8">Eight</option> <option value="9">Nine</option> <option value="10">Ten</option> </select> </div> </div> <button type="submit" class="btn btn-primary" data-toggle="modal" data-target="">Submit</button> </form> </div> </div> </div> </div> <div class="tab-pane fade" id="pills-dropdown2" role="tabpanel" aria-labelledby="pills-dropdown2-tab"> <!-- tab section head--> <div class="row"> <div class="col-sm-12"> <ol class="breadcrumb"> <li class="breadcrumb-item active"> <p class="WD-txt-hd">Organaisational Account</p> </li> </ol> </div> </div> <!-- tab section head--> <div class="row"> <div class="col-sm-12"> <div class="card"> <form> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputOrgAccNum" class="col-form-label">Account Number</label> <input type="text" class="form-control" id="inputOrgAccNum" placeholder="Account Number"> </div> <div class="form-group col-md-6"> <label for="inputOrgName" class="col-form-label">Organisation Name</label> <input type="text" class="form-control" id="inputOrgName" placeholder="Organisation Name"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputOrgOpenerName" class="col-form-label">Account Opener Name</label> <input type="text" class="form-control" id="inputOrgOpenerName" placeholder="Account Opener Name"> </div> <div class="form-group col-md-6"> <label for="inputOrgOpenrMobile" class="col-form-label">Account Opener Mobile</label> <input type="text" class="form-control" id="inputOrgOpenrMobile" placeholder="Account Opener Mobile"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputOrgDOB" class="col-form-label">Organisation Started Date</label> <div class="input-group input-append date" id="datePicker-OrgDOB" > <input type="text" class="form-control" name="date" value="" placeholder="Organisation Started Date" /> <span class="input-group-addon add-on"> <i class="fa fa-calendar" aria-hidden="true"></i> </span> </div> </div> <div class="form-group col-md-6"> <label for="inputOrgStatus" class="col-form-label">Organisation Status</label> <input type="text" class="form-control" id="inputOrgStatus" placeholder="Organisation Status"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputOrgRegNumber" class="col-form-label">Organisation Reg: Number </label> <input type="text" class="form-control" id="inputOrgRegNumber" placeholder="Organisation Reg: Number"> </div> <div class="form-group col-md-6"> <label for="inputOrgADD" class="col-form-label">Organisation Address</label> <textarea class="form-control" id="OrgADD" rows="1" placeholder="Organisation Address"></textarea> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputCity" class="col-form-label">City</label> <input type="text" class="form-control" id="inputCity2"> </div> <div class="form-group col-md-4"> <label for="inputState2" class="col-form-label">State</label> <select id="inputState2" class="form-control"> <option selected>Select your state</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> <option value="7">Seven</option> <option value="8">Eight</option> <option value="9">Nine</option> <option value="10">Ten</option> </select> </div> <div class="form-group col-md-2"> <label for="inputZip" class="col-form-label"> Zip </label> <input type="text" class="form-control" id="inputZip" /> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputOegEmail" class="col-form-label"> Organisation Email </label> <input type="email" class="form-control" id="inputOrgEmail" placeholder="Organisation Email"> </div> <div class="form-group col-md-6"> <label for="inputOrgTeli" class="col-form-label"> Teliphone </label> <input type="text" class="form-control" id="inputOrgTeli" placeholder="Organisation Teliphone"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputSrvCentre" class="col-form-label"> Services Centre </label> <select id="inputStatetwo2" class="form-control"> <option selected>Select your Services Centre</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> <option value="7">Seven</option> <option value="8">Eight</option> <option value="9">Nine</option> <option value="10">Ten</option> </select> </div> </div> <button type="submit" class="btn btn-primary" data-toggle="modal" data-target="">Submit</button> </form> </div> </div> </div> </div> <div class="tab-pane fade" id="pills-dropdown3" role="tabpanel" aria-labelledby="pills-dropdown3-tab"> <div class="row"> <div class="col-sm-12"> <ol class="breadcrumb"> <li class="breadcrumb-item active"> <p class="WD-txt-hd">Children Account</p> </li> </ol> </div> </div> <div class="row"> <div class="col-sm-12"> <div class="card"> <form> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputOrgAccNum" class="col-form-label">Account Number</label> <input type="text" class="form-control" id="inputOrgAccNum2" placeholder="Account Number"> </div> <div class="form-group col-md-6"> <label for="inputChildGivName" class="col-form-label">Given Name</label> <input type="text" class="form-control" id="inputChildGivName" placeholder="Given Name"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputChildOpenerName" class="col-form-label">Sure Name</label> <input type="text" class="form-control" id="inputChildOpenerName" placeholder="Sure Name"> </div> <div class="form-group col-md-6"> <label for="inputChildOpenrOther" class="col-form-label">Other Name</label> <input type="text" class="form-control" id="inputChildOpenrOther" placeholder="Other Name"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputChildDOB" class="col-form-label">Date Of Birth</label> <div class="input-group input-append date" id="datePicker-ChildDOB" > <input type="text" class="form-control" name="date" value="" placeholder="DOB" /> <span class="input-group-addon add-on"> <i class="fa fa-calendar" aria-hidden="true"></i> </span> </div> </div> <div class="form-group col-md-6"> <label for="inputChildGENDER" class="col-form-label">Gender</label> <br> <label class="custom-control custom-radio"> <input id="Childradio1" name="radio" type="radio" class="custom-control-input"> <span class="custom-control-indicator"></span> <span class="custom-control-description">Male</span> </label> <label class="custom-control custom-radio"> <input id="Childradio2" name="radio" type="radio" class="custom-control-input"> <span class="custom-control-indicator"></span> <span class="custom-control-description">Female</span> </label> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputChildADD" class="col-form-label">Residential Address</label> <textarea class="form-control" id="ChildADD" rows="1" placeholder="Residential Address"></textarea> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputCity" class="col-form-label">City</label> <input type="text" class="form-control" id="inputCity3"> </div> <div class="form-group col-md-4"> <label for="inputState3" class="col-form-label">State</label> <select id="inputState3" class="form-control"> <option selected>Select your state</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> <option value="7">Seven</option> <option value="8">Eight</option> <option value="9">Nine</option> <option value="10">Ten</option> </select> </div> <div class="form-group col-md-2"> <label for="inputZip" class="col-form-label">Zip</label> <input type="text" class="form-control" id="inputZip2"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputChildMobie" class="col-form-label">Mobile</label> <input type="Text" class="form-control" id="inputChildMobile" placeholder="Mobile"> </div> <div class="form-group col-md-6"> <label for="inputChildTeli" class="col-form-label">Teliphone</label> <input type="text" class="form-control" id="inputChildTeli" placeholder="Teliphone"> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputChildGuardianName" class="col-form-label">Guardian Name</label> <input type="text" class="form-control" id="inputChildGuardianName" placeholder="Guardian Name"> </div> <div class="form-group col-md-6"> <label for="inputSrvCentre2" class="col-form-label">Services Centre</label> <select id="inputStatetwoe2" class="form-control"> <option selected>Select your Services Centre</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> <option value="5">Five</option> <option value="6">Six</option> <option value="7">Seven</option> <option value="8">Eight</option> <option value="9">Nine</option> <option value="10">Ten</option> </select> </div> </div> <button type="submit" class="btn btn-primary" data-toggle="modal" data-target="">Submit</button> </form> </div> </div> </div> </div> </div> <!-- /tab section--> </div> </div> </div> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Terminal appears with much delay when shortcut is used When I press Ctrl+Alt+T the Terminal opens after around 30 seconds. That's pretty annoying. If I open it with Alt+F2 and enter gnome-terminal the window appears instantly as usual. I'm using Ubuntu 16.04 with gnome3. Thank you for your help in advance! A: Temporary workaround discussed in comment 16 https://bugzilla.gnome.org/show_bug.cgi?id=729101#c16 run gnome-keyring-daemon in terminal with no command line options. Then everything works as normal after entering password to unlock keyring. On my system I have to open HUD before the password prompt shows up. If I open the HUD before the terminal command, the password prompt dialog shows immediately. Output of journalctl -f shows gnome-keyring-daemon[12913]: Gkm: using old keyring directory: ... Now Solved: For me and many others the solution to this issue has been to remove dbus-user-session which was added along with a recent install of software that is not needed. For me, it was added when I installed flatpak Solution: sudo apt-get remove --purge dbus-user-session Reboot More context is available starting at comment #67 in this thread. https://bugs.launchpad.net/ubuntu/+source/gnome-keyring/+bug/1689825 A: Based on this answer on superuser: From the bug filed by xgdgsc, this slow response to GNOME shortcuts appears to be caused by gnome-keyring-daemon. In particular, having multiple instances of the daemon appears to cause shortcut execution to pause while attempting to communicate with the daemon until it times out. You can use the following command to check if you have multiple instances of the daemon running: pgrep gnome-keyring --list-full On CentOS 7 with GNOME 3.14.2, I was able to work around this by killing both processes: killall gnome-keyring-daemon gnome-keyring-daemon automatically restarted with only one instance when I next used a GNOME keyboard shortcut, and the shortcut executed instantaneously. A: Open Startup Application and add new Add new Name : whatever Command : killall gnome-keyring-daemon Comment : whatever enjoy..
{ "pile_set_name": "StackExchange" }
Q: Return multiple values from a range To return a value corresponding to another cell from a range if it matches with a cell, I found Chuff's solution helpful (in Excel - match data from one range to another and get the value from the cell to the right of the matched data ): =iferror(vlookup(b31,$f$3:$g$12,2,0),"") However, if there are more than one cells within the column F which match with b1, the formula returns the value of only one cell from the column G. Could it be modified so as to attract the value of more than one cell? Thank you! A: To return multiple corresponding Vlookup values you should use this formula: =IFERROR(INDEX($B$2:$B$9,SMALL(IF($E1=$A$2:$A$9,ROW($A$2:$A$9)-ROW($A$2)+1),COLUMN(A1))),"") Because it it an array formula, please enter it using combination of CTRL+SHIFT+ENTER . For example, if you have you lookup range in A:B column, and lookup values in D column, then please enter formula above to F1 cell, then drag it to the right and to the bottom. You should now see all instances of Vlookup next to the lookup value in D column. If you have only values which you want to sum in case they correspond to your value in cell B31, then simply use SUMIF formula like this =SUMIF($F$3:$F$10,$B31,$G$3:$G$10) entered in cell C31.
{ "pile_set_name": "StackExchange" }
Q: Robot method how to access two different objects in the class I'm trying to write a simple code that calculates the manhattan distance between two robots. The manhattan distance is simply |x1-x2| + |y1-y2|. I have written most of the code but am not sure how to access the x,y coordinates of the second robot that I have created /** * Project 1 -- Robot Position Calculator * * This program creates two Robot objects and * calculates the distance between them. * @author your name * @lab section number and lab instructor's name * @date date of completion */ import java.util.Scanner; /** * The name of each robot is provided as input from the user. * The position of each robot is assigned randomly through the constructor. * The method distance returns the distance between this robot and the other robot. */ public class Robot { /** * The name of the Robot. */ String name; /** * The x-coordinate of the Robot location. */ double x; /** * The y-coordinate of the Robot location. */ double y; /** * Constructor to assign values for instance variables * name assigned using the passed argument. Member variables * x and y are assigned random real values in range [0, 1). * * @param name the robot name */ public Robot(String name) { // TODO assign this.name this.name = name; // TODO assign this.x and this.y using separate calls to Math.random() x = Math.random(); y = Math.random(); } /* * Returns the robot name. * * @returns a string containing no whitespace */ public String getName() { return this.name; } /* * Returns the x-coordinate of the robot location * * @returns a real value in range [0, 1) */ public double getX() { return this.x; } /* * Returns the y-coordinate of the robot location * * @returns a real value in range [0, 1) */ public double getY() { return this.y; } /* * Calculate the Manhattan distance between the robot's location * and the location specified by coordinates (x, y), i.e.: * * @param xCoord a real value for x-coordinate * @param yCoord a real value for y-coordinate * @returns a real value representing the distance */ public double distance(double xCoord, double yCoord) { System.out.println(x); System.out.println(y); double distance = Math.abs(x - this.getX()) + Math.abs(y - this.getY()); return distance; } /** * main() Method * The main method must do the following: * Input Name for robOne * Input Name for robTwo * Create the robOne object * Create the robTwo object * Display position of robOne * Display position of robTwo * Calculate the distance between both robots by calling distance function * Display distance between the robots * * @param args can be ignored. */ public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Insert your name for the first Robot below..."); String a = in.nextLine(); Robot x = new Robot(a); System.out.println("Insert your name for the second Robot below..."); String b = in.nextLine(); Robot y = new Robot(b); System.out.println(x.getName() + ": (" + x.getX() + ", " + x.getY() + ")"); System.out.println(y.getName() + ": (" + y.getX() + ", " + y.getY() + ")"); // TODO Call distance(double xCoord, double yCoord) method of robOne double d = x.distance(y.getX(), y.getY()); // TODO Print out the Manhattan distance between the robots in line 3 System.out.println(d); // Note: be sure to adhere to the output format described below } } A: Simply do that : public double distance(Robot other) { return Math.abs(other.x - this.x) + Math.abs(other.y - this.y); } The second robot is passed along when calling the method distance for the first robot like firstRobot.distance(secondRobot); Then the x and y coordinates of the second robot are accessible in the method distance as other.x and other.y. Be also sure to check if the passed robot is really one or null. In case of passing null, firstRobot.distance(null); your method will throw a NullPointerException when accessing either other.x or other.y. A: This'll fix your problem: public double distance(double xCoord, double yCoord) { System.out.println(x); System.out.println(y); double distance = Math.abs(x - xCoord) + Math.abs(y - yCoord); return distance; } Before, you were calculating the distance between your own object, and that should be 0 all the time. A: Let's look at what you're doing already: public double distance(double xCoord, double yCoord) { System.out.println(x); System.out.println(y); double distance = Math.abs(x - this.getX()) + Math.abs(y - this.getY()); return distance; } The problem with this code is that x and this.getX() are the same value. You are manually accessing your instance variable of x as well as using the getter method that you created to get the same exact value. Because of this, your distance method will always return zero. What you want to do is compare your current Robot (this) with a different Robot. So, change your method to something like this: public double distance(Robot other) { return Math.abs(this.getX() - other.getX()) + Math.abs(this.getY() - other.getY()); } This way, you are accessing the X and Y instance variables of your current object as well as the object that is passed to your method.
{ "pile_set_name": "StackExchange" }
Q: Getting a month as an integer, and taking a year from that as part of a string message I have the below code which gets the earliest date from a selection of date in the format of yyyy-mm-dd, alongside a message. I need to use the date that's been returned to populate my message by way of a declare statement using If and Else I think. For my first yyyy value if the month is less than 8 (August), then I need to use yyyy-1 from my original above mentioned selection, and if its a month greater than 8 (August), then I need to use the returned yyyy from my original selection. I then need this first value to then have / followed by a 2nd year returned, which will be plus 1 year to the first yyyy value. I am using Powershell, so something in .net would be really handy. $dt = New-Object System.Data.DataTable; $dt.Columns.Add("LearnStartDate"); $dt.Columns.Add("Message"); $dr = $DS.Tables["LearningDelivery"].Select("LearnStartDate = min(LearnStartDate)")[0]; Write-Output $dt.Rows.Count; $dt.Rows.Add($dr["LearnStartDate"].Substring(0,10),"Our message"); A: PowerShell can actually convert your string date to a date object automatically by using the [datetime] accelerator: [datetime]$LearnStartDate = $dr["LearnStartDate"] The Datetime object returned to $LearnStartDate then has various properties, including a .Month property that we can use to interrogate what the month value is, and a .AddYears method that we can use to add 1 to the year: if ($LearnStartDate.Month -lt 8) { $FirstYear = $LearnStartDate.AddYears(1).Year } Else { $FirstYear = $LearnStartDate.Year } $SecondYear = $FirstYear + 1 "FirstYear: $FirstYear" "SecondYear: $SecondYear" Beware that using [DateTime] will be using the localisation settings of you local machine, so you might get different results where this varies.
{ "pile_set_name": "StackExchange" }
Q: Not responding to the click of the partial view I have a parent view and a partial view in it. The partial view is 2 pseudo buttons - thumb up and thumb down. A paragraph with classes assigned. It is not responding to a click on either thumb. Nor is it getting into the 2 functions that should be executed on 'ready'. It gets into the jQuery in the partial view when rendered. However not completely as I do not see all the console logs or alerts that I put in. I get the alert and console log for the 'ready' function but not for the other functions. It does not execute the 2 console.log lines which reference the Model properties which are boolean and have each a value of false. I get this error: jQuery.Deferred exception: False is not defined ReferenceError: False is not defined. But it does not seem to be my custom code. The partial view has a model where by I have properties I want to use 2 booleans as well has integers. namespace GbngWebClient.Models { public class LikeOrDislikeVM { public int BlogId { get; set; } public int UserId { get; set; } public int LikeCount { get; set; } public int DisLikeCount { get; set; } public bool LikeDisabled { get; set; } public bool DisLikeDisabled { get; set; } } } Not sure if that is the reason. I show the model coming in and false is in lowercase coming in so that meets the JavaScript requirement. The parent view that has the partial view in it (not showing all the code): @{ // Create the variable form the LikeOrDislikeVM model. var likeOrDislikeVM = new GbngWebClient.Models.LikeOrDislikeVM(); // Set the properties on the variable - most from the parent model. likeOrDislikeVM.BlogId = @Model.BlogPublishedByBlogId.BlogId; likeOrDislikeVM.UserId = Convert.ToInt32(Session["UserId"]); likeOrDislikeVM.LikeCount = @Model.BlogPublishedByBlogId.LikeCount; likeOrDislikeVM.DisLikeCount = @Model.BlogPublishedByBlogId.DisLikeCount; likeOrDislikeVM.LikeDisabled = @Model.BlogPublishedByBlogId.LikeDisabled; likeOrDislikeVM.DisLikeDisabled = @Model.BlogPublishedByBlogId.DisLikeDisabled; } <div class="row"> <div class="col-md-1"> @Html.Partial("_BlogLikeAndDislike", likeOrDislikeVM) </div> </div> The partial view: @model GbngWebClient.Models.LikeOrDislikeVM <style> .fa { cursor: pointer; user-select: none; } .fa:hover { color: blue; } .my-size { font-size: 20px; } </style> @* Use the values that were passed via a model. *@ <div class="row"> <p><span class="blogLike my-size fa fa-thumbs-up"></span><span class="my-size"> : @Model.LikeCount</span> <span class="my-size"> | </span><span class="blogDisLike my-size fa fa-thumbs-down"></span><span class="my-size"> : @Model.DisLikeCount</span></p> </div> @Scripts.Render("~/bundles/jquery") <script type="text/javascript"> $(document).ready(function () { alert('Here at document ready'); console.log('Here at document ready'); console.log(@Model.LikeDisabled); console.log(@Model.DisLikeDisabled); SetLike(@Model.LikeDisabled); SetDisLike(@Model.DisLikeDisabled); $('.blogLike').on('click', function () { alert('Here at like'); $.ajax({ type: 'POST', url: '@Url.Action("SetBlogLikeOrDisLike", "BlogPublished")', data: { likeOrDislikeVM: @Model, likeOrDislikeIndicator: "L"}, success: function (response) { }, error: function (xhr, ajaxOptions, thrownError) { alert("Critical Error: something is wrong in the call to SetBlogLikeOrDisLike for a Like! Status: " + xhr.status + ". Error: " + thrownError.toString() + ". Response Text: " + xhr.responseText); } }) }); $('.blogDisLike').on('click', function () { $.ajax({ type: 'POST', url: '@Url.Action("SetBlogLikeOrDisLike", "BlogPublished")', data: { likeOrDislikeVM: @Model, likeOrDislikeIndicator: "D"}, success: function (response) { }, error: function (xhr, ajaxOptions, thrownError) { alert("Critical Error: something is wrong in the call to SetBlogLikeOrDisLike for a DisLike! Status: " + xhr.status + ". Error: " + thrownError.toString() + ". Response Text: " + xhr.responseText); } }) }); function SetLike(disabledSwitch) { alert('Here at SetLike'); $(".blogLike").attr('disabled', disabledSwitch); //if (disabledSwitch == false ) //{ // $(".blogLike").color('green'); //} } function SetDisLike(disabledSwitch) { alert('Here at SetDisLike'); $(".blogDisLike").attr('disabled', disabledSwitch); //if (disabledSwitch == false) { // $(".blogDisLike").color('green'); //} } }); </script> After surrounding the model properties with ticks. The code now executes but the boolean values are False instead of false. Yet the model screen shot shows them as false. JavaScript needs them to be false. Why is this happening? A: To convert the False to false and True to true, I added const const False = false, True = true; and passed them to the function without ticks. I now get false and true and the code executes properly. SetLike(@Model.LikeDisabled); SetDisLike(@Model.DisLikeDisabled);
{ "pile_set_name": "StackExchange" }
Q: WPF two panel app - reuse or create new instance of panel VM? I have a WPF application whose main window contains two panels. The layout is pretty standard. The left panel is a a list of objects. The right panel displays information about the object selected in the left panel. Right now I have the left panel directly in the XAML of the window, although I'm thinking it should be its own UC/View. The right panel is coded as a UC. The ViewModel for the main window has a field that is the VM for the right panel (call it the properties VM). The properties VM encapsulates the data for the selected object from the model. When a different object is selected in the left panel I see two options: 1) Instantiate a new instance of the properties VM and load the corresponding data from the model 2) Load the corresponding data from the model to the existing properties VM, and issue appropriate change notifications [My current implementation] Is there an advantage or preferred way of doing things between the two options above? Am I missing a better third option? * Edit * Maybe a better question is - what are the advantages and disadvantages of the two methods? Thanks! A: You are describing a very standard scenario in the MVVM world. I believe you have a slight architectural issue that when resolved would make this question moot. The 'list' from where you are making your selection should already be a list of view models that wrap the 'object' a.k.a model. The properties view should simply be databound to the selected VM.
{ "pile_set_name": "StackExchange" }
Q: Set permission for user programmatically? (sharepoint) I am using the following code to set permission for groups when I create a site: // Assign Site Owner role to the selected users string siteOwnerGroup = null; string siteOwnerRole = null; foreach (ListItem item in lbSiteOwner.Items) { siteOwnerGroup = item.Text.ToString(); siteOwnerRole = "Full Control"; SPRoleAssignment roleAssignment = new SPRoleAssignment(web.SiteGroups[siteOwnerGroup]); SPRoleDefinitionBindingCollection roleDefinition = roleAssignment.RoleDefinitionBindings; roleDefinition.Add(web.RoleDefinitions[siteOwnerRole]); web.RoleAssignments.Add(roleAssignment); web.Properties[siteOwnerGroup] = siteOwnerRole; web.Properties.Update(); } Shouldn't it be easy to change this to set permission for users in the lbSiteOwner listbox instead? I tried SPRoleAssignment roleAssignment = new SPRoleAssignment(web.SiteUsers[siteOwnerGroup]); But it doesn't work, any ideas? Thanks in advance. A: following solution will hold true in your case as well in place of list use web Programatically add user permission to a list in Sharepoint
{ "pile_set_name": "StackExchange" }
Q: CKEditor ReadOnly I got a problem since I use the CKEditor (http://ckeditor.com/). The problem is that I can't find a way to make the editor ReadOnly and I can't just use a textarea since I want to keep consistency. I've already seen lots og questions like this at StackOwerflow, but none of them work or are too old. My code so far is only to display/initialize the editor: $(document).ready(function(){ CKEDITOR.replace( 'ckeditor', { on: { // Check for availability of corresponding plugins. pluginsLoaded: function( evt ) { var doc = CKEDITOR.document, ed = evt.editor; if ( !ed.getCommand( 'bold' ) ) doc.getById( 'exec-bold' ).hide(); if ( !ed.getCommand( 'link' ) ) doc.getById( 'exec-link' ).hide(); } } }); }); I use the newest CKEditor version(v.4.1.1 Full package) Thanks in advance! :) A: In the docs readOnly you can set the config to readOnly config.readOnly = true; There is also an example that shows setting it via a method editor.setReadOnly( true); A: try with following lines, <textarea id="editor1" name="editor1" ></textarea> <textarea id="editor2" name="editor2" ></textarea> <input type="button" onclick="EnableEditor2()" value="EnableEditor2" /> <script> $(document).ready(function () { //set editor1 readonly CKEDITOR.replace('editor1', {readOnly:true}); CKEDITOR.replace('editor2'); //set editor2 readonly CKEDITOR.instances.editor2.config.readOnly = true; }); function EnableEditor2() { CKEDITOR.instances.editor2.setReadOnly(false); } </script>
{ "pile_set_name": "StackExchange" }
Q: Delete a git commit pushed on a remote branch We use git and GitFlow as versioning tools, and I'm facing a problem that I am quite sure some people have already encountered. In a feature branch, a colleague did a commit in which a lot of useless files were inserted (all binary and IDE metadata files). This commit was pushed. Now this colleague submits a pull request, and I don't want to integrate all these useless files into develop. Now, my git repository is quite huge, and a git clone becomes a long and boring process... The first (and easy) solution is to remove these files from the feature branch, and commit without these files (or do a revert commit). But if I do that, my git repository will remain quite big because objects (files) will not be removed from the history (because git still knows about them!). What I would like is to "cancel" this commit. The following picture shows my problem (the topmost commit is the oldest): How can I remove this commit and make my git clone quick again ? PS: Thanks to GitGraphJS for their useful tools to draw git graphs! A: There are several methods to delete or undo the commit. In that case, you can use git revert or git rebase or git reset. One information, git rebase don't add one extra commit compared to using git revert. git revert adds one extra commit during the merge. If you're not familiar with using git rebase, I suggest you use git revert then. Revert git revert <commit-ID> after that you commit the changes and push that commit to your origin. Reset You can delete the last pushed commit, after doing this you have to push your branch. You can decide either to merge or rebase the feature branch to development branch. git reset –-hard HEAD~1 or git reset HEAD^ --hard Rebase This command will lead to interactive section of editor, from there you can pick git rebase -i HEAD~ In the interactive section, it lists all the commits. Delete the one you want to get rid off. Finish the rebase and push force to the repo. git rebase --continue then push your branch.
{ "pile_set_name": "StackExchange" }
Q: get pure text form odt file in console I am looking for a small linux tool that would be able to extract text from odt file. It just needs to be human-readable and it can have problems with complicated objects etc. It's almost a duplicate of this question but I need it to be small and have no dependencies on OpenOffice or X server I remember having a 1MB MS-DOS program that could render .doc files quite readibly (with some weird markup getting through from time to time), so i expect it to be possible in the linux world too ;) A: I always find them just after asking in public... odt2txt - avaliable in repos. I feel stupid :P
{ "pile_set_name": "StackExchange" }
Q: Prove that there exist $135$ consecutive positive integers so that the $n$th least is divisible by a perfect $n$th power greater than $1$ Prove that there exist 135 consecutive positive integers so that the second least is divisible by a perfect square $> 1$, the third least is divisible by a perfect cube $> 1$, the fourth least is divisible by a perfect fourth power $> 1$, and so on. How should I go about doing this? I thought perhaps I should use Fermat's little theorem, or its corollary? Thanks! A: Use the Chinese Remainder Theorem. Pick $134$ distinct primes. The perfect square is the square of the first, the cube is the cube of the second, and so on. All your moduli are distinct, so CRT guarantees a solution. If you use the smallest primes in order and $N$ is the least of your $135$ numbers, you have $N+1 \equiv 0 \pmod {2^2}, N+2 \equiv 0 \pmod {3^3}, N+3 \equiv 0 \pmod {5^4}\ldots$ A: By the Chinese remainder theorem, there is an integer $n$ such that $n\equiv -k\ (\text{mod}\ p_k^{k+1})$ for all $k=1,2,\dots 134$, (where $p_k$ is the $k^\text{th}$ smallest prime). Then $n, n+1, \dots, n+134$ satisfy the required condition.
{ "pile_set_name": "StackExchange" }
Q: MySQL LEFT JOIN? I have a table cars(id, name) containing 20 rows. The other table carLog(username, car, count) contains rows which count the cars a player has bought (if there is no row if they haven't bought the car) I want my query to return all twenty cars, and the extra join info, if they've got a row in the carLog table but I can't get it to work. SELECT * FROM cars LEFT JOIN carLog ON cars.id=carLog.car This is returning hundreds of rows, I want it to return 20 rows (one for each car), and the extra info in the row if the username has purchased the car: WHERE carLog.username='Juddling' I have no idea if I'm meant to be using GROUP BY, WHERE or another type of join! A: Move the username condition from the WHERE clause to the ON clause. SELECT * FROM cars LEFT JOIN carLog ON cars.id=carLog.car AND carLog.username='Juddling' The WHERE clause is applied when the JOIN is already completed. This means, it will discard the NULL rows that the LEFT JOIN added.
{ "pile_set_name": "StackExchange" }
Q: Json.NET returns empty objects serializing list of Android.Gms.Maps.Model.LatLng objects While serializing MapRoute object I got JSON data like this: "{\"RouteName\":\"route1\",\"RouteWaypoints\":[{},{},{},{},{}] }" RouteWayPoints list are not serialized properly. using Android.Gms.Maps.Model; using Newtonsoft.Json; using System.Collections.Generic; namespace App3.Model { public class Id { [JsonProperty(PropertyName = "$oid")] public string id { get; set; } } public class MapRoute { public Id _id { get; set; } public string RouteName { get; set; } public List<LatLng> RouteWaypoints { get; set; } } } Here LatLng is Android.Gms.Maps.Model.LatLng from the Google Maps API for Xamarin.Android. Serialize command: string json = JsonConvert.SerializeObject(mapRoute); A: i modified @dbc LatLngDTO class and write two static object returner methods like below: using Android.Gms.Maps.Model; namespace App3.Model { public class LatLngDTO { public double Latitude { get; set; } public double Longitude { get; set; } public LatLngDTO(double lat,double lng) { Latitude = lat; Longitude = lng; } public static LatLng ToLatLng(LatLngDTO latLng) { if (latLng == null) return null; else return new LatLng(latLng.Latitude, latLng.Longitude); } public static LatLngDTO ToLatLngDTO(LatLng latLng) { if (latLng == null) return null; else return new LatLngDTO(latLng.Latitude, latLng.Longitude); } } it solved my issue. And i serialized my model with list of LatLngDTO objects like below: mapRoute.RouteWaypoints = (_wayPoints == null ? null : _wayPoints.Select(l => LatLngDTO.ToLatLngDTO(l)).ToList()); string json = JsonConvert.SerializeObject(mapRoute); Json = json; http.PostHTTPData(urlString, json);
{ "pile_set_name": "StackExchange" }
Q: autocomplete textbox from the database I need my textbox to autocomplete when the user types. The value should come from the database. I am using the textchange property of the textbox. protected void autocomplete(object sender, EventArgs e) { string query = "Select area,codes from tbl_pincode"; SqlConnection conn = new SqlConnection("Data Source=win2008-2;Initial Catalog=h1tm11;User ID=sa;Password=#1cub3123*;Persist Security Info=True;"); SqlCommand com = new SqlCommand(query, conn); conn.Open(); SqlDataReader dr = com.ExecuteReader(); while (dr.Read()) { zipcode.Text = dr.GetValue(0).ToString(); } conn.Close(); } But i m not getting the desired result. Any ideas how to go about it? A: You can use jQuery UI for autocomplete: http://www.dotnetcurry.com/ShowArticle.aspx?ID=515 Another option for ASP.NET autocomplete is AjaxControlToolkit: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AutoComplete/AutoComplete.aspx
{ "pile_set_name": "StackExchange" }
Q: Mongoengine Link to Existing Collection I'm working with Flask/Mongoengine-MongoDB for my latest web application. I'm familiar with Pymongo, but I'm new to object-document mappers like Mongoengine. I have a database and collection set up already, and I basically just want to query it and return the corresponding object. Here's a look at my models.py... from app import db # ---------------------------------------- # Taking steps towards a working backend. # ---------------------------------------- class Property(db.Document): # Document variables. total_annual_rates = db.IntField() land_value = db.IntField() land_area = db.IntField() assessment_number = db.StringField(max_length=255, required=True) address = db.StringField(max_length=255, required=True) current_capital_value = db.IntField valuation_as_at_date = db.StringField(max_length=255, required=True) legal_description = db.StringField(max_length=255, required=True) capital_value = db.IntField() annual_value = db.StringField(max_length=255, required=True) certificate_of_title_number = db.StringField(max_length=255, required=True) def __repr__(self): return address def get_property_from_db(self, query_string): if not query_string: raise ValueError() # Ultra-simple search for the moment. properties_found = Property.objects(address=query_string) return properties_found[0] The error I get is as follows: IndexError: no such item for Cursor instance This makes complete sense, since the object isn't pointing at any collection. Despite trolling through the docs for a while, I still have no idea how to do this. Do any of you know how I could appropriately link up my Property class to my already extant database and collection? A: The way to link a class to an existing collection can be accomplished as such, using meta: class Person(db.DynamicDocument): # Meta variables. meta = { 'collection': 'properties' } # Document variables. name = db.StringField() age = db.IntField() Then, when using the class object, one can actually make use of this functionality as might be expected with MongoEngine: desired_documents = Person.objects(name="John Smith") john = desired_documents[0] Or something similar :) Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Is "as fast" a kind of abbreviation? From Friends(Season 02, Episode 04): Transcript the turns aren't as fast but when Snoopy falls. . . funny. The turn is referring the movement when skating. Is the phrase as fast is a kind of abbreviation of as fast as he need to balance himself? Or just the word has the meaning similar to very? Does this kind of usage of as very common? A: I took a look in the script; having more context is helpful. Here is the relevant part. JULIE: Where you goin'? PHOEBE: Um, I'm gonna go meet Duncan, he's skating tonight at the Garden, he's in the Capades. JOEY: The Ice Capades? CHANDLER: No, no, the gravel capades. Yeah, the turns aren't as fast but when Snoopy falls... funny. I think this Capades should refer to the Ice Capades, and it seems like Duncan was in the Ice Capades. However, Chandler made fun of him (Duncan––or Joey himself, as hunter suggested in the comments below) when Joey asked about which Capades. Chandler said it's not the Ice Capades but the gravel capades. (Note the capitalization. Ice Capades is a proper noun, but "gravel capades" is not.) And this phrase "as fast" would refer to the fact that the turns in the gravel capades wouldn't be as fast as the turns in the Ice Capades. (I laughed while reading the script. Friends always makes me laugh. :-)
{ "pile_set_name": "StackExchange" }
Q: Error C2660: function does not take 2 arguments C++ Okay so I'm a beginner at coding in C++ and I was making this prime number finding program when I stumbled across this error. This may not be the best and i am open to feedback. The code below is in correct order and continuous. #include "stdafx.h" using namespace std; //finds prime numbers using Sieve of Eratosthenes algorithm vector<int> calc_primes(const int max); int main() { unsigned long long int minValue; unsigned long long int maxValue; bool Loop = true; char chContinue; vector<unsigned long long int> primes; std::string Path; Path = "D:\\Work\\Documents\\prime.txt"; // TODO: code your application's behavior here. while (Loop == true) { cout << "Enter minimum prime number checking range (__________)" << endl ; cin >> minValue; cout << "Enter maximum prime number checking range (__________)" << endl ; cin >> maxValue; if (maxValue <= minValue) { cout << "Invalid selection" << endl <<endl <<endl <<endl ; continue; } So this is where it gives me an error calc_primes(maxValue,primes); It tells me that the function doesn't not take two arguments. However, the declaration clearly states that it needs a unsigned long long int and a vector of unsigned long long int, so I'm not very sure. //opens file path std::ofstream of; of.open(Path); //writes to file and displays numbers for(unsigned long long int i = 0; i < primes.size(); i++) { if(primes.at(i) != 0) { cout << primes.at(i) <<" "; of << primes.at(i) << " "; } } cout << endl <<endl <<endl <<endl ; of.close(); cout << "Continue? (y/n)" << endl ; cin >> chContinue; if (chContinue == 'y') { continue; } else { if (chContinue == 'n') { break; } else { cout << "Invalid Selection" << endl << endl ; } } } return 0; } this is the function declaration. Do you think I've made a mistake by putting &primes? void calc_primes(unsigned long long int max, vector<unsigned long long int> &primes) { // fill vector with candidates for(unsigned long long int i = 2; i < max; i++) { primes.push_back(i); } // for each value in the vector... for(unsigned long long int i = 0; i < primes.size(); i++) { //get the value unsigned long long int v = primes[i]; if (v != 0) { //remove all multiples of the value unsigned long long int x = i + v; while(x < primes.size()) { primes[x] = 0; x = x + v; } } } } A: Your function declaration: vector<int> calc_primes(const int max); doesn't match your function definition: void calc_primes(unsigned long long int max, vector<unsigned long long int> &primes) These should be identical to achieve desired results.
{ "pile_set_name": "StackExchange" }
Q: Special characters in CakePHP URL I'm developing a web application where users have profiles, and skills related to that profile. I want to develop a page where a user can see all profiles that correspond to a particular skill. For example, if I wanted to see all users with the skill of "HTML" I could use http://site.com/skills/HTML. Pretty simple. I've got it working, however some users have skills with spaces (for example project management) and some have special characters (for example C#). When I browse to a URL like http://site.com/skills/C#, Cake automatically makes it http://site.com/skills/C because it parses out the special character (# in this case). How can I safely allow skills in the URL that have special characters in them? This is the action I'm currently using: public function view($name) { // Find skill using $name $skill = $this->Skill->find('first', array( 'conditions' => array('Skill.name' => $name) )); if(!$skill) { // Skill doesn't exist, return 404 // TODO: route to 404 page throw new NotFoundException(); } $this->set('skill', $skill); } A: The # is a "special" character that by default jumps to a named anchor. In order to use special characters in an URL, you will need to use urlencode(). But please note that your URL's will not look "fancy", it will just be encoded to the raw HTML entity of the special character. In your case C# will become C%23. So you might want to consider using a different URL alias for your tag, like CSharp (you can just set a "background" database field to "translate" the original value to an URL-friendly one).
{ "pile_set_name": "StackExchange" }
Q: What is the reason for different performance of the same implementation using icc, gcc and clang? I have implemented a program for a[i]=a[i-1]+c and I represent it her. I use begin_rdtsc and end_rdtsc to read and store the rdtsc to measure the speedup. The program is as follows, I use x86intrin.h #define MAX1 512 #define LEN MAX1*MAX1 //array size for time measure ments int __attribute__(( aligned(32))) a[LEN]; int main(){ singleCore // It's a macro to assign the program to a single core of the processor int i, b, c; begin_rdtsc // b=1 and c=2 in this case b = 1; c = 2; i = 0; a[i++] = b;//0 --> a[0] = 1 //step 1: //solving dependencies vectorization factor is 8 a[i++] = a[0] + 1*c; //1 --> a[1] = 1 + 2 = 3 a[i++] = a[0] + 2*c; //2 --> a[2] = 1 + 4 = 5 a[i++] = a[0] + 3*c; //3 --> a[3] = 1 + 6 = 7 a[i++] = a[0] + 4*c; //4 --> a[4] = 1 + 8 = 9 a[i++] = a[0] + 5*c; //5 --> a[5] = 1 + 10 = 11 a[i++] = a[0] + 6*c; //6 --> a[6] = 1 + 12 = 13 a[i++] = a[0] + 7*c; //7 --> a[7] = 1 + 14 = 15 // vectorization factor reached // 8 *c will work for all //loading the results to an vector __m256i dep1; //__m256i dep2; // dep = { 1, 3, 5, 7, 9, 11, 13, 15 } __m256i coeff = _mm256_set1_epi32(8*c); //coeff = { 16, 16, 16, 16, 16, 16, 16, 16 } //step2 for(; i<LEN-1; i+=8){ dep1 = _mm256_load_si256((__m256i *) &a[i-8]); dep1 = _mm256_add_epi32(dep1, coeff); _mm256_store_si256((__m256i *) &a[i], dep1); } end_rdtsc return 0; } I compiled this program with different compilers. My compilers are : icc 18, gcc 7.2, clang 4. The OS is fedora 27. The CPU is Corei7 6700HQ (Skylake) The scalar implementation which is compiled with icc -D _GNU_SOURCE -O3 -no-vec -march=native is the baseline for speedup measurements. The asm output for each compiler is as follows: Because the behavior of ICC is not normal I copied all the code for icc. I marked the section in C program ("mm...mm1/2"). ICC # mark_description "Intel(R) C Intel(R) 64 Compiler for applications running on Intel(R) 64, Version 18.0.1.163 Build 20171018"; # mark_description "-D _GNU_SOURCE -O3 -no-vec -march=native -c -S -o AIC3iccnovec"; .file "AIC3.c" .text ..TXTST0: .L_2__routine_start_main_0: # -- Begin main .text # mark_begin; .align 16,0x90 .globl main # --- main() main: ..B1.1: # Preds ..B1.0 # Execution count [1.00e+00] .cfi_startproc ..___tag_value_main.1: ..L2: #7.11 pushq %rbp #7.11 .cfi_def_cfa_offset 16 movq %rsp, %rbp #7.11 .cfi_def_cfa 6, 16 .cfi_offset 6, -16 andq $-128, %rsp #7.11 subq $128, %rsp #7.11 xorl %esi, %esi #7.11 movl $3, %edi #7.11 call __intel_new_feature_proc_init #7.11 # LOE rbx r12 r13 r14 r15 ..B1.21: # Preds ..B1.1 # Execution count [1.00e+00] vstmxcsr (%rsp) #7.11 vpxor %ymm0, %ymm0, %ymm0 #9.2 orl $32832, (%rsp) #7.11 vldmxcsr (%rsp) #7.11 vmovups %ymm0, mask(%rip) #9.2 vmovups %ymm0, 32+mask(%rip) #9.2 vmovups %ymm0, 64+mask(%rip) #9.2 vmovups %ymm0, 96+mask(%rip) #9.2 # LOE rbx r12 r13 r14 r15 ..B1.2: # Preds ..B1.21 # Execution count [5.00e-01] xorl %edi, %edi #9.2 movl $128, %esi #9.2 movl $mask, %edx #9.2 orq $12, mask(%rip) #9.2 vzeroupper #9.2 ..___tag_value_main.6: # sched_setaffinity(__pid_t, size_t, const cpu_set_t *) call sched_setaffinity #9.2 ..___tag_value_main.7: # LOE rbx r12 r13 r14 r15 ..B1.3: # Preds ..B1.2 # Execution count [1.72e+00] movq $0xdf84757ff, %rax #12.5 movq $.L_2__STRING.1, programName(%rip) #10.2 movq $100000000, elapsed_rdtsc(%rip) #12.5 movq %rax, overal_time(%rip) #12.5 movq $0, ttime(%rip) #12.5 vmovdqu .L_2il0floatpacket.2(%rip), %ymm0 #33.21 # LOE rbx r12 r13 r14 r15 ..B1.4: # Preds ..B1.12 ..B1.3 # Execution count [2.91e+00] # Begin ASM # #mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm1 # End ASM # LOE rbx r12 r13 r14 r15 ..B1.23: # Preds ..B1.4 # Execution count [2.91e+00] vzeroupper #12.5 rdtsc #12.5 shlq $32, %rdx #12.5 orq %rdx, %rax #12.5 # LOE rax rbx r12 r13 r14 r15 ..B1.5: # Preds ..B1.23 # Execution count [2.62e+00] movq %rax, t1_rdtsc(%rip) #12.5 xorl %edx, %edx #35.5 movl $1, a(%rip) #18.5 xorl %eax, %eax #35.5 movl $3, 4+a(%rip) #21.5 movl $5, 8+a(%rip) #21.5 movl $7, 12+a(%rip) #21.5 movl $9, 16+a(%rip) #21.5 movl $11, 20+a(%rip) #21.5 movl $13, 24+a(%rip) #21.5 movl $15, 28+a(%rip) #21.5 vmovdqu .L_2il0floatpacket.2(%rip), %ymm1 #35.5 # LOE rax rbx r12 r13 r14 r15 edx ymm1 ..B1.6: # Preds ..B1.6 ..B1.5 # Execution count [4.29e+04] vpaddd a(%rax), %ymm1, %ymm0 #38.16 incl %edx #35.5 vmovdqu %ymm0, 32+a(%rax) #39.41 addq $32, %rax #35.5 cmpl $2047, %edx #35.5 jb ..B1.6 # Prob 99% #35.5 # LOE rax rbx r12 r13 r14 r15 edx ymm1 ..B1.7: # Preds ..B1.6 # Execution count [2.91e+00] vzeroupper #46.5 rdtsc #46.5 shlq $32, %rdx #46.5 orq %rdx, %rax #46.5 # LOE rax rbx r12 r13 r14 r15 ..B1.8: # Preds ..B1.7 # Execution count [2.91e+00] movq %rax, t2_rdtsc(%rip) #46.5 # LOE rbx r12 r13 r14 r15 ..B1.26: # Preds ..B1.8 # Execution count [2.91e+00] # Begin ASM # #mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm2 # End ASM # LOE rbx r12 r13 r14 r15 ..B1.25: # Preds ..B1.26 # Execution count [2.91e+00] movq t2_rdtsc(%rip), %rdx #46.5 subq t1_rdtsc(%rip), %rdx #46.5 movq ttbest_rdtsc(%rip), %rsi #46.5 movq %rdx, ttotal_rdtsc(%rip) #46.5 cmpq %rsi, %rdx #46.5 jge ..B1.10 # Prob 50% #46.5 # LOE rdx rbx rsi r12 r13 r14 r15 ..B1.9: # Preds ..B1.25 # Execution count [1.45e+00] movq elapsed_rdtsc(%rip), %rcx #46.5 movq %rcx, %rax #46.5 negq %rax #46.5 movq %rdx, %rsi #46.5 addq $100000000, %rax #46.5 movq %rdx, ttbest_rdtsc(%rip) #46.5 movq %rax, elapsed(%rip) #46.5 jmp ..B1.11 # Prob 100% #46.5 # LOE rdx rcx rbx rsi r12 r13 r14 r15 ..B1.10: # Preds ..B1.25 # Execution count [1.45e+00] movq elapsed_rdtsc(%rip), %rcx #46.5 # LOE rdx rcx rbx rsi r12 r13 r14 r15 ..B1.11: # Preds ..B1.9 ..B1.10 # Execution count [2.91e+00] movq ttime(%rip), %rax #46.5 addq %rdx, %rax #46.5 movq %rax, ttime(%rip) #46.5 testq %rcx, %rcx #46.5 je ..B1.14 # Prob 50% #46.5 # LOE rax rcx rbx rsi r12 r13 r14 r15 ..B1.12: # Preds ..B1.11 # Execution count [1.45e+00] decq %rcx #46.5 movq %rcx, elapsed_rdtsc(%rip) #46.5 cmpq overal_time(%rip), %rax #46.5 jl ..B1.4 # Prob 82% #46.5 jmp ..B1.15 # Prob 100% #46.5 # LOE rcx rbx rsi r12 r13 r14 r15 ..B1.14: # Preds ..B1.11 # Execution count [1.45e+00] movq $-1, elapsed_rdtsc(%rip) #46.5 movq $-1, %rcx #46.5 # LOE rcx rbx rsi r12 r13 r14 r15 ..B1.15: # Preds ..B1.12 ..B1.14 # Execution count [1.00e+00] negq %rcx #46.5 movl $.L_2__STRING.2, %edi #46.5 addq $100000000, %rcx #46.5 xorl %eax, %eax #46.5 movq elapsed(%rip), %rdx #46.5 ..___tag_value_main.8: # printf(const char *__restrict__, ...) call printf #46.5 ..___tag_value_main.9: # LOE rbx r12 r13 r14 r15 ..B1.16: # Preds ..B1.15 # Execution count [1.00e+00] movl $.L_2__STRING.3, %edi #46.5 movl $.L_2__STRING.4, %esi #46.5 # fopen(const char *__restrict__, const char *__restrict__) call fopen #46.5 # LOE rax rbx r12 r13 r14 r15 ..B1.17: # Preds ..B1.16 # Execution count [1.00e+00] movl $128, %ecx #46.5 movq %rax, %rdi #46.5 movq %rax, fileForSpeedups(%rip) #46.5 movl $.L_2__STRING.5, %esi #46.5 movl %ecx, %r8d #46.5 xorl %eax, %eax #46.5 movq programName(%rip), %rdx #46.5 movq ttbest_rdtsc(%rip), %r9 #46.5 # fprintf(FILE *__restrict__, const char *__restrict__, ...) call fprintf #46.5 # LOE rbx r12 r13 r14 r15 ..B1.18: # Preds ..B1.17 # Execution count [1.00e+00] xorl %eax, %eax #47.9 movq %rbp, %rsp #47.9 popq %rbp #47.9 .cfi_def_cfa 7, 8 .cfi_restore 6 ret #47.9 .align 16,0x90 # LOE .cfi_endproc # mark_end; .type main,@function .size main,.-main ..LNmain.0: .data # -- End main .bss .align 8 .align 8 .globl fileForSpeedups fileForSpeedups: .type fileForSpeedups,@object .size fileForSpeedups,8 .space 8 # pad .align 8 .globl ttime ttime: .type ttime,@object .size ttime,8 .space 8 # pad .data .align 8 .align 8 .globl programName programName: .quad .L_2__STRING.0 .type programName,@object .size programName,8 .align 8 .globl ttbest_rdtsc ttbest_rdtsc: .long 0x5d89ffff,0x01634578 .type ttbest_rdtsc,@object .size ttbest_rdtsc,8 .align 8 .globl elapsed_rdtsc elapsed_rdtsc: .long 0x05f5e100,0x00000000 .type elapsed_rdtsc,@object .size elapsed_rdtsc,8 .align 8 .globl overal_time overal_time: .long 0xf84757ff,0x0000000d .type overal_time,@object .size overal_time,8 .section .rodata, "a" .align 32 .align 32 .L_2il0floatpacket.2: .long 0x00000010,0x00000010,0x00000010,0x00000010,0x00000010,0x00000010,0x00000010,0x00000010 .type .L_2il0floatpacket.2,@object .size .L_2il0floatpacket.2,32 .section .rodata.str1.4, "aMS",@progbits,1 .align 4 .align 4 .L_2__STRING.1: .long 860047681 .byte 0 .type .L_2__STRING.1,@object .size .L_2__STRING.1,5 .space 3, 0x00 # pad .align 4 .L_2__STRING.2: .long 1701344266 .long 1936024096 .long 1936269428 .long 1819026720 .long 1852383332 .long 1819026720 .long 543716452 .long 1919251561 .long 1869182049 .long 1851859054 .long 1814372452 .long 1914725484 .long 1952804965 .long 1869182057 .long 684910 .type .L_2__STRING.2,@object .size .L_2__STRING.2,60 .align 4 .L_2__STRING.3: .long 1701603686 .long 1400008518 .long 1684366704 .long 7565429 .type .L_2__STRING.3,@object .size .L_2__STRING.3,16 .align 4 .L_2__STRING.4: .word 97 .type .L_2__STRING.4,@object .size .L_2__STRING.4,2 .space 2, 0x00 # pad .align 4 .L_2__STRING.5: .long 539783973 .long 628646949 .long 622865508 .long 174353516 .byte 0 .type .L_2__STRING.5,@object .size .L_2__STRING.5,17 .space 3, 0x00 # pad .align 4 .L_2__STRING.0: .word 32 .type .L_2__STRING.0,@object .size .L_2__STRING.0,2 .data .comm mask1,128,32 .comm t1_rdtsc,8,8 .comm t2_rdtsc,8,8 .comm ttotal_rdtsc,8,8 .comm elapsed,8,8 .comm mask,128,32 .comm a,65536,32 .section .note.GNU-stack, "" // -- Begin DWARF2 SEGMENT .eh_frame .section .eh_frame,"a",@progbits .eh_frame_seg: .align 8 # End GCC //gcc -D _GNU_SOURCE -O3 -fno-tree-vectorize -fno-tree-slp-vectorize -march=native -c -S -o "AIC3" "AIC3.c" rdtsc salq $32, %rdx movq %r10, a(%rip) orq %rdx, %rax movq %r9, a+8(%rip) movq %r8, a+16(%rip) movq %rdi, a+24(%rip) vmovdqa a(%rip), %ymm1 movq %rax, t1_rdtsc(%rip) movl $a+32, %eax .p2align 4,,10 .p2align 3 .L2: vpaddd %ymm1, %ymm2, %ymm0 addq $32, %rax vmovdqa %ymm0, -32(%rax) vmovdqa %ymm0, %ymm1 cmpq %rax, %rcx jne .L2 rdtsc Clang //clang -D _GNU_SOURCE -O3 -fno-vectorize -fno-slp-vectorize -march=native -c -S -o "AIC3"clang " rdtsc shlq $32, %rdx orq %rax, %rdx movq %rdx, t1_rdtsc(%rip) movq %r8, a(%rip) movq %r9, a+8(%rip) movq %r10, a+16(%rip) movq %rcx, a+24(%rip) vmovdqa a(%rip), %ymm8 movl $64, %eax jmp .LBB0_2 .p2align 4, 0x90 .LBB0_9: # in Loop: Header=BB0_2 Depth=2 vpaddd %ymm7, %ymm8, %ymm8 vmovdqa %ymm8, a(,%rax,4) addq $64, %rax .LBB0_2: # Parent Loop BB0_1 Depth=1 # => This Inner Loop Header: Depth=2 vpaddd %ymm0, %ymm8, %ymm9 vmovdqa %ymm9, a-224(,%rax,4) vpaddd %ymm1, %ymm8, %ymm9 vmovdqa %ymm9, a-192(,%rax,4) vpaddd %ymm2, %ymm8, %ymm9 vmovdqa %ymm9, a-160(,%rax,4) vpaddd %ymm3, %ymm8, %ymm9 vmovdqa %ymm9, a-128(,%rax,4) vpaddd %ymm4, %ymm8, %ymm9 vmovdqa %ymm9, a-96(,%rax,4) vpaddd %ymm5, %ymm8, %ymm9 vmovdqa %ymm9, a-64(,%rax,4) vpaddd %ymm6, %ymm8, %ymm9 vmovdqa %ymm9, a-32(,%rax,4) cmpq $16383, %rax # imm = 0x3FFF jl .LBB0_9 # BB#3: # in Loop: Header=BB0_1 Depth=1 rdtsc The speedups are ~1.30, ~4.10 and 4.00 using icc, gcc and clang, respectively. As I mentioned, I've compiled the same code with different compilers and recorder the rdtsc. speedup for ICC is not as I expected. I used IACA to watch the inner loop, the summarized output is: ----------------------------------------------------- | compilers | icc | gcc | clang | ------------------------------------------------------ | Throughput |1.49 cycle |1.00 cycle |1.49 cycle | ------------------------------------------------------ | bottleneck | Front End | dependency | Front End | ------------------------------------------------------ UPDATE-0 : I've compared with and without IACA generated codes. The reason that IACA does not help, in this case, is the outputs are not the same. It seems injecting the IACA marks forces the compilers to stop their optimization, GCC has the same generated code as ICC and Clang has. But, calculating the addresses in GCC is more efficient in throughput point of view. In summary, IACA cannot help for this code. UPDATE-1 : The outputs for perf is as follows: 512*512 ICC: 86.06 │loop: vpaddd 0x604580(%rax),%ymm1,%ymm0 0.17 │ inc %edx 4.73 │ vmovdq %ymm0,0x6045a0(%rax) │ add $0x20,%rax │ cmp $0x7fff,%edx 8.98 │ jb loop GCC: 30.62 │loop: vpaddd %ymm1,%ymm2,%ymm0 15.12 │ add $0x20,%rax 46.03 │ vmovdq %ymm0,-0x20(%rax) 2.40 │ vmovdq %ymm0,%ymm1 0.01 │ cmp %rax,%rcx 5.62 │ jne loop LLVM: 3.00 │loop: vpaddd %ymm0,%ymm7,%ymm8 6.61 │ vmovdq %ymm8,0x6020e0(,%rax,4) 15.96 │ vpaddd %ymm1,%ymm7,%ymm8 5.19 │ vmovdq %ymm8,0x602100(,%rax,4) 1.89 │ vpaddd %ymm2,%ymm7,%ymm8 6.16 │ vmovdq %ymm8,0x602120(,%rax,4) 13.25 │ vpaddd %ymm3,%ymm7,%ymm8 8.01 │ vmovdq %ymm8,0x602140(,%rax,4) 2.10 │ vpaddd %ymm4,%ymm7,%ymm8 5.37 │ vmovdq %ymm8,0x602160(,%rax,4) 13.92 │ vpaddd %ymm5,%ymm7,%ymm8 7.95 │ vmovdq %ymm8,0x602180(,%rax,4) 0.89 │ vpaddd %ymm6,%ymm7,%ymm7 4.34 │ vmovdq %ymm7,0x6021a0(,%rax,4) 2.82 │ add $0x38,%rax │ cmp $0x3ffff,%rax 2.24 │ jl loop The ICC assembly output show that there is some SIMD instructions inside the rdtsc. If I miss something, or something is wrong I really have no idea. I spent a lot of time to realize the problem but zero achievement. Please, if somebody knows the reason help me. Thanks in advance. A: The different compilers actually use fairly different implementation strategies here. GCC notices that it never has to re-load a[i-8] which was calculated in the previous iteration and therefore can be sourced from a register. This relies on mov-elimination somewhat, otherwise the reg-reg move would still add some latency, though even without mov-elimination it would be a lot faster than reloading every time. ICC's codegen is very naive, it just does it exactly the way you wrote it. The store/reload adds quite a lot of latency. Clang does approximately the same thing as GCC, but unrolls by 8 (minus the first iteration). Clang often likes to unroll more. I'm not sure why it's slightly worse than what GCC does. You can avoid the reloading by explicitly not doing it in the first place: (not tested) dep1 = _mm256_load_si256((__m256i *) &a[0]); for(; i<LEN-1; i+=8){ dep1 = _mm256_add_epi32(dep1, coeff); _mm256_store_si256((__m256i *) &a[i], dep1); }
{ "pile_set_name": "StackExchange" }
Q: Why can we "separate" variables? Possible Duplicate: What am I doing when I separate the variables of a differential equation? My school textbook has a section on differential equations. One of the tricks used is the following- $$\frac{dx}{dy}=\frac{x}{y}\implies\frac{dx}{x}=\frac{dy}{y} $$ Integration is then duly carried out.Sparation of the variables leaves an impression on me that somehow, $dy$ is "dividing" $dx$. Whereas,when I studied the definition of the derivative, it was like $$f'(x)=\lim_{h\rightarrow 0}\frac{f(x+h)-f(x)}{h}.$$ I am not convinced how the so-called separation of variables is legal .Does it follow from the definition of the derivative ? Can anyone guide me to a proof? A: There's a notion called a "differential form". If $x$ and $y$ are functionally dependent and differentiable, then it turns out that the differential forms $dx$ and $dy$ are (more or less) multiples of each other, and the ratio happens to be $$ dx = \frac{dx}{dy} dy$$ This fact isn't really just cancelling the numerator and denominator. Before I learned differential forms, I imagined a term "$dz$" as being a derivative with respect to some variable I hadn't decided yet. So I had interpreted the equation above as really meaning $$ \frac{dx}{du} = \frac{dx}{dy} \frac{dy}{du} $$ where I hadn't really decided what variable I wanted to use for $u$.
{ "pile_set_name": "StackExchange" }
Q: UISegmentedControl iOS 13 SelectedTint Default Color I would like to match the default SelectedTintColor from the UISegmentControl to another view but I cannot find a matching color from the default system* colors provided in Attribute Inspector. The background seems to be .quaternarySystemFill but there is no color which matches the selected color in both light and dark mode. Even setting the color this way does not work since the .selectedSegmentTintColor returns nil: label.backgroundColor = segmentedControl.selectedSegmentTintColor Does anyone know the correct color or do I need to do this with a custom color? Edit: Edit 2: Currently this line kind of works, but maybe there is a better way? label.backgroundColor = label.traitCollection.userInterfaceStyle == .light ? .white : .tertiaryLabel A: From my understanding of your question, you want to change the background color same as UISegmentControl tint color. What you need to do is simply use this: label.backgroundColor = segmentedControl.tintColor Hope this will help you
{ "pile_set_name": "StackExchange" }
Q: search aspx page data to find out how to search the file and folder seach page A: To list Files and Folders you can use something called DirectoryInfo EXample void Page_Load(object s, EventArgs e) { DirectoryInfo di = new DirectoryInfo("c:/inetpub/wwwroot/demos"); FileInfo[] rgFiles = di.GetFiles("*.aspx"); foreach(FileInfo fi in rgFiles) { Response.Write("<br><a href=" + fi.Name + ">" + fi.Name + "</a>"); } } example taken from here
{ "pile_set_name": "StackExchange" }
Q: How to plot a time series graph using seaborn or plotly? I have a time series data as follows: Datum Menge 1/1/2018 0:00 19.5 1/1/2018 0:15 19.0 1/1/2018 0:30 19.5 1/1/2018 0:45 19.5 1/1/2018 1:00 21.0 1/1/2018 1:15 19.5 1/1/2018 1:30 20.0 1/1/2018 1:45 23.0 and the dataframe data has a shape of (14880, 2). In the Menge column, there are only 11807 values available and the rest are nan I am trying to plot it as follows: data.plot() plt.show() and this gives me But I want to plot the same using seaborn or plotly for seaborn I have tried: x = data.Datum y = data.Menge.values sns.lineplot(x = x, y = y, data = data) and it gives me the output as: Out[3]: <matplotlib.axes._subplots.AxesSubplot at 0x21286bb8668> and a new graph window is opened but it says Figure 1 (Not Responding) So, I have 2 questions: In the above graph, we can see the x-axis has index, but I would like it to be the Datum values there. How can it be changed? I would like to achieve this in seaborn or plotly, so is there a way to achieve all this in either? A: Considering a toy dataframe: seaborn solution import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.DataFrame({"Datum": ['1/1/2018 0:00', '1/1/2018 0:15', '1/1/2018 0:30', '1/1/2018 0:45', '1/1/2018 1:00', '1/1/2018 1:15', '1/1/2018 1:30', '1/1/2018 1:45 '], "Menge": [19.5, 19.,19.5,19.5,21,19.5,20,23]}) sns.lineplot(x="Datum", y="Menge", data=df) plt.xticks(rotation=15) plt.title('seaborn-matplotlib example') plt.show() plotly solution import pandas as pd import numpy as np import plotly.graph_objs as go from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot init_notebook_mode(connected=True) trace1 = go.Scatter(x=df.Datum, y=df.Menge, name = "plotly example", line = dict(color = 'blue'), opacity = 0.4) layout = dict(title='plotly example',) fig = dict(data=[trace1], layout=layout) iplot(fig) A: The cleanest setups for data of a wide format, even for multiple time series, are: plotly: go.Figure() seaborn: lineplot() plotly: fig = go.Figure([{ 'x': df.index, 'y': df[col], 'name': col } for col in df.columns]) Seaborn: sns.lineplot(data = df) Complete code for both seaborn and plotly: The following code sample will let you produce both plots in an off-line Jupyter Notebook. import plotly.graph_objs as go from datetime import datetime import plotly.express as px import matplotlib as mpl import seaborn as sns import pandas as pd import numpy as np sample data in a pandas dataframe np.random.seed(23) observations = 75 df=pd.DataFrame(dict(A=np.random.uniform(low=-1, high=1.1, size=observations).tolist(), B=np.random.uniform(low=-1, high=1.1, size=observations).tolist(), C=np.random.uniform(low=-1, high=1.1, size=observations).tolist(), )) df.iloc[0,] = 0 df = df.cumsum() firstdate = datetime(2020,1,1) df['date'] = pd.date_range(firstdate, periods=df.shape[0]).tolist() df.set_index('date', inplace=True) plotly fig = go.Figure([{ 'x': df.index, 'y': df[col], 'name': col } for col in df.columns]) fig.show() seaborn sns.set_style("darkgrid") sns.lineplot(data = df)
{ "pile_set_name": "StackExchange" }
Q: Mysql comparison of curtime() with a constant in utf8 I don't understand why the following comparison don't work in utf8 (mysql 5.5.27 - dotdeb). select '00:00:00' < curtime(); Can you explain how mysql evaluates this expression because I don't see any logical reasons why this is not working : mysql> set names 'utf8'; Query OK, 0 rows affected (0.00 sec) mysql> select '00:00:00' < curtime(); ERROR 1267 (HY000): Illegal mix of collations (utf8_general_ci,COERCIBLE) and (latin1_swedish_ci,NUMERIC) for operation '<' mysql> set names 'latin1'; Query OK, 0 rows affected (0.00 sec) mysql> select '00:00:00' < curtime(); +------------------------+ | '00:00:00' < curtime() | +------------------------+ | 1 | +------------------------+ 1 row in set (0.00 sec An other example, it works if the comparison is done in a certain order : mysql> set names 'utf8'; Query OK, 0 rows affected (0.00 sec) mysql> select '00:00:00' < curtime(); ERROR 1267 (HY000): Illegal mix of collations (utf8_general_ci,COERCIBLE) and (latin1_swedish_ci,NUMERIC) for operation '<' mysql> select curtime() > '00:00:00'; +------------------------+ | curtime() > '00:00:00' | +------------------------+ | 1 | +------------------------+ 1 row in set (0.00 sec) The collation and character variables in utf8 : mysql> show variables like 'collation%'; +----------------------+-------------------+ | Variable_name | Value | +----------------------+-------------------+ | collation_connection | utf8_general_ci | | collation_database | latin1_swedish_ci | | collation_server | latin1_swedish_ci | +----------------------+-------------------+ 3 rows in set (0.00 sec) mysql> show variables like 'character%'; +--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | utf8 | | character_set_connection | utf8 | | character_set_database | latin1 | | character_set_filesystem | binary | | character_set_results | utf8 | | character_set_server | latin1 | | character_set_system | utf8 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+----------------------------+ 8 rows in set (0.00 sec) This is working with MariaDb (5.5.25-MariaDB) MariaDB [(none)]> set names 'utf8'; Query OK, 0 rows affected (0.00 sec) MariaDB [(none)]> select '00:00:00' < curtime(); +------------------------+ | '00:00:00' < curtime() | +------------------------+ | 1 | +------------------------+ 1 row in set (0.00 sec) MariaDB [(none)]> SHOW VARIABLES LIKE 'character_set%'; +--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | utf8 | | character_set_connection | utf8 | | character_set_database | latin1 | | character_set_filesystem | binary | | character_set_results | utf8 | | character_set_server | latin1 | | character_set_system | utf8 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+----------------------------+ 8 rows in set (0.00 sec) MariaDB [(none)]> SHOW VARIABLES LIKE 'collation%'; +----------------------+-------------------+ | Variable_name | Value | +----------------------+-------------------+ | collation_connection | utf8_general_ci | | collation_database | latin1_swedish_ci | | collation_server | latin1_swedish_ci | +----------------------+-------------------+ 3 rows in set (0.00 sec) A: You are trying to compare different data types - string and time, in this case MySQL uses type conversion and throws an error. Try to use STR_TO_DATE function to convert string to TIME and compare two identical types: SET NAMES 'utf8'; SELECT STR_TO_DATE('00:00:00', '%H:%i:%s') < CURTIME(); More information here - Type Conversion in Expression Evaluation.
{ "pile_set_name": "StackExchange" }
Q: How to dump byte array to INSERT INTO SQL script (Java + PostgreSQL) How can I populate Postgres SQL base INSERT INTO SQL script with following Java Entity class based data collection. Issue is how can I write content of the byte array as a INSERT INTO value ('content of the byte[]') on SQL script. That mean it can not feed this data via java application, according to requirement it needs some row SQL script for populate existing data base on production environment. Thanks. Entity class @Entity @Table(name="image_table") public class ImageData implements Serializable { @Id @GeneratedValue @Column(name = "id") private Integer id; @Column(name = "content") private byte[] content; } Format of the row SQL script need to generate INSERT INTO image_table (id, content) VALUES ('1', '<content of the byte[]>'); INSERT INTO image_table (id, content) VALUES ('2', '<content of the byte[]>'); A: To answer your question literally: You can write a SQL INSERT script for an integer and a blob value, but that would be rather horrible with hex escaped strings for bytes and you could easily run into problems with long statements for larger blobs; PostgreSQL itself has no practical limit, but most regular text editors do. As of PostgreSQL 9.0 you can use the hex format (documentation here). Basically, a hex value in text representation looks like E'\x3FB5419C' etc. So you output from your method E'\x, then the byte[] as a hex string, then the closing '. Writing the hex string from the byte[] content can be done with org.apache.commons.codec.binary.Hex.encodeHexString(content) or use this SO answer for a plain Java solution. Depending on your production environment you may have to escape the backslash \\ and fiddle with the newline character. I suggest you give this a try with a small blob to see what works for you. A better approach is direct insertion. Assuming that you are using the PostgreSQL JDBC driver, the documentation has a worked out example. Given that you have a byte[] class member, you should use the setBytes() method instead of setBinaryStream() (which expects an InputStream instance): PreparedStatement ps = conn.prepareStatement("INSERT INTO image_table (id, content) VALUES (?, ?)"); ps.setInteger(1, 1); ps.setBytes(2, content); ps.executeUpdate(); ps.setInteger(1, 2); ps.executeUpdate(); ps.close();
{ "pile_set_name": "StackExchange" }
Q: Can't insert date with \maketitle (using llncs.cls) I'm just trying to write some notes on Overleaf using the llncs template (you can play with it here), but when I put \date{06 August 2016} before \maketitle, nothing appears. Currently my notes begin with \documentclass{llncs} \begin{document} \title{My Notes on Bla Bla} \author{John Doe} \institute{ \email{[email protected]}\\ } \date{06 August 2016} \maketitle (I know my \email probably wasn't inserted correctly, but at this point I just need something that works) All I want is something very basic like this: A: The \date does not form part of \maketitle under llncs. You'll either have to update the subsequent \@maketitle manually or perhaps patching it using something like etoolbox. However, an easier option is to just add it manually after a call to \maketitle: \documentclass{llncs} \title{My Notes on Bla Bla} \author{John Doe} \institute{ \email{[email protected]}\\ } \date{06 August 2016} \begin{document} \maketitle \noindent \makebox[\linewidth]{\small 06 August 2016} \end{document} Here would be a possible patch applied to \@maketitle using etoolbox: \usepackage{etoolbox} \makeatletter \patchcmd{\@maketitle}% <cmd> {\end{center}}% <search> {\bigskip\small\@date \end{center}}% <replace> {}{}% <success><failure> \makeatother It inserts a gap and the \date supplied at the \end{center} - the end of \@maketitle.
{ "pile_set_name": "StackExchange" }
Q: Reusing a phone number in two (or more) Facebook accounts - Is it allowed? I have two Facebook accounts for some personal reasons. I have my phone number registered to one of them. I want to register my phone number to also the other one for security reason, but I'm worried for fact that Facebook does not allow multiple accounts. My question is, will Facebook ban one or both of my accounts if I reuse my phone number in a second account? A: Yes, you can use the same phone number or address in your contact information. However, you can't verify multiple accounts with the same number.
{ "pile_set_name": "StackExchange" }
Q: Angular 2 disable form button from ts? Using the Angular 2 Validators, if the form is invalid, the form button is disabled from the HTML itself like so: <button class="btn btn-info" [disabled]="!signupForm.valid">Sign Up</button> How would I use this same effect in the appropriate TS? For instance: youshallnotpass(){ !this.signupForm.valid; } A: If you are using template driven forms, you could get a hold of the it using ViewChild. Here's something you can do: Considering: <form ... #myForm="ngForm"> You could, at the TypeScript component code: import { ViewChild, NgForm } from '@angular/core'; ... export class MyFormComponent { ... @ViewChild('myForm') public myForm: NgForm; youshallnotpass(){ return !this.myForm || !this.myForm.valid; } ...
{ "pile_set_name": "StackExchange" }
Q: making a method to remove the zeros from an array in java was curious on how to write a method to remove all zeros from an array. If I have the array in the main method. for example my Main Method would look something like public static void main(String[] args) { int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0}; System.out.println(Arrays.toString(test) + ": length = " + test.length); int[] result = removeZeros(test); System.out.println(Arrays.toString(result) + ": length = " + result.length); } and have the code output the length and the array without the zeros like: [1, 0, 4, 7, 0, 2, 10, 82, 0]: length = 9 [1, 4, 7, 2, 10, 82]: length = 6 I don't know how to write a method for this other than doing something like this: int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0}; int length = 0; for (int i=0; i<test.length; i++){ if (test[i] != 0) length++; } int [] intResult = new int[length]; for (int i=0, j=0; i<test.length; i++){ if (test[i] != 0) { intResult[j] = test[i]; j++; } } any ideas how to make this a method and have it print out both the original array and the new array without zeros in it + the length? A: I didn't test it, but this should work: public class Blah { public static void main(String[] args) { int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0}; System.out.println(Arrays.toString(test) + ": length = " + test.length); int[] result = removeZeros(test); System.out.println(Arrays.toString(result) + ": length = " + result.length); } public int[] removeZeros(int[] test) { int length = 0; for (int i=0; i<test.length; i++){ if (test[i] != 0) length++; } int [] intResult = new int[length]; for (int i=0, j=0; i<test.length; i++){ if (test[i] != 0) { intResult[j] = test[i]; j++; } return intResult; } }
{ "pile_set_name": "StackExchange" }
Q: What is the idiomatic way of dealing with return data from a conditionally asynchronous function? I have a function which may or may not be called as an asynchronous go-routine. func APICall(request *HTTPRequest) *HTTPResponse *HTTPRequest is a pointer to a struct which contains various pieces of data required in order to build a request: type HTTPRequest struct { // Represents a request to the twitter API method string baseurl string urlParams map[string]string bodyParams map[string]string authParams map[string]string responseChan chan *HTTPResponse } If called as a goroutine, i.e a channel is passed in; we build the request and write the response into the *HTTPResponse object (also a struct) of the provided channel. What is the most graceful / idiomatic way to accept a call to the function without a channel (ie. Not async) At the moment, we do something like this within the body of APICall to deal with both kinds of function call: if request.responseChan != nil { // If a response channel has been specified, write to that channel request.responseChan <- &twitterHTTPResponse{body, nil} return nil // Not returning a struct } else { return &twitterHTTPResponse{body, nil} // Return a pointer to a new struct representing the response } Are we along the right lines? A: The idiomatic approach is to provide a synchronous API: type HTTPRequest struct { // Represents a request to the twitter API method string baseurl string urlParams map[string]string bodyParams map[string]string authParams map[string]string } func APICall(request *HTTPRequest) *HTTPResponse { ... return &twitterHTTPResponse{body, nil} } The caller an can easily create a goroutine if it needs to run the call concurrently. For example: r := make(chan *HTTPResponse) go func() { r <- APICall(req) }() ... do some other work resp := <- r Synchronous APIs are idiomatic for a couple of reasons: Synchronous APIs are easier to use and understand. Synchronous APIs don't make incorrect assumptions about how the application is managing concurrency. For example, the application may want to use a wait group to wait for completion instead of receiving on a channel as assumed by the API.
{ "pile_set_name": "StackExchange" }
Q: New to Vue.js need help as to why the bars wont update beyond the first command The bars won't update with the health score after the first attempt, though if you keep clicking attack eventually the game ends. I get this error on console but don't know what to do about it to fix the issue. Any help would be appreciated. [Vue warn]: Invalid handler for event "click": got undefined (found in <Root>) new Vue({ el:'#app', data:{ playerHealth:100, monsterHealth:100, gameIsRunning:false }, methods: { startGame: function(){ this.gameIsRunning= true; this.playerHealth = 100; this.monsterHealth = 100; }, attack: function(){ this.monsterHealth -= this.calculateDamage(3,10) if(this.checkWin()){ return; } this.monsterAttacks(); }, specialAttack: function(){ this.monsterHealth -= this.calculateDamage(10,20) if(this.checkWin()){ return; } this.monsterAttacks(); }, heal: function(){ }, giveUP: function(){ }, calculateDamage: function(min,max){ return Math.max(Math.floor(Math.random() * max) + 1,min); }, checkWin: function(){ if(this.monsterHealth <= 0){ if(confirm('You Won! new Game?')){ this.startGame(); }else{ this.gameIsRunning = false; } return true }else if(this.playerHealth <= 0){ if(confirm('You Lost! new Game?')){ this.startGame(); }else{ this.gameIsRunning = false; } return true; } return false; }, monsterAttacks: function(){ this.playerHealth -= this.calculateDamage(5,12); this.checkWin(); } } }); .text-center { text-align: center; } .healthbar { width: 80%; height: 40px; background-color: #eee; margin: auto; transition: width 500ms; } .controls, .log { margin-top: 30px; text-align: center; padding: 10px; border: 1px solid #ccc; box-shadow: 0px 3px 6px #ccc; } .turn { margin-top: 20px; margin-bottom: 20px; font-weight: bold; font-size: 22px; } .log ul { list-style: none; font-weight: bold; text-transform: uppercase; } .log ul li { margin: 5px; } .log ul .player-turn { color: blue; background-color: #e4e8ff; } .log ul .monster-turn { color: red; background-color: #ffc0c1; } button { font-size: 20px; background-color: #eee; padding: 12px; box-shadow: 0 1px 1px black; margin: 10px; } #start-game { background-color: #aaffb0; } #start-game:hover { background-color: #76ff7e; } #attack { background-color: #ff7367; } #attack:hover { background-color: #ff3f43; } #special-attack { background-color: #ffaf4f; } #special-attack:hover { background-color: #ff9a2b; } #heal { background-color: #aaffb0; } #heal:hover { background-color: #76ff7e; } #give-up { background-color: #ffffff; } #give-up:hover { background-color: #c7c7c7; } <!DOCTYPE html> <html> <head> <title>Monster Slayer</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <link rel="stylesheet" href="foundation.min.css"> <link rel="stylesheet" href="app.css"> </head> <body> <div id="app"> <section class="row"> <div class="small-6 columns"> <h1 class="text-center">YOU</h1> <div class="healthbar"> <div class="healthbar text-center" style="background-color: green; margin: 0; color: white;" :style="{width: playerHealth + '%'}"> {{ playerHealth }} </div> </div> </div> <div class="small-6 columns"> <h1 class="text-center">MONSTER</h1> <div class="healthbar"> <div class="healthbar text-center" style="background-color: green; margin: 0; color: white;" :style="{width: monsterHealth + '%'}"> {{ monsterHealth }} </div> </div> </div> </section> <section class="row controls" v-if="!gameIsRunning"> <div class="small-12 columns"> <button id="start-game" @click="startGame">START NEW GAME</button> </div> </section> <section class="row controls" v-else> <div class="small-12 columns"> <button id="attack" v-on:click="attack">ATTACK</button> <button id="special-attack" @click="specialAttack">SPECIAL ATTACK</button> <button id="heal" @click="heal">HEAL</button> <button id="give-up" @click="giveUp">GIVE UP</button> </div> </section> <section class="row log"> <div class="small-12 columns"> <ul> <li> </li> </ul> </div> </section> </div> <script src="work.js"></script> </body> </html> A: The method bound to the click handler is giveUp(), while in your methods, it is spelled giveUP(). The discrepancy is likely throwing the warning.
{ "pile_set_name": "StackExchange" }
Q: Angularjs dom load ready I am working on angularjs. I created a scrlipt. When I started applciation on browser, appearing like this, and a little later coming result, <body> <div data-ng-controller="SimpleController"> Search By Name: <input type="text" data-ng-model="searchTerm" /> <ul> <li data-ng-repeat="cust in customers | filter:searchTerm | orderBy:name">{{cust.name}} - {{cust.city | uppercase}}</li> </ul> </div> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script> <script type="text/javascript"> function SimpleController($scope) { $scope.customers = [ { name: 'John', city: 'Barcelona' }, { name: 'Scott', city: 'Madrid' }, { name: 'Jennifer', city: 'Seattle' }, { name: 'Mike', city: 'Atalanta' } ]; } </script> </body> I want to see result after loaded everything like second Picture. A: You want the ngCloak directive, which keeps Angular templates hidden until your application is ready: <body> <div data-ng-controller="SimpleController"> Search By Name: <input type="text" data-ng-model="searchTerm" /> <ul data-ng-cloak> <li data-ng-repeat="cust in customers | filter:searchTerm | orderBy:name">{{cust.name}} - {{cust.city | uppercase}}</li> </ul> </div> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script> <script type="text/javascript"> function SimpleController($scope) { $scope.customers = [ { name: 'John', city: 'Barcelona' }, { name: 'Scott', city: 'Madrid' }, { name: 'Jennifer', city: 'Seattle' }, { name: 'Mike', city: 'Atalanta' } ]; } </script> </body> Edit: This will only have the desired effect if you load Angular in the <head> section of your HTML (or before you use the ngCloak directive). If you still want to load Angular at the end of the document, you need to include this CSS before your templates: [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { display: none !important; }
{ "pile_set_name": "StackExchange" }
Q: can i pass php file into geoXml parser i am having problems while fetching data from kml file. geoXml.parse("http://localhost/maps/phpmysqlajax_genkml.kml"); error in console is Could not convert JavaScript argument arg 0 [nsIDOMCanvasRenderingContext2D.drawImage [Break On This Error] (92 out of range 43) and what if i send a php file instead geoXml.parse("http://localhost/maps/phpmysqlajax_genkml.php"); this file sending KML as output. A: geoXml and KmlOverlay (in version 3 of the API) both require a KML file or GeoRSS file to be hosted on a server that is available to Google's servers to go and parse. localhost isn't. This is because you're not sending the KML to Google's servers, but rather telling them to fetch it.
{ "pile_set_name": "StackExchange" }
Q: Derivatives of functions satisfying Euler-ish inequality $f(x+y)\le f(x)f(y)$. Conjecture. Let $f:\mathbb R\to\mathbb R_{>0}$ be a continuously differentiable function such that $$f(x+y)\le f(x)\cdot f(y)$$ for all reals $x,y$. Then $$f'(x)\le c_1\cdot\exp(c_2\cdot x)$$ for some constants $c_1,c_2$; and all $x\in\mathbb R$. Is this conjecture true? How can we (dis-)prove it? Remarks My conjecture originates from the fact that all continuous functions satisfying $g(x+y)=g(x)\cdot g(y)$ are of the type $g(x)=\exp(c\cdot x)$. In particular, $g'(x)=c\exp(cx).$ My first instinct was to use $$f(x+y)-f(x)\le f(x)\cdot(f(y)-1)$$ so if we could conclude that $f(x)\le \exp(cx)$ for all $x$, then $$f'(x)=\lim_{y\to0}\frac{f(x+y)-f(x)}{y}\le \exp(cx)\lim_{y\to0}\frac{\exp(cy)-1}y=\exp(cx)\cdot c.$$ However, $f(x)\le \exp(cx)$ is not always true (consider $f(x)=2\cdot\exp x$). A: This is unfortunately not true. The issue is that your condition essentially only restricts the behaviour of $f$ "in the large", but not locally. The derivative of $f$, however, is determined by the local behaviour. What exactly I mean by this will be made clear by the counterexample. Define $$ f : R \to (0,\infty), x \mapsto e^x \cdot (4 + \sin(e^{x^{2}})) . $$ Since $-1 \leq \sin(y) \leq 1$, it is then easy to see $3 e^x \leq f(x) \leq 5 \cdot e^x$ for all $x \in \Bbb{R}$, and hence $$ f(x+y) \leq 5 \cdot e^{x+y} \leq 3 e^x \cdot 3 e^y \leq f(x) \cdot f(y). $$ However, we have $$ f'(x) = e^x \cdot (4 + \sin(e^{x^{2}})) + e^x \cdot \cos(e^{x^{2}}) \cdot e^{x^{2}} \cdot 2x. $$ Now, for $n \geq 5$, let $x_n := \sqrt{\ln (2 \pi n)}$. Observe $\ln(2 \pi n) \geq \ln(e) = 1$, and thus $e^{x_n} \geq e \geq 1$. Furthermore, $e^{x_n^2} = e^{\ln(2 \pi n)} = 2\pi n$, and thus $\cos(e^{x_n^2}) = \cos(2\pi n) = 1$. Overall, this implies $$ f'(x_n) \geq 3 \cdot e^{x_n} + e^{x_n} \cdot \cos(e^{x_n^2}) \cdot e^{x_n^2} \cdot 2 x_n \geq 2 \pi n \cdot 2 x_n \geq 4 \pi n. $$ However, if your desired inequality was true, we would have $$ 2 e^{x_n^2} = 4 \pi n \leq f'(x_n) \leq C \cdot e^{c x_n}, $$ and thus $$ e^{x_n^2 - c x_n} \leq C / 2, $$ meaning that $x_n^2 - c x_n = x_n \cdot (x_n - c)$ is bounded, which is clearly not the case.
{ "pile_set_name": "StackExchange" }
Q: Relation between angular resolution and aperture? The angular resolution of a telescope is given by $\frac{1.22\lambda}{D}$. This should mean that the smaller the aperture D, the higher the angular resolution. But it is exactly the opposite - why? A: The angular resolution only tells you your ability to distinguish ("resolve") two separate points of light. For example, your ability to distinguish the two distinct headlamps on a car from being a single light in the distance. The angular magnification has nothing to do with the angular resolution: it is determined by the focal lengths of your primary and objective, and the eyepiece if applicable. A: Your formula is correct. In the absence of instrumental effects or blurring of the atmosphere, it gives (approximately) the minimum angular separation between two objects that can be resolved. The larger this is, the worse your telescope is. You want the resolution to be small. A: Part of the confusion stems from the words used. "higher" resolution doesn't mean better, it means only bigger objects can be resolved; but we want to be able to resolve small objects, such as the angular distance between a pair of double stars. So small is better in this situation.
{ "pile_set_name": "StackExchange" }
Q: Using History API for Ajax div load In my WP site I have post content loaded into a div with ajax on a click event. I need it now to change the url for the current post, would prefer not using hashes. How would I implement this using my js? JS: jQuery(document).ready(function() { jQuery('#main-content').on('click', '.page a', function(e) { e.preventDefault(); var url = jQuery(this).attr('href'); jQuery('#main-content').html('<h4>Loading...</h4>').load(url+ ' #main-content'); }); }); I have researched History API but I'm not sure how to implement it with my js. A: I haven't done this yet myself, but this should be very simple using the pushState: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history var stateObj = { foo: "bar" }; history.pushState(stateObj, "New Page Title", "newPath.html"); Here's an extended example, where you would replace the content, path, and title with the results from your WordPress query that would grab the next post. <!doctype html> <html> <head> <title>Push State Testing</title> <script type='text/javascript'> var i = 1; function goToPage( pageNumber, pushState ) { var content = "Hello World " + pageNumber, path = "hello_world_" + pageNumber, title = content, stateObj = {"content":content} ; document.title = title; document.getElementById('content').innerHTML = content; if( pushState ) { history.pushState({index:pageNumber}, title, path); } i = pageNumber; } function nextPage() { goToPage( i+1, true ); } window.onload = function() { goToPage(1); history.replaceState({index:1}, "Hello World 1", "hello_world_1"); } window.onpopstate = function(event) { goToPage(event.state.index, false); } </script> </head> <body> <div id='content'>Push State Testing</div> <button type='button' onclick='nextPage()'>Next</button> </body> </html> In answer to the question in the comments. No, you don't need to know the path of the URL until you know the content. You replace the content and do the pushState at the exact same time: $('#mainContent').html( contentFromWp ); history.pushState( state, titleFromWp, pathFromWp ); Okay, so to take the above and try to write it for you, which I can't test, so I can't guarantee that this will be working like my above examples...it would be something like this: jQuery(document).ready(function() { jQuery('#main-content').on('click', '.page a', function(e) { e.preventDefault(); var url = jQuery(this).attr('href'), title = jQuery(this).attr('title') ; jQuery('#main-content').html('<h4>Loading...</h4>').load(url+ ' #main-content'); document.title = title; history.pushState({url:url,title:title}, title, url ); }); }); window.onpopstate = function(event) { document.title = event.state.title; jQuery('#main-content').html('<h4>Loading...</h4>').load(event.state.url+ ' #main-content'); } Note the need for onpopstate to make the back button work. You will also want to call a history.replaceState when your webpage first loads like I did in my example so that when users go back to the very first page the first page they were on will reload...otherwise, the user will only be able to go back to the second page they navigated to since going back to the first won't have a stateObj.
{ "pile_set_name": "StackExchange" }
Q: Remove extra column of icons from Angular UI-Grid TreeView I want to remove extra column of icons for expand and collapse and merge it with my main treebase column. Plunkr Source In the following link you can see that on a tree view it creates extra column for expansion and collapse but i want to merge it with my first column (name) and i also want to change the icon. Please help me that how can i achieve that. onRegisterApi: function( gridApi ) { $scope.gridApi = gridApi; $scope.gridApi.treeBase.on.rowExpanded($scope, function(row) { if( row.entity.$$hashKey === $scope.gridOptions.data[50].$$hashKey && !$scope.nodeLoaded ) { $interval(function() { $scope.gridOptions.data.splice(51,0, {name: 'Dynamic 1', gender: 'female', age: 53, company: 'Griddable grids', balance: 38000, $$treeLevel: 1}, {name: 'Dynamic 2', gender: 'male', age: 18, company: 'Griddable grids', balance: 29000, $$treeLevel: 1} ); $scope.nodeLoaded = true; }, 2000, 1); } }); } A: The rowHeader can be hidden just by a property, showTreeRowHeader: false, To have the tree expand buttons as part of the first column, you just need to replicate the template as part of the cell. Define the cell template like this, { name: 'name', width: '30%' , cellTemplate : "<div class=\"ui-grid-cell-contents\" title=\"TOOLTIP\"><div style=\"float:left;\" class=\"ui-grid-tree-base-row-header-buttons\" ng-class=\"{'ui-grid-tree-base-header': row.treeLevel > -1 }\" ng-click=\"grid.appScope.toggleRow(row,evt)\"><i ng-class=\"{'ui-grid-icon-minus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'expanded', 'ui-grid-icon-plus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'collapsed'}\" ng-style=\"{'padding-left': grid.options.treeIndent * row.treeLevel + 'px'}\"></i> &nbsp;</div>{{COL_FIELD CUSTOM_FILTERS}}</div>" }, This plnkr shows a working model, http://plnkr.co/edit/rkHZs0?p=preview Now to change the icons, all you need to do is to change the <i ng-class=\"{'ui-grid-icon-minus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'expanded', 'ui-grid-icon-plus-squared': ( ( grid.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) && row.treeNode.state === 'collapsed'}\" ng-style=\"{'padding-left': grid.options.treeIndent * row.treeLevel + 'px'}\"></i> in the cell template. The default template uses ui-grid-icon-plus-squared and ui-grid-icon-minus-squared and can be changed to whatever you like.
{ "pile_set_name": "StackExchange" }
Q: Mysql replication not rewriting the database name I'm replicating two database tables in two databases in the same MySql instant. I have my.ini as: [mysqld] server-id=1 log-bin report-host=master-is-slave-host log-bin=D:/wamp/logs/log_bin.log relay-log=D:/wamp/logs/relaylog.log replicate-same-server-id=1 binlog-do-db=test replicate-rewrite-db=test->test2 And when the errors are checked it says that: Duplicate entry '18' for key 'PRIMARY'' on query. Default database: 'test2'. Query: 'INSERT INTOtest.c(id,a,b,c) VALUES (NULL, 'fff', '', '')', Error_code: 1062 It seems that the rewrite has not worked. Any one who has done this before? UPDATE I empty the table test.c (master) and restarted the slave. That table got repopulated with data. Where the slave table test2.c must be the one to get populated. A: The error doesn't look it relates to replication. You're attempting to insert values where you're adding in "18" where "18" already exists. As that column is the primary key, you can only have one "18". I doubt that query would even run on the primary, let alone make its way to the slave and work.
{ "pile_set_name": "StackExchange" }
Q: VSTS History Queries I'm looking for a way to query the VSTS history to return me all cards that have a Discussion entry within the last 2 days and have the word "public" in it. Anyone have something for me? It's easy enough to find the word "public", but I can't figure out how to relate that to the date of that Discussion entry date. Thanks. A: If you mean the work item History Queries, we cannot exactly achieve your requirements as no such a specific date field associated to the field System.History. However we can narrow down the scope, just try below query with the clauses: Please note that below query will get all work items within the last 2 days which have discussions with the word "public" in it. That means if some work items have discussions which meets the conditions were added 2 days ago and someone changed other fields of the work items within the last 2 days, then these work items will also be included in the query result. After that, you can open the specific work item and navigate to History tab to see the related discussions. For the history queries please see History & auditing and Query by date or current iteration for details.
{ "pile_set_name": "StackExchange" }
Q: Error while trying to connect to the database server: [1045] Access denied for user I have a MySQL database running and I created a new user called 'ssluser' with SSL REQUIRED. I'm having trouble with this user logging in from a client to a remote server. I verified the firewall is not an issue. iptables are not reporting dropped packets. I am able to connect from nonssluser to the remote server without an issue. On the server my.cnf I have the CA, Cert, and Key file in place and MySQL WorkBench shows that SSL is enabled. On the client, I have CA, Cert, and Key file in place as well. For both certificates I used the FQDN as the common name. I'm not sure if that is the issue or not. Any ideas? The connection is on a private network in the Digital Ocean datacenter NYC. A: [1045] Access denied for user is a MySQL thing - which means that you are connecting - SSL does not seem to be the problem. This most likely means you are authenticating wrong (have the wrong password). Check this to see if it helps if you are sure you have the right password.
{ "pile_set_name": "StackExchange" }
Q: Get auto generated ID right after flush() Symfony3 I have a Project entity and when creating a new project I need to be able to upload files. For this reason I have created Files entity which saves the path and projectID. My problem is that I don't know how to retrieve it after creating it. Here is what I am trying to do $projectService->createProject($project,$user,$isWithoutTerm,self::NO_TERM_DEFAULT_VALUE); $filesService = $this->get('app.service.files_service'); foreach ($managerFiles as $managerFile){ $fileName = $filesService->uploadFileAndReturnName($managerFile); $filesService->createFile($fileName,$project->getId(),$user); } Currently my $project doesn't have ID which means that I cant create a new file. I heard that I could use $em->retrieve(object), but the actual flushing is not done in the controller. If i try to use it in my createProject function and return it for some reason I can't. PHPStorm says that it is a void function. Here is the code in createProject $project->setFromUser($user->getFullName()); $project->setDepartment($user->getDepartment()); $project->setIsOver(false); $project->setDate(new \DateTime()); if($isWithoutTerm){ $project->setTerm(\DateTime::createFromFormat('Y-m-d', $noTermDefaultValue)); } $this->entityManager->persist($project); $this->entityManager->flush(); Is there a way to retrieve the projectID after flushing and being able to use it in my controller? A: It could be a race condition where the $project is not available yet and so the service cannot load it and thus getId() fails. First, create your project entity: //build your $project $this->entityManager->flush(); Second, send this $project to your "service" $projectService->createProject($project,$user,$isWithoutTerm,self::NO_TERM_DEFAULT_VALUE); $filesService = $this->get('app.service.files_service'); foreach ($managerFiles as $managerFile){ $fileName = $filesService->uploadFileAndReturnName($managerFile); $filesService->createFile($fileName,$project->getId(),$user); } More specifically if you wrap this in a try/catch you can identify exactly what is happening: try { $project = new Project(); //build project $this->entityManager->flush(); //load $projectService.. $projectService->createProject($project,$user,$isWithoutTerm,self::NO_TERM_DEFAULT_VALUE); $filesService = $this->get('app.service.files_service'); foreach ($managerFiles as $managerFile){ $fileName = $filesService->uploadFileAndReturnName($managerFile); $filesService->createFile($fileName,$project->getId(),$user); } } catch(\Exception $e) { //$e->getMessage() will tell you if you're good to go, or if there //is actually an issue } However, it could also be as simple as PHPStorm not being able to introspect your getId() method and thus doesn't understand it. OR getId() is not actually returning the id.
{ "pile_set_name": "StackExchange" }
Q: Django include static CSS JS files - path included but not read My project base directory is, then app and static dirs as below. I am trying to load CSS and JS. These does get rendered in the html but when I try to open the js css files directly in the browser for verification to see if the page is really addressed, it gives a page not found an error. What is missing here? How do I do this? /data/projectname/ #BASE_DIR /data/projectname/app/ /data/projectname/app/statics/ /data/projectname/app/statics/js/ Settings STATICFILES_DIRS = ( os.path.join(BASE_DIR, '/app/statics/'), ) View <script type="text/javascript" src="/app/statics/js/css-doodle.min.js"></script> {% load static %} <script type="text/javascript" href="{% static 'js/css-doodle.min.js' %}"></script> HTML rendered, tried both ways <script type="text/javascript" src="/app/statics/js/css-doodle.min.js"></script> renders home page instead of showing the actual js <script type="text/javascript" href="/static/js/css-doodle.min.js"></script> 404 page not found, it should show raw js file if it is truly properly included/addressed.debug output doesnt give any details A: The path rendered should be in relation to the html file not the actual file system. Not clear what is your directory for html page, but you may remove the leading '/' in src attribute of the script element and try. In other words change /app/.. should to app/..
{ "pile_set_name": "StackExchange" }
Q: Linker error with GLFW on OS 10.10 I'm trying to compile the following #include <GLFW/glfw3.h> int main() { glfwInit(); return 0; } just to verify that my GLFW installation is working. I use the terminal with clang++ -framework Cocoa -framework OpenGL -framework IOKit -framework CoreVideo -I/opt/local/include/ test.c but I receive a linker error for the glfwInit function: Undefined symbols for architecture x86_64: "_glfwInit", referenced from: _main in test-d8c21e.o ld: symbol(s) not found for architecture x86_64 I have installed glfw with sudo port install glfw and followed every possible tutorial I've found. I can verify that the libglfw.dylib file can be found at /opt/local/lib/ as (I think) it should. Any suggestions? A: You need to link with GLFW[3] as well, e.g., add: -L/opt/local/lib -lglfw3 If you have the pkgconfig port installed, you can also take advantage of that with: clang `pkg-config glfw3 --cflags` test.c -o test \ `pkg-config glfw3 --static --libs` You may not need the --static flag if you have: libglfw3.dylib, as opposed to using: libglfw3.a, but it doesn't hurt.
{ "pile_set_name": "StackExchange" }
Q: click Server Side Button and Select/Deselect Chechboxes using JQuery I'm having issues trigger the server side button, i want to do something similar to this but with a server side button and checkboxes. It currently isn't working and i can't figure out why? $(function all() { $("<%= btnSelect.ClientID %>").click(function () { if (document.getElementById("<%= btnSelect.ClientID %>") == 'Select All') { $('.button input').prop('checked', true); document.getElementById("<%= btnChkboxSelect.ClientID %>").value = "Unselect All"; } else { $('.button input').prop('checked', false); document.getElementById("<%= btnChkboxSelect.ClientID %>").value = "Select All"; } }); }); <body> <div id="main"> <div id="first"> <asp:Button ID="btnSelect" runat="server" UseSubmitBehavior="false" Text="Select All" OnClientClick="all();" /> <div class="button"> <div> <asp:CheckBox ID="checbox1" runat="server" /> </div> <div> <asp:CheckBox ID="checbox2" runat="server" /> </div> <div> <asp:CheckBox ID="checbox3" runat="server" /> </div> </div> </body> A: You are missing # as id selector for btnSelect in your code. $(function { $("#<%= btnSelect.ClientID %>").click(function () { if($(this).text() == "Select All") { $('.button input:checkbox').prop('checked', true); $(this).text("Unselect All"); } else { $('.button input:checkbox').prop('checked', false); $(this).text("Select All"); } }); });
{ "pile_set_name": "StackExchange" }
Q: Using sql-server datetime2 with TADOQuery.open I want to start using datetime2 fields in SQL Server and I need to insert into the tables via ADO from Delphi XE5. I am using TADOQuery.ExecSQL to insert and everything works fine. However most of my tables have identity columns, e.g. id integer identity(1,1) not null To save round-trips to the server, I usually use Open with two commands in the query text. The first command is the insert the second command is "select scope_identity() as scope_id" so I can retrieve the newly inserted id in the same round-trip. This has worked for all my tables, but not now when I add datetime2 or time column - I get the error: Project "Foo.exe raised exception class EOleException with message 'Conversion failed when converting date and/or time from character string". I am using SQL Server 2008 if that matters. Does anyone know what might be the problem? A: The problem is that datetime2 does not come back to ADO clients using the SQLOLEDB provider as the correct ADO data type (adDBTimestamp): adDBTimeStamp (135) Indicates a date/time stamp (yyyymmddhhmmss plus a fraction in billionths) (DBTYPE_DBTIMESTAMP). Instead it comes back as a unicode string (adVarWChar): adVarWChar (202) Indicates a null-terminated Unicode character string. 2016-11-03 12:06:01.0000000 SQL Server Native Client (SQLNCLI) You could try switching to one of the "native" OLEDB providers (e.g. SQLNCLI, SQLNCLI10, SQLNCLI11). The problem with those is that: the SQL Server Native client doesn't come with the operating system (you have to install it yourself on client PCs) the SQL Server Native Client is derpricated the SQLNCLI provider exposes XML columns as an unsupported ADO DataTypeEnum value (141, DBTYPE_XML) the SQLNCLI provider exposes TIME columns as an unsupported ADO DataTypeEnum value (145) the SQLNCLI provider exposes UDT columns as an unsupported ADO DataTypeEnum value (132) You can use the DataTypeCompatibility=80 option in your connection string to cause XML columns to return as adLongVarWChar (as they do in SQLOLEDB), but then datetime2, date, and time return as strings The problem with use DataTypeCompatibility=80 is that there's a bug in the native client driver. It mistakenly converts an SQL Server DATE column from adDBDate into adVarWChar: | SQL Server data type | SQLOLEDB | SQLNCLI | SQLNCLI w/DataTypeCompatibilyt=80 | |----------------------|-----------------|--------------------|-----------------------------------| | Xml | adLongVarWChar | 141 (DBTYPE_XML) | adLongVarChar | | datetime | adDBTimeStamp | adDBTimeStamp | adDBTimeStamp | | datetime2 | adVarWChar | adDBTimeStamp | adVarWChar | | date | adVarWChar | adDBDate | adVarWChar | | time | adVarWChar | 145 (unknown) | adVarWChar | | UDT | | 132 (DBTYPE_UDT) | adVarBinary (documented,untested) | | varchar(max) | adLongVarChar | adLongVarChar | adLongVarChar | | nvarchar(max) | adLongVarWChar | adLongVarWChar | adLongVarWChar | | varbinary(max) | adLongVarBinary | adLongVarBinary | adLongVarBinary | | timestamp | adBinary | adBinary | adBinary | This bug in the SQL Native Client Provider was documented on MS Connect. But the person from Microsoft, not understanding what he was told, closed it as Won't fix. So, if you really want to use a datetime2 from ADO, you will have to read it as a string, and parse it yourself. Bonus Reading MSDN: Using ADO with SQL Server Native Client
{ "pile_set_name": "StackExchange" }
Q: Why is my simple_fields_for not iterating I have the following (simplified) classes: class CandidateList < ActiveRecord::Base has_many :candidates, inverse_of: :candidate_list, dependent: :destroy ... end and class Candidate < ActiveRecord::Base belongs_to :candidate_list, inverse_of: :candidates ... end In my controller, I create a CandidateList with 10 Candidate objects and querying the database verifies that they exist and are attached. In my form, I've got the following: <%= simple_form_for save_bingo_terms_path( candidate_list_id: @candidate_list ) do |f| %> ... <%= @candidate_list.candidates.count %> <table> <%= f.simple_fields_for :candidates do |cf| %> <tr> <td><%= cf.input :name, label: false %></td> <td><%= cf.input :definition, label: false %></td> </tr> <% end %> <% end %> Can anyone help me understand why it only shows me a single row in the table with an input field for name and definition even though the count output above the table shows 10? Thanks in advance! A: :candidates is not associated with the @candidate_list object, it's associated with a save_bingo_terms_path Change the simple_form_for to <%= simple_form_for @candidate_list do |f| %> And don't forget to specify... class CandidateList < ActiveRecord::Base has_many :candidates, inverse_of: :candidate_list, dependent: :destroy accepts_nested_attributes_for :candidates ... end Alternatively you can explicitly specify an each loop and reference each candidate <% @candidate_list.candidates each do |candidate| %> <% f.simple_fields_for :candidates, candidate do |cf| %> <tr> <td><%= cf.input :name, label: false %></td> <td><%= cf.input :definition, label: false %></td> </tr> <% end %> <% end %>
{ "pile_set_name": "StackExchange" }
Q: Template apps for iPhone Is there a good place to get starter apps for iPhone, where you choose from any of a large set of permutations?...for instance with a nav bar and a flip screen and a 3 deep table view, with Core Data support etc. I guess what I was hoping for is some kind of wizard where you can check a few boxes and have a working app as a starting point....but more than just the 3 or 4 choices that come with xCode. If not a wizard, just a nice set of a couple dozen permutations. Also....is there any good sample apps out there that show the difference between identical apps, one which uses Interface Builder and one not? Aside from being handy for myself, I'd think these would be great as a teaching tool. I've googled a bit and come up with nothing. A: http://www.appsamuck.com/ may not be all you want but is a good place for you to start.
{ "pile_set_name": "StackExchange" }
Q: Puppeteer : How to install puppeteer on ec2 server I want to install Puppeteer on ec2 server. So Do I need to install puppeteer and chromium on each machine on which I need to scrap data. A: You'll only need to install puppeteer. puppeteer auto-downloads a version of Chromium that works with it - everything works together out of the box! So once you've got puppeteer installed, you're already good to go! See the puppeteer readme for more info: https://github.com/GoogleChrome/puppeteer#readme
{ "pile_set_name": "StackExchange" }
Q: Why doesn't PostGIS use gist index when doing a ST_DUMP(ST_UNION)? My query: DROP TABLE IF EXISTS tmp; CREATE TEMP TABLE tmp AS SELECT *, ST_BUFFER(the_geom::GEOGRAPHY, 3000)::GEOMETRY AS buffer FROM af_modis_master LIMIT 20000; CREATE INDEX idx_tmp_the_geom ON tmp USING gist(buffer); EXPLAIN SELECT (DUMP(ST_UNION(buffer))).path[1], (DUMP(ST_UNION(buffer))).geom FROM tmp; Output from EXPLAIN: Aggregate (cost=1705.52..1705.54 rows=1 width=32) -> Seq Scan on tmp (cost=0.00..1625.01 rows=16101 width=32) Seq Scan means it is not using the index, right? Why not? UPDATE: Even adding a where clause that filters based on the buffer causes a Seq Scan: ANALYZE tmp; EXPLAIN SELECT (DUMP(ST_UNION(buffer))).path[1], (DUMP(ST_UNION(buffer))).geom FROM tmp WHERE ST_XMIN(buffer) = 0.0; (This question was also posted here. Apologies for cross-posting but the community there is a bit more active (maybe just on PostGIS query topics?), so perhaps wil provide an answer quicker.) A: An index is used to filter a query using the "WHERE" part of the statement. A GiST index is not used by ST_Union. Without a "WHERE" part, then no filtering (or index) is required to return the result, and the query just chugs through all the rows in the query. As described in the manual, not all functions make use of indicies, for example ST_Distance and ST_XMin don't benefit from a spatial index. Other spatial functions make use of a GiST index if the query would benefit from it. For example, with my test data: EXPLAIN SELECT (ST_Dump(ST_Union(buffer))).path[1], (ST_Dump(ST_Union(buffer))).geom FROM tmp WHERE ST_DWithin(buffer, ST_MakeEnvelope(90900, 190900, 100100, 200100), 100); Aggregate (cost=8.53..8.55 rows=1 width=2272) -> Index Scan using idx_tmp_the_geom on tmp (cost=0.00..8.52 rows=1 width=2272) Index Cond: (buffer && '0103000000010000000500000000000000002BF64000000000804A074100000000002BF6400000000040700841000000008076F8400000000040700841000000008076F84000000000804A074100000000002BF64000000000804A0741'::geometry) Filter: (('01030000000100000005000000000000004031F64000000000A04D0741000000004031F64000000000206D0841000000004070F84000000000206D0841000000004070F84000000000A04D0741000000004031F64000000000A04D0741'::geometry && st_expand(buffer, 100::double precision)) AND _st_dwithin(buffer, '01030000000100000005000000000000004031F64000000000A04D0741000000004031F64000000000206D0841000000004070F84000000000206D0841000000004070F84000000000A04D0741000000004031F64000000000A04D0741'::geometry, 100::double precision))
{ "pile_set_name": "StackExchange" }
Q: RxSwift - Button Tap using Publish Subject So I have a button inside my ViewController which is connected to ViewModel and than whenever the button is tapped, in my coordinator I navigate to another screen. The code is like this: VC btnShowShopsMap.rx.tap .bind(to: viewModel.selectShowMap) VM let selectShowMap: AnyObserver<Void> let showShopMap: Observable<Void> //Inside init let _selectShowMap = PublishSubject<Void>() selectShowMap = _selectShowMap.asObserver() showShopMap = _selectShowMap.asObservable() Coordinator viewModel.showShopMap .subscribe(onNext: { _ in self.showShopMap()}) .disposed(by: userShopVC.disposeBag) Is it possible to refactor above code? rather than using PublishSubject is there any other way to do what i am doing using PublishSubject My VC, VM & Coordinator Flow Coordinator func showLoginScreen(logout: Bool = false) { guard let viewController = LoginViewController.instantiate(storyboard: .main) else { return } viewController.viewModelFactory = { inputs in let viewModel = LoginViewModel(inputs: inputs) viewModel.showHome .subscribe(onNext: { isLogged in if isLogged { self.showHomeScreen() } }) .disposed(by: viewController.disposeBag) inputs.showOnboarding .subscribe(onNext: { _ in self.showOnboardingScreen() }) .disposed(by: viewController.disposeBag) return viewModel } navController.pushViewController(viewController, animated: true) VC var viewModelFactory: (LoginViewModel.UIInputs) -> LoginViewModel = { _ in fatalError("factory not set")} let inputs = LoginViewModel.UIInputs(userNumber: txtUserNumber.rx.text.orEmpty.asDriver(), password: txtPassword.rx.text.orEmpty.asDriver(), loginTapped: btnLogin.rx.tap.asSignal(), userNumberLostFocus: txtUserNumber.rx.controlEvent(.editingDidEnd).asSignal(), passwordLostFocus: txtPassword.rx.controlEvent(.editingDidEnd).asSignal(), indicator: indicator, showOnboarding: btnShowOnboarding.rx.tap.asObservable()) VM struct UIInputs { let userNumber: Driver<String> let password: Driver<String> let loginTapped: Signal<Void> let userNumberLostFocus: Signal<Void> let passwordLostFocus: Signal<Void> let indicator: ActivityIndicator let showOnboarding: Observable<Void> } init(inputs: UIInputs) {} A: I found very easy and simple way to solve my issue and avoid using Subject, As there was no logic related to my button in VM, I don't need pass my Button tap to my VM either by using Observable or using Subject. Instead I directly accessed my button in my Coordinator like this: viewController.btnShowOnboarding.rx.tap .subscribe(onNext: { _ in self.showOnboardingScreen() }) .disposed(by: viewController.disposeBag)
{ "pile_set_name": "StackExchange" }
Q: How to resize c# marker images? I am trying to make a neat little bar graph with unique markers on the columns. I used a 20x20px png image for this purpose and set it with chart1.Series[0].Points[chart1.Series[0].Points.Count - 1].MarkerImage = imageIWanToUse; but the marker is huge, tried to use chart1.Series[0].Points[chart1.Series[0].Points.Count - 1].MarkerSize = 1; but with no luck, i get this on all of the columns, where can i fix this? image of a column A: You need to make sure that the image you use has the proper dpi setting, so that it fits with your screen's dp, which probably is around 75-96 dpi. If it looks too large than the dpi of the image is too small.. You can change it in code like this: Bitmap bmp = (Bitmap) Bitmap.FromFile("D:\\stop32.png"); bmp.SetResolution(50, 50); bmp.Save("D:\\stop32_50dpi.png"); bmp.SetResolution(250, 250); bmp.Save("D:\\stop32_250dpi.png"); Series S0 = chart1.Series[0]; S0.Points[chart1.Series[0].Points.Count - 3].MarkerImage = "D:\\stop32.png"; S0.Points[chart1.Series[0].Points.Count - 2].MarkerImage = "D:\\stop32_50.png"; S0.Points[chart1.Series[0].Points.Count - 1].MarkerImage = "D:\\stop32_250.png"; Here are the resulting markers: The original resolution was 96dpi. (Left marker.) You will have to watch out for varying screen dpi and use either different images or create the right one dynamically. You can get the current screen dpi e.g. by testing the current Graphics object in a Paint event: Console.WriteLine(e.Graphics.DpiX + " dpi x"); For my screen this resulted in 120 dpi..
{ "pile_set_name": "StackExchange" }
Q: How to extract a DWORD color variable into its parameters? (decimal type) I have the example : unsigned int dwColor = 0xAABBCCFF; //Light blue color And its parameters from left to right are : "alpha, red, green, blue"; each parameter requires two hexadecimal values. The maximum value of each parameter is 255; lowest : 0 And, how to extract then convert all parameters of a DWORD color to decimals? I like the value range "0.00 -> 1.00". For example : float alpha = convert_to_decimal(0xAA); //It gives 0.666f float red = convert_to_decimal(0xBB); //It gives 0.733f float green = convert_to_decimal(0xCC); //It gives 0.800f float blue = convert_to_decimal(0xFF); //It gives 1.000f EDIT : I've just seen union, but the answerer says it's UB (Undefined Behaviour). Does anyone know the better solution? :) A: I usually use an union: union color { unsigned int value; unsigned char component[4]; }; color c; c.value = 0xAABBCCFF; unsigned char r = c.component[0]; unsigned char g = c.component[1]; unsigned char b = c.component[2]; unsigned char a = c.component[3]; If you need to treat it as a float value: float fr = c.component[0] / 255.0f; float fg = c.component[1] / 255.0f; float fb = c.component[2] / 255.0f; float fa = c.component[3] / 255.0f; EDIT: As mentioned in the comments below, this use of union is Undefined Behaviour (UB), see this question from Luchian Grigore. EDIT 2: So, another way to break a DWORD into components avoiding the union is using some bitwise magic: #define GET_COMPONENT(color, index) (((0xFF << (index * 8)) & color) >> (index * 8)) But I do not advise the macro solution, I think is better to use a function: unsigned int get_component(unsigned int color, unsigned int index) { const unsigned int shift = index * 8; const unsigned int mask = 0xFF << shift; return (color & mask) >> shift; } How it works? Lets supose we call get_component(0xAABBCCFF, 0): shift = 0 * 8 shift = 0 mask = 0xFF << 0 mask = 0x000000FF 0x000000FF & 0xAABBCCFF ---------- 0x000000FF 0x000000FF >> 0 = 0xFF Lets supose we call get_component(0xAABBCCFF, 2): shift = 2 * 8 shift = 16 mask = 0xFF << 16 mask = 0x00FF0000 0x00FF0000 & 0xAABBCCFF ---------- 0x00BB0000 0x00BB0000 >> 16 = 0xBB Warning! not all color formats will match that pattern! But IMHO, the neater solution is to combine the function with an enum, since we're working with a limited pack of values for the index: enum color_component { A,B,G,R }; unsigned int get_component(unsigned int color, color_component component) { switch (component) { case R: case G: case B: case A: { const unsigned int shift = component * 8; const unsigned int mask = 0xFF << shift; return (color & mask) >> shift; } default: throw std::invalid_argument("invalid color component"); } return 0; } The last approach ensures that the bitwise operations will only be performed if the input parameters are valid, this would be an example of usage: std::cout << "R: " << get_component(the_color, R) / 255.0f << '\n' << "G: " << get_component(the_color, G) / 255.0f << '\n' << "B: " << get_component(the_color, B) / 255.0f << '\n' << "A: " << get_component(the_color, A) / 255.0f << '\n'; And here is a live demo.
{ "pile_set_name": "StackExchange" }
Q: How can I increase the number of volume levels? Is it possible to increase the number of steps in the volume control? I'd like a finer grained control over the volume level. I have a Galaxy Nexus. Note: I don't want to boost the volume just change the number of levels so I can find a sweet spot when listening to music. A: Many people have this problem with Android. You can see it has been reported in Android's bug tracking system. The number of levels is controlled by a setting that's compiled into the Android system image. Use a different ROM It's possible that flashing a custom-rom could increase the number of levels, but I don't know which, if any, custom ROMs do this. This bug report in cyanogenmod's tracker suggests they don't plan to add that feature, for fear it may cause compatibility problems with some apps. Use a different app (easy) Some media apps have their own volume control, on top of that provided by Android. I believe Poweramp is one such (but I don't use it myself). If there's one particular app you need more control of, such as a music app, you might want to replace it with one that has this feature. Edit your phone's OS (advanced) If you're not worried about the risk of breaking some (badly-written) apps, and your device is rooted, then you can follow these instructions to edit the Android system image to increase the number of levels. That site gives step-by-step instructions, including installing the developer tools you'll need to make system changes; a summary for knowledgeable people is as follows: Get framework.jar from your device and run baksmali on it. Edit framework\android\media\AudioService.smali Search for 0xft 0x0t 0x0t 0x0t to find the table of audio levels. Replace the first number of each row with the desired number of levels (in hexadecimal). Run smali to generate a new framework.jar, and then replace the original on the device. A: Edit: This app looks worth a go - https://forum.xda-developers.com/android/apps-games/app-precise-volume-override-androids-t3573562 (https://play.google.com/store/apps/details?id=com.phascinate.precisevolume) I ended up using this app on my nexus 4 - supports up to 100 volume levels. Its not perfect but should suffice till they hopefully fix what seems like such a simple problem. https://play.google.com/store/apps/details?id=opotech.finevolumev2 Discussed here- http://androidforums.com/android-lounge/490543-volume-control-in-android-os.html A: If you're phone is rooted or you have a custom recovery (like TWRP), this is actually much easier. The only thing you'll have to do, is to add the following line to your build.prop file located in /system: ro.config.media_vol_steps=30 Where 30 represents the number of steps. This can be done with a root file explorer (like Root Browser) or via VI in the TWRP terminal or via adb.
{ "pile_set_name": "StackExchange" }
Q: Are load ops deallocated from the RS when they dispatch, complete or some other time? On modern Intel1 x86, are load uops freed from the RS (Reservation Station) at the point they dispatch2, or when they complete3, or somewhere in-between4? 1 I am also interested in AMD Zen and sequels, so feel free to include that too, but for the purposes of making the question manageable I limit it to Intel. Also, AMD seems to have a somewhat different load pipeline from Intel which may make investigating this on AMD a separate task. 2 Dispatch here means leave the RS for execution. 3 Complete here means when the load data returns and is ready to satisfy dependent uops. 4 Or even somewhere outside of the range of time defined by these two events, which seems unlikely but possible. A: The following experiments suggest that the uops are deallocated at some point before the load completes. While this is not a complete answer to your question, it might provide some interesting insights. On Skylake, there is a 33-entry reservation station for loads (see https://stackoverflow.com/a/58575898/10461973). This should also be the case for the Coffee Lake i7-8700K, which is used for the following experiments. We assume that R14 contains a valid memory address. clflush [R14] clflush [R14+512] mfence # start measuring cycles mov RAX, [R14] mov RAX, [R14] ... mov RAX, [R14] mov RBX, [R14+512] # stop measuring cycles mov RAX, [R14] is unrolled 35 times. A load from memory takes at least about 280 cycles on this system. If the load uops stayed in the 33-entry reservation station until completion, the last load could only start after more than 280 cycles and would need another ~280cycles. However, the total measured time for this experiment is only about 340 cycles. This indicates that the load uops leave the RS at some time before completion. In contrast, the following experiments shows a case where most uops are forced to stay in the reservation until the first load completes: mov RAX, R14 mov [RAX], RAX clflush [R14] clflush [R14+512] mfence # start measuring cycles mov RAX, [RAX] mov RAX, [RAX] ... mov RAX, [RAX] mov RBX, [R14+512] # stop measuring cycles The first 35 loads now have dependencies on each other. The measured time for this experiment is about 600 cycles. The experiments were performed with all but one core disabled, and with the CPU governor set to performance (cpupower frequency-set --governor performance). Here are the nanoBench commands I used: ./nanoBench.sh -unroll 1 -basic -asm_init "clflush [R14]; clflush [R14+512]; mfence" -asm "mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RAX, [R14]; mov RBX, [R14+512]" ./nanoBench.sh -unroll 1 -basic -asm_init "mov RAX, R14; mov [RAX], RAX; clflush [R14]; clflush [R14+512]; mfence" -asm "mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RAX, [RAX]; mov RBX, [R14+512]" A: Just came across this question. Here is my attempt at an answer. Short Answer: I'm still a bit uncertain about some parts but based on some measurements using various performance counters along with performance monitoring interrupts, it "looks like" the load uop gets removed from RS during the same cycle it is dispatched to load ports or at least very shortly afterwards. Details: A while ago I tried writing a kernel module which mimics the ideas here. The blog post linked describes the idea really well so I won't explain it in detail here. The main idea is to trigger a performance monitoring interrupt after a set number of cycles have elapsed, freeze all counter values (currently tracked), store them and reset/repeat. Doing this for 1, 2, ... n cycles gives us some picture of what is going on micro-architecturally at the cycle granularity. How accurate of a picture is a different story... The source for the kernel module I used for measuring can be found here. Long Answer: I profiled the following code below using the kernel module mentioned above on a i7-1065G7 (Ice Lake) and tracked 11 different performance counters. Prior to the mov instruction profiled, clflush was called on the address stored in r8. This was done so that the load would take long enough to make it easy to tell whether the uop was removed from RS before, after or during execution (otherwise the load completes in about 4 cycles). In total I measured up to 600 cycles with most of the events which are of interest in this question happening within 65 cycles. To account for noise I did 1024 trials for each cycle and stored the counter value which occurred the most. Luckily for each cycle in the chart below and each counter I only saw deviations in value from at most a single trial with the remaining 1023 trials giving the same counter values. 563: 0f 30 wrmsr 565: 4d 8b 00 mov (%r8),%r8 568: 0f ae f0 mfence 56b: 0f ae e8 lfence The counters tracked are listed below. Descriptions are summarized from Intel SDM. INST_RETIRED_ANY_P: To track when wrmsr retired RS_EVENTS_EMPTY_CYCLES: Count of cycles RS is empty UOPS_DISPATCHED_PORT_PORT_0: # uops dispatched to port 0 UOPS_DISPATCHED_PORT_PORT_1: # uops dispatched to port 1 UOPS_DISPATCHED_PORT_2_3: # uops dispatched to port 2,3 (load addr ports) UOPS_DISPATCHED_PORT_4_9: # uops dispatched to port 4,9 (store data ports) UOPS_DISPATCHED_PORT_PORT_5: # uops dispatched to port 5 UOPS_DISPATCHED_PORT_PORT_6: # uops dispatched to port 6 UOPS_DISPATCHED_PORT_7_8: # uops dispatched to port 7,8 (store addr ports) UOPS_EXECUTED_THREAD: # uops executed UOPS_ISSUED_ANY: # uops sent to RS from RAT The table below lists each counter value at each cycle. So based on the table below one uop is sent to RS at cycle 47 and occupies the RS for cycles 51-54. This is presumably the load uop. At cycle 54 RS_EVENTS_EMPTY_CYCLES and UOPS_DISPATCHED_PORT_2_3 increment which means (at least how I'm interpreting it) that the load uop has been dispatched and is freed from the RS. What I'm not sure about is that at cycle 52 three more uops are issued to the RS. They seem to arrive and occupy the RS for cycle 55-58. But only two uops are dispatched to the execution ports and the RS is emptied. Regardless by cycle 59 the RS is empty (count is increasing each cycle). The load completes and mov retires about 500 cycles later. +-------+--------------+-----------------+--------+--------+----------+----------+--------+--------+----------+---------------+-------------------+------------------------+ | Cycle | Inst Retired | Cycles RS Empty | Port 0 | Port 1 | Port 2,3 | Port 4,9 | Port 5 | Port 6 | Port 7,8 | uops executed | uops issued to RS | Comments | +-------+--------------+-----------------+--------+--------+----------+----------+--------+--------+----------+---------------+-------------------+------------------------+ | 1 | 0 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | | | 2 | 0 | 4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | | | 3 | 0 | 5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | | | 4 | 0 | 6 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 2 | 2 uops issued | | 5 | 0 | 7 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 2 | | | 6 | 0 | 8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 2 | | | 7 | 0 | 9 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 2 | | | 8 | 0 | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 2 | | | 9 | 0 | 11 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 2 | | | 10 | 0 | 12 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 2 | | | 11 | 0 | 12 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 2 | | | 12 | 0 | 12 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 2 | | | 13 | 0 | 12 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 2 | | | 14 | 0 | 13 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 3 | 2 | | | 15 | 0 | 14 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 3 | 2 | 2 uops dispatched | | 16 | 0 | 15 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 4 | 2 | | | 17 | 0 | 16 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 2 | 2 uops executedd | | 18 | 0 | 17 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 2 | | | 19 | 0 | 18 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 2 | | | 20 | 0 | 19 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 2 | | | 21 | 0 | 20 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 2 | | | 22 | 0 | 21 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 2 | | | 23 | 0 | 22 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 5 | | | 24 | 0 | 23 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 6 | 4 uops issued | | 25 | 0 | 24 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 6 | | | 26 | 0 | 25 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 6 | | | 27 | 0 | 25 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 6 | | | 28 | 0 | 25 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 6 | | | 29 | 0 | 25 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 5 | 6 | | | 30 | 0 | 25 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 5 | 6 | | | 31 | 0 | 26 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 5 | 6 | | | 32 | 0 | 27 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 6 | 6 | | | 33 | 0 | 28 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 7 | 6 | | | 34 | 0 | 29 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | 3 uops executed | | 35 | 0 | 30 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | | | 36 | 1 | 31 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | wrmsr retired | | 37 | 1 | 32 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | | | 38 | 1 | 33 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | | | 39 | 1 | 34 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | | | 40 | 1 | 35 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | | | 41 | 1 | 36 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | | | 42 | 1 | 37 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | | | 43 | 1 | 38 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | | | 44 | 1 | 39 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | | | 45 | 1 | 40 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | | | 46 | 1 | 41 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | | | 47 | 1 | 42 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 6 | | | 48 | 1 | 43 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 7 | 1 uop issued | | 49 | 1 | 44 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 7 | | | 50 | 1 | 45 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 7 | | | 51 | 1 | 46 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 7 | | | 52 | 1 | 46 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 10 | 3 uops issued | | 53 | 1 | 46 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 10 | | | 54 | 1 | 46 | 0 | 1 | 0 | 0 | 0 | 4 | 0 | 8 | 10 | port 2,3 load addr | | 55 | 1 | 47 | 0 | 1 | 1 | 0 | 0 | 4 | 0 | 8 | 10 | | | 56 | 1 | 47 | 0 | 1 | 1 | 0 | 0 | 4 | 0 | 8 | 10 | executing load | | 57 | 1 | 47 | 0 | 1 | 1 | 0 | 0 | 4 | 0 | 9 | 10 | | | 58 | 1 | 47 | 0 | 1 | 1 | 0 | 0 | 4 | 0 | 9 | 10 | port 4,9 store data | | 59 | 1 | 48 | 0 | 1 | 1 | 1 | 0 | 4 | 1 | 9 | 10 | port 7,8 store address | | 60 | 1 | 49 | 0 | 1 | 1 | 1 | 0 | 4 | 1 | 9 | 10 | | | 61 | 1 | 50 | 0 | 1 | 1 | 1 | 0 | 4 | 1 | 11 | 10 | 2 uops executed | | 62 | 1 | 51 | 0 | 1 | 1 | 1 | 0 | 4 | 1 | 11 | 10 | | | 63 | 1 | 52 | 0 | 1 | 1 | 1 | 0 | 4 | 1 | 11 | 10 | | | 64 | 1 | 53 | 0 | 1 | 1 | 1 | 0 | 4 | 1 | 11 | 10 | | | 65 | 1 | 54 | 0 | 1 | 1 | 1 | 0 | 4 | 1 | 11 | 10 | | +-------+--------------+-----------------+--------+--------+----------+----------+--------+--------+----------+---------------+-------------------+------------------------+ So based on the table it looks like the load uop is removed from the RS either at the same time as dispatching to load port or a couple of cycles later. I did some sanity checking of the values in the chart and for the most part all the counter values makes sense. Two things I haven't figure out is the fact that 4 uops are to be sent to RS (cycle 24) but only 3 gets executed (cycle 35). Similarly 3 uops is issued at cycle 52, but only 2 are executed (cycle 61) Thanks
{ "pile_set_name": "StackExchange" }
Q: What's the female equivalent of "suitor"? I'm looking for a word which could satisfy the usage of "suitor", except it would be used to indicate female "suitors": E.g.: She had a host of suitors eagerly awaiting her favour... Now, I want a word that could fit in this sentence, except it would be about females: He had a bevy of ?????? eagerly awaiting his favour... A: I think one day the word for this will be suitor, just as now actresses are sometimes simply called actors. Until then, it seems that female suitor is the most common phrase. This example is from a New York Times book review of An Available Man: He picks it up to hear the clamorous, intrusive voice of a female suitor, attempting to break in on his grief. But he’d rather iron the blouses of his deceased wife, Bee, “as a way of reconnecting with her when she was so irrevocably gone” than date any of the women now scurrying in his direction. Bee, on her deathbed, had predicted this fate: “Look at you. They’ll be crawling out of the woodwork.” A: It may be a bit of a dated term, but suitress would be the female equivalent. (I'm not sure about the collective noun, though. Instead of "a host of suitresses," you might want to use bevy instead). A: If you want to give the impression of aggressive females, then the "female suitor" term fits. I think that "admirer" could work in many situations where you don't want to necessarily indicate aggressiveness. "He had a bevy of admirers eagerly awaiting his favour."
{ "pile_set_name": "StackExchange" }
Q: How to solve TypeScript typing issue with component composition React promotes composition over inheritance, but I I have a React component in TypeScript that should host certain kinds of React components. For example, let's say I have a MenuBar component, and it takes an array of various MenuBarItem components it can host as a prop. I want to force all menu bar items to have the same root element structure, so they must be rendering the MenuBarItem component at the root. The problem I have is that, if I was using inheritance, I can achieve this by defining the prop as something like items: MenuBarItem[], but I cannot figure this out how to enforce this with composition. By using composition, I created FooMenuBarItem and BarMenuBarItem, and let them render the MenuBarItem internally (See below). So, they don't share the common base class that I can use as a type. How would I solve this typing problem with composition? export class MenuBarItem extends React.Component<{}, {}> { render() { return /*...*/; } } export class FooMenuBarItem extends React.Component<{}, {}> { render() { return <MenuBarItem>Foo</MenuBarItem>;} } export class BarMenuBarItem extends React.Component<{}, {}> { render() { return <MenuBarItem>Bar</MenuBarItem>;} } export interface MenuBarProps { items: MenuBarItem[]; // This would only work if I use inheritance to get the common base type! } export class MenuBar extends React.Component<MenuBarProps , {}> { render() { <div>{this.props.menuBarItems}</div> } } I found a similar question here, but with no answers. A: I think the short answer is that there is no way to declare the exact type you want (I would be interested to hear otherwise!). To be honest I would normally just go with: export interface MenuBarProps { items: React.ReactNode; } And rely on consumers of the code to do the sensible thing. The only other thing I would consider is that perhaps you could use: export interface MenuBarProps { items: React.Component<MenuItemProps>; } This would only make sense if the various different menu item components all shared a set of common props.
{ "pile_set_name": "StackExchange" }
Q: Previewing the ruby elements in html.erb with Aptana I'm making my first rails app with Aptana studios and I'm trying to preview some of the basic partials I'm making to add to the other views. The problem I have is when I run them using Firefox/IE the ruby elements of the file get printed to screen as is and are not evaluated. Is there a work around to get this to run the ruby elements properly either using Aptana's run/preview options or using another program. Thanks for any help anyone has as it's starting to get frustrating after looking for solutions for 5 hours -------------------------------- Edit Code from _topnav.html.erb <div> <table> <tbody> <% @categories.each do |c| %> <tr><%= c.name %></tr> <% end %> </tbody> </table> </div> code snippet from index.html.erb <%= render 'shared/topnav' %> controller categories_controller.rb snippet def index @categories = Category.all end When _topnav.html.erb is run this is seen on the web page <% @categories.each do |c| %> <%= c.name %> <% end %> When index.html.erb is run this is seen on the web page <%= render 'shared/topnav' %> A: I have managed to find a way to solve the problem. Firstly I ran rails server on the command line in Aptana that set up the server for me. Then I got up the internal web browser within Aptana under Windows->Show Views->Web Browser and went to the url of the page specified in routes.rb in this case http://localhost:3000/ as it was the root page and it finally evaluated the ruby code and it appeared as expected. P.s Thanks for trying to help NibbleX
{ "pile_set_name": "StackExchange" }
Q: using TabControl in windows phone I read the article about using a TabControl on Windows Phone application. I can avoid it to fire when it is first load. However, the selectionChanged fired twice when user click the tab. Would someone can help me how to fix it. Thanks in advance. There is my TabControl: <cc:TabControl Grid.Row="1" SelectionChanged="tabList_SelectionChanged" x:Name="tabList"> <cc:TabItem Height="80" Header="Events" Foreground="Black"/> <cc:TabItem Height="80" Header="Details" Foreground="Black"/> <cc:TabItem Height="80" Header="Notes" Foreground="Black" /> </cc:TabControl> There is cobe behind: public partial class Tab : PhoneApplicationPage { private bool blnFristLoad=true; public Tab() { InitializeComponent(); tabList.SelectionChanged += new SelectionChangedEventHandler(tabList_SelectionChanged); } private void tabList_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (blnFristLoad == false) { TabItem t = (sender as TabControl).SelectedItem as TabItem; t.Content = "202020"; } else blnFristLoad = false; } A: It's very obvious in your code. You are adding SelectionChanged event handler twice. One from your XAML code and the other from the code behind. As you are using += symbol, the eventhandler is added as a seperate instance. Remove one of those statements.
{ "pile_set_name": "StackExchange" }
Q: How to get all console error messages in Angular application I'm working on a angular application, the problem is when I want to debug it on some smart TVs there is no debug mode and in the background I have some errors that cause application to crash, so, is there any way to get all error messages and print it in a part of the page in my application? Actually I want to have some kind of virtual console in my own application. Thank you so much A: There are several ways to debug it: Console.log() - this outputs your message to console. Not sure if you can see it on tv though. Create a global error handler, as provided in Angular documentation If above does not work, you can try to use this solution, which I also found out somewhere on the internet a while ago by using a snackbar component, which displays errors as a popup: error.service.ts: import { Injectable } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class ErrorService { checkOnline() { if (!navigator.onLine) { return 'No Internet Connection'; } } getClientMessage(error: Error): string { return error.message ? error.message : error.toString(); } getClientStack(error: Error): string { return error.stack; } getServerMessage(error: HttpErrorResponse): string { var msg = error.error.Message; if (!!msg) return msg + " : " + error.error.ExceptionMessage; return "Application can not execute because API hasn\'t been started"; } getServerStack(error: HttpErrorResponse): string { return error.error.StackTrace; } } global-error-handler-component.ts: import { ErrorHandler, Injectable, Injector } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { ErrorService } from './services/error.service'; import { MatSnackBar } from '@angular/material'; @Injectable() export class GlobalErrorHandler implements ErrorHandler { constructor(private injector: Injector, public snackBar: MatSnackBar) { } handleError(error: Error | HttpErrorResponse) { const errorService = this.injector.get(ErrorService); let message; let stackTrace = errorService.getClientStack(error); if (error instanceof HttpErrorResponse) // Server Error message = errorService.getServerMessage(error); else // Client Error message = errorService.getClientMessage(error); this.snackBar.open(message, 'X', { panelClass: ['error'] }); } } app.module.ts: import { GlobalErrorHandler } from './global-error-handler.component'; import { MatSnackBarModule } from '@angular/material/snack-bar'; ... imports: [ ... MatSnackBarModule, ... ], providers: [ ... { provide: ErrorHandler, useClass: GlobalErrorHandler }, ...
{ "pile_set_name": "StackExchange" }
Q: Search key in array and return value from query result I have run my query with CI Active Record, and these is the result: Array ( [0] => Array ( [id_kelurahan] => 6 [id_indikator] => 8 [nilai] => 20 ) [1] => Array ( [id_kelurahan] => 6 [id_indikator] => 9 [nilai] => 20 ) ) From that results, i want to search, 'where "id_kelurahan=6"' and return value of 'nilai'. Thanks. A: Do a loop on your array and check for it's element. Assuming your array is stored in variable called $theArray: foreach( $theArray as $arrayEach){ if(6 == $arrayEach['id_kelurahan']){ echo $arrayEach['nilai']; } }
{ "pile_set_name": "StackExchange" }
Q: ¿Porque al correr mi codigo no ejecuta ningun cambio en pantalla? codeblocks edicion Buenas mi problema continua con el compilador del codeblocks o la forma en la que compila, en varios cursos de youtube he visto que no tienen este problema y ninguno me a podido dar razon. Lo que pasa es que al momento de correr un programa el compilador sigue ejecutando las instrucciones anteriores, me explico con un codigo, bool logico; int a=4, b=6; logico = a <= b; cout << logico; con esto al compilar me bota por pantalla 1 bueno hasta ahi bien ahora, si hago una modificacion, bool logico; int a=4, b=6; logico = a >= b; cout << logico; con esto me deberia aparecer en pantalla 0, pero no me sigue apareciendo 1. bool logico; logico = false; cout << logico; Y si lo pongo asi en false sigue botando 1 es como si no compilara o no sobreescribiera el ejecutable, claro yo estoy guardando el codigo cada vez que lo modifico. Si me podrian ayudar me salvarian la vida de verdad estoy cansado con esto es estresante. A: Definitivamente debes obtener un valor de 0 bool logico; logico = false; cout << logico; Vuelve a construir tu proyecto (Rebuild) dando click al icono azul O mediante el menu, Build > Rebuild.
{ "pile_set_name": "StackExchange" }
Q: Hadoop - Multiple input and join between these input files I want to use Hadoop on multiple files (actually 2 files) as a input files. For example: File input 1: user1 italy user2 spain user3 italy ... File input 2: user1 trackname1 user2 trackname2 user3 trackname1 ... I need the number of users per country, then for each country the most popular tracks in (file 2). And finally the number of occurrences of the most popular tracks. I Would like to have as outputs, something like: Popular track (italy): trackname1 (occurrences) Popular track (spain): trackname2 ... Actually i've tried to use 2 mappers and 1 reducer. But I don't know how to make the "join" between the two input files on the user field. What could be the best solution for that? Any advice? Thanks! A: I think you 're going to need a chain of three jobs (maybe I use too many jobs, but this will give you the intuition and you can later optimize it): Job 1 (the join) Map of file1 output key: userid output value: country (you can put a special prefix to know it's a country and not a track) Map of file2 output key: userid output value: track Reduce (userid, < country, track >) output key: (country-track) output value: 1 Job 2 (the counting) Map: Identity Mapper Reduce (country-track, < 1,1,1,... >) sum up the 1's for each (country-track) output key: country output value: (track, count) pair Job 3 (the sorting) Map: Identity Mapper Reduce keep from the values the track with the maximum count and output: output key: country output value: track Jobs 2 and 3 can use a combiner, similar (but not identical) to their reducer. I repeat that this is not the best solution and much can be done to optimize it (especially Jobs 2 and 3). For example, you could output from Job 1 a country as a key and a (track, 1) as a value and then finish at Job 2.
{ "pile_set_name": "StackExchange" }
Q: R trailing cumsum per group I need to compute the running cumsum per group in R but the window over which to cumsum must only be the last 3 observations: If for example I have a table with a person's name, a date and a score as follow: Name Date Score 1 John 2017-01-01 4 2 John 2017-01-02 5 3 John 2017-01-03 3 4 John 2017-01-04 1 5 John 2017-01-05 4 6 John 2017-01-06 4 7 Ben 2017-01-01 4 8 Ben 2017-01-02 4 9 Ben 2017-01-03 5 10 Ben 2017-01-04 2 11 Ben 2017-01-05 3 12 Ben 2017-01-06 4 13 Ben 2017-01-07 4 14 Ben 2017-01-08 4 I want to add a "custom cumsum" column which cumsums (per group) the last three days' scores, i.e. I want the following result: Name Date Score Special_cum_sum 1 John 2017-01-01 4 4 2 John 2017-01-02 5 9 3 John 2017-01-03 3 12 4 John 2017-01-04 1 9 5 John 2017-01-05 4 8 6 John 2017-01-06 4 9 7 Ben 2017-01-01 4 4 8 Ben 2017-01-02 4 8 9 Ben 2017-01-03 5 13 10 Ben 2017-01-04 2 11 11 Ben 2017-01-05 3 10 12 Ben 2017-01-06 4 9 13 Ben 2017-01-07 4 11 14 Ben 2017-01-08 4 12 A: You can use zoos rollapply combined with dplyrs group_by and mutate: library(zoo) library(dplyr) ?rollapply Data <- Data %>% group_by(Name) %>% mutate(Special_cum_sum = rollapply(Score, 3, sum, align = "right", partial = T))
{ "pile_set_name": "StackExchange" }
Q: dart:ui:1: Error: Not found: dart:ui. flutter/dart: When I start a debugging session (pressing F5) I receive the following messages: dart:ui:1: Error: Not found: dart:ui. Exited (sigterm) There is no indication as to where the problem occurred. Output from flutter doctor -v is: [√] Flutter (Channel beta, v0.8.2, on Microsoft Windows [Version 6.1.7601], locale en-US) • Flutter version 0.8.2 at C:\Downloads\flutter\flutter_windows_v0.5.1-beta\flutter • Framework revision 5ab9e70727 (2 weeks ago), 2018-09-07 12:33:05 -0700 • Engine revision 58a1894a1c • Dart version 2.1.0-dev.3.1.flutter-760a9690c2 [√] Android toolchain - develop for Android devices (Android SDK 27.0.3) • Android SDK at C:\Users\gggustafson\AppData\Local\Android\sdk • Android NDK location not configured (optional; useful for native profiling support) • Platform android-27, build-tools 27.0.3 • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b02) • All Android licenses accepted. [√] Android Studio (version 3.1) • Android Studio at C:\Program Files\Android\Android Studio • Flutter plugin version 26.0.1 • Dart plugin version 173.4700 • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b02) [√] VS Code, 64-bit edition (version 1.25.1) • VS Code at C:\Program Files\Microsoft VS Code • Flutter extension version 2.18.0 [√] Connected devices (1 available) • SM G925V • 06157df60c7a8e20 • android-arm64 • Android 7.0 (API 24) • No issues found! Any thoughts? A: When running the app, you will find 2 main.dart Choose the one with the flutter icon beside it
{ "pile_set_name": "StackExchange" }
Q: C# WPF button click I wounder if there is a way to check if a key is clicked? What I want to achieve is creating something like text editor, I have finished most of the parts. Now when I press on a button, I have a function under element PreviewKeyUp and the other PreviewKeyDown ... Is there something like PreviewKeyClick or KeyClick? PS: I'm using visual studio 2010 and compiling against .NET Framework 3.5 ... I know I can use 4.0 but 3.5 is due to restrictions on client PC. The application targets a specific client and I can't update the .NET Framework on the client machine. If more details is needed, don't hesitate to ask. A: In general, for text editors you would need to handle TextInput (or PreviewTextInput) and KeyDown/PreviewKeyDown events. The latter handles keys not included in TextInput events.
{ "pile_set_name": "StackExchange" }
Q: Slow Performance within While Loop when Updating MYSQL Table The following code runs incredibly slowly when performing a WHILE LOOP using data from table product and updating another table stock_figures within the same database. The code loops through each row in product taking the value from product_id and wholesale_price and then performs some calculations on the product table before updating the stock_figures table with the values. I'd be grateful of any suggestions which would improve the performance of my queries. PHP WHILE LOOP <? // Retrieve data from database $loop = " SELECT product_id, wholesale_price FROM product"; $query= mysql_query($loop); while($rows=mysql_fetch_assoc($query)) { $row = mysql_fetch_row($query); $id = $row[0]; $price = $row[1]; ?> QUERIES WITHIN WHILE LOOP <? $bawtry_stock = " SELECT product_id, ( kids_uk_j_105 + kids_c_17 + kids_c_18 + kids_c_19 + ... etc ) AS SUM FROM product WHERE product_id = '$id'"; $result_bawtry = mysql_query($bawtry_stock) or die (mysql_error()); $line = mysql_fetch_row($result_bawtry); $bawtry = $line[1]; $chain_stock = " SELECT product_id, (quantity_c_size_26_chain + quantity_c_size_28_chain + quantity_c_size_30_chain + ... etc ) AS SUM FROM product WHERE product_id = '$id'"; $result_chain = mysql_query($chain_stock) or die (mysql_error()); $line = mysql_fetch_row($result_chain); $chain = $line[1]; /* * Declare the total value of all pairs from Bawtry, Chain */ $totalpairs = $chain + $bawtry; /* * Insert values for stock to write to databse * Total stock for Bawtry, Chain * Total value of stock for Bawtry, Chain * */ $bawtry_value = (float)($bawtry * $price); $chain_value = (float)($chain * $price); $total_value = (float)($price * ($bawtry + $chain)); $sql2=" UPDATE stock_figures SET bawtry_stock='$bawtry', chain_stock='$chain', totalstock='$totalpairs', bawtry_value='$bawtry_value', chain_value='$chain_value', totalvalue='$total_value' WHERE id='$id'"; $result2=mysql_query($sql2) or die (mysql_error()); ?> // close while loop <? } ?> UPDATED CODE $sql = "SELECT product_id, wholesale_price, (kids_uk_j_105 + kids_c_17 + kids_c_18 + kids_c_19 + kids_c_20 + kids_c_21 + ... ) AS bawtry, (quantity_c_size_26_chain + quantity_c_size_28_chain + quantity_c_size_30_chain + ... ) AS chain from product"; $result = mysql_query($sql) or die (mysql_error()); while ($line=mysql_fetch_assoc($result)) { $id = $line['product_id']; $price = $line['wholesale_price']; $bawtry = $line['bawtry']; $chain = $line['chain']; /* * Declare the total value of all pairs from Bawtry, Chain */ $totalpairs = $chain + $bawtry; /* * Insert values for stock to write to database * Total stock for Bawtry, Chain * Total value of stock for Bawtry, Chain * */ $bawtry_value = (float)($bawtry * $price); $chain_value = (float)($chain * $price); $total_value = (float)($price * ($bawtry + $chain)); $sql2=" UPDATE stock_figures SET bawtry_stock='$bawtry', chain_stock='$chain', totalstock='$totalpairs', bawtry_value='$bawtry_value', chain_value='$chain_value', totalvalue='$total_value' WHERE id='$id'"; $result2=mysql_query($sql2) or die (mysql_error()); However, it's still taking an absolute age to complete. It seems to run really fast when I comment out the UPDATE statement at the end. Obviously this needs to remain in the code, so I'll probably run the whole thing as a cronjob. Unless any further improvements can be suggested? A: It seems you doing a lot of wasted selects. You first select some data from table products, then for each row you select again from the same table. Twice. Then finally inserting this into another table, stock_figures. And the only operation you are doing is adding lots of figures together. All of this can be done in a single query. select product_id, whole_sale_price, sum(kids_uk_j_105, kids_c_17, ...) as bawtry, sum(quantity_c_size_26_chain, quantity_c_size_28_chain, ...) as chain from products; If this still is taking lots of time you need to check some server settings and also number of rows Every write you make is a transaction and depending on your ACID-level it might be slow to do commits. Change innodb-flush-log-at-trx-commit to 2 will speed up writes. You are doing a full table scan on products-table. I guess this is intended but if that table is big reading it will take a while, and writing all those rows back to stock_figures is going to take even longer. Consider another approach. For each write (insert, update or delete) to products have a trigger update the corresponding row in stock_figures. Not only will it eliminate the batch job, it will also make stock_figures be correct at any given time.
{ "pile_set_name": "StackExchange" }
Q: Pull-ups question: look up at the bar or look straight ahead? When doing pull-ups (not chin-ups), I find it harder to get up when I look up and my chest is sticking out and back is titled. On the other hand, these harder pull-ups feel more intense and satisfying, for the few reps that I can do. I feel pumped up afterwards. When I instead just look straight ahead and not look up at the bar, then I find that I can do more pull-ups, more easily. Is the "proper form" looking up or looking straight ahead, when pulling yourself up? A: Extension in the neck is naturally associated with extension in the back (the opposite way - back extension and neck flexion, or vice versa - is also possible, it just feels unnatural). So usually, when people extend the neck (ie. look up), they also extend the spine. As far as the spine and body position is concerned, there are two main ways you can do a pull-up: Hollow body: the spine neutral or even a bit flexed, emphasizing muscles in the front. It has the advantage, that the abs are more engaged. Arched back: the spine extended and the back muscles are emphasized. This has the advantage of engaging the posterior chain more, which is why you feel more energy in the pull-up. Both are correct ways to do pull-ups, it's a matter of preference.
{ "pile_set_name": "StackExchange" }
Q: Jackson JsonSchemaGenerator - How to get Schema as String I'm sure I'm just being dense here. I want to take an object schema, and turn it into a string representation. Like so, but this returns null: JsonSchemaGenerator generator = new JsonSchemaGenerator(MAPPER); JsonSchema jsonSchema = generator.generateSchema(Get.class); System.out.println("jsonSchema: " + jsonSchema.asObjectSchema().asStringSchema()); This is using com.fasterxml.jackson.module.jsonSchema.JsonSchema, found at https://github.com/FasterXML/jackson-module-jsonSchema/wiki A: you can achieve that by doing: ObjectMapper mapper = new ObjectMapper(); SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); mapper.acceptJsonFormatVisitor(mapper.constructType(YOURCLASS.class), visitor); JsonSchema jsonSchema = visitor.finalSchema(); String schemaString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema);
{ "pile_set_name": "StackExchange" }
Q: Кортежи. Python Зачем нужны кортежи в питоне? Защита от дурака? Я, конечно, понимаю, что люди есть разные, могут творить всякую хрень. Но, если я создаю некоторый объект и подразумеваю, что менять его не собираюсь, значит я не буду его менять. Смысл для блокировки вводить новый объект? A: Кортежи - это неизменяемые объекты и он имеет ряд преимуществ. Кортеж может использоваться, например, для хранения информации о подключении к БД и скорость работы с кортежем быстрее, чем, например, со списком. И быстрее он работает как раз потому, что неизменяемый. Кортеж, также, занимает меньше памяти, что может быть полезно, если речь идет о большим объемах данных. Практические примеры могут быть самыми разнообразными, я приведу простые. Если вы пользуетесь выражениями-геренаторами, то выражение будет быстрее работать с кортежем, чем со списком. numbers = (1,2,3,4,5) squares_under_10 = (number*number for number in numbers if number*number < 10) Для того, чтобы убедиться в этом, можно воспользоваться timeit: $ python -m timeit '(number*number for number in [1,2,3,4,5])' 1000000 loops, best of 3: 0.591 usec per loop $ python -m timeit '(number*number for number in (1,2,3,4,5))' 1000000 loops, best of 3: 0.472 usec per loop На небольших объемах данных это может быть незаметно, однако если итерируемых значений много, то выгода становится заметной. *Под звездочкой я обозначу один момент. Если в кортеж положить список, то вы сможете его изменить: T = ([1,2,3], 4, 5, 6); T[0][0] = 10; print(T[0][0]) #выведет 10 Тут вы меняете список внутри кортежа, но не сам кортеж. При этом вы не сможете удалить первый (нулевой) элемент кортежа или заменить его на другой тип данных. Это имеет ряд преимуществ, когда вам необходима конкретная структура данных (неизменяемая), с заданным набором элементов, но при этом некоторые объекты внутри кортежа могут меняться в процессе работы (напр., список).
{ "pile_set_name": "StackExchange" }