text
stringlengths
64
89.7k
meta
dict
Q: implement SQL indexing I am working on the backend of an mobile application. I have created the table structure for the app. How can I implement index for the created tables? I know there are two types of indexing in SQL. Clustered and Non clustered. My concern is What type of index should I provide for my tables? What all are the columns should be indexed? Do I need to apply indexing for “unique identifier” type columns? Do I need to apply indexing for primary key columns? How can I evaluate indexing performance? any help would be greatly appreciated A: I would always recommend putting a clustered index on your tables - it just makes everything faster (see Kimberly Tripp's blog post on this ). A good clustered index is: narrow unique stable ever-increasing and so a column like ID INT IDENTITY is perfect that way (again: See Kimberly Tripp's blog post on WHY those properties are vitally important to a clustering index ). Next, I would put a non-clustered index on any foreign key columns. That speeds up JOINs and other operations relating to referential integrity. Then STOP - let your app run, observe, measure performance. How does it behave? Take profile log to see what queries are executed and which of those are overly heavy on I/O and/or CPU time. Then go about and optimize those queries - maybe adding an index here and there to speed up one or two queries. Then observe and measure again - repeat ad infinitum. To learn a lot more - go read Kimberly Tripp's blog and watch videos of her presentations at conferences - she's the Queen of Indexing for SQL Server and her knowledge and insights are vast and priceless. Read her stuff, reflect - use it.
{ "pile_set_name": "StackExchange" }
Q: Differential and Linear trail propagation in Noekeon In the Noekeon Cipher Specification they write the following : The propagation through Lambda is denoted by $(a \rightarrow A)$, also called a step. Because of the linearity of Lambda it is fully deterministic: both for LC and DC patterns, we have: $A = \operatorname{Lambda}(a)$. The fact that the relation is the same for LC and DC is thanks to the fact that the Lambda is an orthogonal function. If represented in a matrix, its inverse is its transpose. I'm having a hard time understanding why the orthogonality of Lambda affects the relation with regards to selection patterns (LC). Why does the orthogonality of Lambda make it so that the relationship is the same as for DC ? How would the selection pattern propagate through the linear layer if Lambda was not orthogonal ? A: This is due to the duality between linear and differential trails. Let $L$ be an invertible linear map on $\mathbb{F}_2^n$, think of it as a matrix for convenience. In general, a nonzero differential $\Delta_1 \to \Delta_2$ over $L$ must satisfy $$\Delta_2 = L\,\Delta_1.$$ A nonzero linear approximation $u_1 \to u_2$, however, must satisfy $$u_2 = L^{-\top}\,u_1$$ An elementary way to see this is to observe that $u_1^\top x = u_2^\top (Lx)$ is equivalent to $u_1^\top x = (L^\top\,u_2)^\top x$. This holds for all $x \in \mathbb{F}_2^n$ whenever $u_2 = L^{-\top}\,u_1$, and otherwise for half (some hyperplane) the $x$. If $L$ is orthogonal, then $L^{-T} = L$. So then we have both $\Delta_2 = L\Delta_1$ and $u_2 = L u_1$.
{ "pile_set_name": "StackExchange" }
Q: PHP - Illegal offset type, after is_array and is_object I have this method: public function setVariable($variable, $value = null) { $variables = json_decode($this->variables); if(is_array($variable) || is_object($variable)) foreach($variable as $key => $value) if(in_array($key, $this->variableNames)) $variables[$key] = $value; else $variables[$variable] = $value; $this->variables = json_encode($variables); $this->save(); } But, if I call the method like this: setVariable(['test' => 'test', 'bla' => 'bla']) It return this error: ErrorException in User.php line 60: Illegal offset type Line 60 is this line: $variables[$variable] = $value; But, why it return the error? I check if $variable is array or object, But it continues return this error. Why? A: This code if(is_array($variable) || is_object($variable)) foreach($variable as $key => $value) if(in_array($key, $this->variableNames)) $variables[$key] = $value; else $variables[$variable] = $value; for php is the same as: if(is_array($variable) || is_object($variable)) { foreach($variable as $key => $value) { if(in_array($key, $this->variableNames)) $variables[$key] = $value; else $variables[$variable] = $value; } } See the difference? That's why use {} to show what you really need: if (is_array($variable) || is_object($variable)) { foreach($variable as $key => $value) { if(in_array($key, $this->variableNames)) { $variables[$key] = $value; } } } else { $variables[$variable] = $value; } Also be aware (thanks to @FirstOne) that foreach over stdClass object (when $variable is object) is invalid operation and will raise error.
{ "pile_set_name": "StackExchange" }
Q: Using the same Scanner in java Can I use the Scanner to read from the user to enter a certain input, and then, create a new instance of it to read from a file for example? Scanner sc = new Scanner(System.in); System.out.print("Enter the file name: "); String fileName = sc.next(); sc = new Scanner(fileName); displayAll(sc); //a static void method that takes the Scanner object as a parameter and is supposed to read and display the input stored in the .txt file A: Well, you need to use a File: Scanner sc = new Scanner(System.in); System.out.print("Enter the file name: "); String fileName = sc.next(); sc = new Scanner(new File(fileName)); It would be safer to try-catch not-existing file. You can use if-else. Well... logic is up to you. Maybe something like that: Scanner sc = new Scanner(System.in); while (true) { System.out.println("Enter file name"); String filename = sc.next(); if (!filename.startsWith("sth")) { //this will reask if the file name doesn't start with "sth" continue; try { Scanner s = sc; //just in case you never gonna use System.in sc = new Scanner(new File(filename)); s.close(); //just in case you're sure you never gonna use System.in break; } catch (Exception e) { System.out.println("Wrong filename - try again"); } } Obviously, you can change the if condition to whatever you like. I just wanted to give you a wider perspective. You can switch to equals if you wish ofc.
{ "pile_set_name": "StackExchange" }
Q: How to Publish Checked-In changes only in Team Foundation Server 2013 to SQL Server? I would like to ask you how to publish checked-in changes only in Team Foundation Server 2013 to SQL Server? It's a new installation of TFS 2013 - installed by me. Currently when I create new object like table as a part of the project and don't do check-in on this table and next publish the project, such table is published anyway. I was thinking that only checked-in (approved) changes are published to SQL Server (without objects which has no approval). It's important because I want publish only complete objects to the SQL Server. Without objects which are still in development. A: If you want to publish only checked in changes while you have uncommitted development, don't use your development workspace for publishing. Instead, create a separate workspace for that purpose. Perform a get latest in the publishing workspace so that it includes only the latest checked in objects and then publish from there. A separate build box is often used for this purpose in larger development environments. EDIT: A new workspace for publishing can be created using TFS Source Control Explorer. Select "Workspaces..." from the Workspace drop down and click add. In the working folder mapping dialog, provide a mnemonic workspace name, specify the same source control folder you use for development but specify a new empty local folder. Click yes when prompted to get the latest from source control. This new workspace will contain only the latest checked-in objects. These development and publishing workspaces share the same source control path but are independent due to the different local folders and files. Be mindful to make changes only in the development workspace (and get latest to see other team members checked-in changes) and use only get latest to update the deployment workspace.
{ "pile_set_name": "StackExchange" }
Q: SVN and RTC Integration I have a requirement integrate RTC(Jazz) and SVN(Subversion) inorder to link the svn commits to RTC workitems. Please share the process to be followed. A: You can link the work items to the Subversion commit by following the procedure mentioned in the official documentation here: https://www.ibm.com/support/knowledgecenter/SSYMRC_7.0.1/com.ibm.team.scm.svn.doc/topics/t_link_workitems.html This works and currently using the same.
{ "pile_set_name": "StackExchange" }
Q: ResponsiveSlides.js slideshow not being called I am trying to add a responsiveSlides.js slideshow to a website I am working on (here), but the method doesn't seem to be being called. I'm guessing it is just a syntax error, but I can't for the life of me find it. In the head of the site, I have <link rel="stylesheet" type="text/css" href="{stylesheet=home/responsiveslides}" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://stonewatercc.com/js/responsiveslides.min.js"></script> <script type="text/javascript"> $(function () { $('#slider1').responsiveSlides(); }); </script> and the code containing the images for the slideshow (in the body) is <ul class="rslides" id="slider1"> <li><img src="{site_url}images/stonewatercc/slider/stonewater_pics01.jpg" alt=""></li> <li><img src="{site_url}images/stonewatercc/slider/stonewater_pics02.jpg" alt=""></li> <li><img src="{site_url}images/stonewatercc/slider/stonewater_pics03.jpg" alt=""></li> </ul> I can put an alert before the line '$('slider1').responsiveSlides();', but if I put it after that line, it doesn't get called. I can type either url into the browser to get to the respective .js files. I would really appreciate help with this since it is driving me mad knowing that it is probably something quite simple that I am just missing... A: When you call it, you should use this: (function ($) { $('#slider1').responsiveSlides(); }(jQuery)); This namespaces jQuery to this particular function, which will ensure you don't have any conflicting libraries, such as Prototype which I see is loaded. To help with trouble shooting an issue of this nature you should first make sure you have jQuery by typing jQuery in your console. In the case of your site, it is there: Next, try to get the object from the console: $('#slider1'). In doing so, you can see that it returns null: Obviously there is something wrong because we can see id="slider1" by viewing source. The final step I took was to make sure it was correct (I have never seen it $(function()...), so I typed directly into the console: (function($) { $('#slider1').responsiveSlides() }(jQuery)) and voila, your slideshow started.
{ "pile_set_name": "StackExchange" }
Q: How secure are iPhone/Android/Windows 8 "PIN"/Pattern Lock features? Most modern (and tablet-oriented) operating systems now offer alternative ways of logging on other than a strong password. For example, iPhones offer a 4-digit PIN, Android devices offer this and a 'Pattern Lock', and Windows 8 devices offer the 'Picture Lock' in addition. Obviously, these passwords are not terribly secure, and so (as with bank cards) some sort of lock-out applies. For iPhones, you get dramatically increasing delays, and for Windows, the PIN option is taken away leaving only the password entry option. What is not clear to me is how these methods actually get enforced. What stops someone from attacking the system outside of the operating system? Or (at the very 'worst'), simply taking a copy of the storage and reloading the image onto the original device repeatedly? It's my understanding that even having Bitlocker on a Windows system wouldn't protect against the latter... or am I wrong and there is something clever with the TPM chip going on? Also, as a semi-related question: Windows obviously encrypts credentials (such as those in Credential Manager) against the logon password. But since a PIN can bypass the logon password, does this mean the logon password is weakly encrypted somewhere (against the 4-digit PIN)? Thanks, Chris A: You are missing the point of the lockscreens of the various mobile operating systems. They are not an effective deterrent for attackers who has stolen your phone and has an unlimited period of time to attack it. However, they are effective in deterring chance attackers who happens to walk by and only has a short period of access to your phone. A: Some mobile devices provide on device encryption to protect them, tied to the passcode/password that the user enters. When tied to a device wipe after a certain (small) number of incorrect attempts, they can provide an effective mechanism to protect the data held on the device in a "lost/stolen device" scenario. To take iOS devices as an example, you can't easily bypass this kind of protection without the ability to get access to the device storage before the device boots, or by dis-assembling the device to remove it's storage and then crack the crytpto on the device. Now using a 4-digit passcode or pattern lock reduces the protection provided considerably as it raises the possibility that an attacker will be able to guess the credential before the lockout occurs. for passcodes the fact is that most users do not choose random numbers but instead base it on dates (e.g. year of birth) which increases an attackers chances of getting the right code in the attempts available. For pattern lock there has been research showing that the pattern is visible on the screen in the grease from fingerprints, unless the screen is well cleaned at all times. So if you use a decent password and have the device wipe after a number of incorrect attempts, I'd say that the security is reasonable unless the attacker has an exploit for the platform which allows him to get access to the device storage before it's booted..
{ "pile_set_name": "StackExchange" }
Q: special characters in Java I have a form (struts 1) that is being validated and during the validation I have been asked to remove MS Word's curly single and double quote marks. Seems like such a simple request and I am tearing my hair out over it. My test text is ’ “ ”. First of all, I found that when I run my code in the debugger and watch what IntelliJ thinks the values are, it displays â\u0080\u0099 â\u0080\u009C â\u0080\u009D and it seems that â\u0080 are nonprinting characters. I used a piece of code that iterates over a StringBuilder of the text in the field and tests each char in the text. It replaces or deletes some chars, as below: switch (origCharAsInt) { case ((int)'\u00C2'): sbOriginal.deleteCharAt(isb); break; // weird Word A with the caret over it case ((int)'\u00C3'): sbOriginal.deleteCharAt(isb); break; // weird Word A with the tilde over it case ((int)'\u00E2'): sbOriginal.deleteCharAt(isb); break; // weird Word a with the caret over it case ((int)'\u0099'): sbOriginal.setCharAt(isb, '\''); break; // Word single quote case ((int)'\u009C'): sbOriginal.setCharAt(isb, '"'); break; // Word left double quote case ((int)'\u009D'): sbOriginal.setCharAt(isb, '"'); break; // Word right double quote case ((int)'\u2018'): sbOriginal.setCharAt(isb, '\''); break; // left single quote case ((int)'\u2019'): sbOriginal.setCharAt(isb, '\''); break; // right single quote case ((int)'\u201A'): sbOriginal.setCharAt(isb, '\''); break; // lower quotation mark case ((int)'\u201C'): sbOriginal.setCharAt(isb, '"'); break; // left double quote case ((int)'\u201D'): sbOriginal.setCharAt(isb, '"'); break; // right double quote case ((int)'\u201E'): sbOriginal.setCharAt(isb, '"'); break; // double low quotation mark case ((int)'\u2039'): sbOriginal.setCharAt(isb, '\''); break; // Single Left-Pointing Quotation Mark case ((int)'\u203A'): sbOriginal.setCharAt(isb, '\''); break; // Single right-Pointing Quotation Mark default: break; } This seems to work, in that it replaces some of the more egregious cruft, and the form now appears to contain ' " ". If I then save again, though, the IntelliJ thinks the field contains Â\u0080 Â\u0080\" Â\u0080\". So I added a few more cases to remove those  characters. But I'm flummoxed by the persistence of the \u0080 characters. I tried adding in a few more cases to try to remove them, but they did not work. case ((int)'\u0080'): sbOriginal.deleteCharAt(isb); break; // another weird Word non-printing char case ((int)'\u0082'): sbOriginal.deleteCharAt(isb); break; // another weird Word non-printing char case ((int)'\u0083'): sbOriginal.deleteCharAt(isb); break; // another weird Word non-printing char case ((int)'\u0000'): sbOriginal.deleteCharAt(isb); break; // why are these weird symbols showing up? Any help/explanation would be greatly appreciated. A: You need to escape HTML properly. Unicode isn't the answer here. This link is your jam.
{ "pile_set_name": "StackExchange" }
Q: Is there a meaningful difference between biased and unbiased composition? In higher category theory, there are notions of biased and unbiased definitions of composition of $n$-morphisms (or, as a special case, tensor products of objects). In the biased framework, we define what it means to have a $2$-fold composition of $n$-morphisms as well as the $0$-fold composition (i.e., the identity $n$-morphism), and then we add in some sort of coherent associativity relating the various ways of composing $k$ $n$-morphisms for all $k$. In the unbiased framework, we define, for all $k$, the notion of a $k$-fold composition of morphisms, and then give compatible isomorphisms between a $k$-fold composition and the various composites of smaller-fold compositions. The traditional definitions of mathematics lean strongly towards the biased framework. Perhaps the simplest example is a group (or monoid), which is usally defined as having a binary operation ($2$-fold product) and identity ($0$-fold product), with the condition that $(xy)z = x(yz)$. Of course, this definition is easier to write out than an unbiased one. In the unbiased world, we would define a group to have a $k$-fold product for all $k$ and then say that for any $k_1, k_2, \ldots, k_r \in \mathbb{N}$ such that $\sum_{i = 1}^r k_i = k$, and any $x_{11}, \ldots, x_{1k_1}, x_{21}, \ldots, x_{2k_2}, \ldots, x_{r1}, \ldots, x_{rk_r}$, the $k$-fold product of the $x_{ij}$ is equal to the $r$-fold product of the $k_i$-fold products of the $x_{ij}$. However, the relative simplicity of biased definitions seems to vanish as one moves up the $n$-categorical ladder, as more and more complicated coherence axioms are required for fully weak notions of composition of $n$-morphisms. It seems that in many cases, an unbiased definition feels more natural. For instance, when defining tensor products of modules, we use a universal property, and this universal property definition works just as well for any number of modules as it does for two. Moreover, the universal property immediately provides the relevant maps from the $k$-fold tensor product to composites of smaller-fold tensor products, whereas I'm not sure of an obvious direct way to give an isomorphism $(X \otimes Y) \otimes Z \to X \otimes (Y \otimes Z)$ without using elements or at least implicitly going through the three-fold tensor product. Ross Street, in his review of Leinster's Higher Operads, Higher Categories (which is a good reference for biased and unbiased definitions), seems to imply that the difference between unbiased and biased notions is more technical than foundational. Is this the case, or are some concepts of tensor product or morphism really more suited to a biased or an unbiased interpretation? It seems, for instance, that the theory of Lie algebras of Lie groups is rather firmly planted in a biased definition of group, as it relates to the failure of $2$-fold products to commute. Is there a formulation of Lie algebras that is unbiased? Do biased or unbiased definitions better lend themselves to categorification? EDIT: I should probably clarify what I mean by technical vs. foundational. I imagine any biased gadget should be equivalent to an unbiased one and vice versa, so I'm not envisaging the creation of new types of objects by taking an unbiased viewpoint. Rather, I'm asking if the unbiased viewpoint can provide fundamental insights that the biased viewpoint cannot (or vice versa). An example of such a foundational reformulation would be the use of the functor of points in algebraic geometry. That you can view schemes in terms of their functors of points is a triviality, but this change of reference frame is more than a technical convenience; in fact, it buys us a great deal. For instance, it leads to the theory of algebraic stacks. It might have been possible for algebraic stacks to have been developed in the absence of the functor of points, but I imagine that it would have taken much longer and would be less elegant and more inaccessible. So my overarching question is, might viewing composition in one way or the other be more than just a technical convenience? A: As you probably know, I definitely agree that the difference is technical rather than foundational. That said, the technicalities can be formidable. There is an initial hurdle to get over in starting out with unbiased things, in that you have to have infinitely many operations and axioms, but once you're past that, I agree that the operations and axioms are usually much more natural and proofs happen much more easily. My favorite example is that while it's true that biased and unbiased monoidal categories are equivalent, the proof of that requires essentially the entire strength of Mac Lane's coherence theorem! The coherence theorem for unbiased monoidal categories can be shown via 2-categorical abstract nonsense about 2-monads; basically all the difficulty comes from insisting on a biased definition. I also think that unbiased definitions often lead to more natural categorifications. For instance, Leinster's unbiased notion of "contractible globular operad" fits nicely into a language of weak factorization systems, while I'm not sure if the same is true of Batanin's original biased version. There is certainly an unbiased definition of Lie algebra, since Lie algebras are the algebras for an operad. Whether that unbiased definition admits a nice presentation in terms of n-ary operations, I don't know. A: Certainly unbiased definitions are the norm in modern homotopy theory. I guess an example of a biased definition is the (original?) definition by Stasheff of an $A_\infty$ space—the homotopy theorist's monoid. (For simplicity, I'll ignore matters related to the unit.) Informally, it consists of a space $X$, a multiplication $\mu : X \times X \to X$, a homotopy $\alpha$ between the maps $\mu(\mu(x,y),z)$ and $\mu(x,\mu(y,z))$ from $X \times X \times X$ to $X$, a "pentagonator" $\pi$ which extends a map $S^1 \times X^4 \to X$ built from $\mu$ and $\alpha$ to $D^2 \times X^4$, and so on. This seems to be the appropriate generalization of your biased definition of monoids to the situation where we need infinitely many higher coherence homotopies. More precisely, an $A_\infty$ space under this definition consists of a space $X$ together with maps $\mu_n : A_n \times X^n \to X$, where $A_n$ is the $n$th associahedron—a certain convex polyhedron in $\mathbb{R}^{n-2}$—and on the boundary of $A_n$, $\mu_n$ is required to be equal to a certain expression built out of the $\mu_k$ for $k$ smaller than $n$. Thus, we may think of it as a null-homotopy of a prescribed map $\partial A_n \times X^n \to X$. This definition is quite complicated combinatorially, since it depends on the polyhedra $A_n$. Peter May realized that certain features of the $A_n$ could be abstracted into the notion of a (non-symmetric) operad. I don't want to define exactly what an operad is, but instead just observe the change in perspective: rather than thinking of $A_n$ as a space which encodes a null-homotopy of a map defined on its boundary, we think of the points of $A_n$ as describing various $n$-ary multiplications on $X$ via the map $\mu_n : A_n \to \mathrm{Map}(X^n, X)$. The contractibility of $A_n$ guarantees that there is essentially just one way to multiply $n$-tuples. So we see that the same definition can be viewed as either biased or unbiased. However, in the world of operads, we are free to consider algebras over any operad whose $n$th space is contractible for all $n$, and any such space is an $A_\infty$ algebra. This definition no longer has the combinatorial complexity of the associahedra, although operads require a certain amount of machinery. I would call it an unbiased definition. From this point of view, the biased definition consists of giving a certain kind of homotopical presentation of the terminal operad, which is a useful thing to have, but quite unnecessary from the point of view of giving a definition! Since homotopy theory is "just the easy part of ∞-category theory", I expect that as higher-categorical structures become more commonplace, we will see a similar phenomenon: the easy definitions to write down and work with abstractly are the unbiased ones, and biased definitions are certain presentations of the unbiased notions, which might become quite complicated as the categorical level increases.
{ "pile_set_name": "StackExchange" }
Q: How to create my custom tslint rule set? I want to introduce a typescript coding guideline that can be shared accross multiple projects. I don't want to copy paste a tslint.json over multiple times, it has happened currently and we have diverged version of it going around. I want to base my guideline on tslint:recommended. And I see that the tslint syntax allows for extend, yet I am unclear about its usage and how to structure such a package. Can such a project consists of merely a tslint.json itself or do I need to export a module? I want the package to then be hosted on npm/sinopia instance, yet am unsure how to proceed. A: Yes. You can create an NPM module that contains your rule set and can reference that in a tslint.json file's extends setting. For example, you can create an NPM module named my-rule-set with this package.json: { "name": "my-rule-set", "version": "0.0.0", "main": "my-rule-set.json" } and this my-rule-set.json (note that the main in the package.json references the my-rule-set.json file): { "extends": "tslint:recommended", "rules": { ... } } Then, with my-rule-set installed in node_modules, you can extend a tslint.json file with your own rule set: { "extends": "my-rule-set" } There is more information on sharable configurations in this TSLint blog post. If your rule set contains only configurations of existing rules, that's all you need to do. However, if you intend to implement some custom rules, in my-rule-set.json you'll need to link to the directory where your custom rules are. So for example, it should also have something like: "rulesDirectory": "./rules". Then the ./rules directory should contain the compiled .js versions of your rules.
{ "pile_set_name": "StackExchange" }
Q: Is a short stay visa required for collecting boarding pass if office is located outside international zone? Source: LA Airport (USA) Destination: Bangalore (India) Stop: Paris (CDG airport) Type of flight: Non-Connecting ( Two different tickets) Travelling Document: Indian Passport Currently Holding Visa: US F1 (Student) Baggage: Only cabin baggage, No Check-In baggage, so I won't have to collect any baggage at the CDG Airport Time Difference between flight: 6 Hours When departing from US, I will only have a single boarding pass. So I need to collect my boarding pass from the airways office (Air India, Not sure about its location on the airport, whether in International/Outside) Ticket: 2 separate tickets with different e ticket nos. And separate PNRs I've tried contacting French Embassy, Indian Embassy, their twitter handles, multiple times, but to I haven't gotten a clear response, and this has made me more doubtful about the action to take. French Embassy: French embassy says I won't require a visa if I don't leave international zone of Paris airport, otherwise I would require a short stay visa Paris Airport: Paris airport says that to check in to my departure i.e. air india flight (which is on a separate terminal than my arrival Norwegian Airways flight), I would have to leave the international zone to collect my boarding pass for air india and hence would require a transit visa A travel agent: As the Air India office in Paris Airport is outside the International Zone, you will need a Short Stay Visa. Internet: From July 2018, Indians do not require transit visa in france In my condition, there is no valid purpose of stay for short stay visa according to France visas website Also Is there any other way to legally obtain my boarding pass without short stay, iff it is required ? I could not find any help on other forums, hence looking for an answer here. I have 15 days before I travel, and so will have to try best to get Visa, if required, as returns tickets are also booked. EDIT: In the ticket booked from kiwi.com, It is mentioned that online check-in is not available for this, so I will have to manually collect. A: To answer the updated question title: If you do need to exit the international zone (airside), then you need a visa. Not an airport transit visa, but a regular one. If you can stay airside, then Indian citizens no longer require an airport transit visa (they used to need one even if they stayed airside, though there were exceptions). To stay airside, you would need to: not have any checked luggage (which you stated is the case) be able to either do online check-in, or to reach a transfer desk which can issue the boarding pass for you. Air India has a transfer desk in CDG, however it is unclear where it is located, and its hours are restrictive. You should contact Air India for details. Note that you would also have the issue of being able to board the first flight: as far as they know, Norwegian considers your flight ends up in Paris, so they may not let you board without a visa valid for France. Even if they accept the evidence that you are in transit and will stay airside, they may not be up-to-date with the relatively recent drop of the airport transit visa requirement. The safest option is to get a visa. This will make sure you can do landside if you need to, and will satisfy Norwegian. If you do not get a visa (having verified that you can get the boarding pass for the next flight while staying airside), then arrive early at LAX, and have all relevant documentation readily available, but be prepared for possible trouble. In the worst case, Norwegian may flatly refuse to let you board, and there wouldn't be much you could do about it.
{ "pile_set_name": "StackExchange" }
Q: Insertion Sort in bash Can you please help me to understand why this piece of code is not working. I am meant to write insertion sort and apply it to the file to sort its elements. However, it even fails to print the k-th elements in the while construct. I am using Windows and working in Git Bash. j=0 for line in $(cat $1) do elements[$j]="$line" j=$((j+1)) done for i in $(seq "${#elements[@]}"); do key=${elements[i]} echo index: $i Key: $key k=$((i-1)) while [ $k -gt 0 ] && [ ${elements[k]} > $key ]; do echo ${elements[k]} $key elements[$((k+1))]=${elements[k]} k=$((k-1)) done elements[$((k+1))]=$key done The file I am reading as array elements is a .txt file with the following information: 3 1 2 3 2 A: You have a significant number of basic errors in your script. Before posting on StackOverflow, you will always want to use ShellCheck to fix all basic errors. While you generally do not use hand-written sorting routines in shell programming (utilities like sort are used), for a learning exercise there is nothing wrong with doing so. As mentioned in the comments, to fill an array from the lines of an input file, use readarray or use mapfile (both are equivalent). For example if providing the filename as the first argument to your script, you can fill array from the filename given (or read from stdin by default) using: infile="${1:-/dev/stdin}" ## set filename or read from stdin [ -r "$infile" ] || { ## validate file readable printf "error: invalid filename.\n" >&2 exit 1 } readarray -t array < "$infile" ## readarray from file By using $(seq "${#elements[@]}") you are creating an indexing nightmare. In bash valid array indexes are from 0 -> n-1, however by using $(seq "${#elements[@]}") you are providing numbers 1 -> n (which you will have to subtract 1 from to map to valid indexes. Instead you are better served by using a C-style for loop and staying with indexes from the array itself with, for example: for ((i = 0; i < ${#elements[@]}; i++)); do ... done Next, as noted above in the comments your attempted comparison with [ ${elements[k]} > $key ] fails because within [ ... ] the > operates as a redirection instead of a comparison. If you are using the arithmetic operator ((....)) for the test, then > provides the greater-than comparison. Finally, if you are going to the trouble of writing an insertion sort for an array in bash, you may as well make it a function so it is reusable. The only caveat there is bash doesn't provide a direct mechanism for passing an array to a function. (which is another reason you generally do not find hand-rolled sorting functions in bash) You can however, for the purpose of this learning exercise, expand the array (e.g. "${elements[@]}" ) and then capture the elements in a local array within the function for sorting and then output the elements for reading back into the original array. For example, you could write an inssort() function taking advantage of that similar to: ## inssort() expects expanded array as positional parameters # outputs sorted array to stdout inssort() { [ $# -gt 1 ] || { ## validate at least 2 arguments given printf "error: cannot sort single value.\n" >&2 return 1 } local arr=( "$@" ) ## local array to insert values in sort order local n=${#arr[@]} ## local values to use in sort local i=0 local j=0 local tmp=0 ## insertion sort arr for ((i = 0; i < n; i++)); do for ((j = i-1; j >= 0; j--)); do if (( ${arr[j]} > ${arr[$((j+1))]} )); then tmp=${arr[j]} arr[j]=${arr[$((j+1))]} arr[$((j+1))]=$tmp else break fi done done echo "${arr[@]}" ## output sorted array } An then back in your script your could call and capture the results similar to: array=( $(inssort "${array[@]}") ) ## insertion sort array I can't impress on you enough, for sorting in an actual shell script, rely on the utilities that have been written to handle sorting, like sort. But for completion of this example, you could put your script together similar to the following: #!/bin/bash ## inssort() expects expanded array as positional parameters # outputs sorted array to stdout inssort() { [ $# -gt 1 ] || { ## validate at least 2 arguments given printf "error: cannot sort single value.\n" >&2 return 1 } local arr=( "$@" ) ## local array to insert values in sort order local n=${#arr[@]} ## local values to use in sort local i=0 local j=0 local tmp=0 ## insertion sort arr for ((i = 0; i < n; i++)); do for ((j = i-1; j >= 0; j--)); do if (( ${arr[j]} > ${arr[$((j+1))]} )); then tmp=${arr[j]} arr[j]=${arr[$((j+1))]} arr[$((j+1))]=$tmp else break fi done done echo "${arr[@]}" ## output sorted array } infile="${1:-/dev/stdin}" ## set filename or read from stdin [ -r "$infile" ] || { ## validate file readable printf "error: invalid filename.\n" >&2 exit 1 } readarray -t array < "$infile" ## readarray from file echo "array : ${array[*]}" ## output original array array=( $(inssort "${array[@]}") ) ## insertion sort array echo "sorted : ${array[*]}" ## output sorted array Then you can either pass input to the script on stdin or provide a filename to read the array elements from, e.g. Example Input File $ cat dat/20int.txt 91 -72 5 -33 -60 -54 95 13 62 1 70 -3 68 -99 89 77 100 8 31 -43 Example Use/Output $ bash inssortarr.sh dat/20int.txt array : 91 -72 5 -33 -60 -54 95 13 62 1 70 -3 68 -99 89 77 100 8 31 -43 sorted : -99 -72 -60 -54 -43 -33 -3 1 5 8 13 31 62 68 70 77 89 91 95 100 Look things over and let me know if you have questions, then after you have finished your exercise, rely on the shell utility sort to handle your sorting needs. It will be much faster and much less error-prone...
{ "pile_set_name": "StackExchange" }
Q: Regular expression to match a dot Was wondering what the best way is to match "test.this" from "blah blah blah [email protected] blah blah" is? Using Python. I've tried re.split(r"\b\w.\w@") A: A . in regex is a metacharacter, it is used to match any character. To match a literal dot, you need to escape it, so \. A: In your regex you need to escape the dot "\." or use it inside a character class "[.]", as it is a meta-character in regex, which matches any character. Also, you need \w+ instead of \w to match one or more word characters. Now, if you want the test.this content, then split is not what you need. split will split your string around the test.this. For example: >>> re.split(r"\b\w+\.\w+@", s) ['blah blah blah ', 'gmail.com blah blah'] You can use re.findall: >>> re.findall(r'\w+[.]\w+(?=@)', s) # look ahead ['test.this'] >>> re.findall(r'(\w+[.]\w+)@', s) # capture group ['test.this'] A: "In the default mode, Dot (.) matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline." (python Doc) So, if you want to evaluate dot literaly, I think you should put it in square brackets: >>> p = re.compile(r'\b(\w+[.]\w+)') >>> resp = p.search("blah blah blah [email protected] blah blah") >>> resp.group() 'test.this'
{ "pile_set_name": "StackExchange" }
Q: What is sandboxing? I have read the Wikipedia article, but I am not really sure what it means, and how similar it is to version control. It would be helpful if somebody could explain in very simple terms what sandboxing is. A: A sandpit or sandbox is a low, wide container or shallow depression filled with sand in which children can play. Many homeowners with children build sandpits in their backyards because, unlike much playground equipment, they can be easily and cheaply constructed. A "sandpit" may also denote an open pit sand mine. Well, A software sandbox is no different than a sandbox built for a child to play. By providing a sandbox to a child we simulate the environment of real play ground (in other words an isolated environment) but with restrictions on what a child can do. Because we don't want child to get infected or we don't want him to cause trouble to others. :) What so ever the reason is, we just want to put restrictions on what child can do for Security Reasons. Now coming to our software sandbox, we let any software(child) to execute(play) but with some restrictions over what it (he) can do. We can feel safe & secure about what the executing software can do. You've seen & used Antivirus software. Right? It is also a kind of sandbox. It puts restrictions on what any program can do. When a malicious activity is detected, it stops and informs user that "this application is trying to access so & so resources. Do want to allow?". Download a program named sandboxie and you can get an hands on experience of a sandbox. Using this program you can run any program in controlled environment. The red arrows indicate changes flowing from a running program into your computer. The box labeled Hard disk (no sandbox) shows changes by a program running normally. The box labeled Hard disk (with sandbox) shows changes by a program running under Sandboxie. The animation illustrates that Sandboxie is able to intercept the changes and isolate them within a sandbox, depicted as a yellow rectangle. It also illustrates that grouping the changes together makes it easy to delete all of them at once. Now from a programmer's point of view, sandbox is restricting the API that is allowed to the application. In the antivirus example, we are limiting the system call (operating system API). Another example would be online coding arenas like topcoder. You submit a code (program) but it runs on the server. For the safety of the server, They should limit the level of access of API of the program. In other words, they need to create a sandbox and run your program inside it. If you have a proper sandox you can even run a virus infected file and stop all the malicious activity of the virus and see for yourself what it is trying to do. In fact, this will be the first step of an Antivirus researcher. A: This definition of sandboxing basically means having test environments (developer integration, quality assurance, stage, etc). These test environments mimic production, but they do not share any of the production resources. They have completely separate servers, queues, databases, and other resources. More commonly, I've seen sandboxing refer to something like a virtual machine -- isolating some running code on a machine so that it can't affect the base system. A: For a concrete example: suppose you have an application that deals with money transfers. In the production environment, real money is exchanged. In the sandboxed environment, everything runs exactly the same, but the money is virtual. It's for testing purposes. Paypal offers such a sandboxed environment, for example.
{ "pile_set_name": "StackExchange" }
Q: One view to do everything or a different view per page? If I need to display the last 10 nodes created on my front page regardless of content type and need to do the same in my sub-pages but need to filter by specific content type, is it easier to create several different views or to create one view that does all of that? If I need to create one view, how would I restrict different pages to specific content types? A: Personally, I create a view per content type and set up decent defaults and then have displays to handle the different uses. Special pages and other one offs (like the home page in your case) have specific views. I find this approach better handles changes that may come down the line.
{ "pile_set_name": "StackExchange" }
Q: Finding all permutations which satisfy given condition In a symmetric group $S_n$ find number of permutations $P$ such that in the disjoint cycle decomposition of $P$ , length of cycle containing $1$ is $k$ . Here's my attempt at this . I found number of cycles containing $1$ and of length $k$ as $\frac{(n-1)!}{(n-k)!}$. Rest of them can be permutated in $(n-k)!$ ways. So number of such permutations $P$ comes out to be $(n-1)!$. But I doubt my answer because it is independent of $k$. Please help me if I proceeded right or wrong! A: The solution is correct, the number of permutations with a fixed length of the cycle containing 1 is $(n-1)!$. The length may be any number between $1$ and $n$, i.e. $n$ choices, so the total number of permutations is $n\times (n-1)!=n!$, as expected. Because this $(n-1)!$ is independent of $k$, we may say that all the lengths of the cycle including $1$ are "equally likely" among the permutations.
{ "pile_set_name": "StackExchange" }
Q: JQGrid form edit close form Simple question: How can one close ajqgrid edit form? I close dialog boxes with the following: $("#submitDialog").dialog("close"); However, after inspecting the jqgrid form I'm having troubles finding the id to close. Here is the editGridRow call that I use to create the form (this is for adding a row, but the same applies to editing a row). jQuery("#myGrid").editGridRow( "new", { url:'addRow?type=' + gridForm.famousType, recreateForm:true, afterSubmit: function(responseData) { openDialog("#errorDialog", responseData.responseText); return [true, "true", 1]; }, errorTextFormat: function(serverresponse) { return serverresponse.responseText; }, beforeSubmit: function(postdata, formid) { if(validationFunction == null) { return [true, ""]; } return validationFunction.validate(postdata, formid); }, beforeShowForm: (gridForm.beforeShowFormAdd)?gridForm.beforeShowFormAdd.run:null //false or null? }); return false; My guess is this is easy, I just haven't seen anything that says how to do it, including on the jqgrid wiki. Ideas? A: It may not be the answer you're looking for, but since I couldn't find it myself I ended up using this workaround: jQuery('.ui-jqdialog-titlebar-close').click(); Which will click the X button of the dialog, closing it.
{ "pile_set_name": "StackExchange" }
Q: SQL:How sum each columns in oracle? select t.col1 a, t.col1+...+t.coln-1 b, t.col1+...+t.coln-1+t.coln c from table Can direct use b+t.col3? I can think of: with t1 as (select col1+...+coln-1 b from table) select t2.col1 a, t1.b, t1.b+t2.coln c from table t2 inner join t1 on t1.id=t2.id Is there another way to do this. A: I think you can also do it in this way . select a, b, b+col3 from ( select t.col1 a, t.col1+t.col2 b, t.col3 from t)
{ "pile_set_name": "StackExchange" }
Q: Windows phone 8 placeholder issue with Windows Phone Toolkit I'm developing a windows phone 8 app. I'm new to windows phone 8 development. I need to add placeholder for text box . I searched in Google & Stack Overflow i got one solution by using The windows phone Toolkit. I try with following Code. Step-1: Add Windows Phone Toolkit In Reference By Using Nuget gallery Step-2: Add namespace in page header xmlns:xtk="using:WinRTXamlToolkit.Controls" Step-3: My Textbox XAML code <TextBox Name="Usernametxt" Text="User Name"></TextBox> <TextBox Name="Passwordtxt" Text="Password"></TextBox> <TextBox Name="Emailtxt" Text="Eamail Address"></TextBox> Step-4: I add the following code under the Usernametxt box [I don't know it's correct or not] <xtk:WatermarkTextBox WatermarkText="some text" /> I got error in above line The Name WatermarkTextBox does not exist in namespace"using:WinRTXamlToolkit.controls" I got this solution Here I don't know how to use this property . I need to add placeholder for 4 to 5 textbox in same page. Help me to solve this problem. A: You are mixing up Windows Phone 8 and Windows 8. You need a reference to correct toolkit xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" And then you can <toolkit:PhoneTextBox Hint="some text" Name="Usernametxt" /> Make sure you can got the right Nuget package, more details here.
{ "pile_set_name": "StackExchange" }
Q: Rmove javaScript function from response API How to remove this function (adsbygoogle = window.adsbygoogle || []).push; from response from API as string. I used: contnt.Replace("\\(adsbygoogle = window.adsbygoogle || []).push\\", ""); Which is not working. Also: contnt = Regex.Replace(contnt,"\\\\(adsbygoogle = window.adsbygoogle || []).push;\\\\",""); Which is not working either. How can I remove that? A: you shouldn't need to escape any characters contnt = contnt.Replace("(adsbygoogle = window.adsbygoogle || []).push;", "");
{ "pile_set_name": "StackExchange" }
Q: Median of numbers stored in array Problem is to calculate median of numbers. My idea is : Fill array of integer with numbers using Arraymake() function copy the address into a pointer created in main() function pass that array to Median() function and calculate that median Code: #include <stdio.h> #include <stdlib.h> int* Arraymake(size_t);//Function for creating array of numbers. void Median(size_t ,int* );//Function for calculate the median. int main(int argc, char **argv) { size_t count;//Size of the list of numbers. puts("Size of the list:"); scanf("%Iu",&count); int *ArResult=Arraymake(count);//Result of the first function Median(count,ArResult); free(ArResult); return 0; } int* Arraymake(size_t ln) //ln~lenght { int* Array=(int*) malloc(ln*sizeof(int)); int number ,i; //numbers filling the array puts("Please input numbers.\n"); for(i=0;i<(ln);i++) { scanf("%i", &number); Array[i]=number; } return Array; } void Median(size_t ln,int* Array) { float median; if((ln)%2==0) { median= (Array[(ln)/2]+Array[(ln/2 )-1] )/2; printf("%f",median); } else { median= Array[((ln-1)/2)]; printf("%f",median); } } I want to find a way to optimize my variables and make my code more self-documented? How can I improve my code? A: 1. Arraymake: Change the name to MakeArray as it makes more sense or name it MakeArrayFromInput to make it more descriptive to what it actually does Name the parameter length, as in : int* MakeArray(size_t length) - this is descriptive and you don't have to put the comment explaining what it does Name local variables in camelCase, so array instead of Array Matter of preference but consider declaring array as int *array instead of int* array - you won't forget that the variable itself is a pointer and you have to declare additional pointers in the same statement with *s - int *array, *anotherPointer; int number ,i; //numbers filling the array - comment is redundant and you don't have to declare i here, you can do it in the for - speaking of which: for(i=0;i<(ln);i++) can become for(int i = 0; i < length; i++) - parentheses over ln are redundant, you should use better spacing to make it more readable. 2. Median: The same story with the parameter and naming, also pass the array first, then the length : void Median(int *array, size_t length) You don't have to declare the median variable before the if Parentheses in the if are redundant : if(length % 2 == 0) The calculation of the median in the case of an even number of elements is flawed - you do an integer division as both operands of / are ints - you'd have to make at least one of them a float e.g. like this median= (Array[(ln)/2]+Array[(ln/2 )-1] )/2.0; - see the 2.0 - this is a double literal, a floating-point number, not an int You can shorten the calculation a bit by changing array[(length - 1) / 2]; to array[length / 2]; in the case of an odd number - the integer division will truncate the result into what you need The function should do one thing - you're calculating the median and printing it in the same function. Consider making the function Median return the value of the median and print it somewhere else The function then should look more or less like this : float Median(int *array, size_t length) { if(length % 2 == 0) { float median = (array[length / 2] + array[length / 2 - 1]) / 2.0; return median; } else { float median = array[length / 2]; return median; //or just simply return array[length / 2]; } } Something more complex, the function can be greatly simplified by using the ternary operator ?: : float Median(int *array, size_t length) { return length % 2 == 0 ? (array[length / 2] + array[length / 2 - 1]) / 2.0 : array[length / 2]; } However, this is just trivia and you should aim to make your code as readable as possible 3. main I think that all of the comments are redundant here, everything is self-documenting Naming : ArResult should be something descriptive and simple - the most simple way would be to name it just array Spacing in function parameters e.g. scanf("%Iu", &count); instead of scanf("%Iu",&count); 4. General advice Work on the spacing - try to put spaces between operands and operators as in if(length % 2 == 0), in places like for loops : for(int i = 0; i < length; i++) and in function parameters : scanf("%Iu", &count); Put comments before the thing they're describing, not at the end of the line - this way if you want to make it a multi-line comment you won't have problems and it's more readable that way e.g. like this: //Function for creating array of numbers. int* MakeArray(size_t); //Function for calculating the median. int Median(int*, size_t); This is just an example - I think the function names are descriptive enough not to put comments there, they will clutter the view : int* MakeArray(size_t); int Median(int*, size_t); EDIT What I didn't initially remember is that to calculate the median, you have to use a sorted array. You should probably do that separately int *array = MakeArray(count); qsort(array, count, sizeof(int), compare) float result = Median(count, array); The qsort is a function from stdlib.h. You have to also declare a function compare to use in it e.g. int compare(const void* a, const void* b) { int int_a = *((int*) a); int int_b = *((int*) b); if(int_a == int_b) return 0; else if (int_a < int_b) return -1; else return 1; } This is taken from https://stackoverflow.com/a/3893967/7931009
{ "pile_set_name": "StackExchange" }
Q: why unexpected behaviour for conditional operator I have a piece of code like follows public class Test{ public static void main(String[] args) { System.out.println(true?false:true == true?false:true); ----------------------- } } The output is false. If you are using Eclipse you get a wavy (dashed here) line and warning like "Comparing identical expressions". Note the start of the wavy line. I changed the code to the following public class Test{ public static void main(String[] args) { System.out.println((true?false:true) == (true?false:true)); --------------------------------------- } } The output is true. If you are using Eclipse you get a wavy (dashed here) line and warning like "Comparing identical expressions". Note the start of the wavy line now. Why the difference? A: Because ternary operator (?:) has lower priority than equality operator (==). This means that: true?false:true == true?false:true is actually interpreted as: true?false:(true == true?false:true) This, in turns, is evaluated to: true?false:((true == true)?false:true) cont.: true?false:(true?false:true) ...and eventually: true?false:(false) and eventually: true?false:false And obviously this explains the output of the first code snippet. Eclipse correctly recognizes operator precedence and highlights possibly incorrect statement. UPDATE: Thanks for all the comments. In fact I forgot about operator precedence on the left side. I checked the exact behaviour using the program below: public static boolean a(char label, boolean result) { System.out.println(label); return result; } public static void main(String[] args) { System.out.println( a('a', true) ? a('b', false) : a('c', true) == a('d', true) ? a('e', false) : a('f', true) ); } The results are consistent with @Milad Naseri suggestion. A: In case your problem is the difference of outcomes, this is because of the order of precedence of the operators you use. Check here for details. According to that order of precedence: true ? false : true == true ? false : true is the same as this: true ? false : ((true == true) ? false : true) so it will always evaluate to false. You could put anything after the colon since it's never evaluated anyway (if I remember correctly and the ternary operator uses lazy evaluation); the reason for this is that true ? A : B always evaluates to A. On the other hand, (true ? false : true) == (true ? false : true) will have both sides of the comparison operator == evaluate to false, so false == false which is a true statement. So the difference here is the order in which the operators are evaluated, which is determined by the parentheses you use and, if there is ambiguity that isn't resolved by parentheses, by the order of precedence of the operators that are used. In general, the ternary operator "? :" works like this A ? B : C If A is true, evaluate to B, else evaluate to C. A has to be a boolean expression, B and C can be whatever you want; you'll have to deal with type mismatches though if you want to assign the evaluated value to a variable and they are of different types.
{ "pile_set_name": "StackExchange" }
Q: HTML table border only in middle I'm looking to make a table with a line right down the middle with CSS. No other borders aside from the center of the table. My table is 2x4 I tried to use the attached code but it adds lines on outside left and right table { border-collapse: collapse; } tr { border: none; } td { border-right: solid 1px #f00; border-left: solid 1px #f00; } <table> <tbody> <tr> <td>a</td> <td>a</td> </tr> <tr> <td>a</td> <td>a</td> </tr> <tr> <td>a</td> <td>a</td> </tr> <tr> <td>a</td> <td>a</td> </tr> </tbody> </table> A: You can change your td rule to use the first-child pseudo class like: td:first-child { border-right: solid 1px #f00; } Example: table { border-collapse: collapse; } tr { border: none; } td:first-child { border-right: solid 1px #f00; } <table> <tbody> <tr> <td>a</td> <td>a</td> </tr> <tr> <td>a</td> <td>a</td> </tr> <tr> <td>a</td> <td>a</td> </tr> <tr> <td>a</td> <td>a</td> </tr> </tbody> </table>
{ "pile_set_name": "StackExchange" }
Q: How to handle a question where a feature is now possible? In May I asked this question How to specify the location a MVC view will be created for a MVC controller? on SO. At the time the answer required a hack to be done since the feature was not supported in MVC 1. With the latest release of MVC 2 Preview the above feature is implemented as areas, and therefore it can now be done, and since the goal of SO is to keep information new and up to date I would like to update the question to reflect this. What would the correct procedure be to handle this scenario? Make the question a CW, and add the above as an answer? Add the above as an answer and make it the accepted answer? Ask the question specifying MVC 2 rather the just MVC? Edit the question and add the change with a link to MSDN for the new feature? I apologize if this has been asked before. I have to admit I could not come up with the right search terms to search for this A: If you have already accepted an answer, you could do the good community thing and edit their answer to reflect the changes. Otherwise you could create your own answer to your own question providing the new details and then after some point setting that as the new accepted answer. I don't think it would be a good idea to fracture off into another question just because it is a different version. As long as you make your original question pretty explicit in the answers (i.e. detailing that the new information is for Version 2) then you shouldn't have a problem.
{ "pile_set_name": "StackExchange" }
Q: How to find and replace a string in %PATH% system variable with variables in a batch file? I am trying to upgrade Java with a batch file, and I need to change the PATH system variable to reflect that change. At the beginning of the PATH variable I have C:\Program Files\Java\jdk1.8.0_51;... I need to change the jdk value to be jdk1.8.0_60. I'm relatively new to command line and batch files, and so I may be misunderstanding something. Here is what I am trying. I have a couple variables jVersion=1.8.0_ javaPath=C:\Program Files\Java newVersion=60 oldVersion=51 I found something about replacing strings with literal values like so set PATH=%PATH:1.8.0_51=1.8.0_60% but I can't get it to work with variables... set PATH=%%PATH:%jVersion%%oldVersion%=%jVersion%%newVersion%%% I don't know if you need 2 %'s around the outside, or just one, or !'s. I'm not super confident in my knowledge of delayed expansion. I also don't know if this is possible. As a bonus, I would really like to be able to take whatever comes after ...\Java\ and replace it with my new value. This would be just in case I don't know the value in the PATH variable for the jdk Thanks! EDIT: By using the command call before a modified version of my code I was able to get it to work call set PATH=%PATH:%jVersion%%oldVersion%=%jVersion%%newVersion%% I'm still trying to figure out how to make it generic and change whatever comes after ...\jdk to the values I have. A: paste the Below Code in a bat file and that should solve the problem @echo off setlocal EnableDelayedExpansion set jVersion=1.8.0_ set "javaPath=C:\Program Files\Java" set newVersion=60 set oldVersion=51 set PATH=%jVersion%%oldVersion% echo before path change : !PATH! set PATH=!PATH:%jVersion%%oldVersion%=%jVersion%%newVersion%! echo final path change : !PATH! pause
{ "pile_set_name": "StackExchange" }
Q: Nested loops or function application I have 2 sets of latitude/longitude coordinates, 4 arrays total. My goal was to find the distance between one group (airbnb_coord) and the closest member of the second group (station_coord). I've written an nested for loop to accomplish this shortest_distance = make_array() for air_lat, air_long in zip(airbnb_coord[0],airbnb_coord[1]): for stat_lat, stat_long in zip(station_coord[0],station_coord[1]): distances = make_array() distances = np.append(distances, np.sqrt(((air_lat-stat_lat)**2)+((air_long-stat_long)**2))) shortest_distance = np.append(shortest_distance, min(distances)) The problem is, airbnb_coord is 40,000 long, and station_coord is 500 long. This has been running for more than an hour now. Can someone tell me if there is a better way? I'm pretty weak at function application, but I'm sure there is a strategy that uses such. A: You can reduce the time significantly if you don't calculate the minimum in distances each iteration shortest_distance = make_array() for air_lat, air_long in zip(airbnb_coord[0],airbnb_coord[1]): min_distance = np.sqrt(((air_lat-station_coord[0][0])**2)+((air_long-station_coord[0][0])**2)) for stat_lat, stat_long in zip(station_coord[0], station_coord[1]): distance = np.sqrt(((air_lat-stat_lat)**2)+((air_long-stat_long)**2)) if distance < min_distance: min_distance = distance shortest_distance = np.append(shortest_distance, min_distance)
{ "pile_set_name": "StackExchange" }
Q: Dynamically nest key value in HashMap with object as value I have a requirement to nest a key-value in an existing key value pair of a HashMap. my current output as json is ... "x": { "y": yhyhy, "z": "zhzhz", "d": 123 } ... I want to add a new pair as follows: ... "x": { "y": yhyhy, "z": "zhzhz", "d": 123, "k": "khkhkh" } .. The issue with achieving this is : the hashmap prepared initially is by inserting an entire object as value (reposneObject is an immutableMap being used elsewhere) Map<Object, Object> responseMap = new HashMap<>(responseObject); responseMap.put("x", someObject); I do not want to separately insert each field of the someObject into the map (as the count can be huge) Is there any other way of doing it using maps or something? (dynamically adding a field in an object doesn't seem possible) A: Assuming someObject is a Map: Map<Object, Object> responseMap = new HashMap<>(responseObject); responseMap.put("x", someObject); responseMap.get("x").put("k": "khkhkh");
{ "pile_set_name": "StackExchange" }
Q: Arithmetic Progression Sum of Sequence The sum of the first 19 terms of an arithmetic progression is equal to twice of the value of 10th term. The value of 10th term will be? A: Hint: For an arithmetic sequence, we have $$u_1+\dots+u_{19}=19\,\dfrac{u_1+u_{19}}2=19\,u_{10}.$$ What can you conclude from the hypothesis?
{ "pile_set_name": "StackExchange" }
Q: Injecting a group into itself Let $G$ be a group with elements $g_1, g_2\in G$ and injective endomorphisms $\phi_1, \phi_2$ s.t. $\phi_1 (g_1)=g_2$ and $\phi_2(g_2)=g_1$. Does this imply there is an automorphism $\psi$ with $\psi(g_1)=g_2$. I expect the answer to be no but I'm unsuccessful producing a counter example. A: Let $S$ be the group of finitary permutations of $\mathbb{N}$ (i.e., permutations that fix all but finitely many elements of $\mathbb{N}$), and $A$ the subgroup of even permutations. Let $\sigma\in A$ be the $3$-cycle $(1,2,3)$. There is an injective homomorphism $\theta: S\to A$ with $\theta(\sigma)=\sigma$. [Take a permutation $\tau\in S$ to a permutation of $\mathbb{N}\setminus\{4,5\}$, multiplied by the $2$-cycle $(4,5)$ if $\tau$ is odd.] Let $G=S\times A$, and $\varphi:G\to G$ the injective homomorphism given by $\varphi(\tau_1,\tau_2)=\left(\tau_2,\theta(\tau_1)\right)$. Then $\varphi(\sigma,1)=(1,\sigma)$ and $\varphi(1,\sigma)=(\sigma,1)$. However, there is no automorphism of $G$ taking $(\sigma,1)$ to $(1,\sigma)$, since the quotient of $G$ by the normal subgroup generated by $(\sigma,1)$ is isomorphic to $C_2\times A$, whereas the quotient by the normal subgroup generated by $(1,\sigma)$ is isomorphic to $S$, and $C_2\times A\not\cong S$ (only one has non-trivial centre).
{ "pile_set_name": "StackExchange" }
Q: When is the subspace of functions vanishing on a closed set complemented? Suppose $A$ is a closed subset of a smooth manifold $M$. Denote by $C(M)$ continuous functions with uniform norm. When is the subspace of functions vanishing on $A$ complemented in $C(M)$? This is true if $A$ is a finite set of points (since then it's finite codimensional and closed) and if $A$ is a retraction of $M$. An easier question I don't know how to answer is whether continuous functions on the disk that vanish on the boundary are complemented in all continuous functions on the disk. Thanks in advance! A: In the special case of the disk (where the closed set is its boundary), it seems like you have a complement consisting of functions that are harmonic on the interior of the disk and extend continuously to the boundary. Indeed let $H(D)$ be the space of all such harmonic functions. Then $H(D)$ is a linear subspace because the sum of two functions which are harmonic on the interior is still harmonic on the interior; same story for scalar multiples. Also $H(D)$ is closed because any uniform limit of harmonic functions is harmonic. Let $S$ denote the subspace of functions vanishing on the boundary. Then $H(D)\cap S = \{0\}$ because any harmonic function vanishing on the boundary is zero, by the maximum principle for instance. Furthermore, any continuous function on the disk can be expressed as $f = \phi+(f-\phi)$, where $\phi$ solves the Laplace equation with boundary data $f|_{\partial D}$. Then clearly $\phi \in H(D)$ and $f-\phi \in S$. Edit: I added another answer generalizing this construction to all closed sets $A$. A: After doing some research, I found out that the answer is always yes: the subspace $S$ of functions vanishing on $A$ is always complemented in $C(M)$, whenever $M$ is any compact metric space and $A$ is any closed subset. To prove this, it is enough to show that there exists a family $\{\mu_x\}_{x\in M}$ of finite signed measures on $A$ with the following two properties: (i) $x \mapsto \mu_x$ is weakly continuous. (ii) $\mu_x=\delta_x$ for every $x \in A$, where $\delta_x$ is a point mass at $x$. Indeed, if such a family of measures exists, then we can define a map $T:C(A) \to C(M)$ by defining $Tf(x):=\int_A f(y)\mu_x(dy)$. Then the image of $T$ is easily checked to be a complement for $S$. Indeed, the image is closed because $\|Tf\|_{C(M)} \geq \|f\|_{C(A)}$ trivially. It trivially intersects $S$ because any $g=Tf \in S \cap T(C(A))$ satisfies $$f(x)=\int_A f(y) \delta_x(dy)=Tf(x)=g(x)=0 \;\;\;\;for \;\;\;\;x \in A.$$ And finally, $S+T(C(A))=C(M)$ because we can write any function $f\in C(M)$ as $(f-\phi)+\phi$ where $\phi = T(f|_A)$. Then clearly $f-\phi\in S$ and $\phi \in T(C(A))$. So let's prove that such a family of measures always exists for any closed subset $A$ of a compact metric space $M$. We are going to use a generalization of the Tietze extension theorem which holds whenever the target space is a locally convex topological vector space. Let $E$ be the space of all finite signed measures on $A$, i.e., $E=C(A)^*$. Equip $E$ with the weak topology, i.e., the topology generated by the family of seminorms $N_f(\mu) = |\mu(f)|$, with $f\in C(A)$. Define a map $u:A \to E$ by sending $x \mapsto \delta_x$. Obviously this is continuous. Therefore by the Tietze extension theorem, $u$ can be extended continuously to a map $v: M \to E$. Then set $\mu_x:=v(x)$.
{ "pile_set_name": "StackExchange" }
Q: Every time I create a new database it's creating a table in that database Every time I create a new database it's creating a table in that database. I'm finding information about model databases for Microsoft SQL Server, but I can't find anything for Postgres. A: You probably created that table in the template1 database. When you create a database, Postgres doesn't really create it from scratch, it copies an existing one. Quote from the manual By default, the new database will be created by cloning the standard system database template1. A different template can be specified by writing TEMPLATE name. Just connect to the template1 database and drop the table there.
{ "pile_set_name": "StackExchange" }
Q: WiFi direct: how often to call peer discovery? I am developing a P2P app and was following the tutorial HERE and while I was testing it on 2 phones I was wandering when do I have to initiate Peer Discovery? Only once when the app is started, periodically or every time in onResume? I'm asking because some times when I try to show the list of peers it can't find any. I would also like to know the cause of this AND what actualy is peer discovery and what is it doing. A: I start the discovery through listeners registered in the app every 'x' seconds and yes, you would want to initiate discovery onResume() as well. Also, I presume you are already leveraging broadcast intents to determine the state change. I can't however, clarify on the internals of P2P discovery but the discovery could fail because the network is busy or due to an internal error or simply because the device doesn't support P2P as mentioned here.
{ "pile_set_name": "StackExchange" }
Q: Container not going 100% height I am setting container to display: flex with the bootstrap 4 class d-flex but it is not going to 100% height. I want column to be 100% height so I can vertically center the contents. Here is code snippet: #recruitment-header { background-image: url(http://cdn01.androidauthority.net/wp-content/uploads/2015/11/00-best-backgrounds-and-wallpaper-apps-for-android.jpg); background-size: cover; min-height: 400px; background-repeat: no-repeat; background-position: center; color: #fff; } #recruitment-header .container, #recruitment-header .row { height: 100%; } #recruitment-header .slogan1 { font-size: 46px; } <link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css'> <div id="recruitment-header" class="d-flex"> <div class="container d-flex"> <div class="row d-flex"> <div class="col-12 d-flex flex-column justify-content-center"> <div class="slogan1">message one</div> <div class="slogan2">message two</div> </div> </div> </div> </div> Why is it not going to 100% height? A: Try adding the following #recruitment-header .container, #recruitment-header .row { flex-direction: column; flex: 1; }
{ "pile_set_name": "StackExchange" }
Q: New Relic showing data from my local development environment and not the Heroku environment So I have New Relic set up on my Rails app, which I run both locally for development and which I deploy to Heroku. However, the New Relic dashboard shows data from my local setup and not from Heroku. I know because the data I can see corresponds to what's happening on the local environment, and on the new relic dashboard the listed servers includes the hostname of my local machine. How do I make sure New Relic monitors the heroku environment instead? New Relic is setup in my app this way: 'newrelic_rpm" gem is included in the Gemfile config/newrelic.yml exist and has been downloaded from the New Relic setup page The license key in config/newrelic.yml is the one generated on the New Relic setup page The heroku environment variables NEW_RELIC_APP_NAME and NEW_RELIC_LICENSE_KEY. The first one is the same name as the Heroku app. The second one contains the same key as the config/newrelic.yml file. The heroku newrelic:stark addon is added to the heroku app A: As per comments, check to make sure you config/newrelic.yml file is monitoring a production application. Set all newrelic keys only on heroku, not on local app. You only need a reference to: NEW_RELIC_LICENSE_KEY in all places. That constant should have nothing to read locally, and only read the heroku configs in production. Replace any local license keys with license_key: '<%= ENV["NEW_RELIC_LICENSE_KEY"] %>' and turn development monitor_mode to false and production monitor_mode to true. All: read comments above for further details if this is unclear.
{ "pile_set_name": "StackExchange" }
Q: Adding multiple buttons in TinyMce in a loop doesn't work I have a config list for buttons like this: var config = [{ name: 'first', insertionConfig: { title: 'first button', onsubmit: function(){ // do sth } } },{ name: 'second', insertionConfig: { title: 'second button', onsubmit: function(){ // do sth } } } ] and in my TinyMce plugin I want to add all buttons according to their config. So it would end up like this: tinymce.PluginManager.add('myPlugin', function(editor, url) { for (var i in config) { item = config[i]; editor.addButton(item.name, { text: item.name, onclick: function() { editor.windowManager.open({ title: item.insertionConfig.title, onsubmit: item.insertionConfig.onsubmit } }; } }); but when I click on first button, it shows the second button's title. all configs of buttons refer to last added button. I know problem is something about the 'item' in the loop (all buttons refer to same item object which is the last one) but I don't know how to fix it. A: Try creating a locally scoped variable for item inside the onclick function: The issue you are running into is how variables are managed in JavaScript at the time the function is actually run. The click function is not actually run until you click an item and at that time item is pointing to the last item in the array. EDIT: Check out this TinyMCE Fiddle for how this may happen: http://fiddle.tinymce.com/REfaab/1
{ "pile_set_name": "StackExchange" }
Q: Converting and Formatting Time Zones I am dealing with my worst nightmare - timezones and DST. I already read a lot of posts on stackoverflow but I still cannot figure it out. Here is the problem: I am making an API request for what needs to be a UTC one day of data but the system I work with needs a request in a US/Pacific time. The documentation says: Time zone is supported for report range filtering, but all responses are returned in US Pacific time zone please adjust Daylight Savings Time end accordingly. API calls after DST starts should have -07:00 appended and after DST ends should have -08:00 appended 2018 Daylight Savings Time starts on Sunday March 11th 2018 at 2 AM. API calls prior to March 11th should have the following syntax: &start=2017-03-10T00:00:00-08:00&end=2017-03-10T23:59:59-08:00 API call for the actual day of Daylight Savings should have the following syntax: &start=2018-03-11T00:00:00-08:00&end=2017-03-11T23:59:59-07:00 Apart from the confusing 2017 and 2018 mixture, there is no actual parameter to specify the time zone you need but you have to adjust the data that is in the following format : 2018-03-11T00:00:00-08:00. To me it looks like a ISO format but I spent quite some time trying to get yyyy-MM-dd'T'HH:mm:ssXXX and not 'yyyy-MM-dd'T'HH:mm:ss.SSSXXX' and couldn't make this work. So I created the following workaround: def dst_calc(single_date): zone = pytz.timezone("US/Pacific") day = single_date.strftime("%Y-%m-%d") tdelta_1 = datetime.strptime('2:00:00', '%H:%M:%S') - datetime.strptime('1:00:00', '%H:%M:%S') tdelta_0 = datetime.strptime('1:00:00', '%H:%M:%S') - datetime.strptime('1:00:00', '%H:%M:%S') logger.info('check for DST') if zone.localize(datetime(single_date.year, single_date.month, single_date.day)).dst() == tdelta_1: logger.info('summertime') start = single_date.strftime("%Y-%m-%d") + "T00:00:00-07:00" end = single_date.strftime("%Y-%m-%d") + "T23:59:59-07:00" elif zone.localize(datetime(single_date.year, single_date.month, single_date.day) + timedelta(days=1)).dst() == tdelta_1: logger.info('beginning of summertime') start = single_date.strftime("%Y-%m-%d") + "T00:00:00-08:00" end = single_date.strftime("%Y-%m-%d") + "T23:59:59-07:00" elif zone.localize(datetime(single_date.year, single_date.month, single_date.day)).dst() == tdelta_0: logger.info('wintertime') start = single_date.strftime("%Y-%m-%d") + "T00:00:00-08:00" end = single_date.strftime("%Y-%m-%d") + "T23:59:59-08:00" Obviously this is only in US/Pacific timezone and to get the UTC day I need to subtract 8h difference from the start and 8 timestamp i.e. have T16:00:00-08:00 but I am wondering if there is a better way / package / formatter that can do this is a more logic-proof way. A: You can use datetime's astimezone method to determine the correct hours. import datetime, pytz now = datetime.datetime.now() # datetime.datetime(2019, 2, 12, 17, 0, 0, 0) now.astimezone(pytz.utc) # datetime.datetime(2019, 2, 12, 16, 0, 0, 0, tzinfo=<UTC>) now.astimezone(pytz.timezone('US/Pacific')) # datetime.datetime(2019, 2, 12, 8, 0, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)
{ "pile_set_name": "StackExchange" }
Q: Fancytree not visible has class ui-helper-hidden I have just started with fancytree 2.6.0 and I am populating it from a web service request. My problem is that all the nodes are present but are made invisible by the ui-helper-hidden class. I have put in a temporary fix with: $(rootNode.ul).removeClass('ui-helper-hidden'); but I am sure I am missing something. The scripts and css: <link href="Scripts/jquery-plugins/fancytree-2.6.0/src/skin-themeroller/ui.fancytree.css" rel="stylesheet" type="text/css" /> <script src="Scripts/jquery-1.11.1/jquery-1.11.1.js" type="text/javascript"></script> <script src="Scripts/jquery-1.11.1/jquery-migrate-1.2.1.js" type="text/javascript"></script> <script src="Scripts/jquery-ui-1.11.2/jquery-ui.js" type="text/javascript"></script> <script src="Scripts/jquery-plugins/fancytree-2.6.0/src/jquery.fancytree.js" type="text/javascript"> </script> <script src="Scripts/jquery-plugins/fancytree-2.6.0/src/jquery.fancytree.themeroller.js" type="text/javascript"> </script> The code: $('#selectedClausesDiv').fancytree(); $.when( $.getJSON("Handlers/GetQuotationHandler.ashx?jsoncallback=?", { quoteReference: quoteReference, quoteVersion: quoteVersion }) ).then(function (data) { if (data.ErrorCode == 0 && data.Quotation != null) { var rootNode = $("#selectedClausesDiv").fancytree("getRootNode"); $.each(data.Quotation.Covers, function (index, item) { addCover(rootNode, item); }); // FIXME: why is this necessary ?? // $(rootNode.ul).removeClass('ui-helper-hidden'); } }); function addCover(rootNode, cover) { var coverId = 'selected_' + cover.BusinessClassId + '_' + cover.CoverId; var coverNode = rootNode.addChildren({ title: cover.Name, tooltip: "This folder and all child nodes were added programmatically.", folder: true }); } The generated html: <div class="grid_13 alpha omega" id="selectedClausesDiv"> <ul class="ui-fancytree fancytree-container ui-fancytree-source ui-helper-hidden" tabindex="0"> <li class=""> <span class="fancytree-node fancytree-folder fancytree-exp-n fancytree-ico-cf"> <span class="fancytree-expander"/> <span class="fancytree-icon"/> <span title="This folder and all child nodes were added programmatically." class="fancytree-title">P&amp;I Owned</span> </span> </li> <li class="fancytree-lastsib"> <span class="fancytree-node fancytree-folder fancytree-lastsib fancytree-exp-nl fancytree-ico-cf"> <span class="fancytree-expander"/> <span class="fancytree-icon"/> <span title="This folder and all child nodes were added programmatically." class="fancytree-title">P&amp;I Extended Cargo</span> </span> </li> </ul> </div> A: Fancytree will automatically hide the root element if no data source is provided. If you are adding data using the API and no initial source, providing a blank source option will prevent Fancytree from hiding the root element. $("#tree").fancytree({ source: [] });
{ "pile_set_name": "StackExchange" }
Q: JQuery stop show/hide on click I have a code snippet that shows a div once you click the menu item, there are different divs on this space and what the menu does is hide the one that was there before and show the new one, the problem is when I click on the same menu item it shows the current div again and I want to stop that from happening, it should only show the animation if it's not the current one, if it is nothing should happen. Here is the code snippet: var curPage=""; $("#menu a").click(function() { if (curPage.length) { $("#"+curPage).hide("slide"); } curPage=$(this).data("page"); $("#"+curPage).show("slide"); }); And here is a demo of how it's occuring now: https://jsfiddle.net/Lfsvc1ta/ A: Just add an additional check to see whether curPage is the same as the clicked page. var curPage; $("#menu a").click(function () { var page = $(this).data("page"); if (curPage && page != curPage) { $("#" + curPage).stop().hide("slide"); } $("#" + page).stop().show("slide"); curPage = page; }); Demo: Fiddle
{ "pile_set_name": "StackExchange" }
Q: How to validate text input on alertDialog using Form and GlobalKey? I've a textfield on alertDialog which accepts Email and want to validate it. The alertDialog opens in front of current login screen after tapping on forgot password button. I've implemented login validation and was trying to use similar logic to achieve above. For login validation, I used GlobalKey(_formKey) and Form widget which works perfectly. I am using another GlobalKey named _resetKey to get the currentState of validation and then saving it's state. Although this approach is working, I see that the validation message is also displayed on Email and Password fields too. ie, If I tap on 'forgot password' that opens dialog, and tap on send email, it correctly shows the validation message, but at the same time, the validation message for login screen is triggered too after tapping on cancel button from alertdialog. Something like this: For alertDialog validation, below is my code: // Creates an alertDialog for the user to enter their email Future<String> _resetDialogBox() { final resetEmailController = TextEditingController(); return showDialog<String>( context: context, barrierDismissible: false, // user must tap button! builder: (BuildContext context) { return AlertDialog( title: new Text('Reset Password'), content: new SingleChildScrollView( child: new Form( key: _resetKey, autovalidate: _validate, child: ListBody( children: <Widget>[ new Text( 'Enter the Email Address associated with your account.', style: TextStyle(fontSize: 14.0),), Padding( padding: EdgeInsets.all(10.0), ), Row( children: <Widget>[ new Padding( padding: EdgeInsets.only(top: 8.0), child: Icon( Icons.email, size: 20.0, ), ), new Expanded( child: TextFormField( validator: validateEmail, onSaved: (String val) { resetEmail = val; }, new FlatButton( child: new Text( 'SEND EMAIL', style: TextStyle(color: Colors.black),), onPressed: () { setState(() { _sendResetEmail(); }); void _sendResetEmail() { final resetEmailController = TextEditingController(); resetEmail = resetEmailController.text; if (_resetKey.currentState.validate()) { _resetKey.currentState.save(); try { Fluttertoast.showToast( msg: "Sending password-reset email to: $resetEmail", toastLength: Toast.LENGTH_LONG, bgcolor: "#e74c3c", textcolor: '#ffffff', timeInSecForIos: 4); _auth.sendPasswordResetEmail(email: resetEmail); } catch (exception) { print(exception); Fluttertoast.showToast( msg: "${exception.toString()}", toastLength: Toast.LENGTH_LONG, bgcolor: "#e74c3c", textcolor: '#ffffff', timeInSecForIos: 4); } } else { setState(() { _validate = true; }); } } The login validation using _formKey gist is as below: // Creates the email and password text fields Widget _textFields() { return Form( key: _formKey, autovalidate: _validate, child: Column( children: <Widget>[ Container( decoration: new BoxDecoration( border: new Border( bottom: new BorderSide(width: 0.5, color: Colors.grey), ), ), margin: const EdgeInsets.symmetric( vertical: 25.0, horizontal: 65.0), // Email text field child: Row( children: <Widget>[ new Padding( padding: EdgeInsets.symmetric( vertical: 10.0, horizontal: 15.0), child: Icon( Icons.email, color: Colors.white, ), ), new Expanded( child: TextFormField( validator: validateEmail, onSaved: (String val) { email = val; }, I think it has to do something with the 2 keys, since the alertDialog is displayed in front of the current activity. How can I achieve with _formKey or is there any other approach ? ************ required full code ************ void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: LoginScreen(), ), ); } } class LoginScreen extends StatefulWidget { @override LoginScreenState createState() => new LoginScreenState(); } class LoginScreenState extends State<LoginScreen> { final FirebaseAuth _auth = FirebaseAuth.instance; final _formKey = GlobalKey<FormState>(); final _resetKey = GlobalKey<FormState>(); bool _validate = false; String email; String password; String resetEmail; // The controller for the email field final _emailController = TextEditingController(); // The controller for the password field final _passwordController = TextEditingController(); // Creates the 'forgot password' and 'create account' buttons Widget _accountButtons() { return Container( child: Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Container( child: new FlatButton( padding: const EdgeInsets.only( top: 50.0, right: 150.0), onPressed: () => sendPasswordResetEmail(), child: Text("Forgot Password", style: TextStyle(color: Colors.white)), ), ) ]), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Container( child: new FlatButton( padding: const EdgeInsets.only(top: 50.0), onPressed: () => Navigator.push( context, MaterialPageRoute( builder: (context) => CreateAccountPage())), child: Text( "Register", style: TextStyle(color: Colors.white), ), ), ) ], ) ])), ); } // Creates the email and password text fields Widget _textFields() { return Form( key: _formKey, autovalidate: _validate, child: Column( children: <Widget>[ Container( decoration: new BoxDecoration( border: new Border( bottom: new BorderSide(width: 0.5, color: Colors.grey), ), ), margin: const EdgeInsets.symmetric( vertical: 25.0, horizontal: 65.0), // Email text field child: Row( children: <Widget>[ new Padding( padding: EdgeInsets.symmetric( vertical: 10.0, horizontal: 15.0), child: Icon( Icons.email, color: Colors.white, ), ), new Expanded( child: TextFormField( validator: validateEmail, onSaved: (String val) { email = val; }, keyboardType: TextInputType.emailAddress, autofocus: true, // cursorColor: Colors.green, controller: _emailController, decoration: InputDecoration( border: InputBorder.none, hintText: 'Email', // contentPadding: EdgeInsets.fromLTRB(45.0, 10.0, 20.0, 1.0), contentPadding: EdgeInsets.only(left: 55.0, top: 15.0), hintStyle: TextStyle(color: Colors.white), ), style: TextStyle(color: Colors.white), ), ) ], ), ), // Password text field Container( decoration: new BoxDecoration( border: new Border( bottom: new BorderSide( width: 0.5, color: Colors.grey, ), ), ), margin: const EdgeInsets.symmetric( vertical: 10.0, horizontal: 65.0), child: Row( children: <Widget>[ new Padding( padding: EdgeInsets.symmetric( vertical: 10.0, horizontal: 15.0), child: Icon( Icons.lock, color: Colors.white, ), ), new Expanded( child: TextFormField( validator: _validatePassword, onSaved: (String val) { password = val; }, // cursorColor: Colors.green, controller: _passwordController, decoration: InputDecoration( border: InputBorder.none, hintText: 'Password', contentPadding: EdgeInsets.only( left: 50.0, top: 15.0), hintStyle: TextStyle(color: Colors.white), ), style: TextStyle(color: Colors.white), // Make the characters in this field hidden obscureText: true), ) ], ), ) ], ) ); } // Creates the button to sign in Widget _signInButton() { return new Container( width: 200.0, margin: const EdgeInsets.only(top: 20.0), padding: const EdgeInsets.only(left: 20.0, right: 20.0), child: new Row( children: <Widget>[ new Expanded( child: RaisedButton( shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(30.0)), splashColor: Colors.white, color: Colors.green, child: new Row( children: <Widget>[ new Padding( padding: const EdgeInsets.only(left: 35.0), child: Text( "Sign in", style: TextStyle(color: Colors.white, fontSize: 18.0), textAlign: TextAlign.center, ), ), ], ), onPressed: () { setState(() { _signIn(); }); }), ), ], )); } // Signs in the user void _signIn() async { // Grab the text from the text fields final email = _emailController.text; final password = _passwordController.text; if (_formKey.currentState.validate()) { _formKey.currentState.save(); try { Fluttertoast.showToast( msg: "Signing in...", toastLength: Toast.LENGTH_LONG, bgcolor: "#e74c3c", textcolor: '#ffffff', timeInSecForIos: 2); firebaseUser = await _auth.signInWithEmailAndPassword( email: email, password: password); // If user successfully signs in, go to the pro categories page Navigator.pushReplacement(context, MaterialPageRoute( builder: (context) => ProCategories(firebaseUser))); } catch (exception) { print(exception.toString()); Fluttertoast.showToast( msg: "${exception.toString()}", toastLength: Toast.LENGTH_LONG, bgcolor: "#e74c3c", textcolor: '#ffffff', timeInSecForIos: 3); } } else { setState(() { _validate = true; }); } } // Creates an alertDialog for the user to enter their email Future<String> _resetDialogBox() { final resetEmailController = TextEditingController(); return showDialog<String>( context: context, barrierDismissible: false, // user must tap button! builder: (BuildContext context) { return AlertDialog( title: new Text('Reset Password'), content: new SingleChildScrollView( child: new Form( key: _resetKey, autovalidate: _validate, child: ListBody( children: <Widget>[ new Text( 'Enter the Email Address associated with your account.', style: TextStyle(fontSize: 14.0),), Padding( padding: EdgeInsets.all(10.0), ), Row( children: <Widget>[ new Padding( padding: EdgeInsets.only(top: 8.0), child: Icon( Icons.email, size: 20.0, ), ), new Expanded( child: TextFormField( validator: validateEmail, onSaved: (String val) { resetEmail = val; }, keyboardType: TextInputType.emailAddress, autofocus: true, decoration: new InputDecoration( border: InputBorder.none, hintText: 'Email', contentPadding: EdgeInsets.only( left: 70.0, top: 15.0), hintStyle: TextStyle( color: Colors.black, fontSize: 14.0) ), style: TextStyle(color: Colors.black), ), ) ], ), new Column( children: <Widget>[ Container( decoration: new BoxDecoration( border: new Border( bottom: new BorderSide( width: 0.5, color: Colors.black) ) ), ) ] ), ], ), ) ), actions: <Widget>[ new FlatButton( child: new Text('CANCEL', style: TextStyle(color: Colors.black),), onPressed: () { Navigator.of(context).pop(""); }, ), new FlatButton( child: new Text( 'SEND EMAIL', style: TextStyle(color: Colors.black),), onPressed: () { setState(() { _sendResetEmail(); }); Navigator.of(context).pop(resetEmail); }, ), ], ); }, ); } // Sends a password-reset link to the given email address void sendPasswordResetEmail() async { String resetEmail = await _resetDialogBox(); // When this is true, the user pressed 'cancel', so do nothing if (resetEmail == "") { return; } try { Fluttertoast.showToast( msg: "Sending password-reset email to: $resetEmail", toastLength: Toast.LENGTH_LONG, bgcolor: "#e74c3c", textcolor: '#ffffff', timeInSecForIos: 4); _auth.sendPasswordResetEmail(email: resetEmail); } catch (exception) { print(exception); Fluttertoast.showToast( msg: "${exception.toString()}", toastLength: Toast.LENGTH_LONG, bgcolor: "#e74c3c", textcolor: '#ffffff', timeInSecForIos: 4); } } @override Widget build(BuildContext context) { return Scaffold( // prevent pixel overflow when typing resizeToAvoidBottomPadding: false, body: Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage( "", ), fit: BoxFit.cover)), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ // QuickCarl logo at the top Image( alignment: Alignment.bottomCenter, image: AssetImage(""), width: 180.0, height: 250.0, ), new Text('', style: TextStyle( fontStyle: FontStyle.italic, fontSize: 12.0, color: Colors.white) ), _textFields(), _signInButton(), _accountButtons() ], ), ), ); } String validateEmail(String value) { String pattern = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'; RegExp regExp = new RegExp(pattern); if (value.length == 0) { return "Email is required"; } else if (!regExp.hasMatch(value)) { return "Invalid Email"; } else { return null; } } String _validatePassword(String value) { if (value.length == 0) { return 'Password is required'; } if (value.length < 4) { return 'Incorrect password'; } } void _sendResetEmail() { final resetEmailController = TextEditingController(); resetEmail = resetEmailController.text; if (_resetKey.currentState.validate()) { _resetKey.currentState.save(); try { Fluttertoast.showToast( msg: "Sending password-reset email to: $resetEmail", toastLength: Toast.LENGTH_LONG, bgcolor: "#e74c3c", textcolor: '#ffffff', timeInSecForIos: 4); _auth.sendPasswordResetEmail(email: resetEmail); } catch (exception) { print(exception); Fluttertoast.showToast( msg: "${exception.toString()}", toastLength: Toast.LENGTH_LONG, bgcolor: "#e74c3c", textcolor: '#ffffff', timeInSecForIos: 4); } } else { setState(() { _validate = true; }); } } } A: Well, there are mainly two issues: The first one is that you need to use another 'validate' variable local to the dialog. Otherwise, when you set it to true and call setState() the whole page is rebuilt and all the fields are checked against the validate value. But even if you do that, the validate in the dialog does not produce any result because when you call setState() the Form widget is not recreated and the changed value of validate does not get injected as a parameter. To understand this problem, please head over to this article in Medium that I wrote some time ago. The solution to solve both problems, according to the explanation in the article is to create a completely new stateful widget. So when calling setState() the Form is rebuilt and the new value for validate taken into account. This is the code to make it work: // Creates an alertDialog for the user to enter their email Future<String> _resetDialogBox() { return showDialog<String>( context: context, barrierDismissible: false, // user must tap button! builder: (BuildContext context) { return CustomAlertDialog( title: "Reset email", auth: _auth, ); }, ); } class CustomAlertDialog extends StatefulWidget { final String title; final FirebaseAuth auth; const CustomAlertDialog({Key key, this.title, this.auth}) : super(key: key); @override CustomAlertDialogState createState() { return new CustomAlertDialogState(); } } class CustomAlertDialogState extends State<CustomAlertDialog> { final _resetKey = GlobalKey<FormState>(); final _resetEmailController = TextEditingController(); String _resetEmail; bool _resetValidate = false; StreamController<bool> rebuild = StreamController<bool>(); bool _sendResetEmail() { _resetEmail = _resetEmailController.text; if (_resetKey.currentState.validate()) { _resetKey.currentState.save(); try { // You could consider using async/await here widget.auth.sendPasswordResetEmail(email: _resetEmail); return true; } catch (exception) { print(exception); } } else { setState(() { _resetValidate = true; }); return false; } } @override Widget build(BuildContext context) { return Container( child: AlertDialog( title: new Text(widget.title), content: new SingleChildScrollView( child: Form( key: _resetKey, autovalidate: _resetValidate, child: ListBody( children: <Widget>[ new Text( 'Enter the Email Address associated with your account.', style: TextStyle(fontSize: 14.0), ), Padding( padding: EdgeInsets.all(10.0), ), Row( children: <Widget>[ new Padding( padding: EdgeInsets.only(top: 8.0), child: Icon( Icons.email, size: 20.0, ), ), new Expanded( child: TextFormField( validator: validateEmail, onSaved: (String val) { _resetEmail = val; }, controller: _resetEmailController, keyboardType: TextInputType.emailAddress, autofocus: true, decoration: new InputDecoration( border: InputBorder.none, hintText: 'Email', contentPadding: EdgeInsets.only(left: 70.0, top: 15.0), hintStyle: TextStyle(color: Colors.black, fontSize: 14.0)), style: TextStyle(color: Colors.black), ), ) ], ), new Column(children: <Widget>[ Container( decoration: new BoxDecoration( border: new Border( bottom: new BorderSide( width: 0.5, color: Colors.black))), ) ]), ], ), ), ), actions: <Widget>[ new FlatButton( child: new Text( 'CANCEL', style: TextStyle(color: Colors.black), ), onPressed: () { Navigator.of(context).pop(""); }, ), new FlatButton( child: new Text( 'SEND EMAIL', style: TextStyle(color: Colors.black), ), onPressed: () { if (_sendResetEmail()) { Navigator.of(context).pop(_resetEmail); } }, ), ], ), ); } } String validateEmail(String value) { String pattern = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'; RegExp regExp = new RegExp(pattern); if (value.length == 0) { return "Email is required"; } else if (!regExp.hasMatch(value)) { return "Invalid Email"; } else { return null; } } I had to extract the validateEmail() method to make it available to the new widget.
{ "pile_set_name": "StackExchange" }
Q: How to find the end of Pipe In the code below how can I change stdoutCharConsumer so that it prints a newline after printing all the data from the input stream implement mixin and mixin' without going into Pipes.Internal? Is it possible? I need someting like the next function for Producers. I use Pipes 4.1.0 #!/usr/bin/env runhaskell {-# OPTIONS_GHC -Wall #-} import Pipes digits, characters :: Monad m => Producer Char m () digits = each "0123456789" characters = each "abcdefghijklmnopqrstuvwxyz" interleave :: Monad m => Producer a m () -> Producer a m () -> Producer a m () interleave a b = do n <- lift $ next a case n of Left () -> b Right (x, a') -> do yield x interleave b a' stdoutCharConsumer :: Consumer Char IO () stdoutCharConsumer = await >>= liftIO . putChar >> stdoutCharConsumer -- first element of the mixin should go first mixin :: Monad m => Producer b m () -> Pipe a b m () mixin = undefined -- first element of the pipe should go first mixin' :: Monad m => Producer b m () -> Pipe a b m () mixin' = undefined main :: IO () main = do -- this prints "a0b1c2d3e4f5g6h7i8j9klmnopqrstuvwxyz" runEffect $ interleave characters digits >-> stdoutCharConsumer putStrLn "" -- this prints "0a1b2c3d4e5f6g7h8i9jklmnopqrstuvwxyz" runEffect $ interleave digits characters >-> stdoutCharConsumer putStrLn "" -- should print "0a1b2c3d4e5f6g7h8i9jklmnopqrstuvwxyz" runEffect $ characters >-> mixin digits >-> stdoutCharConsumer putStrLn "" -- should print "a1b2c3d4e5f6g7h8i9jklmnopqrstuvwxyz" runEffect $ digits >-> mixin characters >-> stdoutCharConsumer putStrLn "" -- should print "a1b2c3d4e5f6g7h8i9jklmnopqrstuvwxyz" runEffect $ characters >-> mixin' digits >-> stdoutCharConsumer putStrLn "" -- should print "0a1b2c3d4e5f6g7h8i9jklmnopqrstuvwxyz" runEffect $ digits >-> mixin' characters >-> stdoutCharConsumer putStrLn "" UPD: Now after I read about pull/pushs based streams I think it is impossible even with Pipes.Internal. Is it true? A: Neither Consumers nor Pipes are aware of upstream end-of-input. You need Parsers from pipes-parse for that. Compared to Consumers, Parsers a more direct knowledge of Producers; their draw function (roughly analogous to await) returns a Nothing when end-of-input is found. import qualified Pipes.Parse as P stdoutCharParser :: P.Parser Char IO () stdoutCharParser = P.draw >>= \ma -> case ma of Nothing -> liftIO (putStrLn "\n") Just c -> liftIO (putChar c) >> stdoutCharParser To run a parser, we invoke evalStateT instead of runEffect: P.evalStateT stdoutCharParser (interleave characters digits) As for mixin and mixin', I suspect they will be impossible to write to work as intended. The reason is that the result Pipe would have to be aware of upstream termination in order to know when to yield the remaining values of the Producer passed as parameter.
{ "pile_set_name": "StackExchange" }
Q: Is aged beef salted and soaked before or after the aging process? Some kosher butchers are now offering aged beef. Is this meat salted and soaked before or after the aging process? A: Before, presumably. A law was instituted by the Gaonim that if you're planning on salting meat to extract the blood (rather than broiling it), it must be soaked or at least hosed down within the first 72 hours after slaughter -- and then every 72 hours after that. A: Since one has 72 hours(Geonim) from shechita to do nikkur and melicha I would assume that it was done first because aging takes more than 3 days.
{ "pile_set_name": "StackExchange" }
Q: What's a good way to get Demonite ore in terraria? I want to get as much Demonite ore as possible to make Shadow armor and to sell the leftover ore, but there is no way I could get enough from mining.What should I do? A: The quickest way to obtain large amounts of Demonite Ore is to defeat Eater of Worlds. Over and over. It can be summoned using Worm Food.
{ "pile_set_name": "StackExchange" }
Q: Internet Explorer forces user to log into site with DOMAIN\USERNAME I have a public Internet facing site running on SHarePoint 2010 using NTLM authentication. Users using FireFox/Chrome/Safari are able to log into the site using just their username and password. Internet Explorer users, however, are forced to log in with domain\username. If the domain is left out the site will not grant the user access. I have been instructing users to try to use another browser but most of our user base uses IE. We have two separate domains. Internal users belong to DomainA and External users are in DomainB. I am not sure why IE is forcing the inclusion of the domain in the username while the others do not. I need users to be able to log in with just username and password only. Has anyone seen this before? Thanks! A: Try using "\\" before the username when you login to the sharepoint website from client machines. A: A Couple of things you can try: In internet explorer, uncheck the "Enable Integrated Windows Authentication" box in the security options page. This doesn't actually disable it, it just forces NTLM. When the checkbox is clicked it will try to use Kerberos first, than it is supposed to fall back to NTLM (IE7+). I would also suggest loading up fiddler and comparing the authentication headers when you use the other browsers with the one generated by IE. Does this happen to both internal (users on same domain as server) and external (trusted domain)? How are the authentication option in the WebApp configured (IIS settings)?
{ "pile_set_name": "StackExchange" }
Q: .htaccess mod-rewrite conditional statements and sending GET request? Not necessarily a problem, just something that I am not yet knowledgeable enough to do. I have an .htaccess file that I am using for url rewriting. This is what I have now. ErrorDocument 404 /inc/error_documents/404.php ErrorDocument 503 /inc/error_documents/503.php # For security reasons, Option followsymlinks cannot be overridden. #Options +FollowSymLinks Options +SymLinksIfOwnerMatch RewriteEngine ON RewriteRule ^home$ /index.php [nc] RewriteRule ^(about|contact|giving-tree)/?$ /$1.php [nc] RewriteRule ^giving-tree/([0-9+]?)/?$ giving-tree.php?ageBegin=$1 [nc] RewriteRule ^giving-tree/([0-9+]?)/([0-9+]?)/?$ giving-tree.php?ageBegin=$1&ageEnd=$2 [nc] RewriteRule ^giving-tree/([0-9+]?)/([0-9+]?)/([0-9+]?)/?$ giving-tree.php?ageBegin=$1&ageEnd=$2&page=$3 [nc] What I want to be able to do is make some of the parts in the 3 bottom rules optional. I know that I can accomplish this with RewriteCond, but I'm not sure how. What I need is basically this: RewriteCond %{HTTP_HOST} ^hearttohandparadise.org/giving-tree RewriteRule /beginAge-([0-9+]) #make it send GET request with beginAge as the variable RewriteRule /endAge-([0-9+]) \?beginAge=$1 #make it send GET request with endAge as the variable etc... etc... Is there any way to accomplish this just by relying on .htaccess? or am I just fantasizing? Forgive me is I sound stupid. A: No, it's a perfectly valid idea. You'd basically want to allow the user to write the URI in an unstructured manner, without a strict order imposed, right? Like, I could write giving-tree/page-6/endAge-23? If so, this is what you're looking for: RewriteRule /beginAge-([0-9]+) giving-tree.php?beginAge=$1 [QSA,NC] RewriteRule /endAge-([0-9]+) giving-tree.php?endAge=$1 [NC,QSA] RewriteRule /page-([0-9]+) giving-tree.php?page=$1 [NC,QSA] You see, if any part of the URI matches the expression "/beginAge-([0-9]+)", it'll be redirected to giving-tree.php?beginAge=$1; the magic is done by the QSA, Query String Append, option, which, well, appends any existing query string to the resulting URI. So as more and more matches are found and more and more GET parameters added, the query string just grows. If you want a stricter thing, where some parameters are optional, but their order is fixed, then it's uglier by magnitudes: RewriteRule /(beginAge-)?([0-9]+)/?(endAge-)?([0-9]+)?/?(page-)?([0-9]+)? giving-tree.php?beginAge=$2&endAge=$4&page=$6 [NC] I just made everything optional by using the ? operator. This one may use some prettifying/restructuring. (Alternatively, you could just do this: RewriteRule ^giving-tree/([^/]+)/?$ process.php?params=$1 [nc] That is, grabbing the entire part of the URI after the giving-tree part, lumping the whole thing into a single parameter, then processing the thing with PHP (as it's somewhat better equipped to string manipulation). But the first version is certainly more elegant.) By the way, are you sure about the ([0-9+]?) parts? This means "One or no single character, which may be a digit or the plus sign". I think you meant ([0-9]+), i.e. "one or more digit".
{ "pile_set_name": "StackExchange" }
Q: Connect to MySQL database with RMySQL I am making the move from RSQLite to RMySQL and I am confused by the user and password fields. FWIW, I'm running Windows 7, R 2.12.2, MySQL 5.5 (all 64 bit), and RMySQL 0.7-5. I installed RMySQL as prescribed in this previous SO question, and as far as I know it works (i.e., I can load the package with library(RMySQL)). But when I try to run the tutorial from the R data import guide, I get a "failed to connect to database..." error. This is the code from the tutorial from the guide: library(RMySQL) # will load DBI as well ## open a connection to a MySQL database con <- dbConnect(dbDriver("MySQL"), user = "root", password = "root", dbname = "pookas") ## list the tables in the database dbListTables(con) ## load a data frame into the database, deleting any existing copy data(USArrests) dbWriteTable(con, "arrests", USArrests, overwrite = TRUE) dbListTables(con) ## get the whole table dbReadTable(con, "arrests") ## Select from the loaded table dbGetQuery(con, paste("select row_names, Murder from arrests", "where Rape > 30 order by Murder")) dbRemoveTable(con, "arrests") dbDisconnect(con) On the second line I get the following error: > con <- dbConnect(dbDriver("MySQL"), user = "richard", password = "root", dbname = "pookas") Error in mysqlNewConnection(drv, ...) : RS-DBI driver: (Failed to connect to database: Error: Access denied for user 'richard'@'localhost' (using password: NO) ) I have tried with and without user and password and with admin as user. I have also tried using a dbname that I made before with the command line and with one that doesn't exist. Any tips? Is there a good reference here? Thanks! A: That is most likely a setup issue on the server side. Make sure that networked access is enabled. Also, a local test with the command-line client is not equivalent as that typically uses sockets. The mysql server logs may be helpful.
{ "pile_set_name": "StackExchange" }
Q: Signal/Slots feature for different classes in Qt C++ For just one class , i declare a slot and a signal , and in slot method definition i call signal method with emit keyword. But how can i emit signals with one class to another class which has a slot. Well i try with a button to modify a label text. Button is created by A class (which must emit a signal) , and label is created by class B which must have a slot to modify text on it A: It seems like you have class 1, which has a method that will be executed, and will call "emit". When that happens, the slot of another class will find out. definition of 1st class: class songs_text { public: signals: void send_signal(); } int songs_text:function() { emit send_signal(); } definition of class 2: class wind { public slots: void continue_job() { }; } and your main program: Wind wind(); Get_source songs_text(&mtempfile); QObject::connect(&songs_text, SIGNAL(send_signal()), &wind, SLOT(continue_job()));
{ "pile_set_name": "StackExchange" }
Q: Show that $f_n(x) = n(x^{1/n}-1)$ converges pointwise to $f(x) = \ln x$. Let $f_n:(0,\infty) \rightarrow \mathbb{R}$ be defined by $f(x) = n(x^{1/n}-1)$. Show that $f_n$ converges pointwise to $f(x) = \ln x$. I'm not getting anywhere here. I can't seem to find a way to rewrite $d(f_n(x), f(x)) = |n(x^{1/n}-1)-\ln x| < \epsilon$, such that for any given $\epsilon$, the inequality makes sense whenever $n\geq N$. What's really throwing me off is that I have no feeling for what the function $f_n(x) = n(x^{1/n}-1)$ is and how I can relate it to $\ln x$, in a sensible way. Arrriving at $|n \ln \frac{e^{x^{\frac{1}{n}}-1}}{x^{\frac{1}{n}}}| < \epsilon$, and then examining the limit is the best approach I can think of. If the RHS vanishes as $n\rightarrow \infty$, then certainly there exists a large enough $N$ so that the inequality makes sense. But I don't really get anywhere doing so. Maybe I'm going about this wrong. Any help on the way is very welcome! A: A simple option based on recognizing a derivative: For $x > 0$, you have $x^{\frac{1}{n}} = e^{\frac{1}{n}\ln x}$. Fix any $x_0 > 0$, and consider the function $f\colon \mathbb{R} \to \mathbb{R}$ defined by $f(t) = e^{t\ln x_0}$. It is differentiable, and $f^\prime(t) = \ln x_0\cdot e^{t\ln x_0}$; and further $$ f^\prime(t) = \lim_{h\to0} \frac{f(t+h)-f(t)}{h}. $$ Now, what is $f^\prime(0)=\lim_{h\to0} \frac{f(h)-f(0)}{h} = \lim_{h\to0} \frac{f(h)-1}{h}$? (To conclude, take "$h=\frac{1}{n}$.")
{ "pile_set_name": "StackExchange" }
Q: Comparing 2D arrays Im trying to compare two 2D arrays by using this. But I keep getting "Arrays are not the same." even when they are the same. int i; int j = 0; int k; int l; List<Integer> list = new ArrayList<Integer>(); List<Integer> list1 = new ArrayList<Integer>(); List<Integer> zero = new ArrayList<Integer>(); for ( i = 1; i <= 16; i++) { list.add(i); } //System.out.println(list); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] Collections.shuffle(list.subList(1, 15)); System.out.println(list); Collections.replaceAll(list, 16, 0); System.out.println(list); // System.out.println(list); //[11, 5, 10, 9, 7, 0, 6, 1, 3, 14, 2, 4, 15, 13, 12, 8] int[][] a2 = new int[4][4]; int [][] a3 = new int[4][4]; for ( i = 0; i < 4; i++) { for ( j = 0; j< 4; j++) { a2[i][j] = list.get(i*4 + j); a3[i][j] = list.get(i*4 + j); } } for (int[] row : a2) { System.out.print("["); for ( int a : row) System.out.printf("%4d", a); System.out.println("]"); } for (int[] row : a3) { System.out.print("["); for ( int a : row) System.out.printf("%4d", a); System.out.println("]"); } boolean check1 = Arrays.equals(a2, a3); if(check1 == false) System.out.println("Arrays are not same."); else System.out.println("Both Arrays are same."); I can't do it like this either. boolean check1 = Arrays.equals(a2[i][j], a3[i][j]); A: The first one does not work because a two-D int array is really an array of arrays (that is, an array of objects). The Arrays.equals() method for an array of objects uses equals() to test whether corresponding elements are equal. Unfortunately for your code, equals() for arrays is the default Object implementation: they are equal() only if they are the identical object. In your case, they are not. In the second case, when you code Arrays.equals and pass two int values, the compiler can't match it to any signature of the Arrays class. One way to check equality is to use deepEquals: boolean check1 = Arrays.deepEquals(a2, a3); Another way is to iterate the outer array explicitly: boolean check1 = true; for (int i = 0; check1 && i < a2.length; ++i) { check1 = Arrays.equals(a2[i], a3[i]); } A: boolean check1 = Arrays.deepEquals(a2, a3); is definitely a possibility. The implementation of that uses Object[], which may be appealing to you because it checks the types of the arrays you pass on-the-fly. But if you want stronger typing and a little less overhead, you can write your own as follows. import java.util.Arrays; /** * Operations on multi-dimensional arrays. * * @author stephen harrison */ public class ArrayUtils { private ArrayUtils() { // Static methods only } public static <T> boolean equals(final T[][] a, final T[][] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i < a.length; ++i) { if (!Arrays.equals(a[i], b[i])) { return false; } } return true; } public static <T> boolean equals(final T[][][] a, final T[][][] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.length != b.length) { return false; } for (int i = 0; i < a.length; ++i) { if (!equals(a[i], b[i])) { return false; } } return true; } } The first equals on 2D arrays calls Arrays.equals(). The 3D version similarly calls the 2D one. I hope that helps.
{ "pile_set_name": "StackExchange" }
Q: What does it mean to get rewards on the DAO? How are the reward tokens generated on the DAO? I don't really understand. If I back a project it gets funding right? Are the managers of the project required to "give back" to the DAO if the project is very successful (economically speaking)? A: Reward won't be tokens but Ether as I understood. DAO tokens are only used to share voting power as shares in a company. When you invest in a company, your reward is (most of the time) dollars, not shares.
{ "pile_set_name": "StackExchange" }
Q: excel vlookup inside countif criteria I am trying to combine a countif in excel with the criteria retrieved from a vlookup table. This sounds simple enough, but I am having trouble making it work. =countif(a1:z1,">=4") I want the column values from a to z counted every time the value is greater than or equal to 4 which is my criteria. But I don't want to type the four in the above formula. I want it to come from a vlookup. VLOOKUP("myValue",AA1:DD4,2,FALSE) <--formula would retrieve the 4 Any suggestions how I can do this? A: To make the ">=4" a parameter, you just need to do some string building: ">=" & VLOOKUP("myValue",AA1:DD4,2,FALSE) The full formula would be: =COUNTIF(a1:z1,">=" & VLOOKUP("myValue",AA1:DD4,2,FALSE)) The & operator is a shorthand for =CONCATENATE(,) which is a long word for "join strings together".
{ "pile_set_name": "StackExchange" }
Q: how to exclude certain views with laravel view composer How can I make sure that I load data via view composer for select views and only exclude a few, two views to be specific? Can i use a regex instead of '*'? public function boot() { view()->composer( '*', 'App\Http\ViewComposers\ProfileComposer' ); } There are just two views i'd like to avoid, they extend the same blade used by others, not sure declaring all the 99 others would be the best - if i can just define the ones to be left out that'd be great. A: Perhaps it is not the best way for doing this but it can do like this In your services provider register your view composer public function boot() { view()->composer( '*', 'App\Http\ViewComposers\ProfileComposer' ); } In Your ProfileComposer compose method View class repository is type hinted. Use it to get the name of the current name of the view and make a condition for excluded view name. class ProfileComposer { public function __construct() { // Dependencies automatically resolved by service container... } /** * Bind data to the view. * * @param View $view * @return void */ public function compose(View $view) { $excludedViews = ['firstView','SecondView']; //Check if current view is not in excludedViews array if(!in_array($view->getName() , $excludedViews)) { $view->with('dataName', $this->data); } } }
{ "pile_set_name": "StackExchange" }
Q: How to download multiple files at once with TIdHTTP I'm currently using TIdHTTP from Indy with my Embarcadero C++Builder 10.1 Berlin. I have read some online tutorials on how to make TIdHTTP multi-threaded, but the main issue is I already tested this component in a thread. So here is how it works. I created a thread object and I made a function to download a file in that thread, apparently the thread works fine and the file get downloaded to my Disk. But, when I create additional threads for file downloads, the first thread stops. I don't want that, I want both files to continue to download at the same time (without pausing the first thread), like in IDM (Internet Download Manager). The thread class is like in the code below: class TIdHTTPThread : public TThread { protected: void __fastcall Execute(); void __fastcall PutDownloadedFile(); public: __fastcall TIdHTTPThread(bool CreateSuspended); void __fastcall IdHTTPBeginWork(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCountMax); void __fastcall IdHTTPWork(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCount); void __fastcall IdHTTPEndWork(TObject *ASender, TWorkMode AWorkMode); void __fastcall DownloadFile(UnicodeString AFileURL, UnicodeString AFileDest); void __fastcall CreateQueue(TWinControl* wcParent, TAlign alAlign); private: TIdHTTP* IdHTTP; TMemoryStream* msMemoryStream; UnicodeString uFileURL; UnicodeString uFileDest; int iDownProgress; int iFileSize; int iMaxProgress; int iDownSpeed; TWinControl* wcParent; TIFDQueue *ifdQueue; }; Please don't bother about the additional properties and methods in the class, I just want to achieve what I need in my question. CPP File: void __fastcall TIdHTTPThread::CreateQueue(TWinControl* wcParent, TAlign alAlign) { this->wcParent = wcParent; ifdQueue = new TIFDQueue(this->wcParent, alAlign); } void __fastcall TIdHTTPThread::IdHTTPBeginWork(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCountMax) { this->iFileSize = AWorkCountMax; this->iMaxProgress = AWorkCountMax; ifdQueue->SetFileSize(this->iFileSize); ifdQueue->SetMaxProgress(this->iMaxProgress); ifdQueue->SetFileURL(this->uFileURL); ifdQueue->SetFilePath(this->uFileDest); ifdQueue->OnBeginUpdate(); } void __fastcall TIdHTTPThread::IdHTTPWork(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCount) { this->iDownProgress = AWorkCount; this->iDownSpeed = AWorkCount / 1024; ifdQueue->SetDownProgress(this->iDownProgress); ifdQueue->SetDownSpeed(this->iDownSpeed); ifdQueue->OnWorkUpdate(); } void __fastcall TIdHTTPThread::IdHTTPEndWork(TObject *ASender, TWorkMode AWorkMode) { ifdQueue->OnEndUpdate(); this->Terminate(); } //**// void __fastcall TIdHTTPThread::DownloadFile(UnicodeString AFileURL, UnicodeString AFileDest) { this->uFileURL = AFileURL; this->uFileDest = AFileDest; } void __fastcall TIdHTTPThread::PutDownloadedFile() { try { this->msMemoryStream = new TMemoryStream; this->IdHTTP = new TIdHTTP(NULL); this->IdHTTP->OnWorkBegin = this->IdHTTPBeginWork; this->IdHTTP->OnWork = this->IdHTTPWork; this->IdHTTP->OnWorkEnd = this->IdHTTPEndWork; this->IdHTTP->ConnectTimeout = 20000; this->IdHTTP->ReadTimeout = 60000; this->IdHTTP->Get(this->uFileURL, this->msMemoryStream); this->msMemoryStream->SaveToFile(this->uFileDest); } __finally { delete this->msMemoryStream; delete this->IdHTTP; } } __fastcall TIdHTTPThread::TIdHTTPThread(bool CreateSuspended) : TThread(CreateSuspended) { } //--------------------------------------------------------------------------- void __fastcall TIdHTTPThread::Execute() { //---- Place thread code here ---- FreeOnTerminate = true; Synchronize(&this->PutDownloadedFile); } //--------------------------------------------------------------------------- UPDATE: void __fastcall TIdHTTPThread::PutDownloadedFile() { try { this->CookieManager = new TIdCookieManager(NULL); this->SSLIOHandlerSocket = new TIdSSLIOHandlerSocketOpenSSL(NULL); this->msMemoryStream = new TMemoryStream; // Configure SSL IOHandler this->SSLIOHandlerSocket->SSLOptions->Method = sslvSSLv23; this->SSLIOHandlerSocket->SSLOptions->SSLVersions = TIdSSLVersions() << sslvTLSv1_2 << sslvTLSv1_1 << sslvTLSv1; // Setup HTTP this->IdHTTP = new TIdHTTP(NULL); this->ifdQueue->StopDownload(this->IdHTTP); // Function To stop download When Fired (doesn't fire imidiatly) this->IdHTTP->OnWorkBegin = this->IdHTTPBeginWork; this->IdHTTP->OnWork = this->IdHTTPWork; this->IdHTTP->OnWorkEnd = this->IdHTTPEndWork; this->IdHTTP->OnRedirect = this->IdHTTPRedirect; this->IdHTTP->HandleRedirects = true; this->IdHTTP->AllowCookies = true; this->IdHTTP->CookieManager = this->CookieManager; this->IdHTTP->IOHandler = this->SSLIOHandlerSocket; this->IdHTTP->Get(this->uFileURL, this->msMemoryStream); if ( this->msMemoryStream->Size >= this->IdHTTP->Response->ContentLength ) { this->msMemoryStream->SaveToFile(this->uFileName); } } __finally { delete this->msMemoryStream; delete this->CookieManager; delete this->SSLIOHandlerSocket; delete this->IdHTTP; } } A: The problem is your thread's Execute() method is doing ALL of its work inside a Synchronize() call, so ALL of its work is actually being done inside the main UI thread instead, thus serializing your downloads and defeating the whole point of using a worker thread. DO NOT call PutDownloadedFile() itself with Synchronize(). You need to instead change your individual TIdHTTP status events to use Synchronize() (or Queue()) when updating your UI controls.
{ "pile_set_name": "StackExchange" }
Q: Which is better for the 555, a smaller capacitor or a larger one? As I understand it, there are many ways to combine two resistors and a capacitor to give the same time characteristics in a astable 555 setup. My question is which is better, a larger capacitor or a smaller one? and does it effect power consumption? A: Well a larger capacitor needs more energy stored to trigger the threshold pin, this energy is just dumped when the output is low. A lower valued capacitor needs larger resistors for the same timing but waste less power. I'd say make the capacitor as small as possible while keeping the circuit functional to save power. Eventually the resistor needed will be too large compared to the 555 input resistance and you'll hit your timing limit for the small value capacitor. An input pin on any device needs to have a large input resistance as to not disturb the point it is measuring, you can visualize this as a really large resistor connected to the pin and ground. This means that if you connect it to a point in the circuit with a high resistance value before it you'll get a voltage divider at that point. If you keep your resistors small enough this ought never to be a problem. Going higher will tend to degrade performance and could cause the unit from working completely. For example the resistors above should be chosen to pass at least a certain amount of current to the 555. Examining the data sheet gives the minimum values: Trigger current (pin 2): 1uA Reset current (pin 4): 0.5mA Threshold current (pin 6): 0.25uA The values of your resistors will thus depend on the configuration of your circuit, operating voltage and these minimum currents. Don't worry too much about this, play around with your circuit, keep increasing the resistance for a specific capacitor value and when the circuit doesn't work as expected anymore you know you have to increase your capacitor value instead to get a longer delay. Or, if you're up for it, try to calculate the best values for your configuration.
{ "pile_set_name": "StackExchange" }
Q: How to have a text label on links in d3 force directed graphs I am using a force directed graph, and i would like to have the text on the link centred on the link (see image). Is there a way to do it ? A: I believe Lars is correct. Based on the last response from the link he provided, I added this code to one of my force graphs and it worked fine: var path = svg.append("g").selectAll(".link") .data(force.links()) .enter().append("path") .attr("id",function(d,i) { return "linkId_" + i; }) ... var labelText = svg.selectAll(".labelText") .data(force.links()) .enter().append("text") .attr("class","labelText") .attr("dx",20) .attr("dy",0) .style("fill","red") .append("textPath") .attr("xlink:href",function(d,i) { return "#linkId_" + i;}) .text(function(d,i) { return "text for link " + i;});
{ "pile_set_name": "StackExchange" }
Q: How to count group records based on certain values? I have a report, divided into set of groups, one of them is grouped by "Status". Status values are: S, R, V. I need to make two total fields to get 1- Count of S and V records. 2- Count of R records. Any suggestions? FYI: I use CrystalReport Designer embedded with VisualStudio.NET 2005. A: I do it by using running totals.Put a formula which only select the appropriate records into the running total's evaluate option. You will have two running total -one for the S and V records and another one for the R records.
{ "pile_set_name": "StackExchange" }
Q: c: type casting char values into unsigned short starting with a pseudo-code snippet: char a = 0x80; unsigned short b; b = (unsigned short)a; printf ("0x%04x\r\n", b); // => 0xff80 to my current understanding "char" is by definition neither a signed char nor an unsigned char but sort of a third type of signedness. how does it come that it happens that 'a' is first sign extended from (maybe platform dependent) an 8 bits storage to (a maybe again platform specific) 16 bits of a signed short and then converted to an unsigned short? is there a c standard that determines the order of expansion? does this standard guide in any way on how to deal with those third type of signedness that a "pure" char (i called it once an X-char, x for undetermined signedness) so that results are at least deterministic? PS: if inserting an "(unsigned char)" statement in front of the 'a' in the assignment line, then the result in the printing line is indeed changed to 0x0080. thus only two type casts in a row will provide what might be the intended result for certain intentions. A: The type char is not a "third" signedness. It is either signed char or unsigned char, and which one it is is implementation defined. This is dictated by section 6.2.5p15 of the C standard: The three types char , signed char , and unsigned char are collectively called the character types. The implementation shall define char to have the same range, representation, and behavior as either signed char or unsigned char. It appears that on your implementation, char is the same as signed char, so because the value is negative and because the destination type is unsigned it must be converted. Section 6.3.1.3 dictates how conversion between integer types occur: 1 When a value with integer type is converted to another integer type other than _Bool ,if the value can be represented by the new type, it is unchanged. 2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. 3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised. Since the value 0x80 == -128 cannot be represented in an unsigned short the conversion in paragraph 2 occurs.
{ "pile_set_name": "StackExchange" }
Q: uninitialized constant UserController/undefined method `user_path' ok, i have users, and i want to have the options to edit their names. my route looks like this namespace :admin do resources :users end my index: - @users.each do |user| %tr %td= link_to user.last_name, admin_user_path(user) %td= user.first_name %td= link_to "Edit", edit_admin_user_path(user), class: "btn" = paginate @users controller class Admin::UsersController < AdminController def edit @user = User.find(params[:id]) end and the form: = simple_form_for @user do |f| %p New first name = f.input :first_name %p New last name = f.input :last_name = f.button :submit When i press the 'edit' button on the index page, it gives me 'undefined method `user_path'' error, pointing into first line of the form. i tried to solve it poorly with adding resources :users and it allowed me to render form, but when i try to save it, it gives me uninitialized 'constant UsersController'. What is going on with this user_path since i'm not using it anywhere? how can i solve this problem, best would be without any extra routes... A: change the form to =simple_form_for [:admin, @user] do |f|
{ "pile_set_name": "StackExchange" }
Q: Polynomial expansion Question from the Probability and Computing book by Mitzenmacher M. and Upfal E. Given is the following polynomial: $$F(x)=\prod_{i=1}^d(x-a_i)$$ Then the book says: Transforming $F(x)$ to its canonical form by consecutively multiplying the $i$th monomial with the product of the first $i-1$ monomials requires $\Theta(d^2)$ multiplications of coefficients. Did the authors mean to write $2^d$? If not, what does $\Theta(\cdot)$ mean then? A: No, they meant $\Theta(d^2)$. They describe a process for going from a polynomial of degree $k$ to one of degree $k+1$, or rather, from the coefficients of a degree $k$ polynomial to the coefficients of a degree $k+1$ polynomial. This takes $O(k)$ multiplications, and $\sum_{k=1}^dO(k) = \Theta(d^2)$.
{ "pile_set_name": "StackExchange" }
Q: What's the passcode? One morning, as you wake up, you feel something on your face: It's a letter. As you take it off your face to read it, You fall off your bed. Uurrrgh, you say and stand up. The letter says: &$t |* }p|t Hmmm. Seems angry. Meet me at 8th and main st. behind the post office in half an hour. Be there. From Yout Ried. Ok, you think. Once you arrive, you head into a room and the door slams shut. You try it but it's locked. On the floor you see a "clue". On the wall you read: Say the code and escape. You have 3 tries. Just beneath that you read: wco ard_q'r uigv wywqwxx wwv kmill, z xvhqigx. rvczym, _h_l nrz. ohlnmv lq: smlvvg_ Good Luck! HINT 1 The angry message isn't really angry... HINT 2 The rulebook for Kandoodle might be of help... HINT 3 What you can decrypt from the clue will fill the blank spaces on the message on the wall. HINT 4 If you can't figure out what the letter means, look up rot13 cyrptii and fiddle with settings. A: Using Hint 4, the angry letter translates into - Use My Name, the letter was from Yout Ried, so maybe use that name. Use it where though, not sure. Using Hint 2, the clue translates to- IAFH , these are the actual letters written there, according to the rule book. so the writing in the wall is - "wco ardiq'r uigv wywqwxx wwv kmill, z xvhqigx. rvczym, ahfl nrz. ohlnmv lq: smlvvgh." Which using youtried as key translates into: you haven't gone outside for hours, i presume. anyway, good job. answer is: essence. [done with vigenere cipher of variant Beaufort ] Finally the passcode is: Essence
{ "pile_set_name": "StackExchange" }
Q: In Android how to get the width of the Textview which is set to Wrap_Content I am trying to add a text to the textview for which i have set the width as Wrap_content. I am trying to get the width of this textview. But its showing 0 in all the cases. How Can i get the width of the textview after setting the text into it. the code is as: LinearLayout ll= new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); ll.addView(tv); tv.setText("Hello 1234567890-0987654321qwertyuio787888888888888888888888888888888888888888888888888"); System.out.println("The width is == "+tv.getWidth());// result is 0 this.setContentView(ll); Please suggest. Thanks in advance. A: Views with the dynamic width/height get their correct size only after a layout process was finished (http://developer.android.com/reference/android/view/View.html#Layout). You can add OnLayoutChangeListener to your TextView and get it's size there: tv.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { final int width = right - left; System.out.println("The width is == " + width); }); A: You can not get the width of a View with dynamic size before the layout is completely built. That means there is no way you can get it in onCreate(). One way would be to create a class that inherits from TextView and overrides onSizeChanged().
{ "pile_set_name": "StackExchange" }
Q: Show/hide images in sequence on hover I'm trying to hide and show images one after the other in a sequence using jquery, the last image to show and stay showing should be .img2. The following code doesn't work, the delay's dont seem to work, it just hides them all at the same time and shows .img2. JQUERY $(".start-page-img").hover(function() { $('.img5').delay(6000).hide() $('.img4').delay(7000).show() $('.img4').delay(9000).hide() $('.img3').show(10000).show() $('.img3').delay(12000).hide() $('.img2').delay(13000).show() }); HTML <div class="start-page-img"> <img src="img/img1.jpg" class="img1" /> <img src="img/img2.jpg" class="img2" /> <img src="img/img3.jpg" class="img3" /> <img src="img/img4.jpg" class="img4" /> <img src="img/img5.jpg" class="img5" /> </div> CSS .start-page-img{ width:400px; float:left; position:relative; cursor:pointer; } .start-page-img img{ position:absolute; top:0; left:0; display:block; } .start-page-img .img1, .start-page-img .img2, .start-page-img .img3, .start-page-img .img4, { display:none; } A: I think I managed to create the effect you are going for by using setTimeout() instead of delay(). Here is a fiddle to play around. Notice, how some calls show() and hide() have a duration parameter, which in one case somehow overlaps the start of the next animation, so timing is everything. There is probably a more elegant way, maybe with jQuery.animate() and/or jQuery.queue(). Hope it helps.
{ "pile_set_name": "StackExchange" }
Q: Can a vector space over an infinite field be a finite union of proper subspaces? Can a (possibly infinite-dimensional) vector space ever be a finite union of proper subspaces? If the ground field is finite, then any finite-dimensional vector space is finite as a set, so there are a finite number of 1-dimensional subspaces, and it is the union of those. So let's assume the ground field is infinite. A: Let $V$ be the union $\cup_{i=1}^n V_i$, where the $V_i$ are proper subspaces and the ground field $k$ is infinite. Pick a non-zero vector $x\in V_1$. Pick $y\in V-V_1$, and note that there are infinitely many vectors of the form $x+\alpha y$, with $\alpha\in k^\ast$. Now $x+\alpha y$ is never in $V_1$, and so there is some $V_j$, $j\neq 1$, with infinitely many of these vectors, so it contains $y$, and thus contains $x$. Since $x$ was arbitrary, we see $V_1$ is contained in $\cup_{i=2}^n V_i$; clearly this process can be repeated to find a contradiction. Steve A: You can prove by induction on n that: An affine space over an infinite field $F$ is not the union of $n$ proper affine subspaces. The inductive step goes like this: Pick one of the affine subspaces $V$. Pick an affine subspace of codimension one which contains it, $W$. Look at all the translates of $W$. Since $F$ is infinite, some translate $W'$ of $W$ is not on your list. Now restrict all other subspaces down to $W'$ and apply the inductive hypothesis. This gives the tight bound that an $F$ affine space is not the union of $n$ proper subspaces if $|F|>n$. For vector spaces, one can get the tight bound $|F|\geq n$ by doing the first step and then applying the affine bound. A: I recently completed a short expository note on this subject, Covering Numbers in Linear Algebra. See: http://math.uga.edu/~pete/coveringnumbersv2.pdf
{ "pile_set_name": "StackExchange" }
Q: I am installing the Detecto library in anaconda environment but it fails while importing As a source, I apply the guide here: Object Detection I applied the pip3 install detecto command as shown here and it was successfully installed. But when I run python and try to run the detecto command, I get an error. How can I solve it? Operation: A: I don't think you can import detecto directly. Use from detecto import <lib> . Try from detecto.core import Model and see if it works in your terminal
{ "pile_set_name": "StackExchange" }
Q: How to call php if/else statement if value empty Hopefully a nice simple question to start the day... In success.phtml, I would like to achieve the following using PHP: $_commissionGroupCode = [If $_voucher is empty, echo "DEFAULT". Else echo "VOUCHER"] Below is a snippet of my code so far: $lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId(); $order = Mage::getModel('sales/order')->load($lastOrderId); $_products = $order->getAllItems(); $_totalData = $order->getData(); $_discount = $_totalData['discount_amount']; $_voucher = $_totalData['coupon_code']; $_commissionGroupCode = ANSWER GOES HERE You will notice I already have $_voucher to call the voucher code A: You can do it like this: $_commissionGroupCode = (!$_voucher ? "DEFAULT" : "VOUCHER");
{ "pile_set_name": "StackExchange" }
Q: MySQL Server using same data in windows and linux? I have a dual boot (windows 7/linux) computer. I have an NTFS partition to exchange data between them. I want to install a MySQL Server. However, I don't have another computer and, as I would like to use the data from windows and linux, I want to install MySQL and store the data in the shared disk. However, the idea makes me cringe. Should this be possible at all? How careful must I be with updates? I.e. if the linux updater installs a sqcurity patch, would it be safe to not install it in windows? A: You could do a dump export when you shut down after changes are made, and then import when starting the other OS. In this case, however, you may consider not having MySQL start automatically.
{ "pile_set_name": "StackExchange" }
Q: Changing collectionview button's image in Cocoa Tools: xCode, Objective-C, Mac, Cocoa Purpose: I am creating a collection view with many buttons. Each button opens a file in a folder and each of them has a background picture of the file (for example: jpeg file) so it looks like what you would see in a folder. Question: How to make each button have a different image? Also, is this too difficult for a beginner? P.S. : If i did this without the collectionview option, I would just drag the button on xib and change their background images, however I need my window to be collapsable and scrollable, hence I am using the collection view. I would very much appreciate any comments/help/answers. Thanks! A: This should not be difficult. A CollectionView holds a collection of CollectionViewItems. Inside the Item you can create any views you need. One of them could be an NSImageView that you set at runtime to the image you like. I suggest to play around with CollectionView and some f the samples Apple provides on it.
{ "pile_set_name": "StackExchange" }
Q: Dual Monitors with DisplayPort and DVI-D I have a Dell Optiplex 990 with an AMD Radeon HD 6670 graphics card. I would like to use my two Dell UltraSharp U2711 monitors in a dual configuration with my computer. Both monitors have a single DisplayPort port and two DVI-D connectors. The graphics card has one Displayport and one DVI-D. The motherboard on the computer also has a DisplayPort and DVI-D wired directly into it. My first guess for how to do this is to connect both monitors directly to the graphics card, one via DisplayPort, one via DVI-D. However, is it possible to connect the two monitors to each other via DVI-D and one to the computer via DisplayPort? Am I correct to assume that I should not use the port wired into the motherboard? What is the best way to configure the cables for connecting the monitors to the computer? Thank you for your help. A: The ATI 6000 series supposed supports DisplayPort spec 1.2 which supports Daisy-Chaining. However, I'm not sure how it would connect in your case as each of your monitors only contains a single DP connector. You're probably best off using one DP and one DVI connection.
{ "pile_set_name": "StackExchange" }
Q: What polygons can be shrunk into themselves? Let's call a polygon $P$ shrinkable if any down-scaled (dilated) version of $P$ can be translated into $P$. For example, the following triangle is shrinkable (the original polygon is green, the dilated polygon is blue): But the following U-shape is not shrinkable (the blue polygon cannot be translated into the green one): Formally, a compact $\ P\subseteq \mathbb R^n\ $ is called shrinkable iff: $$\forall_{\mu\in [0;1)}\ \exists_{q\in \mathbb R^n}\quad \mu\!\cdot\! P\, +\, q\ \subseteq\ P$$ What is the largest group of shrinkable polygons? Currently I have the following sufficient condition: if $P$ is star-shaped then it is shrinkable. Proof: By definition of a star-shaped polygon, there exists a point $A\in P$ such that for every $B\in P$, the segment $AB$ is entirely contained in $P$. Now, for all $\mu\in [0;1)$, let $\ q := (1-\mu)\cdot A$. This effectively translates the dilated $P'$ such that $A'$ coincides with $A$. Now every point $B'\in P'$ is on a segment between $A$ and $B$, and hence contained in $P$. My questions are: A. Is the condition of being star-shaped also necessary for shrinkability? B. Alternatively, what other condition on $P$ is necessary? A: Any simply connected polygon must be star-shaped to be shrinkable. I have made minor edits below to treat the more general case. Let $D$ be a polygon with convex hull $H$. Assume we are given a non-trivial shrinking of $D$; view this as a map from $H$ to itself. This map must have a fixed point $x$, either by algebraic topology or an iterative construction. This means it suffices to consider only dilations centered at a point $x$ in $H$, rather than dilations followed by translations. For any $x$, if there is a point $y$ in $D$ so that the segment from $x$ to $y$ is not contained in $D$, then a $(1-\epsilon)$-dilation of $H$ centered at $x$ will not carry $D$ into $D$ for any positive $\epsilon$ smaller than some $\epsilon(x)>0$. If $D$ is not star-shaped, take the minimum $\delta$ of $\epsilon(x)$ over $x\in H$, and then no $(1-\delta)$-dilation of $H$ centered at a point in $H$ carries $D$ into $D$. A: Let $\ L\ $ be a Hilbert space. Let $\ P\subseteq L\ $ be a non-empty compact subset. Then $\ P\ $ is called $\ \mu$-shrinkable $\ \Leftarrow:\Rightarrow$ $$\exists_{q\in L}\ \ \mu\cdot P\ +\ q\ \subseteq\ P$$ for arbitrary $\ \mu\ge 0\ $ (thus $\ \mu \le 1\ $ when $\ |P|>1$). Let $\ m(P)\ $ be the set of all $\ \mu\ge 0\ $ such that $\ P\ $ is $\ \mu$-shrinkable. Following @E.S.Halevi, let $\ P\ $ be called shrinkable $\ \Leftarrow:\Rightarrow\ \ m(P) = [0;1].\ $ Then THEOREM  The following three properties of a non-empty compact $\ P\subseteq L\ $are equivalent: P is a star set; P is shrinkable; $\ \sup (\ m(P)\cap[0;1)\ )\ =\ 1$ PROOF   Implications $\ 1\Rightarrow 2\Rightarrow 3\ $ are trivial. we need only $\ 3\Rightarrow 1.\ $ Thus assume condition $3$. Consider map $\ f_\mu : x\mapsto \mu\cdot x + q_\mu,\ $ of $\ P\ $ into itself, for every $\ \mu\in m(P)\cap[0;1).\ $ Then by Banach's fpp there exists a unique $c_\mu\in P\ $ such that $\ c_\mu = \mu\cdot c_\mu + q_\mu,\ $ so that $\ q_\mu = (1-\mu)\cdot c_\mu.\ $ Thus there is a limit point $\ c_1\in P\ $ of a certain sequence of points $\ c_\mu\ $ for which $ \lim \mu = 1$. Observe that for $\ \nu:=\mu^k\ $ the composition $\ g_\nu:=\bigcirc^k f_\mu\ $ has the same fixed point (I am going to choose at the most one $\ k\ $ for each $\ \mu;\ $ also $$\forall_{x\in L}\ \ g_\nu(x)\ =\ \nu\cdot x\ +\ (1-\nu)\cdot c_\mu$$ Now let's consider an arbirary $\ \kappa\in[0;1).\ $ I'll show that function $$\ F_\kappa\ :\ x\ \mapsto\ \kappa\cdot (x-c_1)+c_1\ \ =\ \ \kappa\cdot x\ +\ (1-\kappa)\cdot c_1$$ maps $\ P\ $ into itself (for every such $\kappa,\ $ so that will be the end of the proof). Thus let $\ \epsilon > 0.\ $ Then there exist $\ \mu\in[0;1)\ $ and natural $\ k,\ $ such that $\ |c_\mu-c_1|<\epsilon\ $ and $\ |\nu-\kappa|<\epsilon\ $ for $\ \nu:=\mu^k,\ $ hence for arbitrary $\ x\in P$: $$ |g_\nu(x)-F_\kappa(x)|\ \le\ |g_\nu(x)-F_\nu(x)|\ +\ |F_\nu(x)-F_\kappa(x)|$$ where $$\ |F_\nu(x)-F_\kappa(x)|\ =\ |(\nu-\kappa)\cdot x + (\kappa-\nu)\cdot c_1|\ =\ |\nu-\kappa|\cdot|x-c_1|$$ henceforth $$|F_\nu(x)-F_\kappa(x)|\ \le\ \epsilon\cdot |x-c_1|$$ Next $$|g_\nu(x)-F_\nu(x)|\ =\ |(1-\nu)\cdot c_\mu - (1-\nu)\cdot c_1|\ =\ |1-\nu|\cdot|c_\mu-c_1|\ \le\ \epsilon$$ These inequalities imply: $$ |g_\nu(x)-F_\kappa(x)|\ \le\ (|x-c_1|+1)\cdot\epsilon$$ or $$ |g_\nu(x)-F_\kappa(x)|\ \le\ D\cdot\epsilon$$ where  $\ D := diam(P)$ Thus for every $\ \delta > 0\ $ let $\ \epsilon:=\frac\delta D\ $ such that... OK, enough of this $\delta$-$\epsilon$ business, $\ F_\kappa(x)\in P$. END of PROOF REMARK The theorem holds not just for the Hilbert spaces but also for Banach spaces. One should be also able to replace translations by arbitrary linear isometries. I am even curious and hopeful about considering this kind of theorems for the locally convex linear spaces.
{ "pile_set_name": "StackExchange" }
Q: How to get all(!) closest directives/components in Angular? Looking at : <div class="widget-content"> <div class="widget-content"> <div> <widget-item></widget-item> </div> </div> </div> I'm able to get the first(!) closest widget-content within the <widget-item></widget-item> component. It's pretty easy to do it by creating a directive : @Directive({ selector: '.widget-content' }) export class WidgetContentDirective { } And by Injecting to the constructor of widget-item : constructor(private widgetContentQuery: WidgetContentDirective) { } ngOnInit() { console.log(this.widgetContentQuery); } Result : Question: There are two widget-content wrappers. How can I get an array of them both within the widget-item constructor ? full disclosure: for learning purpose. There is no real scenario. ( I'm not after jQuery solutions) Stackblitz A: Well, that's an unusual request, but I believe there is a way to do this. It's not easy, but it uses an InjectionToken on the WidgetContentDirective: stackblitz Basically you've got this InjectionToken: export const WidgetContents: InjectionToken<WidgetContentDirective[]> = new InjectionToken('WIDGET_CONTENTS'); And using @Optional() and @SkipSelf() inject this in the providers array of your WidgetContentDirective, together with the current WidgetContentDirective: @Directive({ selector: '.widget-content', providers: [{ provide: WidgetContents, useFactory: ( widgetContent: WidgetContentDirective, parents?: WidgetContentDirective[] ) => { // filter because of optional return [widgetContent, ...parents].filter(widget => widget); }, deps: [ forwardRef(() => WidgetContentDirective), [new Optional(), new SkipSelf(), new Inject(WidgetContents)] ] } ] }) You can then use this InjectionToken inside your WidgetItemComponent: export class WidgetItemComponent implements OnInit { constructor( @Inject(WidgetContents) private widgetContentQuery: WidgetContentDirective[] ) {} ngOnInit() { console.log(this.widgetContentQuery); } }
{ "pile_set_name": "StackExchange" }
Q: How to convert properties to JSON the Spring MVC way? I need my web service to serve me the messages.properties which contains localized texts in JSON format. I know that I can write my own parser to do that but where should I insert this logic in the Spring framework? Or is there a Spring infrastructure feature that already can do that? A: You can use @PropertySource annotation on your class to load your property file into memory. @Configuration class MessagesConfiguration { @Bean(name = "messageProperties") public static PropertiesFactoryBean mapper() { PropertiesFactoryBean bean = new PropertiesFactoryBean(); bean.setLocation(new ClassPathResource("messages.properties")); return bean; } @Resource(name="messageProperties") private Properties messages = new Properties(); public Properties getMessages() { return messages; } } Properties.class is just a wrapper for Map<String, String> so you can convert it to JSON.
{ "pile_set_name": "StackExchange" }
Q: Where can I find the yum repos files for centos 4.7 i386? Does anyone know where I can find the i386 centos 4.7 repos files that would normally sit in /etc/yum.repos.d. Alas, it looks like someone copied the 5.5 edition over to a 4.7 system. I can setup a new VM, install 4.7 and extract the files from that system (but I was hoping for a faster approach. Please let me know if you know where these files live on the net. I'm off to RPMfind to see what I can locate. Thanks Peter A: They should be in this RPM: http://vault.centos.org/4.7/os/i386/CentOS/RPMS/centos-release-4-7.i386.rpm
{ "pile_set_name": "StackExchange" }
Q: Convert a 9 digit Canadian SIN to an 11 character SIN (adding spaces) in SQL Server I am importing data that is providing a Canadian Sin in 9 digit string and I need to convert it to an 11 digit Sin (adding spaces every three characters). So the original value of 123456789 becomes 123 456 789. The 11 digit Sin is how the rest of the database looks up people by Sin. Trying to find a T-SQL procedure to convert from 9 to 11. A: Another way would be STUFF select stuff(stuff(123456789,4,0,' ' ),8,0,' ' ) So... select stuff(stuff([Sin],4,0,' ' ),8,0,' ' )
{ "pile_set_name": "StackExchange" }
Q: Designing configuration for subobjects I have the following situation: I have a class (let's call it Main) encapsulating a complex process. This class in turn orchestrates a sequence of subalgorithms (AlgoA, AlgoB), each one represented by an individual class. To configure Main, I have a configuration stored into a configuration object MainConfig. This object contains all the config information for AlgoA and AlgoB with their specific parameters. AlgoA has no interest to the information relative to the configuration of AlgoB, so technically I could have (and in practice I have) a contained MainConfig.AlgoAConfig and MainConfig.AlgoBConfig instances, and initialize as AlgoA(MainConfig.AlgoAConfig) and AlgoB(MainConfig.AlgoBConfig). The problem is that there is some common configuration data. One example is the printLevel. I currently have MainConfig.printLevel. I need to propagate this information to both AlgoA and AlgoB, because they have to know how much to print. MainConfig also needs to know how much to print. So the solutions available are I pass the MainConfig to AlgoA and AlgoB. This way, AlgoA has technically access to the whole configuration (even that of AlgoB) and is less self-contained I copy the MainConfig.printLevel into AlgoAConfig and AlgoBConfig, so I basically have three printLevel information repeated. I create a third configuration class PrintingConfig. I have an instance variable MainConfig.printingConfig, and then pass to AlgoA both MainConfig.AlgoAConfig and MainConfig.printingConfig. Have you ever found this situation? How did you solve it ? Which one is stylistically clearer to a new reader of the code ? A: I would say it's better to have multiple small classes with a single responsibility than one big god-configurator, even if that means you will have some duplication. If the duplicate logic is complicated, (I'm assuming that printLevel was just an oversimplified example) then you can solve it with creating an object specifically for printLevel and packing it in the others. In your example, this would mean delete MainConfig completely and put the common printing configuration in a PrintConfig aggregate the new class where it's needed, for ex AlgoAConfig.PrintConfig and AlgoBConfig.PrintConfig
{ "pile_set_name": "StackExchange" }
Q: Filtering results based on most common occurrences of values in other columns (excluding outlying values) Consider the following table and pseudo query: Distinct Customers WHERE Most common PaymentMethod = 'CreditCard' AND Most common DeliveryService = '24hr' Customer TransID PaymentMethod DeliveryService ----------------------------------------------------- Susan 1 CreditCard 24hr Susan 2 CreditCard 24hr Susan 3 Cash 24hr John 4 CreditCard 48hr John 5 CreditCard 48hr Diane 6 CreditCard 24hr Steve 7 Paypal 24hr Steve 8 CreditCard 48hr Steve 9 Paypal 24hr Should return (2) records: Customer --------- Susan Diane Another way to look at it is that I want to exclude minority cases, i.e.: I don't want to return 'Steve', because although he used a creditcard once, he doesn't generally do so, I only care about the majority behaviour, across multiple columns. In reality, there are more columns (10s) that need the same principle applied so I'm after a technique that will scale at least that far searching 100ks of records. A: One method uses window functions and aggregation: with cp as ( select customerid, paymentmethod, count(*) as cnt, rank() over (partition by customerid order by count(*) desc) as seqnum from t group by customerid, paymentmethod ), cd as ( select customerid, deliveryservice, count(*) as cnt rank() over (partition by customerid over by count(*) desc) as seqnum from t group by customerid, deliveryservice ) select cp.customerid from cp join cd on cp.customerid = cd.customerid where (cp.seqnum = 1 and cp.PaymentMethod = 'CreditCard') and (cd.seqnum = 1 and cd.DeliveryService = '24hr'); Because you need the ranks along two different dimensions, I think you need two subqueries (or the equivalent).
{ "pile_set_name": "StackExchange" }
Q: Comparing elements of deque and list I have currently this piece of code import collections as c a1 = ['a' , 'b','c'] q1 = c.deque(maxlen=3) q1.append('a') q1.append('d') q1.append('c') q1 = list(q1) counter = 0 for i in q1: if i == q1.dequeue(): counter += 1 Is there any faster or more efficent way to compare the elements of 2 lists and evaluating the overlap between them? A set is not the way to go as i need the duplicate elements and they would have to be in order. Lists are ordered elements. Hence my deqeue would have a length equivalent to the list. I would to compute how much overlap is between the list and the dequeue. A: Based on your revised question, I would take advantage of the fact that deque objects can be iterated by running over the zip of the list and deque objects. EG: import collections as c a1 = ['a' , 'b','c'] q1 = c.deque(maxlen=3) q1.append('a') q1.append('d') q1.append('c') counter = sum(1 if a == q else 0 for (a, q) in zip(a1, q1)) # or, they're basically equivalent counter = sum(1 for (a, q) in zip(a1, q1) if a == q) That will compute the number of indices at which a1 and q1 have the same value, ending as soon as either is exhausted (so if a1 is 100 elements long, only the first three will be checked).
{ "pile_set_name": "StackExchange" }
Q: Eruv around towns for the purpose of carrying I was learning the first few chapters of Eyruvin, and I wondering which of the mishnas are the source (or inspiration more likely) for the idea of a string around an area that allows one to carry inside that area. I would have thought that case of the caravan where they create a "wall" of three strings (1:10) would be the most analogous case, with the issue that as mentioned in the footnotes (it mentioned Eruvin 17b, but don't see where, but I see where it is in the Rambam Hilchot Shabbat 16:12 if I am reading it right) that one cannot enclose an area that has an empty area of size beit satyam (5000 sq amot). It would seem to me that parks, and many other places probably (parking lots?) would fall under this category. So in essence I have three questions: Is Eruvin 1:10 the source/inspiration for the eruv around towns that exist today? If so and if the issue of the beit satyam of "utensil-less space" is in the gemara, then how is this issue dealt with? If the issue is not brought up in the Gemara, then where does the Rambam get this idea? A: Eruvin 1:10 is actually talking about a different kind of mechitzah, one based on the halachic principle of lavud (where objects within three tefachim of each other are considered joined). So the case there is that they place vertical stakes in the ground, each within three tefachim of the next. (The previous mishnah describes the opposite case - where they string horizontal ropes whose aggregate thickness is more than a tefach, and place them within three tefachim of each other, thus creating a partition ten tefachim tall - the minimum for it to be valid.) Today's eruvin use instead a series of tzuras hapesach, doorframes (a pair of vertical poles, such as utility poles, and a horizontal crossbeam or wire atop them), which halachically can be considered walls. The concept is mentioned in Eruvin 1:1, and the details - in particular, the idea of using a series of them - in the Gemara ibid. 11a; Rambam deals with it in Hil. Shabbos 16:16. It should be noted, though, that Rambam would not accept most present-day city eruvin, because he understands the Gemara there to be saying that in any eruv that doesn't use lavud as its operating principle, there must be more filled-in space than open space (e.g., for an eruv whose perimeter is 2 miles, the material for the partitions must have an aggregate width of over one mile). Shulchan Aruch, Orach Chaim 362:10 cites other opinions that this is not necessary, and it is those opinions that those who make and use city eruvin follow. (Some people will not use such eruvin, either because they hold with Rambam's opinion, or because of other halachic and/or meta-halachic considerations.) A: In the positive integer number of Eruvin that I've seen, the Eruv excludes uninhabitable and purposeless land (such as cemeteries and bodies of water) from its boundary by encircling that land with another internal set of strings, poles and fences.
{ "pile_set_name": "StackExchange" }
Q: Fast replacement of tzinfo of a pandas.Series of datetime I have a pandas.Seriesof datetime and need to replace the tzinfo for every element in it. I know how to do it using apply with python function but it's very slow: ~16s for 1M elements on a MacBookPro In [71]: s = pd.date_range('2015-1-1', freq='h', periods=1e6).to_series().reset_index(drop=True) In [72]: %timeit s.apply(lambda x: x.replace(tzinfo=pytz.utc)) 1 loops, best of 3: 16.7 s per loop Is there a numpy ufunc function for it? A: Use dt.localize: In [33]: import pytz %timeit s.dt.tz_localize(pytz.utc) %timeit s.apply(lambda x: x.replace(tzinfo=pytz.utc)) 10 loops, best of 3: 107 ms per loop 1 loops, best of 3: 10.4 s per loop As you can see ~100X faster
{ "pile_set_name": "StackExchange" }
Q: How do i achieve this sort of swipe navigation I have a grid layout containing multiple linear layouts. Each linear layout contains an image view and a text view. Currently all the images and their description appear on the screen but i want to create a swipe functionality which will make another set of images appear when the user swipe the screen. I want to create something just like this what i want to achieve Here is my xml file <GridLayout android:layout_width="match_parent" android:layout_height="match_parent" android:columnCount="4"> <LinearLayout android:onClick="facility_click" android:id="@+id/layout_facility1" android:layout_columnWeight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/image1" android:layout_width="50dp" android:layout_height="100dp" android:layout_gravity="center" android:src="@drawable/fridge1"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Fridge" android:textAlignment="center"/> </LinearLayout> <LinearLayout android:onClick="facility_click" android:id="@+id/layout_facility2" android:layout_columnWeight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/image2" android:layout_width="50dp" android:layout_height="100dp" android:layout_gravity="center" android:src="@drawable/alarmclock" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Alarm clock" android:textAlignment="center"/> </LinearLayout> <LinearLayout android:onClick="facility_click" android:id="@+id/layout_facility3" android:layout_columnWeight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/image3" android:layout_width="50dp" android:layout_height="100dp" android:layout_gravity="center" android:src="@drawable/dishwasher1" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Dish washer" android:textAlignment="center"/> </LinearLayout> <LinearLayout android:onClick="facility_click" android:id="@+id/layout_facility4" android:layout_columnWeight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/image4" android:layout_width="50dp" android:layout_height="100dp" android:layout_gravity="center" android:src="@drawable/fridge1" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Fridge" android:textAlignment="center"/> </LinearLayout> <LinearLayout android:layout_columnWeight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:layout_width="50dp" android:layout_height="100dp" android:layout_gravity="center" android:src="@drawable/fridge1"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Fridge" android:textAlignment="center"/> </LinearLayout> <LinearLayout android:layout_columnWeight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:layout_width="50dp" android:layout_height="100dp" android:layout_gravity="center" android:src="@drawable/alarmclock" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Alarm clock" android:textAlignment="center"/> </LinearLayout> <LinearLayout android:layout_columnWeight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:layout_width="50dp" android:layout_height="100dp" android:layout_gravity="center" android:src="@drawable/dishwasher1" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Dish washer" android:textAlignment="center"/> </LinearLayout> <LinearLayout android:layout_columnWeight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:layout_width="50dp" android:layout_height="100dp" android:layout_gravity="center" android:src="@drawable/fridge1" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Fridge" android:textAlignment="center"/> </LinearLayout> </GridLayout> A: I'd guess that you need ViewPager: https://developer.android.com/training/animation/screen-slide.html Each "grid" will be separate fragment. EDIT: Also see this: it seems very simmilar to what you want to get: Android ViewPager with bottom dots
{ "pile_set_name": "StackExchange" }
Q: Norm of operator $g\mapsto \int fg$ Let $T_f:(C([a,b],\mathbb C), \lVert \cdot \rVert_1) \to \mathbb C$ with $g\mapsto \int_a^b f(x)g(x) dx$ for any given $f\in C([a,b],\mathbb C)$. I have to find the norm of $T_f$. I started with: $$|T_fg| = \left|\int_a^b f(x)g(x)dx\right| \leqslant\int_a^b |f(x)g(x)|dx \leqslant\lVert g \rVert _1 \lVert f \rVert _\infty.$$ For the last step I used Hölder. Now all I need is an example $g\in C([a,b],\mathbb C)$ with $\lVert g \rVert_1 = \int_a^b |g(x)|dx = 1$ and $|T_fg| = \lVert f \rVert _\infty$ (I suppose $\lVert f \rVert _\infty$ is the operator norm here). I have tried several functions, but none worked, maybe $\lVert T_f \rVert < \lVert f \rVert _\infty$? A: Assume that $\max_{0\leqslant t\leqslant 1}|f(t)|=f(x_0)$ for some $x_0\in [0,1]$. I assume that $t\in (0,1)$, otherwise the argument can be adapted. Let $g_n$ the function such that $g_n=1$ on $(x_0-n^{-1},x_0+n^{-1})$, $0$ on $[0,x_0-2n^{-1})$ and $[x_0+2n^{-1},1)$, and piecewise linear. Then $$T_f(g_n)=2n^{-1}f(x_0)+\int_{x_0-2n^{-1}}^{x_0-n^{—1}}f(t)g_n(t)dt+\int_{x_0+n^{-1}}^{x_0+2n^{—1}}f(t)g_n(t)dt.$$ We have $\lVert g_n\rVert=3n^{-1}$, and $$T_f(g_n)=3n^{-1}f(x_0)-\int_{x_0-2n^{-1}}^{x_0-n^{—1}}(f(t)-f(x_0)g_n(t)dt+\int_{x_0+n^{-1}}^{x_0+2n^{—1}}(f(t)-f(x_0))g_n(t)dt\\ .$$ By continuity of $f$, $$\lim_{n\to +\infty}\frac{\int_{x_0+n^{-1}}^{x_0+2n^{—1}}(f(t)-f(x_0))g_n(t)dt-\int_{x_0-2n^{-1}}^{x_0-n^{—1}}(f(t)-f(x_0)g_n(t)dt}{\lVert g_n\rVert}=0$$ so we get the result.
{ "pile_set_name": "StackExchange" }
Q: Diagonlisation of certain matrices Why is it that the matrix $\begin{pmatrix} -1 & -3 & -1 \\ -3 & 5 & -1 \\ -3 & 3 & 1 \end{pmatrix}$ is diagonalisable, even though it has eigenvalues 1, 2, 2 (which are not all distinct) but $\begin{pmatrix} 1 & 1 & 0 \\ -1 & 3 & 0 \\ 0 & 1 & 3 \end{pmatrix}$ is not, despite the fact that it too has two eigenvalues which are not distinct (in fact exactly the same eigenvalues: 1, 2, 2)? A: A $n \times n$ matrix (over $\mathbb{R}$ or any other field) is diagonalizable if the set of his eigenvector is a basis for $\mathbb{R}^n$. So the matrix must have $n$ linearly independent eigenvector. For $n=3$, if the matrix has an eigenvalue of multiplicity $2$ (as in your case), then we have two possibilities: 1) this ''double'' eigenvalue has two linearly independent eigenvector, and in this case we say that it has algebraic multiplicity $2$ and geometric multiplicity $2$ ( this means that the eigenvalue ''span'' a plane in $R^3$). 2) The ''double'' eigenvalue has only one eigenvector, and his geometric multiplicity is $1$ ( the eigenvalue ''span'' a straight line). So, your first matrix has two distinct eigenvalues, one of them ( $\lambda=2$) of algebraic multiplicity 2, but has three linearly independent eigenvectors since $\lambda=2$ has geometric multiplicity $2$. So this matrix is diagonalisable. For the second matrix you can see that the geometric multiplicity of the eigenvalue $\lambda=2$ is $1$, so that there are not three linearly independent eigenvectors.
{ "pile_set_name": "StackExchange" }
Q: Speakers' location in determining venir vs. ir In English, we use the word "come" very loosely (at least in day-to-day spoken English): Want to come over to my place later? Can I come over to your house for New Years'? Can you come meet me at the coffee shop after work? I'll bring pictures of the kids the next time I come visit you in Florida. etc. In other words, "come" can be used regardless of where the speaker and the listener are located, either now or in the future. In Spanish, I've heard that venir is supposed to be used only for situations where the listener is coming to the speaker's current location, and ir should be used for other situations (the same goes for traer and llevar). Is this the rule? If so, is it just in formal, written contexts, or does it apply to spoken language too? A: Yes, you use "venir" when moving to the speaker's current location, and "ir" to another location. However, as in English, you can say "¿Quieres venir a mi casa?" without being in said place. The RAE has a very simple but good explanation: Venir Llegar a donde está quien habla. Ir Moverse de un lugar hacia otro apartado de quien usa el verbo ir y de quien ejecuta el movimiento. From rae.es Venir and Ir.
{ "pile_set_name": "StackExchange" }
Q: Scheduling a task in Java for a specified date i am looking forward to learn java. I made this program , so that when the current date matches the specified date, it will execute some code, in this case, it will exit the while loop. I'd like to know if there any other ways, but for now i will stick with this string comparison. For somewhat reasons the If loop isn't working properly, i monitor the current date with System.out.println(date) but when it reaches the desired date (by format HH:MM:SS) to do the action,the strings aren't equal and the while loop continues, is there anything i miss? EDIT: Platform = windows 7 public class Main { static String DesiredDate; static String date; static boolean Programisrunning; public static void main(String[] args) { DesiredDate = "17:24:10"; while(Programisrunning = true) { date = CurrentDate.GetDate(); System.out.println(date); if(date.equals(DesiredDate)) { Programisrunning = false; } } System.out.println("Program succesfully terminated"); } } //another class import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class CurrentDate { public static String GetDate(){ DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } } A: Executors While loop solution is bad because CPU is busy. Use executors, specifically ScheduledExecutorService. long delay = desiredDate.getTime() - System.currentTimeMillis(); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.schedule(task, delay, TimeUnit.MILLISECONDS); A: To schedule a task, use a ScheduledExecutorService: Date desiredDate = // ... Date now = new Date(); long delay = desiredDate.getTime() - now.getTime(); ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor(); ses.schedule(new Runnable(){ @Override public void run() { Programisrunning = false; // + do other things? } }, delay, TimeUnit.MILLISECONDS); // run in "delay" millis
{ "pile_set_name": "StackExchange" }
Q: C++ What does delete pointer,pointer=0; statement work ? Does it clear memory twice? int *ptr = new int(10); printf("%d \n",*ptr); delete ptr,ptr=0; printf("%d",ptr); Output: 10 0 My question here is how this statment "delete ptr,ptr = 0" works ? Does it free the memory twice ? A: The pointer and the memory the pointer points to are 2 different things. Setting the pointer to 0 after you delete it is just an added safety mechanism to ensure you don't try to use a memory address that you shouldn't. int *ptr = new int(10); ptr will have a value like 0xabcd1234, but *ptr will be 10 You can "do stuff" with the memory address 0xabcd1234 because it's allocated to you. printf("%d \n",*ptr); delete ptr,ptr=0; delete ptr "gives back" the memory, but you still have it's address (that's dangerous_. ptr = 0 means you forget the address, so all is good. I guess the "trick" is the comma operator: delete ptr,ptr=0; which as other have said means "do the left hand part, then the right hand part." If you try to get a result (int i_know_it_is_a_stupid_example = 10,20; the result is the RHS [20]) A: delete ptr Frees the memory at the address pointed to by ptr. However, ptr still points to that memory address. ptr = 0 ptr no longer points to a specific memory address. Therefore, the point of ptr = 0 is to enable the programmer to test whether the pointer is still usable (in use). If you don't set ptr = 0, but only delete ptr, ptr will still point to a location in memory which may contain garbage information. A: No, it won't. In C++, it's comma operator . Quote from wiki: In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). Therefore, in that statement delete ptr, ptr = 0; is equivalent to delete ptr; // executed first, its return value is ignored ptr = 0; // the return value of '=', which is '0' is returned by ',' operator
{ "pile_set_name": "StackExchange" }
Q: Manipulating height attribute of renderPlotly object? I want to include multiple plots of varying heights within a single shiny dashboard tab. Many existing answers cover setting the height parameter in ggplotly. Using this parameter does change how a figure will render. But, it doesn't fix my problem. Objects around it render as if the adjusted figure still has its original height. For example, if the first figure is lengthened, the second figure will appear over top of it. Or, if the first figure is shortened, there will be a large empty space before the next figure. Alexander Leow provides one solution to my problem in his buried answer to the following question: Shiny plotlyOutput() not responding to height and width sizes Unfortunately, his answer seems unnecessarily complicated by the multiple plot list structure. I tried to adapt his solution for a single plot but I was unsuccessful. The following code produces an error when running in an app: "object type closure is not subsettable" library(plotly) library(shiny) library(shinydashboard) ui <- dashboardPage(dashboardHeader(title = "Test"), dashboardSidebar( menuItem("Test", tabName = "test") ), dashboardBody( tabItems( tabItem(tabName = "test", fluidRow( column(12, uiOutput('plot')) ) ) ) ) ) server <- function(input, output) { output$plot <- renderUI({ plot_output_object <- renderPlotly({ p <- ggplot() + geom_point(aes(x=1,y=2)) ggplotly(p) }) attr(plot_output_object,'outputArgs') <- list(height="200px") return(plot_output_object) }) } shinyApp(ui = ui, server = server) The following example demonstrates how the ggplotly height parameter does not solve my issue. There is a large gap between the first and second plots. library(shiny) library(shinydashboard) library(plotly) ui <- dashboardPage(dashboardHeader(title = "Test"), dashboardSidebar( menuItem("Test", tabName = "test") ), dashboardBody( tabItems( tabItem(tabName = "test", fluidRow( column(12, plotlyOutput('plot')) ), fluidRow( column(12, plotlyOutput('plot2')) ) ) ) ) ) server <- function(input, output, session) { output$plot <- renderPlotly({ p <- ggplot() + geom_point(aes(x = 1, y = 2)) ggplotly(p, height = 200) }) output$plot2 <- renderPlotly({ p2 <- ggplot() + geom_point(aes(x = 1, y = 2)) ggplotly(p2) }) } shinyApp(ui = ui, server = server) A: ggplotly has a height argument. The following should do the job: library(shiny) library(shinydashboard) library(plotly) ui <- dashboardPage(dashboardHeader(title = "Test"), dashboardSidebar( menuItem("Test", tabName = "test") ), dashboardBody( tabItems( tabItem(tabName = "test", fluidRow( column(12, plotlyOutput('plot', height = "200px")) ), fluidRow( column(12, plotlyOutput('plot2')) ) ) ) ) ) server <- function(input, output, session) { output$plot <- renderPlotly({ p <- ggplot() + geom_point(aes(x = 1, y = 2)) ggplotly(p, height = 200) }) output$plot2 <- renderPlotly({ p2 <- ggplot() + geom_point(aes(x = 1, y = 2)) ggplotly(p2) }) } shinyApp(ui = ui, server = server)
{ "pile_set_name": "StackExchange" }
Q: IIS script privileges with powershell I've created a script for most of the functions I need when creating a Site for my IIS, however, there is still one thing missing. Namely, I can't seem to find the commands for setting script privileges on a Site. I want all script rights but no execution rights if I've understood it correctly. So, how do you set those privileges through powershell? Edit: The answer I was looking for was: set-webconfigurationproperty -filter /system.webserver/handlers -name accesspolicy -value $flagsPermissions -PSPath $PS_PATH -Location $siteDescription It works nicely. A: A new site on IIS 7+ should have it's handler accessPolicy set to 'Read, Script' so that's exactly what you want, no need for changes. If you still want to change it: You could use appcmd.exe from PowerShell: appcmd set config /section:handlers /accessPolicy:Read,Script More info on TechNet For specific sites this setting is usually set in web.config rather than ApplicationHost.config
{ "pile_set_name": "StackExchange" }
Q: How to read from stdin each byte and process them in c# I have a problem to reading each byte goes to stdin in c# from another application. The code is simple: Stream instrm=Console.OpenStandardInput(); while(true){ int b=instrm.ReadByte(); Environment.Exit(1); } How I think it should work: When on instrm will be a byte - application will close. But when I fire bytes to application, nothing happening. Am I doing it in wrong way, or what? any clues... A: There is another solution for me: compile project using .net version 3.5 or lower, in that case everything starts work as expected.
{ "pile_set_name": "StackExchange" }
Q: My loop works like this: loop, script, loop. I want this: loop, loop, code. The ForgottenServer 0.3.6 this is the code with loop: for _, pid in ipairs(getPlayersOnline()) do if getCreatureStorage(pid, tmp[i].storeDamage) > -1 then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_ORANGE, getPlayerName(pid)..': '..getCreatureStorage(pid, 11005)) end doCreatureSetStorage(pid, tmp[i].storeDamage, -1) end every players with a storage 11005 get the message like: Player name:random number The current player is CID and every online players are PID. Now I want to set the random number to -1 after the message is shown to every online players. The problem is that the loop works like this: show the message to CID (first player) then reset number to -1 and then show the message to second player. It cannot be done that way, because first player sees correct message like: player name1:number of player1, player name2:numberof player2 but second player sees player name1:-1(number of this player), player name2:-1 (nr of second player). Loop has been done this way probably: loop, setStorage, loop. I need this way: loop, loop, set storage. I've tried to check the last loop using " if next(getPlayersOnline(), _) == nil then , but does not work. A: Can you just move the "set storage" to a second loop after the first? That's the only way that you'll be able to send all of the messages before doing any of the set storage calls. for _, pid in ipairs(getPlayersOnline()) do if getCreatureStorage(pid, tmp[i].storeDamage) > -1 then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_ORANGE, getPlayerName(pid)..': '..getCreatureStorage(pid, 11005)) end end for _, pid in ipairs(getPlayersOnline()) do doCreatureSetStorage(pid, tmp[i].storeDamage, -1) end
{ "pile_set_name": "StackExchange" }
Q: How to generate SHA1 fingerprint for OAuth client ID, for two different projects? I am trying to generate SHA1 fingerprint for OAuth client ID , its generating successfully but problem is that i am using same SHA1 fingerprint(in both project android studio generate same SHA1 fingerprint) for two different project with different package name . see the image below ! Note : i found this link but never answered ! SHA1 fingerprint already used by another OAuth2 client How to create OAuthClient Id in Goole API console for multiple projects Thank You ! A: finally i am able to deploy two or more projects , so trick is that don't insert your SHA1 code in any projects . Note: I don't know what happen if i published apk on aplaystore
{ "pile_set_name": "StackExchange" }
Q: JSON parser error with java: I would like to parse a json file, here is my code: import org.json.JSONArray; import org.json.JSONObject; public class principale { public static void main(String[] args) { // TODO Auto-generated method stub String fichier ="C:\\listesanscoord.json"; JSONObject obj = new JSONObject("fichier"); String pageName = obj.getJSONObject("pageInfo").getString("pageName"); JSONArray arr = obj.getJSONArray("oaci"); for (int i = 0; i < arr.length(); i++) { String url = arr.getJSONObject(i).getString("url"); } } } and here is my json file: listesanscoord.json I have the following error: Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1] at org.json.JSONTokener.syntaxError(JSONTokener.java:433) at org.json.JSONObject.<init>(JSONObject.java:198) at org.json.JSONObject.<init>(JSONObject.java:325) at metar.principale.main(principale.java:13) Can someone help me please I am unable to find where is the problem, thank you. A: In Extension to @nogard answer I detected that there is error in JSON text in your file ,JSON string are like java map or javascript object have key value pairs,in your file key is define wrongly, it should be in double quotes (" ") so key value pair will look like "key":"value String" or "key":value Number. For more info look link. After modification your json will look like below. [ { "oaci": "LFXA", "aeroport": "Aérodrome d'Ambérieu", "url": "https://fr.wikipedia.org/wiki/A%C3%A9rodrome_d%27Amb%C3%A9rieu", "commune": "Chateau-Gaillard, Ambronay" } //more json objects ] if you modify your json file like above will resolve your problem.
{ "pile_set_name": "StackExchange" }
Q: Highlighting active tab in navigation I am trying to highlight the active tab in my tabbed navigation site. This is html snippet for tabs. <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Title here</title> <link href="style.css" media="all" rel="stylesheet" type="text/css" /> <style type="text/css"> .auto-style1 { font-size: medium; } </style> </head> <body> <div id="container"> <div id="navigation"> <ul> <li class="link"><a href="default.html" title="Product">Home</a></li> <li class="link"><a href="Research.html" title="Product">Research</a></li> <li class="link"><a href="Teaching.html" title="Progress">Teaching</a></li> <li class="link"><a href="about.html" title="About">Contact</a></li> <li class="link"><a href="CV.html" title="CV">CV</a></li> </ul> </div> This is my Stylesheet /* --------------------------------------------- RESET */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; text-decoration: none; font-weight: normal;} body { margin: 0pt;} ol, ul { list-style-type: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } :focus { outline: 0; } ins { text-decoration: none; } del { text-decoration: line-through; } /* tables still need 'cellspacing="0"' in the markup */ table { border-collapse: collapse; border-spacing: 0; } /* --------------------------------------------- STRUCTURE STYLES */ body { font-family: Georgia, "Times New Roman", Times, serif; background: url('bg.jpg') repeat-x top left #f0f0f0; } #container { width: 960px; height: auto; margin: 0 auto 0 auto; } #header { color: #fff; font-size: .9em; width: 190px; height: 40px; float: left; margin-right: 2px; } /* --------------------------------------------- NAVIGATION */ #navigation { padding-top: 15px; width: 960px; float: left; } #navigation .link { background: #f0f0f0; float: left; text-align:center; font-size:0.5cm } #navigation .link:hover { background: #92c19b; } #navigation .link:focus{ background:silver; } #navigation .link:active{ background:silver; } #navigation li a { padding-top: 15px; padding-left: 15px; width: 176px; height: 45px; margin-bottom: 1px; border-left: #fff solid 1px; color: #000; float: left; font-size: 1em; } #navigation p { position: absolute; font-size: .8em; top: 45px; padding-left: 15px; } /* --------------------------------------------- FONTS & IMAGES */ h1 {font-size: 1.9em;} #header h1 {padding: 15px; background: #000; text-align: center; font-weight: bold;} #header a {color: #fff;} h2 {font-size: 1.9em;} #splash h2 {color: #12884f;} h3 {font-size: 1.4em; line-height: 1.1em;} h4 {font-size: 1em; font-weight: bold;} p {font-size: .8em; line-height: 1.6em;} p.footer {font-size: .6em; color: #000; text-align: right; padding-top: 100px;} p.header {font-size: .8em; font-style: italic; color: #ababab;} #content p, #content h3, #sidebar h3, #content h4, #sidebar p {margin-bottom: 25px;} img {margin: 0 0 25px 0;} li {font-size: .7em; margin-bottom: 10px;} both li:active and li:focus don't highlight the active tab. But strangely li:hover does work Anything i can do to resolve this?? I am looking for highlighting something like this: A: Sorry my mistake, just remove the last comma "," before the opening the curly brackets "{" and it should work. Here's an example I just tested: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Home</title> <style> #home #nav_home a, #research #nav_research a, #teaching #nav_teaching a, #about #nav_about a, #cv #nav_cv a { color:aqua; } </style> </head> <body id="research"> <ul> <li id="nav_home"><a href="">Home</a></li> <li id="nav_research"><a href="">Research</a></li> <li id="nav_teaching"><a href="">Teaching</a></li> <li id="nav_about"><a href="">About</a></li> <li id="nav_cv"><a href="">CV</a></li> </ul> </body> </html> I hope this helps :) Sorry about the wrong answer before, as I said I'm just starting web development myself. Cheers!
{ "pile_set_name": "StackExchange" }
Q: Replacing specific values with others in a .csv, 'tuple' object has no attribute I can find hwo to debugge my code with open("f_in.csv",'rb') as f, open("f_out.csv", "w") as outputfile: for line in f: replacements = ( ("(B)", "0"), ("(D)", "2"), ("Entrée air absente", "2"), ("+", "0,5"), ("++", "1"), ("+++", "2"), ("(S) +", "0,5"), ("(S) expi. ++", "1"), ("(S) +++", "2"), ("100", "0"), ("99", "0"), ("98", "0"), ("97", "0"), ("96", "0"), ("95", "0"), ("94", "1"),("93", "1"), ("92", "1"),("91", "1"),("90", "1"),("89", "1")) for i, j in replacements.iteritems(): line = line.replace(i, j) outputfile.write(line)` for pair in replacements: line = line.replace(*pair) I want to replace some value by a specific number for each of them on each line of my csv file So (B) will be 0, (D) will be 2, + will be 0.5 , ++ will be 1, +++ will be 2 and so one for the other Sample of the csv file : 1277|2013-12-17 16:00:00|100|+| 1360|2014-01-15 16:00:00|(B)|99|++|E 1402|2014-02-05 20:00:00|(D)|99|++|D 1360|2014-01-29 08:00:00|(D)|99||C 1378|2014-01-21 20:00:00|(B)|100||D But with my program i get this error : for i, j in replacements.iteritems(): AttributeError: 'tuple' object has no attribute 'iteritems' A: Usually a dictionary is preferred in replacements or even translations, you can change the replacements into a dictionary by using the function dict(replacements): replacements = ( ("(B)", "0"), ("(D)", "2"), ("Entrée air absente", "2"), ("+", "0,5"), ("++", "1"), ("+++", "2"), ("(S) +", "0,5"), ("(S) expi. ++", "1"), ("(S) +++", "2"), ("100", "0"), ("99", "0"), ("98", "0"), ("97", "0"), ("96", "0"), ("95", "0"), ("94", "1"),("93", "1"), ("92", "1"),("91", "1"),("90", "1"),("89", "1")) import re replvalues = dict(replacements) regex = "|".join(map(re.escape,replvalues.keys())) repl = lambda x : replvalues.get(x.string[x.start():x.end()]) with open("f_in.csv") as f: for i in f: line = re.sub(regex,repl, i) print(line) Now the rest remains the same. ie, you can add the outputfile.write(line) etc
{ "pile_set_name": "StackExchange" }
Q: terminal create file(file_name as bash arguments) then write text into it, relate to .bash_profile I am using sublime, I guess any text editors work the same. I've just learned from this form that alias won't work and I should use function. here is what I come up with, in .bash_profile: function sln() { sublime "$1" | echo "'use strict';" > "$1"; } type sln does return the function I defined, as this: sln is aliased to 'sublime "" | echo "'use strict';" > ""'; but when I do sln test.js, console says: No such file or directory FYI: it works when I do sublime test.js | echo "'use strict';" > test.js, and test.js will open with text 'use strict'; at the beginning. Can someone explain and offer some solutions? Thanks. A: After modifying .bash_profile you have to either source the modified bash profile with source ~/.bash_profile or close the current and reopen a new Terminal window to have the changes take effect. UPDATE: I had done some testing, now the solution is definitely restart Terminal.app. source ~/.bash_profile to reload is not enough.
{ "pile_set_name": "StackExchange" }
Q: Column not updating when tried to update a value of type varchar I am using SQL Server 2000. When I try to update a column of type varchar(20) with a text value of more than 10 characters, I get an error String or binary data would be truncated. Why is it? varchar(20) should accept a text of up to 20 characters... why can I not update it with text with more than 10 characters? A: If your string variable is declared as nvarchar(n), then it will take up twice as much space as a varchar(n) 10 x 2 = 20 So, anything greater than 10 double-byte chars will not fit into a varchar(20) If you are inserting/updating into a column of type varchar, also declare your string variable as varchar with the appropriate size. declare @str varchar(20)
{ "pile_set_name": "StackExchange" }
Q: How do I install libsandbox? I have some problems during installation I have some problems installing libsandbox and pysandbox. I've tried with binary and source packages but no. It seems to do OK but, when I run: from sandbox import * it displays Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/sandbox/__init__.py", line 57, in <module> from . import _sandbox ImportError: /usr/local/lib/python2.7/dist-packages/sandbox/_sandbox.so: wrong ELF class: ELFCLASS32 How can I make it work? I'm running on Linux 64-bit. A: Seems like you have installed 32bit pysandbox on a 64bit machine, and trying to import the 32bit module from a 64bit python interpreter. DISCLAIMER: I am the author of libsandbox.
{ "pile_set_name": "StackExchange" }
Q: Image upload permissions problem I have my local site running on my Win 7 machine using Acquia Dev Desktop. I also have a "live" version of the site. In both environments I cannot upload an image for an article. I must have messed something up because it was working several days ago. This link https://www.drupal.org/documentation/modules/image was useful, but the suggestions on Troubleshooting/The image doesn't show up didn't fix the problem. I'm sure it's because I don't really understand what I'm doing. I'm wondering if a disable of the image module then a re-enable would solve the problem? A: I was rumaging through the module listing and found Debut Article. On the oft-chance that this might be causing problems I went to the debut article page on drupal.org and found drupal.org/node/1473574. It states that because fields are not true exportables, the resulting approach may be fragile and prone to breakage if, e.g., debut_media is not enabled prior to the article implementing the hook_alter, i.e., in this case, debut_article. I enabled debut media and it worked!
{ "pile_set_name": "StackExchange" }
Q: Getting NSDate for today with 00:00:00 as time I am writing a categorie in Xcode, that would extend the current NSDate class. I want to add two methods which I use regularly and somehow I can't get them to work properly. Currently I have this code: + (NSDate*) today { NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *todayComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]]; NSInteger theDay = [todayComponents day]; NSInteger theMonth = [todayComponents month]; NSInteger theYear = [todayComponents year]; NSDateComponents *components = [[NSDateComponents alloc] init]; [components setDay:theDay]; [components setMonth:theMonth]; [components setYear:theYear]; NSDate* todayDate = [gregorian dateFromComponents:components]; [components release]; [gregorian release]; return todayDate; } I want it to return a date like this: "2010-11-03 00:00:00 +01". But somehow the timezone keeps buggin me, because this code returns "2010-11-02 23:00:00 +0000". Can anyone tell me how to fix this code to actually return the correct date? Or can I just use this date and my application will convert it itself because of the timezone the machine is set to. I have to log certain events in my app to a database, which also just uses the [NSDate date] method. Does that mean that the [NSDate date] method also uses the time without timezone information? EDIT: I think it has something to do with the Daylight savings time bug. The things I see is exactly the same as probably the Clock app has, with the bug making people wake up late. Also, the TimeZone defaults to the TimeZone currently set on your device, so it should stay the same until you change the timezone in your settings screen. EDIT2: Ok, some more tests: NSLog(@"CurrentDate: %@", [NSDate date]); NSLog(@"TZ: %@", [NSTimeZone defaultTimeZone]); Gives me the following results: 2010-11-03 23:23:49.000 App[8578:207] CurrentDate: 2010-11-03 22:23:49 +0000 2010-11-03 23:23:49.001 App[8578:207] TZ: Europe/Amsterdam (GMT+01:00) offset 3600 A: See Using Time Zones. You'll want to set the calendar's time zone using NSCalendar's -setTimeZone: method before you start asking it for dates. A: This is an interesting question and I worked at a solution for many hours. These are my findings: NSLog(@"CurrentDate: %@", [NSDate date]); The code shown above will have the same result as the code shown below: NSLog(@"CurrentDate: %@", [[NSDate date] description]); Reading through the NSDate Class Reference produces this documentation on the NSDate's description method. The representation is not guaranteed to remain constant across different releases of the operating system. To format a date, you should use a date formatter object instead (see NSDateFormatter and Data Formatting Guide) I also ran across the documentation for descriptionWithLocale: (id) locale: “Returns a string representation of the receiver using the given locale.” So, change your code NSLog(@"CurrentDate: %@", [NSDate date]); To: NSLog(@"CurrentDate: %@", [[NSDate date] descriptionWithLocale:[NSLocale currentLocale]]); Which should result in what you are looking for. And I can also prove that the [NSDate date] really give's the correct date, but is just being displayed with wrong method: We can use the [today] (Wim Haanstra) to create two dates. dateLastDay: 2010-11-02 23:59:00 +01 dateToday: 2010-11-03 24:01:00 +01 Then we use the code below to show the two dates: NSLog(@"CurrentDate: %@", dateLastDay); NSLog(@"CurrentDate: %@", dateToday); Or: NSLog(@"CurrentDate: %@", [dateLastDay description]); NSLog(@"CurrentDate: %@", [dateToday description]); The two groups show the same results, like this: "2010-11-02 22:59:00 +0000" and "2010-11-02 23:01:00 +0000". It looks like the two dates have the same ‘day’, but really? Now we compare the days of the dates: NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSUInteger unitFlags = NSDayCalendarUnit; NSDateComponents *lastDayComponents = [gregorian components:unitFlags fromDate:dateLastDay]; NSDateComponents *todayComponents = [gregorian components:unitFlags fromDate:dateToday]; NSInteger lastDay = [lastDayComponents day]; NSInteger today = [todayComponents day]; return (lastDay == today) ? YES : NO; We will get NO! Although the two dates appear to have the same day, month and year, they DON'T. It only appears that way because we displayed them in the wrong way.
{ "pile_set_name": "StackExchange" }
Q: Return Item into for loop after exception in Python que = [] def worker(x): for idx, Item in enumerate(range(1, 3)): try: #Do Stuff print("Fin", Item, "For Worker", x) except Item > 2: que.append(Item) pass worker(1) worker(2) My problem is that I dont know how to tell the for function to do the try part also for items in que when there are some. So It would see that Item 3 in open in que, switch to worker 2 and try from there again. Current output looks like: Fin 1 For Worker 1 Fin 2 For Worker 1 Fin 1 For Worker 2 Fin 2 For Worker 2 Expected output should look like: Fin 1 For Worker 1 Fin 2 For Worker 1 Fin 3 For Worker 2 A: If I understand your question correctly you might want something like this, this goes over the range AND the que in the for loop que = [] def worker(x): for Item in range(1, 3).extend(que): try: #Do Stuff print("Fin", Item, "For Worker", x) except Item > 2: que.append(Item) pass worker(1) worker(2)
{ "pile_set_name": "StackExchange" }
Q: Redirecting standard stream I'm trying to create pipes in the shell to redirect standard streams and I am stuck now. When I try to run this code: int fd[2]; pid_t pid; pipe(fd); pid = fork(); if (pid == 0) { // child process // redirect standard input and output dup2(fd[1], STDOUT_FILENO); dup2(fd[0], STDIN_FILENO); // close them (they are now redirected) close(fd[0]); close(fd[1]); char *input_argv[] = {"/bin/ls", "/bin/ls", ">", "out.txt", NULL}; execv(input_argv[0], input_argv); } else if (pid > 0) { // parent process waitpid(pid, NULL,0); } I got this error messages: /bin/ls: cannot access >: No such file or directory /bin/ls: cannot access out.txt: No such file or directory I have no idea what they mean, what cause them and how to fix them. What am I doing wrong? A: All in all, the code doesn't make any sense. I think the best answer one can give here is to explain the most problematic parts: // redirect standard input and output dup2(fd[1], STDOUT_FILENO); dup2(fd[0], STDIN_FILENO); fd[0] is the reading end, fd[1] the writing end of a pipe. Whatever you write to fd[1] is available for read on fd[0]. So, this is just "short-circuiting" your stdio streams, something not usefull at all. What you want to do with pipes normally is have one pipe per direction of communication between parent and child process (e.g. child should read from parent: dup2() the reading end to STDIN_FILENO in the child and write to the writing end from the parent). char *input_argv[] = {"/bin/ls", "/bin/ls", ">", "out.txt", NULL}; Now this doesn't make sense either. A > tells a shell to open a file for writing and exec() the child with a redirected STDOUT_FILENO already in place. It's certainly not an argument understood by ls here. You don't have a shell, you just exec() ls directly. If your original intention was to mimic what the shell would do when given ls > out.txt you should just open the file out.txt for writing and in the child code dup2() the file descriptor of your opened file to STDOUT_FILENO before exec()ing ls. There's no need for a pipe in this scenario. edit in case you want to understand what a shell does internally for ls > out.txt: #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <fcntl.h> #include <unistd.h> int main(void) { /* open file for writing */ int outfd = open("/tmp/out.txt", O_CREAT|O_WRONLY, 00666); if (outfd < 0) { perror("open()"); return EXIT_FAILURE; } /* fork child */ int pid = fork(); if (pid < 0) { perror("fork()"); return EXIT_FAILURE; } if (pid == 0) { /* in the child, redirect stdout to our file */ if (dup2(outfd, STDOUT_FILENO) < 0) { perror("dup2()"); return EXIT_FAILURE; } close(outfd); /* then execute 'ls' */ execlp("ls", "ls", 0); /* only reached when execlp() fails: */ perror("execlp()"); return EXIT_FAILURE; } /* we don't need the output file in the parent process: */ close(outfd); /* wait for child to complete */ int childrc; waitpid(pid, &childrc, 0); /* return exit code of child process */ return childrc; } Of course, the code of the actual shell looks different (doesn't have names hardcoded, uses execv* family of functions because it doesn't know the number of arguments in advance, and so on.)
{ "pile_set_name": "StackExchange" }
Q: Undefined variable in php Hello I have an error script I don't know for why but the variable is defined: public function Updates($user_ids,$lastid) { if($lastid==0) { $loadmore = ""; }else{ $loadmore = " AND M.msg_id < $lastid "; } public function Total_Updates($user_ids) { $sql = "SELECT M.msg_id, M.uid_fk, M.message, M.created, U.fname, U.lname, M.uploads, M.profile_uid FROM messages M, users U WHERE M.uid_fk=U.uid AND M.uid_fk IN ($user_ids) $loadmore UNION SELECT M.msg_id, M.uid_fk, M.message, M.created, U.fname, U.lname, M.uploads, M.profile_uid FROM messages M, users U WHERE M.uid_fk=U.uid AND M.profile_uid IN ($user_ids) $loadmore ORDER BY msg_id DESC "; $query = mysqli_query($db_conx, $sql); $data = mysqli_num_rows($query); exit(); return $data; } The variable that undefined is located in the same line as the SELECT.. I am waiting your help... Thank you A: You have 2 lines with SELECT, however both having the same variables: $user_ids and $loadmore The error message should show what it is warning about. but $user_ids looks declared correctly so that leaves $loadmore. It also looks the function Total_Updates is inside function Updates ? if it is a separate function (and just a copy paste error?) you would probably just want to use global $loadmore; in the beginning of both functions. Edit: Possible changes to Code to use global. With this function Updates, always needs to be called before Total_Updates. public function Updates($user_ids, $lastid) { global $loadmore; // Keep available for Total_Updates if($lastid==0) { $loadmore = ""; }else{ $loadmore = " AND M.msg_id < $lastid "; } $db_conx = mysqli_connect("localhost", "root", "", "test"); $sql = "SELECT M.msg_id, M.uid_fk, M.message, M.created, U.fname, U.lname, M.uploads, M.profile_uid FROM messages M, users U WHERE M.uid_fk=U.uid AND M.uid_fk IN ($user_ids) $loadmore UNION SELECT M.msg_id, M.uid_fk, M.message, M.created, U.fname, U.lname, M.uploads, M.profile_uid FROM messages M, users U WHERE M.uid_fk=U.uid AND M.profile_uid IN ($user_ids) $loadmore ORDER BY msg_id DESC LIMIT " .$this->postcount; $query = mysqli_query($db_conx, $sql); while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){ $data[]=$row; return $data; } } public function Total_Updates($user_ids) { global $loadmore; // From Updates $db_conx = mysqli_connect("localhost", "root", "", "test"); $sql = "SELECT M.msg_id, M.uid_fk, M.message, M.created, U.fname, U.lname, M.uploads, M.profile_uid FROM messages M, users U WHERE M.uid_fk=U.uid AND M.uid_fk IN ($user_ids) $loadmore UNION SELECT M.msg_id, M.uid_fk, M.message, M.created, U.fname, U.lname, M.uploads, M.profile_uid FROM messages M, users U WHERE M.uid_fk=U.uid AND M.profile_uid IN ($user_ids) $loadmore ORDER BY msg_id DESC "; $query = mysqli_query($db_conx, $sql); $data = mysqli_num_rows($query); exit(); // This is just for test? it disables return. return $data; } An alternate solution would be to create a separate function for loadmore ex: public function getUpdates_loadmore($lastid) { if($lastid==0) return ""; return " AND M.msg_id < $lastid "; } And do $loadmore = getUpdates_loadmore($lastid); for this the $lastid parameter would need to be added to function Total_Updates($user_ids) => function Total_Updates($user_ids, $lastid)
{ "pile_set_name": "StackExchange" }