qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
3,159,644
gcc 4.4.4 c89 I am using the code below. However, I keep getting the same number: ``` size_t i = 0; for(i = 0; i < 3; i++) { /* Initialize random number */ srand((unsigned int)time(NULL)); /* Added random number (simulate seconds) */ add((rand() % 30) + 1); } ``` I would like to get 0 to 30 returned. However, the last time I ran this I got 17 three times. Many thanks,
2010/07/01
[ "https://Stackoverflow.com/questions/3159644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70942/" ]
You're seeding *inside* the loop (with the same value because of how quickly the loop will be executed), which causes the random number generated to be the same each time. You need to move your seed function *outside* the loop: ``` /* Initialize random number */ srand((unsigned int)time(NULL)); for(i = 0; i < 3; i++) { /* Added random number (simulate seconds) */ add((rand() % 30) + 1); } ```
It is completely possible that the 3 times 17 are still completely random. There is an about 1 in 10 chance of getting two numbers the same when using a range of 1-30 and three picks. (this is due to the [birthday problem](http://en.wikipedia.org/wiki/Birthday_problem) ) Now, getting three the same results has still a propability of 1 in 900 using the same range. you might want to read more background on the [analysis page of random.org](http://www.random.org/analysis/)
3,159,644
gcc 4.4.4 c89 I am using the code below. However, I keep getting the same number: ``` size_t i = 0; for(i = 0; i < 3; i++) { /* Initialize random number */ srand((unsigned int)time(NULL)); /* Added random number (simulate seconds) */ add((rand() % 30) + 1); } ``` I would like to get 0 to 30 returned. However, the last time I ran this I got 17 three times. Many thanks,
2010/07/01
[ "https://Stackoverflow.com/questions/3159644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70942/" ]
You're seeding *inside* the loop (with the same value because of how quickly the loop will be executed), which causes the random number generated to be the same each time. You need to move your seed function *outside* the loop: ``` /* Initialize random number */ srand((unsigned int)time(NULL)); for(i = 0; i < 3; i++) { /* Added random number (simulate seconds) */ add((rand() % 30) + 1); } ```
You need to do `srand((unsigned int)time(NULL))` only once before the loop.
3,159,644
gcc 4.4.4 c89 I am using the code below. However, I keep getting the same number: ``` size_t i = 0; for(i = 0; i < 3; i++) { /* Initialize random number */ srand((unsigned int)time(NULL)); /* Added random number (simulate seconds) */ add((rand() % 30) + 1); } ``` I would like to get 0 to 30 returned. However, the last time I ran this I got 17 three times. Many thanks,
2010/07/01
[ "https://Stackoverflow.com/questions/3159644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70942/" ]
You're seeding *inside* the loop (with the same value because of how quickly the loop will be executed), which causes the random number generated to be the same each time. You need to move your seed function *outside* the loop: ``` /* Initialize random number */ srand((unsigned int)time(NULL)); for(i = 0; i < 3; i++) { /* Added random number (simulate seconds) */ add((rand() % 30) + 1); } ```
You need to call srand just once, at the beginning of your program. `srand` initializes the pseudo random number generator using time in seconds. If you initialize it with a particular number, you will always get the same sequence of numbers. That's why you usually want to initialize it at the beginning using the time (so that the seed is different each time you run the program) and then use only `rand` to generate numbers which seem random. In your case the time does not change from iteration to iteration, as its resolution is just 1 second, so you are always getting the first number of the pseudo-random sequence, which is always the same.
22,316,620
I have been pulling my hair off since the last few hours trying to get my friendly urls work. I have apache 2.4 with php set up. the app is built using laravel 4 so while this `http://machinename:90/helpsystem/index.php/categories` works the following does **not** work `http://machinename:90/helpsystem/categories` I have enabled the mod\_rewrite module in apache's httpd.conf file Also I have added this to my alias module section of the httpd.conf ``` ScriptAlias /helpsystem "c:/Apache24/htdocs/helpsystem/public" ``` public being the the public folder of the laravel app my directory section looks like this ``` <Directory "c:/Apache24/htdocs/helpsystem/public"> Options Indexes Includes FollowSymLinks MultiViews AllowOverride AuthConfig FileInfo Order allow,deny Allow from all </Directory> ``` and the .htaccess file looks like this ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [L] </IfModule> ``` Can you please let me know what am I doing wrong ? thanks
2014/03/11
[ "https://Stackoverflow.com/questions/22316620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/412628/" ]
AllowOverride All should fix your problem, after restarting apache2 ``` <Directory c:/Apache24/htdocs/helpsystem/public/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> ```
Check out [Apache's upgrade guide from 2.2 to 2.4](http://httpd.apache.org/docs/2.4/upgrading.html). Since 2.4+ is shipped out on most linux distros now (particularly Debian/Ubuntu), you'll see this crop up a lot. I see you're on Windows, so it looks like whatever you happen to be using as updated as well! Specifically, `Order allow,deny Allow from all` Has been replaced with `Require all granted` as Apache now uses [mod\_authz\_host](http://httpd.apache.org/docs/2.4/mod/mod_authz_host.html).
62,670,698
Here is my buttons with different values. ``` <div id="RAM_BtnGroup" class="btn-group" role="group" aria-label="Basic example" name='ram'> <button type="button" value="8GB" class="btn btn-outline-success">8GB </button> <button type="button" value="16GB" class="btn btn-outline-success">16GB </button> <button type="button" value="32GB" class="btn btn-outline-success">32GB </button> <button type="button" value="64GB" class="btn btn-outline-success">64GB </button> Price: <span id="totalCost"></span> ``` So when I randomly click on different buttons, I'm still getting back the value of 8GB. ``` var ram = document.querySelector("button[type=button]"); ram.addEventListener('click', calculateTotal) ``` So how should I click on different buttons in order to get different values? Should I get the value of button regards to something like this? But it is not working in this way. ``` var ram = document.querySelector("button[value=8GB][value=16GB][value=32GB][value=64GB]"); ``` million thanks to the suggested solution, it's good enough but my calculateTotal function still not counting on the ram.Can you guide me how to fix this out. Here is my code. I am pretty sure that unitcost, additional and qty run smoothly, but after added in ramcost to get the value of ram, it seem to not returning any total price of all items. ``` var ram = document.querySelectorAll('button[type="button"]'); ram.forEach((ramm) => { ramm.addEventListener('click', calculateTotal) }); var ram_price = {}; ram_price['8GB'] = 200; ram_price['16GB'] = 300; ram_price['32GB'] = 400; ram_price['64GB'] = 500; function calculateTotal () { var ramcost = ram_price[ramm.value]; var unitCost = product_price[productEl.value]; var additionalCost = size_price[sizeEl.value] || 0; var qty = quantityEl.value || 0; totalCostEl.textContent = `Total cost: $${(unitCost + additionalCost + ramcost) * qty}`; } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62670698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13844964/" ]
You can't extend [DriverManager](https://docs.oracle.com/javase/8/docs/api/java/sql/DriverManager.html), but you can implement `DataSource` instead > > NOTE: The DataSource interface, new in the JDBC 2.0 API, provides another way to connect to a data source. The use of a DataSource object is the preferred means of connecting to a data source. > > >
Every constructor's first line is either a call to its super class constructor or to any current class constructor, so even if you don't keep it compiler will keep a `super();` as first line. Now coming to `DriverManager` its only constructor is `private` and when you extend it to your class, its constructor will try to call the `DriverManager`'s constructor as per above logic and gives Compile time error since its private and becomes not visible. The case will be same even if you don't declare the class without constructor ``` public class myDriverManager extends DriverManager { } ``` This will also give the same error, because the compiler will create a default constructor and its first line will be `super();` by default, again by the above logic, constructor is again invisible. So basically what happens is when you extend `DriverManager` your class has to call `super();` at some part of its code, and gives compile time error and hence `DriverManager` cannot be extended to any class.
50,202,897
I came across this error message in [another question](https://stackoverflow.com/questions/50179683/index-error-message-incorrect-for-third-parameter) and I would like to know what is the meaning of the $: part of the signature, please? ``` Cannot resolve caller index(Str: Str, Any); none of these signatures match: (Str:D $: Cool:D $needle, *%_) (Str:D $: Str:D $needle, *%_) (Str:D $: Cool:D $needle, Cool:D $pos, *%_) (Str:D $: Str:D $needle, Int:D $pos, *%_) ```
2018/05/06
[ "https://Stackoverflow.com/questions/50202897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9146565/" ]
The `$:` is two distinct unrelated tokens, a `$` and a `:`, that have been smooshed together. --- The `$` represents a single item1 aka a scalar2. The single item / scalar hasn't been given a name, so there's no way to reference it. And there's already enough of a parameter (the `Str:D`) to let you and the compiler know that this parameter is a scalar (a single string). Either way, the `$` is redundant and [Elizabeth has made a related change](https://stackoverflow.com/questions/50202897/perl6-what-is-the-for-in-some-subroutine-signatures/50204361#comment87424132_50202897). --- The `:` is a special parameter separator. (The usual parameter separator is a comma `,`.) It may only be used immediately after the first parameter of a method or standalone signature. It may not be used in the signature of a routine that is not a method. If used as a parameter separator after the first parameter in a signature, it marks that parameter as corresponding to a method's ["invocant"](https://en.wikipedia.org/wiki/This_%28computer_programming%29). (If not used, the invocant parameter is implicit.) The corresponding invocant *argument* will arrive anyway, and be aliased to `self`, whether or not the signature explicitly lists an invocant parameter. But if the invocant parameter is explicitly specified, it's possible to give it an additional/alternate name and/or explicitly constrain its type. --- Crazy over-the-top footnotes for added entertainment. If they confuse you, just forget you ever read them. 1 A single item refers to data that is naturally a single thing, like the number `42`, **OR** data that is naturally a composite thing (like an array) that is *being treated like it's a single thing* (like an array). (Did you see what I did there?) I like to point out the mnemonic that a `$` symbol is like an **S** (for single) overlaid with an **I** (for item), or vice-versa. To me this represents the idea of emphasizing the single item nature of any data, hiding any plural aspect even if it's actually an array or other composite data item. 2 "scalar" is a traditional computing term. [Wikipedia's `Scalar` disambiguation page](https://en.wikipedia.org/wiki/Scalar) lists "`Variable (computing)`, or scalar, an atomic quantity that can hold only one value at a time" as a definition. Also, a single item aka *scalar* (all lowercase) is often/usually a [`Scalar`](https://docs.perl6.org/type/Scalar) (uppercase **`S`**), a special case of a single item that's a **S**ingle **I**tem *container* that contains a **S**ingle **I**tem (which can be composite data being treated as a single thing).
The `:` mark the first argument as an [invocant](https://docs.perl6.org/type/Signature#Parameter_Separators). ``` my $word = "bananarama"; say $word.index( "r", 0 ); ``` In this case, it indicates the invocant is going to be treated as an scalar, since it's constrained by a single `$`
522,549
I know how to get the wave equation of light from Maxwell's equation, but I never understood why it is called the solution of the Maxwell equations. If say we have a positive charge standing still from our frame of reference, it generates an electric field that is solution of the Maxwell equations (Gauss law) but it does not propagate, it remains "fixed". I don't understand the difference between this electric field and the ones that do propagate freely through space, and how can it get "de-attached" from its source?
2020/01/01
[ "https://physics.stackexchange.com/questions/522549", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/250618/" ]
The field of a charge in otherwise empty space obeys the wave equation everywhere but at the position of the charge. Because it has zero frequency it cannot propagate. It also is a solution of Poisson's equation, which has no propagating solutions. To generate propagating, non zero frequency solutions, time dependent currents are needed.
Maxwell equations are a set of 4 vectorial differential equations. Given a charge distribution and current (basically think of filling up space with things) that may or may not move, those equations will spit out an electric field and a magnetic field. If you arrange your charge distribution in some specific ways, you can get propagating fields, or stationary ones. You are talking of a special distribution, which is empty space. Solving maxwell equations there gives us the wave equation that you know. Now, if you want to have a propagating field emitted by something is space, you have to have that thing moving. Otherwise, the solution will not be time dependent (this is obvious from the maxwell equations themselves). For example, you can think of an oscillating charge, in that case if you make the amplitude of the oscillation small enough and look far away, you can approximate the electric and magnetic field by a spheric wave with wavelength equal to the amplitude of the oscillation of the charge.
43,898,731
My friend and I are working on an asp.net project and we want to work at same time, he is working on business classes and I want to use his methods. Is there any way to connect our computers, like local Team Foundation Server, and my computer gets latest changes from his computer? I know git but the question is how can I run git on local and get the latest changes immediately?
2017/05/10
[ "https://Stackoverflow.com/questions/43898731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1081336/" ]
`typename` is not used like this, so both cases are invalid and should produce a compilation error, like this: ``` main.cpp:4:20: error: expected a qualified name after 'typename' const typename T* x; ^ ``` Here you would need something like `T::myType` to go on. Or even this, which is worse: ``` main.cpp:4:14: error: expected a qualified name after 'typename' typename const T* x; ^ main.cpp:4:14: error: expected member name or ';' after declaration specifiers ``` Relevant example in [expected a qualified name after 'typename'](https://stackoverflow.com/questions/17998121/expected-a-qualified-name-after-typename). --- > > The keyword typename was introduced to specify that the identifier that follows is a type > > > Read more in: [Officially, what is typename for?](https://stackoverflow.com/questions/1600936/officially-what-is-typename-for)
There's no point in using `typename` here. You'll have to use if you want to access an alias type like `T::type` where you can't have `const` between `typename` and `T::type` ``` const typename T::type * x; // ok typename T::type const * x; // ok typename const T::type * x; // error ```
43,898,731
My friend and I are working on an asp.net project and we want to work at same time, he is working on business classes and I want to use his methods. Is there any way to connect our computers, like local Team Foundation Server, and my computer gets latest changes from his computer? I know git but the question is how can I run git on local and get the latest changes immediately?
2017/05/10
[ "https://Stackoverflow.com/questions/43898731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1081336/" ]
`typename` needs to go with the type your are trying to get. For example if you have ``` template <typename T> void foo(T& t) { typename const T::iterator bar = t.begin(); } int main() { std::vector<int> bar{1,2,3} foo(bar); } ``` You will get a compiler error for `typename const T::const_iterator bar = t.begin();` along the lines of > > expected nested-name-specifier before 'const' > > > Where as ``` const typename T::iterator bar = t.begin(); ``` Works just fine. --- For a comprehensive explanation on when, where, and why `template` and `typename` need to appear see: [Where and why do I have to put the "template" and "typename" keywords?](https://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords)
There's no point in using `typename` here. You'll have to use if you want to access an alias type like `T::type` where you can't have `const` between `typename` and `T::type` ``` const typename T::type * x; // ok typename T::type const * x; // ok typename const T::type * x; // error ```
3,775,228
Is it possible to store a collection of embedded classes in Google App Engine (Java)? If so, how would I annotate it? This is my class: ``` @PersistenceCapable public class Employee { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) Key key; @Persistent(embeddedElement = "true") private List<ContactInfo> contactDetails = new ArrayList<ContactInfo>(); public void addContactInfo(String streetAddress, String city) { this.contactDetails.add(new ContactInfo(streetAddress, city)); } public List<ContactInfo> getContactDetails() { return this.contactDetails; } @PersistenceCapable @EmbeddedOnly public static class ContactInfo { @Persistent private String streetAddress; @Persistent private String city; public ContactInfo(String streetAddress, String city) { this.streetAddress = streetAddress; this.city = city; } public String getStreetAddress() { return this.streetAddress; } public String getCity() { return this.city; } } } ``` Here is the test code: ``` // Create the employee object Employee emp = new Employee(); // Add some contact details emp.addContactInfo("123 Main Street", "Some City"); emp.addContactInfo("50 Blah Street", "Testville"); // Store the employee PersistenceManager pm = PMF.get().getPersistenceManager(); try { pm.makePersistent(emp); } finally { pm.close(); } // Query the datastore for all employee objects pm = PMF.get().getPersistenceManager(); Query query = pm.newQuery(Employee.class); try { List<Employee> employees = (List<Employee>) query.execute(); // Iterate the employees for(Employee fetchedEmployee : employees) { // Output their contact details resp.getWriter().println(fetchedEmployee.getContactDetails()); } } finally { query.closeAll(); pm.close(); } ``` The test code always outputs 'null'. Any suggestions? I've tried annotating the contactDetails list as @Embedded, but the DataNucleus enhancer threw an exception. I've also tried adding defaultFetchGroup = "true" to the @Persistent annotation on the contactDetails list (in case it was a problem with fetching the data), but the output was still null. I've examined the employee object in the console and there's no evidence of any contact detail fields being stored on the object, nor are there any stand-alone ContactInfo objects in the datastore (not that I'd expect there to be, given they are embedded objects). Is this even possible to do? I know that the fields of an embedded class are stored as properties on the entity, so I can see how field name conflicts might arise in a collection scneario, but the [App Engine docs](http://code.google.com/appengine/docs/java/datastore/dataclasses.html#Embedded_Classes) don't explicitly say it cannot be done.
2010/09/23
[ "https://Stackoverflow.com/questions/3775228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/455746/" ]
I don't know if you need the answer still but putting the List into the defaultFetchGroup solved this issue for me: ``` @PersistenceCapable public class Employee { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) Key key; @Persistent(embeddedElement = "true", defaultFetchGroup = "true") private List<ContactInfo> contactDetails = new ArrayList<ContactInfo>(); // Snip... } ```
With JDO you would do it as per the DataNucleus docs <http://www.datanucleus.org/products/accessplatform_2_2/jdo/orm/embedded.html#Collection> The example shows XML, but the annotation names are approximately equivalent. Whether GAE/J's plugin supports this I couldn't say since it's Google's responsibility. Maybe try it?
2,055,975
I have a program which models manufacturing process. In each stage of the process , objects are created. Specific objects can be created only in certain stage . The objects created in later stage, are using the objects created in earlier stages i.e output of previous stage is input to later stage.Which design pattern to use to model this behavior? I am not recognizing in this, any patterns that I am aware of. Thanks
2010/01/13
[ "https://Stackoverflow.com/questions/2055975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152508/" ]
You probably want the [Builder Pattern](http://en.wikipedia.org/wiki/Builder_pattern) (Wikipedia) building a [Composite](http://en.wikipedia.org/wiki/Composite_pattern). More resources [here](http://c2.com/cgi/wiki?BuilderPattern) (c2com) and [here](http://www.allapplabs.com/java_design_patterns/builder_pattern.htm) (Java). In general, always take a look at the most popular [patterns list](http://en.wikipedia.org/wiki/Design_pattern_(computer_science)), and use them as **guidelines**, never allow a pattern to [*pattern* your thinking](http://en.wikipedia.org/wiki/Cargo_cult_programming) :>
Maybe you can model you application on a [Finite State Machine](http://en.wikipedia.org/wiki/Finite-state_machine)?
2,055,975
I have a program which models manufacturing process. In each stage of the process , objects are created. Specific objects can be created only in certain stage . The objects created in later stage, are using the objects created in earlier stages i.e output of previous stage is input to later stage.Which design pattern to use to model this behavior? I am not recognizing in this, any patterns that I am aware of. Thanks
2010/01/13
[ "https://Stackoverflow.com/questions/2055975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152508/" ]
what about Pipeline ?
Maybe you can model you application on a [Finite State Machine](http://en.wikipedia.org/wiki/Finite-state_machine)?
3,959,740
Let $G=\Bbb Z\_{p\_1^{\alpha\_1}}\times \dots \times \Bbb Z\_{p\_n^{\alpha\_n}}$ be listed as $G=\{a\_1,\dots,a\_k\}$, where: * $p\_1\dots,p\_n$ are primes; * $\alpha\_1,\dots,\alpha\_n$ are nonnegative integers; * $k:=\prod\_{i=1}^np\_i^{\alpha\_i}$. As an example, let's take: \begin{alignat}{1} \Bbb Z\_{2^2} \times \Bbb Z\_3\times \Bbb Z\_{2}= &\{(0,0,0),(0,1,0),(0,2,0),(1,0,0),(1,1,0),(1,2,0),\\ &(2,0,0),(2,1,0),(2,2,0),(3,0,0),(3,1,0),(3,2,0),\\ &(0,0,1),(0,1,1),(0,2,1),(1,0,1),(1,1,1),(1,2,1),\\ &(2,0,1),(2,1,1),(2,2,1),(3,0,1),(3,1,1),(3,2,1)\} \\ \end{alignat} Then we get: \begin{alignat}{1} \sum\_{i=1}^{24}a\_i &= \bigl(3\cdot 2\cdot(0+1+2+3),\space\space 2^2\cdot2\cdot (0+1+2)),\space\space 2^2\cdot 3\cdot (0+1)\bigr) \\ &= \biggl(3\cdot 2\cdot\sum\_{i=0}^{2^{2}-1}i,\space\space 2^2\cdot2\cdot\sum\_{i=0}^{3-1}i,\space\space 2^2\cdot 3\cdot \sum\_{i=0}^{2-1}i\biggr) \\ \end{alignat} This suggests the following: **Claim**. Let $G=\Bbb Z\_{p\_1^{\alpha\_1}}\times \dots \times \Bbb Z\_{p\_n^{\alpha\_n}}$ be listed as $G=\{a\_1,\dots,a\_k\}$, where $k:=\prod\_{i=1}^np\_i^{\alpha\_i}$. Then: \begin{alignat}{1} \sum\_{i=1}^{k}a\_i= \biggl(p\_2^{\alpha\_2}\dots p\_n^{\alpha\_n}\sum\_{i=0}^{p\_1^{\alpha\_1}-1}i,\space\space\dots,\space\space p\_1^{\alpha\_1}\dots p\_{n-1}^{\alpha\_{n-1}}\sum\_{i=0}^{p\_n^{\alpha\_n}-1}i\biggr) \\ \tag 1 \end{alignat} I've tried to prove $(1)$ by induction on $(\alpha\_1,\dots,\alpha\_n)$. The claim holds for $(\alpha\_1,\dots,\alpha\_n)=(0,\dots,0)$; in fact, in this case $k=1$ and $G=\{a\_1\}=\{(\underbrace{0,\dots,0}\_{n\space slots})\}$, whence: \begin{alignat}{1} \sum\_{i=1}^{k}a\_i= a\_1=(\underbrace{0,\dots,0}\_{n\space slots}) \end{alignat} and \begin{alignat}{1} &\biggl(p\_2^{\alpha\_2}\dots p\_n^{\alpha\_n}\sum\_{i=0}^{p\_1^{\alpha\_1}-1}i,\space\space\dots,\space\space p\_1^{\alpha\_1}\dots p\_{n-1}^{\alpha\_{n-1}}\sum\_{i=0}^{p\_n^{\alpha\_n}-1}i\biggr)= \\ &\biggl(1\dots 1\sum\_{i=0}^{0}i,\space\space\dots,\space\space 1\dots 1\sum\_{i=0}^{0}i\biggr)= \\ &(1\dots 1\cdot 0,\space\space\dots,\space\space 1\dots 1\cdot 0)= \\ &(\underbrace{0,\dots,0}\_{n\space slots}) \\ \end{alignat} As inductive step, I've assumed $(1)$ to hold for $\{\alpha\_1,\dots,\alpha\_{j-1},\alpha\_j,\alpha\_{j+1},\dots,\alpha\_n\}$ and checked what happens for $\{\alpha\_1,\dots,\alpha\_{j-1},\alpha\_j+1,\alpha\_{j+1},\dots,\alpha\_n\}$, for an arbitrary $j\in\{1,\dots,n\}$. This is where I get stuck, and I don't know whether I get lost in the algebra, or I'm applying induction incorrectly, or simply the claim is false.
2020/12/23
[ "https://math.stackexchange.com/questions/3959740", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Write as $$(101-t)p(t)=(101-(t-1))p(t-1).$$ As this works for all $t$, the two members are a constant, equal to $$(101-1)\frac1{100}.$$
Hint: Write it as a product and use $1+\frac{1}{101-n}=\frac{102-n}{101-n}$, then you can apply the telescoping technique.
3,959,740
Let $G=\Bbb Z\_{p\_1^{\alpha\_1}}\times \dots \times \Bbb Z\_{p\_n^{\alpha\_n}}$ be listed as $G=\{a\_1,\dots,a\_k\}$, where: * $p\_1\dots,p\_n$ are primes; * $\alpha\_1,\dots,\alpha\_n$ are nonnegative integers; * $k:=\prod\_{i=1}^np\_i^{\alpha\_i}$. As an example, let's take: \begin{alignat}{1} \Bbb Z\_{2^2} \times \Bbb Z\_3\times \Bbb Z\_{2}= &\{(0,0,0),(0,1,0),(0,2,0),(1,0,0),(1,1,0),(1,2,0),\\ &(2,0,0),(2,1,0),(2,2,0),(3,0,0),(3,1,0),(3,2,0),\\ &(0,0,1),(0,1,1),(0,2,1),(1,0,1),(1,1,1),(1,2,1),\\ &(2,0,1),(2,1,1),(2,2,1),(3,0,1),(3,1,1),(3,2,1)\} \\ \end{alignat} Then we get: \begin{alignat}{1} \sum\_{i=1}^{24}a\_i &= \bigl(3\cdot 2\cdot(0+1+2+3),\space\space 2^2\cdot2\cdot (0+1+2)),\space\space 2^2\cdot 3\cdot (0+1)\bigr) \\ &= \biggl(3\cdot 2\cdot\sum\_{i=0}^{2^{2}-1}i,\space\space 2^2\cdot2\cdot\sum\_{i=0}^{3-1}i,\space\space 2^2\cdot 3\cdot \sum\_{i=0}^{2-1}i\biggr) \\ \end{alignat} This suggests the following: **Claim**. Let $G=\Bbb Z\_{p\_1^{\alpha\_1}}\times \dots \times \Bbb Z\_{p\_n^{\alpha\_n}}$ be listed as $G=\{a\_1,\dots,a\_k\}$, where $k:=\prod\_{i=1}^np\_i^{\alpha\_i}$. Then: \begin{alignat}{1} \sum\_{i=1}^{k}a\_i= \biggl(p\_2^{\alpha\_2}\dots p\_n^{\alpha\_n}\sum\_{i=0}^{p\_1^{\alpha\_1}-1}i,\space\space\dots,\space\space p\_1^{\alpha\_1}\dots p\_{n-1}^{\alpha\_{n-1}}\sum\_{i=0}^{p\_n^{\alpha\_n}-1}i\biggr) \\ \tag 1 \end{alignat} I've tried to prove $(1)$ by induction on $(\alpha\_1,\dots,\alpha\_n)$. The claim holds for $(\alpha\_1,\dots,\alpha\_n)=(0,\dots,0)$; in fact, in this case $k=1$ and $G=\{a\_1\}=\{(\underbrace{0,\dots,0}\_{n\space slots})\}$, whence: \begin{alignat}{1} \sum\_{i=1}^{k}a\_i= a\_1=(\underbrace{0,\dots,0}\_{n\space slots}) \end{alignat} and \begin{alignat}{1} &\biggl(p\_2^{\alpha\_2}\dots p\_n^{\alpha\_n}\sum\_{i=0}^{p\_1^{\alpha\_1}-1}i,\space\space\dots,\space\space p\_1^{\alpha\_1}\dots p\_{n-1}^{\alpha\_{n-1}}\sum\_{i=0}^{p\_n^{\alpha\_n}-1}i\biggr)= \\ &\biggl(1\dots 1\sum\_{i=0}^{0}i,\space\space\dots,\space\space 1\dots 1\sum\_{i=0}^{0}i\biggr)= \\ &(1\dots 1\cdot 0,\space\space\dots,\space\space 1\dots 1\cdot 0)= \\ &(\underbrace{0,\dots,0}\_{n\space slots}) \\ \end{alignat} As inductive step, I've assumed $(1)$ to hold for $\{\alpha\_1,\dots,\alpha\_{j-1},\alpha\_j,\alpha\_{j+1},\dots,\alpha\_n\}$ and checked what happens for $\{\alpha\_1,\dots,\alpha\_{j-1},\alpha\_j+1,\alpha\_{j+1},\dots,\alpha\_n\}$, for an arbitrary $j\in\{1,\dots,n\}$. This is where I get stuck, and I don't know whether I get lost in the algebra, or I'm applying induction incorrectly, or simply the claim is false.
2020/12/23
[ "https://math.stackexchange.com/questions/3959740", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Write as $$(101-t)p(t)=(101-(t-1))p(t-1).$$ As this works for all $t$, the two members are a constant, equal to $$(101-1)\frac1{100}.$$
$$p(t)=\frac{102-t}{101-t}\, p(t-1)$$ for $t=1$ initial condition is $p(1)=\frac{1}{100}=\frac{1}{101-1}$ for $t=2$ we have $p(2)=\frac{100}{99}\,p(1)=\frac{100}{99}\,\frac{1}{100}=\frac{1}{99}=\frac{1}{101-2}$ for $t=3$, $p(3)=\frac{99}{98}\,p(2)=\frac{100}{99}\,\frac{99}{98}\frac{1}{100}=\frac{1}{98}=\frac{1}{101-3}$ for general $t$ we have $$p(t)=\frac{1}{101-t}$$
25,614,858
I have a code that looks like the code below. ``` public class Controller { public void test(){ Model1 model1 = new Model1(); Test test = new Test(model1); } } public class Test { private Model1 model1; public Test(Model1 model1) { this.model1 = model1;//this line } public Model1 getModel1() { return model1; } public void setModel1(Model1 model1) { this.model1 = model1; } } public class Model1 { private String field1; private String field2; public String getField1() { return field1; } public void setField1(String field1) { this.field1 = field1; } public String getField2() { return field2; } public void setField2(String field2) { this.field2 = field2; } } ``` I just want to know, how many Model1 is actually created in this code? Another question is does this line is passed by reference and does passed by reference is good in memory?
2014/09/02
[ "https://Stackoverflow.com/questions/25614858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3814676/" ]
No, assigning to a field does not allocate memory. Objects are only created when you (directly or indirectly) call a constructor. > > Another question is does this line is passed by reference and does passed > by reference is good in memory? > > > Technically, everything in Java is passed by value. However, in the case of Objects, this value is a reference to the Object (not a copy of its contents). So passing an Object around is just the same as passing a `long` around as far as memory layout is concerned.
You have created just one object of class Model. Basically, you create objects only by using the operator `new`. In java, objects are always passed by value regardless of their type. For non-primitive types (objects), you only have access through reference. So in your case you are passing a reference by value. Passing objects by reference is good in terms of memory, because you only create another pointer, which takes somewhere between 4-8 bytes.
25,614,858
I have a code that looks like the code below. ``` public class Controller { public void test(){ Model1 model1 = new Model1(); Test test = new Test(model1); } } public class Test { private Model1 model1; public Test(Model1 model1) { this.model1 = model1;//this line } public Model1 getModel1() { return model1; } public void setModel1(Model1 model1) { this.model1 = model1; } } public class Model1 { private String field1; private String field2; public String getField1() { return field1; } public void setField1(String field1) { this.field1 = field1; } public String getField2() { return field2; } public void setField2(String field2) { this.field2 = field2; } } ``` I just want to know, how many Model1 is actually created in this code? Another question is does this line is passed by reference and does passed by reference is good in memory?
2014/09/02
[ "https://Stackoverflow.com/questions/25614858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3814676/" ]
There is only one object in memory, by the line: ``` Model1 model1 = new Model1(); ``` And the variable `model1` is a reference to this object. On the constructor ``` public Test(Model1 model1) { this.model1 = model1;//this line } ``` You will have another reference to the same object in memory.
You have created just one object of class Model. Basically, you create objects only by using the operator `new`. In java, objects are always passed by value regardless of their type. For non-primitive types (objects), you only have access through reference. So in your case you are passing a reference by value. Passing objects by reference is good in terms of memory, because you only create another pointer, which takes somewhere between 4-8 bytes.
240,377
From within a `bash` script, how can I use `sed` to write to a file where the filename is stored in a bash variable? Output redirection won't do because I want to edit one file in place, pulling lines that match a regex into a different file and deleting them in the first file. Something like: ``` sed -i '/^my regex here$/{;w file2;d;}' file1 ``` ...but where `file1` and `file2` are both actually *variables* that *hold* the filenames. (Such as `file2=$(mktemp)`.) So what I really want is variable expansion for the filename, but no expansion for the rest of the `sed` command, and leaving the whole thing as a single argument passed to the `sed` command. For whatever reason, the following does not work: ``` sed -i '/my regex here/{;w '"$file2"';d;}' $file1 ``` It says "unmatched {" and I can't see why. Any way I can do this?
2015/11/03
[ "https://unix.stackexchange.com/questions/240377", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/135943/" ]
I found the answer on [Stackoverflow](https://stackoverflow.com/q/11158835/5419599) under "How do I let sed 'w' command know where the filename ends?" As terdon pointed out, the issue is not the variable—but it has nothing to do with curly brackets, either; try `sed '/^l/w testing;p'` and you will see it doesn't throw any error, but writes all the lines starting with an `l` into a file named `testing;p`. The issue is actually the lack of a newline after the filename. So the answer is to either use an inline newline in the sed command: ``` sed -i '/my regex here/{;w '"$file2"' d;}' $file1 ``` *Or*, what is much cleaner, use two separate `-e` arguments: ``` sed -i -e '/my regex here/{;w '"$file2" -e 'd;}' $file1 ``` If you don't like the two adjacent quotes (which you might easily slip on), just put the write command in its own argument: ``` sed -i -e '/^my regex here$/{' -e "w $file2" -e 'd;}' $file1 ```
Use the double quotes instead the single ones in to quote the sed command. And don't forget to escape suitable characters. More info about quoting variables in bash in this [link](http://www.tldp.org/LDP/abs/html/quotingvar.html "link")
240,377
From within a `bash` script, how can I use `sed` to write to a file where the filename is stored in a bash variable? Output redirection won't do because I want to edit one file in place, pulling lines that match a regex into a different file and deleting them in the first file. Something like: ``` sed -i '/^my regex here$/{;w file2;d;}' file1 ``` ...but where `file1` and `file2` are both actually *variables* that *hold* the filenames. (Such as `file2=$(mktemp)`.) So what I really want is variable expansion for the filename, but no expansion for the rest of the `sed` command, and leaving the whole thing as a single argument passed to the `sed` command. For whatever reason, the following does not work: ``` sed -i '/my regex here/{;w '"$file2"';d;}' $file1 ``` It says "unmatched {" and I can't see why. Any way I can do this?
2015/11/03
[ "https://unix.stackexchange.com/questions/240377", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/135943/" ]
Because you're using a single `sed` expression, everything that follows after the `w` (including the `}`) is [interpreted as the *wfile* name](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html): > > The argument `wfile` shall terminate the editing command. > > > You can see that if you add a second command `}` e.g. like: ``` sed -e '/my regex here/{w '"$file2"';d;}' -e '}' $file1 ``` then the lines matching `my regex here` will be saved in a file named `whatever;d;}` where `whatever` is whatever `$file1` expands to. The correct syntax is via separate commands, either with several expressions: ``` sed -e '/my regex here/{w '"$file1" -e 'd' -e '}' $file2 ``` or one command per line: ``` sed '/my regex here/{ w '"$file1"' d } ' $file2 ```
Use the double quotes instead the single ones in to quote the sed command. And don't forget to escape suitable characters. More info about quoting variables in bash in this [link](http://www.tldp.org/LDP/abs/html/quotingvar.html "link")
240,377
From within a `bash` script, how can I use `sed` to write to a file where the filename is stored in a bash variable? Output redirection won't do because I want to edit one file in place, pulling lines that match a regex into a different file and deleting them in the first file. Something like: ``` sed -i '/^my regex here$/{;w file2;d;}' file1 ``` ...but where `file1` and `file2` are both actually *variables* that *hold* the filenames. (Such as `file2=$(mktemp)`.) So what I really want is variable expansion for the filename, but no expansion for the rest of the `sed` command, and leaving the whole thing as a single argument passed to the `sed` command. For whatever reason, the following does not work: ``` sed -i '/my regex here/{;w '"$file2"';d;}' $file1 ``` It says "unmatched {" and I can't see why. Any way I can do this?
2015/11/03
[ "https://unix.stackexchange.com/questions/240377", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/135943/" ]
Because you're using a single `sed` expression, everything that follows after the `w` (including the `}`) is [interpreted as the *wfile* name](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html): > > The argument `wfile` shall terminate the editing command. > > > You can see that if you add a second command `}` e.g. like: ``` sed -e '/my regex here/{w '"$file2"';d;}' -e '}' $file1 ``` then the lines matching `my regex here` will be saved in a file named `whatever;d;}` where `whatever` is whatever `$file1` expands to. The correct syntax is via separate commands, either with several expressions: ``` sed -e '/my regex here/{w '"$file1" -e 'd' -e '}' $file2 ``` or one command per line: ``` sed '/my regex here/{ w '"$file1"' d } ' $file2 ```
I found the answer on [Stackoverflow](https://stackoverflow.com/q/11158835/5419599) under "How do I let sed 'w' command know where the filename ends?" As terdon pointed out, the issue is not the variable—but it has nothing to do with curly brackets, either; try `sed '/^l/w testing;p'` and you will see it doesn't throw any error, but writes all the lines starting with an `l` into a file named `testing;p`. The issue is actually the lack of a newline after the filename. So the answer is to either use an inline newline in the sed command: ``` sed -i '/my regex here/{;w '"$file2"' d;}' $file1 ``` *Or*, what is much cleaner, use two separate `-e` arguments: ``` sed -i -e '/my regex here/{;w '"$file2" -e 'd;}' $file1 ``` If you don't like the two adjacent quotes (which you might easily slip on), just put the write command in its own argument: ``` sed -i -e '/^my regex here$/{' -e "w $file2" -e 'd;}' $file1 ```
41,243,639
Hi I have strcture when I create a new BsonDocument in MongoDB ``` var doct = new BsonDocument { { "fbId", "" }, { "Name", NameTxt.Text.ToString() }, { "pass", PasswTxt.Text.ToString() }, { "Watchtbl", new BsonArray { new BsonDocument { { "wid", "" }, { "name", "" }, { "Symboles", new BsonArray { new BsonDocument { { "Name", "" } } } } } } } }; ``` I want to know how delete some empty records, this is how it look when I try fetch my data in MongoDB ``` { "_id" : ObjectId("582c77454d08e326104879cb"), "fbId" : "", "Name" : "user", "pass" : "user", "Watchtbl" : [ { "wid" : "", "name" : "", "Symboles" : [ { "Name" : "" } ] }, { "wid" : "0000", "name" : "bought stock2", "Symboles" : [ ] }, { "wid" : "", "name" : "", "Symboles" : [ { "Name" : "" } ] }, { "wid" : "", "name" : "", "Symboles" : [ { "Name" : "" } ] }, { "wid" : "", "name" : "", "Symboles" : [ { "Name" : "" } ] }, { "wid" : "", "name" : "", "Symboles" : [ { "Name" : "" } ] } ] } ```
2016/12/20
[ "https://Stackoverflow.com/questions/41243639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5547912/" ]
Let's pick up our discussion from your [keystone issue](https://github.com/keystonejs/keystone/issues/3814) here. The reason should be that `find()` returns a [Promise](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise), so the operation is ran asynchronously. Therefore, at the moment you log the value, it's still `undefined`. There are examples of the promises on the keystone demo site, for example [here](https://github.com/keystonejs/keystone-demo/blob/master/routes/views/blog.js#L22). I think what you want is something like: ``` var gc = "test"; var c = keystone.list('PostCategory').model.find().where('key').equals(gc).exec(function (err, results) { if (err) { console.log(err); } else { console.log(results); } }); ``` or ``` keystone .list('PostCategory') .model .find() .where('key') .equals(gc) .then(function(category) { console.log(category.id); }); ``` Also, I'm not sure here but if `find({"key":"test"})` works in mongoshell, it might also work in mongoose, so have you tried `keystone.list('PostCategory').model.find({"key":"test"}).exec(...)`?
``` var gc = test; ????? ``` obviously test is not defined. from Javascript perspective. JS expects test to be a variable. and it dont know what is DB at that moment.
7,615,213
I just watched such an example which shows how to get all cols by date here it is... ``` DECLARE @MyGetDate DATETIME SELECT @MyGetDate = '2 Mar 2003 21:40' SELECT * FROM @Table WHERE convert(varchar, @MyGetDate, 14) BETWEEN convert(varchar, startDate, 14) AND convert(varchar, endDate, 14) ``` ... but the thing is I was trying to modify it as to get values within past 50 minutes. Here it is ``` SELECT value, my_date_col FROM myTable WHERE convert(varchar, my_date_col, 14) BETWEEN convert(varchar, dateadd(minute, -50, getdate()), 14) AND convert(varchar, getdate(), 14) ``` But it doesn't work :( So my question is how to use col **my\_date\_col** in such kind of statement? Any useful comment is appreciated
2011/09/30
[ "https://Stackoverflow.com/questions/7615213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592704/" ]
I assume your `my_date_col` is DateTime column, then you don't need the casting. Casting is needed because the sample uses string representation of dates. ``` DECLARE @date DATETIME SET @date = GETDATE() SELECT value, my_date_col FROM myTable WHERE my_date_col BETWEEN dateadd(minute, -50, @date) AND @date ```
This should work just fine, assuming `my_date_col` is a `DATETIME`: ``` SELECT value, my_date_col FROM myTable WHERE my_date_col BETWEEN dateadd(minute, -50, getdate()) AND getdate() ``` If nothing is returned, there are *no* rows with a `my_date_col` in the last 50 minutes.
7,615,213
I just watched such an example which shows how to get all cols by date here it is... ``` DECLARE @MyGetDate DATETIME SELECT @MyGetDate = '2 Mar 2003 21:40' SELECT * FROM @Table WHERE convert(varchar, @MyGetDate, 14) BETWEEN convert(varchar, startDate, 14) AND convert(varchar, endDate, 14) ``` ... but the thing is I was trying to modify it as to get values within past 50 minutes. Here it is ``` SELECT value, my_date_col FROM myTable WHERE convert(varchar, my_date_col, 14) BETWEEN convert(varchar, dateadd(minute, -50, getdate()), 14) AND convert(varchar, getdate(), 14) ``` But it doesn't work :( So my question is how to use col **my\_date\_col** in such kind of statement? Any useful comment is appreciated
2011/09/30
[ "https://Stackoverflow.com/questions/7615213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592704/" ]
I assume your `my_date_col` is DateTime column, then you don't need the casting. Casting is needed because the sample uses string representation of dates. ``` DECLARE @date DATETIME SET @date = GETDATE() SELECT value, my_date_col FROM myTable WHERE my_date_col BETWEEN dateadd(minute, -50, @date) AND @date ```
Get rid of the CONVERT statements, you want to compare dates, not varchars. ``` SELECT value, my_date_col FROM myTable WHERE my_date_col BETWEEN dateadd(minute, -50, getdate()) AND getdate(), 14 ```
7,615,213
I just watched such an example which shows how to get all cols by date here it is... ``` DECLARE @MyGetDate DATETIME SELECT @MyGetDate = '2 Mar 2003 21:40' SELECT * FROM @Table WHERE convert(varchar, @MyGetDate, 14) BETWEEN convert(varchar, startDate, 14) AND convert(varchar, endDate, 14) ``` ... but the thing is I was trying to modify it as to get values within past 50 minutes. Here it is ``` SELECT value, my_date_col FROM myTable WHERE convert(varchar, my_date_col, 14) BETWEEN convert(varchar, dateadd(minute, -50, getdate()), 14) AND convert(varchar, getdate(), 14) ``` But it doesn't work :( So my question is how to use col **my\_date\_col** in such kind of statement? Any useful comment is appreciated
2011/09/30
[ "https://Stackoverflow.com/questions/7615213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592704/" ]
I assume your `my_date_col` is DateTime column, then you don't need the casting. Casting is needed because the sample uses string representation of dates. ``` DECLARE @date DATETIME SET @date = GETDATE() SELECT value, my_date_col FROM myTable WHERE my_date_col BETWEEN dateadd(minute, -50, @date) AND @date ```
``` select value1, date_column from @Table WHERE date_column between date1 and date2 ```
7,615,213
I just watched such an example which shows how to get all cols by date here it is... ``` DECLARE @MyGetDate DATETIME SELECT @MyGetDate = '2 Mar 2003 21:40' SELECT * FROM @Table WHERE convert(varchar, @MyGetDate, 14) BETWEEN convert(varchar, startDate, 14) AND convert(varchar, endDate, 14) ``` ... but the thing is I was trying to modify it as to get values within past 50 minutes. Here it is ``` SELECT value, my_date_col FROM myTable WHERE convert(varchar, my_date_col, 14) BETWEEN convert(varchar, dateadd(minute, -50, getdate()), 14) AND convert(varchar, getdate(), 14) ``` But it doesn't work :( So my question is how to use col **my\_date\_col** in such kind of statement? Any useful comment is appreciated
2011/09/30
[ "https://Stackoverflow.com/questions/7615213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592704/" ]
This should work just fine, assuming `my_date_col` is a `DATETIME`: ``` SELECT value, my_date_col FROM myTable WHERE my_date_col BETWEEN dateadd(minute, -50, getdate()) AND getdate() ``` If nothing is returned, there are *no* rows with a `my_date_col` in the last 50 minutes.
Get rid of the CONVERT statements, you want to compare dates, not varchars. ``` SELECT value, my_date_col FROM myTable WHERE my_date_col BETWEEN dateadd(minute, -50, getdate()) AND getdate(), 14 ```
7,615,213
I just watched such an example which shows how to get all cols by date here it is... ``` DECLARE @MyGetDate DATETIME SELECT @MyGetDate = '2 Mar 2003 21:40' SELECT * FROM @Table WHERE convert(varchar, @MyGetDate, 14) BETWEEN convert(varchar, startDate, 14) AND convert(varchar, endDate, 14) ``` ... but the thing is I was trying to modify it as to get values within past 50 minutes. Here it is ``` SELECT value, my_date_col FROM myTable WHERE convert(varchar, my_date_col, 14) BETWEEN convert(varchar, dateadd(minute, -50, getdate()), 14) AND convert(varchar, getdate(), 14) ``` But it doesn't work :( So my question is how to use col **my\_date\_col** in such kind of statement? Any useful comment is appreciated
2011/09/30
[ "https://Stackoverflow.com/questions/7615213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592704/" ]
This should work just fine, assuming `my_date_col` is a `DATETIME`: ``` SELECT value, my_date_col FROM myTable WHERE my_date_col BETWEEN dateadd(minute, -50, getdate()) AND getdate() ``` If nothing is returned, there are *no* rows with a `my_date_col` in the last 50 minutes.
``` select value1, date_column from @Table WHERE date_column between date1 and date2 ```
44,913,282
I am having trouble inserting a guid Id each time a log is written in the database. It throws these errors: ``` Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll Exception thrown: 'System.Data.SqlClient.SqlException' in NLog.dll ``` What I have so far: ``` @"INSERT INTO [dbo].[Nlogs] (Id,Message) values (@Id,@Message)"; databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Id", Guid.NewGuid().ToString())); databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}")); ``` Thanks.
2017/07/04
[ "https://Stackoverflow.com/questions/44913282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3034572/" ]
Ended up doing this: ``` @"INSERT INTO [dbo].[Nlogs] (Id,Message) values (NewID(),@Message)"; databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}")); ```
> > How would I get it to create a new Guid for each entry? > > > Use [`${guid}`](https://github.com/nlog/nlog/wiki/Guid-Layout-Renderer) or [event properties](https://github.com/nlog/nlog/wiki/EventProperties-Layout-Renderer) for example: ```xml <target name="db" xsi:type="Database" connectionStringName="NLogConn" commandText="NSERT INTO [dbo].[Nlogs] (Id,Message) values (@Id,@Message)" > <parameter name="@Id" layout="${guid}" dbType="Guid" /> <parameter name="@Message" layout="${message}" /> </target> ``` Update: added `dbType` attribute to the example above, that would fix any conversion issues! You need NLog 4.6+ for that. From the [docs](https://github.com/NLog/NLog/wiki/Database-target): > > dbType - One of the values of DbType (e.g. "Int32", "Decimal", "DateTime"), or a value of DBType like prefixed with the property name, e.g. "SqlDbType.NChar" will set the property "SqlDbType" on "NChar". Another example: "NpgsqlDbType.Json" with NpgsqlParameter. Introduced in NLog 4.6 > > >
17,666,867
I have an XPATH query I am running in PHP against the following XML from CWE: ``` <Weaknesses> <Weakness ID="211" Name="Test" Weakness_Abstraction="Base" Status="Incomplete"> <Description> <Description_Summary> The software performs an operation that triggers an external diagnostic or error message that is not directly generated by the software, such as an error generated by the programming language interpreter that the software uses. The error can contain sensitive system information. </Description_Summary> </Description> </Weakness> </Weaknesses> ``` I have written the following PHP with XPATH in order to target the content within the "Description\_Summary" child node, however, it simply returns Array(). I have a $\_GET which pulls the $searchString variable from the previous page, pointing to my specific attribute found within the "Weakness" node. ``` <?php $searchString = $_GET["searchString"]; echo "<b>CWE Name: </b>" . $searchString . "</br>"; $xml = simplexml_load_file("cwe.xml"); $description = $xml->xpath('//Weakness[@Name="'. $searchString .'"]/Description/Description_Summary/text()'); echo "<pre>"; print_r($description); echo "</pre>"; ?> ``` What it currently returns: ``` Array ( [0] => SimpleXMLElement Object ( ) ) ``` What is wrong with my print statement or XPATH query? Thanks!
2013/07/16
[ "https://Stackoverflow.com/questions/17666867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1995565/" ]
What you can read from a file depends on what's in the file. If you wrote the names of your variables into the file, then you should be able to read them, too. If not, then you can't. Variables names are not inherently written to files when you wrote data, though. Identify the technique used to write the names into your file. To read them, simply perform the inverse operation. If you wrote the data delimited in some way, then read until you encounter a delimiter. If you preceded the name with its character length, then read the length, and then read that many characters. If you didn't write the names with a technique that's invertible, then you'll have to change how you write your data before proceed to reading it. Your question asked whether it was possible to read the names, and the answer is yes. You've since asked another question, which is whether it's possible to "convert" the name read from the file into the actual variable with the corresponding name. The answer to that is no. Ordinary variables do not have RTTI; Delphi does not maintain the names of all the variables in a program. Once the compiler finishes its job, the names cease to exist within the program. The easiest way to get the variable is to set up a mapping from string to set value. Read the name from the file, look up the name in a data structure, and use the corresponding value. A `TDictionary<string, sMinerals>` would be perfect for that. Just populate the data structure as your program starts up.
Pretty Simple... You need to save your variable mineralsWalkable to a string representation of your eBlockTypes. You'll use GetEnumName to do that. You then need to convert your string representation of your eBlockTypes to an actual eBlockType and then add that to your mineralsWalkable. You'll use GetEnumValue to do that. The following example shows taking the string representation...placing it in a set...and then taking the set...and moving it back to a string... ``` object Form54: TForm54 Left = 0 Top = 0 Caption = 'Form54' ClientHeight = 290 ClientWidth = 554 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnCreate = FormCreate OnDestroy = FormDestroy PixelsPerInch = 96 TextHeight = 13 object Button1: TButton Left = 56 Top = 160 Width = 75 Height = 25 Caption = 'Button1' TabOrder = 0 OnClick = Button1Click end object Edit1: TEdit Left = 56 Top = 64 Width = 265 Height = 21 TabOrder = 1 Text = 'Edit1' end object cbType1: TCheckBox Left = 248 Top = 91 Width = 97 Height = 17 Caption = 'Type1' TabOrder = 2 end object cbType2: TCheckBox Tag = 1 Left = 248 Top = 114 Width = 97 Height = 17 Caption = 'Type2' TabOrder = 3 end object cbType3: TCheckBox Tag = 2 Left = 248 Top = 137 Width = 97 Height = 17 Caption = 'Type3' TabOrder = 4 end end unit Unit54; {Note the code assumes cbType1.Tag = 0, cbType2.Tag = 1, and cbType3.Tag = 2} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, TypInfo, IniFiles; type TMyType = (mtOne, mtTwo, mtThree); TMyTypes= set of TMyType; TForm54 = class(TForm) Button1: TButton; Edit1: TEdit; cbType1: TCheckBox; cbType2: TCheckBox; cbType3: TCheckBox; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private function getTypes1: TMyTypes; procedure setMyTypes1(const Value: TMyTypes); { Private declarations } public { Public declarations } property Types1: TMyTypes read getTypes1 write setMyTypes1; procedure SaveMyTypes(aVariableName: string; aMyTypes: TMyTypes); function ReadMyTypes(aVariableName: string): TMyTypes; end; var Form54: TForm54; implementation {$R *.dfm} procedure TForm54.Button1Click(Sender: TObject); var a_MyTypes: TMyTypes; a_Str: string; a_Index: integer; begin a_MyTypes := []; a_Str := ''; Include(a_MyTypes, TMyType(GetEnumValue(TypeInfo(TMyType), 'mtOne'))); Include(a_MyTypes, TMyType(GetEnumValue(TypeInfo(TMyType), 'mtTwo'))); //purpoesly have mtThree3 instead of mtThree Include(a_MyTypes, TMyType(GetEnumValue(TypeInfo(TMyType), 'mtThree3'))); for a_Index := Ord(Low(TMyType)) to Ord(High(TMyType)) do if TMyType(a_Index) in a_MyTypes then if a_Str = '' then a_Str := GetEnumName(TypeInfo(TMyType), a_Index) else a_Str := a_Str + ',' + GetEnumName(TypeInfo(TMyType), a_Index); //should be mtOne, mtTwo Edit1.Text := a_Str; end; procedure TForm54.FormCreate(Sender: TObject); begin Types1 := ReadMyTypes('Types1'); end; procedure TForm54.FormDestroy(Sender: TObject); begin SaveMyTypes('Types1', Types1); end; function TForm54.getTypes1: TMyTypes; var a_Index: integer; begin Result := []; for a_Index := 0 to Self.ComponentCount - 1 do if Self.Components[a_Index] is TCheckBox and (TCheckBox(Self.Components[a_Index]).Checked) then Include(Result, TMyType(Self.Components[a_Index].Tag)); end; function TForm54.ReadMyTypes(aVariableName: string): TMyTypes; var a_Ini: TIniFile; a_Var: string; a_List: TStrings; a_Index: integer; begin Result := []; a_Ini := nil; a_List := nil; a_Ini := TIniFile.Create('MyType.ini'); a_List := TStringList.Create; try a_Var := a_Ini.ReadString('Sets', aVariableName, ''); a_List.Delimiter := ','; a_List.DelimitedText := a_Var; for a_Index := 0 to a_List.Count - 1 do begin Include(Result, TMyType(GetEnumValue(TypeInfo(TMyType), a_List[a_Index]))); end; finally a_Ini.Free; a_List.Free; end; end; procedure TForm54.SaveMyTypes(aVariableName: string; aMyTypes: TMyTypes); var a_Ini: TIniFile; a_Index: integer; a_Var: string; begin a_Var := ''; a_Ini := TIniFile.Create('MyType.ini'); try for a_Index := Ord(Low(TMyType)) to Ord(High(TMyType)) do if TMyType(a_Index) in aMyTypes then if a_Var = '' then a_Var := GetEnumName(TypeInfo(TMyType), a_Index) else a_Var := a_Var + ',' + GetEnumName(TypeInfo(TMyType), a_Index); a_Ini.WriteString('Sets', aVariablename, a_Var); finally a_Ini.Free; end; end; procedure TForm54.setMyTypes1(const Value: TMyTypes); var a_Index: integer; begin for a_Index := 0 to Self.ComponentCount - 1 do if Self.Components[a_Index] is TCheckBox then TCheckBox(Self.Components[a_Index]).Checked := TMyType(TCheckBox(Self.Components[a_Index]).Tag) in Value; end; end. ```
35,732
### Challenge Challenge is writing a program that takes a **positive** numbers `a` and a **nonzero** number `b` and outputs `a^b` (a raised to the power b). You can only use `+ - * / abs()` as mathematical functions/operators. These can only be applied to scalar values, but not to whole lists or arrays. Examples: ``` 1.234 ^ 5.678 = 3.29980 4.5 ^ 4.5 = 869.874 4.5 ^-4.5 = 0.00114959 ``` Relevant: <http://xkcd.com/217/> ### Details You can write a function or a similar construct for using in console. If you cannot use console input you can assume that both numbers are saved in variables and ouptut via standard output or writing to a file. The output has to be correct to at least 4 significat digits. You can assume that both `a` and `b` are nonzero. A runtime of significantly more than 1 minute is not acceptable. The least number of bytes will win. Please explain your program and your algorithm. EDIT: Only **positive bases** have to be considered. You can assume `a>0`. **Be aware that both numbers do not have to be integers!!!**
2014/08/04
[ "https://codegolf.stackexchange.com/questions/35732", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24877/" ]
JavaScript (E6) 155 ~~174 191~~ =============================== **Edit 2** As suggested by @bebe, using recursive function (performe worse but shorter) Slightly changed R function to avoid 'too much recursion' Test suite added. The function performs well for bases < 3000 and exponent in range -50..50. **Edit** Golfed more and better precision Any real number can be approximate with a rational number (and IEEE standard 'real' numbers store rationals in fact). Any rational number can be expressed as a fraction a/b with a and b integers. x^(a/b) is root b of (x^a) or (root b of x)^a. Integer exponentiation is quite easy by squaring. Integer root can be approximated using numerical methods. **Code** ```js P=(x,e)=>( f=1e7,e<0&&(x=1/x,e=-e), F=(b,e,r=1)=>e?F(b*b,e>>1,e&1?r*b:r):r, R=(b,e,g=1,y=1e-30,d=(b/F(g,e-1)-g)/e)=>d>y|d<-y?R(b,e,g+d,y/.99):g, F(R(x,f),e*f) ) ``` **Test** In FireFox or FireBug console ```js for (i=0;i<100;i++) { b=Math.random()*3000 e=Math.random()*100-50 p1=Math.pow(b,e) // standard power function, to check p2=P(b,e) d=(p1-p2)/p1 // relative difference if (!isFinite(p2) || d > 0.001) console.log(i, b, e, p1, p2, d.toFixed(3)) } ```
JS (ES6), 103 bytes ------------------- ```js t=(x,m,f)=>{for(r=i=s=u=1;i<1<<7+f;r+=s/(u=i++*(f?1:u)))s*=m;return r};e=(a,b)=>t(b,t(a,1-1/a,9)*b-b,0) ``` Examples : ``` e(1.234,5.678) = 3.299798925315965 e(4.5,4.5) = 869.8739233782269 e(4.5,-4.5) = 0.0011495918812070608 ``` Use Taylor series. `b^x = 1 + ln(b)*x/1! + (ln(b)*x)^2/2! + (ln(b)*x)^3/3! + (ln(b)*x)^4/4! + ...` with [natural logarithm approximation](http://en.wikipedia.org/wiki/Natural_logarithm#Derivative.2C_Taylor_series) : `ln(b) = (1-1/x) + (1-1/x)^2/2 + (1-1/x)^3/3 + (1-1/x)^4/4 + ...` I used 128 iterations to compute `b^x` (more iterations is difficult due to factorial) and 262144 iterations for `ln(b)`
35,732
### Challenge Challenge is writing a program that takes a **positive** numbers `a` and a **nonzero** number `b` and outputs `a^b` (a raised to the power b). You can only use `+ - * / abs()` as mathematical functions/operators. These can only be applied to scalar values, but not to whole lists or arrays. Examples: ``` 1.234 ^ 5.678 = 3.29980 4.5 ^ 4.5 = 869.874 4.5 ^-4.5 = 0.00114959 ``` Relevant: <http://xkcd.com/217/> ### Details You can write a function or a similar construct for using in console. If you cannot use console input you can assume that both numbers are saved in variables and ouptut via standard output or writing to a file. The output has to be correct to at least 4 significat digits. You can assume that both `a` and `b` are nonzero. A runtime of significantly more than 1 minute is not acceptable. The least number of bytes will win. Please explain your program and your algorithm. EDIT: Only **positive bases** have to be considered. You can assume `a>0`. **Be aware that both numbers do not have to be integers!!!**
2014/08/04
[ "https://codegolf.stackexchange.com/questions/35732", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24877/" ]
JavaScript (E6) 155 ~~174 191~~ =============================== **Edit 2** As suggested by @bebe, using recursive function (performe worse but shorter) Slightly changed R function to avoid 'too much recursion' Test suite added. The function performs well for bases < 3000 and exponent in range -50..50. **Edit** Golfed more and better precision Any real number can be approximate with a rational number (and IEEE standard 'real' numbers store rationals in fact). Any rational number can be expressed as a fraction a/b with a and b integers. x^(a/b) is root b of (x^a) or (root b of x)^a. Integer exponentiation is quite easy by squaring. Integer root can be approximated using numerical methods. **Code** ```js P=(x,e)=>( f=1e7,e<0&&(x=1/x,e=-e), F=(b,e,r=1)=>e?F(b*b,e>>1,e&1?r*b:r):r, R=(b,e,g=1,y=1e-30,d=(b/F(g,e-1)-g)/e)=>d>y|d<-y?R(b,e,g+d,y/.99):g, F(R(x,f),e*f) ) ``` **Test** In FireFox or FireBug console ```js for (i=0;i<100;i++) { b=Math.random()*3000 e=Math.random()*100-50 p1=Math.pow(b,e) // standard power function, to check p2=P(b,e) d=(p1-p2)/p1 // relative difference if (!isFinite(p2) || d > 0.001) console.log(i, b, e, p1, p2, d.toFixed(3)) } ```
[golflua](http://mniip.com/misc/conv/golflua/) 120 ================================================== I use the fact that ``` a^b = exp(log(a^b)) = exp(b*log(a)) ``` and wrote my own `log` & `exp` functions. The values `a` and `b` need to be entered on newlines when run in the terminal: ``` \L(x)g=0~@ i=1,50 c=(x-1)/x~@j=2,i c = c*(x-1)/x$g=g+c/i$~g$\E(x)g=1;R=1e7~@i=1,R g=g*(1+x/R)$~g$a=I.r()b=I.r()w(E(b*L(a))) ``` Sample runs: ``` 4.5, 4.5 ==> 869.87104890175 4.5, -4.5 ==> 0.0011495904124065 3.0, 2.33 ==> 12.932794624815 9.0, 0.0 ==> 1 2.0, 2.0 ==> 3.9999996172672 ``` An ungolfed Lua version is, ``` -- returns log function L(x) g = 0 for i=1,50 do c=(x-1)/x for j=2,i do c = c*(x-1)/x end g = g + c/i end return g end -- returns exp function E(x) g=1;L=9999999 for i=1,L do g=g*(1+x/L) end return g end a=io.read() b=io.read() print(E(b*L(a))) print(a^b) ```
35,732
### Challenge Challenge is writing a program that takes a **positive** numbers `a` and a **nonzero** number `b` and outputs `a^b` (a raised to the power b). You can only use `+ - * / abs()` as mathematical functions/operators. These can only be applied to scalar values, but not to whole lists or arrays. Examples: ``` 1.234 ^ 5.678 = 3.29980 4.5 ^ 4.5 = 869.874 4.5 ^-4.5 = 0.00114959 ``` Relevant: <http://xkcd.com/217/> ### Details You can write a function or a similar construct for using in console. If you cannot use console input you can assume that both numbers are saved in variables and ouptut via standard output or writing to a file. The output has to be correct to at least 4 significat digits. You can assume that both `a` and `b` are nonzero. A runtime of significantly more than 1 minute is not acceptable. The least number of bytes will win. Please explain your program and your algorithm. EDIT: Only **positive bases** have to be considered. You can assume `a>0`. **Be aware that both numbers do not have to be integers!!!**
2014/08/04
[ "https://codegolf.stackexchange.com/questions/35732", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24877/" ]
Haskell, 85 ~~90~~ ================== Standard exp-log algorithm. Now with different name, shaving off a few more characters: ```hs a%b|a>1=1/(1/a)%b|0<1=sum$scanl((/).((-b*foldr1(\n b->(1-a)*(b+1/n))c)*))1c c=[1..99] ``` `raise` is now called `(%)`, or `%` in infix notation, even making its use consume fewer bytes: `4.5%(-4.5)` The ungolfed version also uses just 172 bytes: ```hs raise a b | a > 1 = 1 / raise (1/a) b | otherwise = expo (-b* ln (1-a)) ln x = foldr1 (\n a -> x*a+x/n) [1..99] expo x = sum $ scanl ((/) . (x*)) 1 [1..99] ```
JS (ES6), 103 bytes ------------------- ```js t=(x,m,f)=>{for(r=i=s=u=1;i<1<<7+f;r+=s/(u=i++*(f?1:u)))s*=m;return r};e=(a,b)=>t(b,t(a,1-1/a,9)*b-b,0) ``` Examples : ``` e(1.234,5.678) = 3.299798925315965 e(4.5,4.5) = 869.8739233782269 e(4.5,-4.5) = 0.0011495918812070608 ``` Use Taylor series. `b^x = 1 + ln(b)*x/1! + (ln(b)*x)^2/2! + (ln(b)*x)^3/3! + (ln(b)*x)^4/4! + ...` with [natural logarithm approximation](http://en.wikipedia.org/wiki/Natural_logarithm#Derivative.2C_Taylor_series) : `ln(b) = (1-1/x) + (1-1/x)^2/2 + (1-1/x)^3/3 + (1-1/x)^4/4 + ...` I used 128 iterations to compute `b^x` (more iterations is difficult due to factorial) and 262144 iterations for `ln(b)`
35,732
### Challenge Challenge is writing a program that takes a **positive** numbers `a` and a **nonzero** number `b` and outputs `a^b` (a raised to the power b). You can only use `+ - * / abs()` as mathematical functions/operators. These can only be applied to scalar values, but not to whole lists or arrays. Examples: ``` 1.234 ^ 5.678 = 3.29980 4.5 ^ 4.5 = 869.874 4.5 ^-4.5 = 0.00114959 ``` Relevant: <http://xkcd.com/217/> ### Details You can write a function or a similar construct for using in console. If you cannot use console input you can assume that both numbers are saved in variables and ouptut via standard output or writing to a file. The output has to be correct to at least 4 significat digits. You can assume that both `a` and `b` are nonzero. A runtime of significantly more than 1 minute is not acceptable. The least number of bytes will win. Please explain your program and your algorithm. EDIT: Only **positive bases** have to be considered. You can assume `a>0`. **Be aware that both numbers do not have to be integers!!!**
2014/08/04
[ "https://codegolf.stackexchange.com/questions/35732", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24877/" ]
Python, 77 ========== As with some other answers this is based on log and exp. But the functions are computed by numerically solving ordinary differential equations. ``` def f(a,b,y=1): if a<1:a=1/a;b=-b while a>1:a/=1e-7+1;y*=b*1e-7+1 return y ``` Does it satisfy the requirements? For the examples in the question, yes. For large a, it will take a very long time. For large a or b, it will become inaccurate. Examples: ``` a b f(a, b) pow(a, b) <1e-5 rel error? 1.234 5.678 3.2998 3.2998 OK 4.5 4.5 869.873 869.874 OK 4.5 -4.5 0.00114959 0.00114959 OK 0.5 0.5 0.707107 0.707107 OK 0.5 -0.5 1.41421 1.41421 OK 80 5 3.27679e+09 3.2768e+09 OK 2.71828 3.14159 23.1407 23.1407 OK ``` Update: flawr asked for more detail on the maths so here you go. I considered the following initial value problems: * x'(t) = x(t), with x(0) = 1. The solution is exp(t). * y'(t) = by(t), with y(0) = 1. The solution is exp(bt). If I can find the value of t such that x(t) = a, then I'll have y(t) = exp(bt) = a^b. The simplest way to numerically solve an initial value problem is [Euler's method](http://en.wikipedia.org/wiki/Euler_method). You compute the derivative the function is supposed to have, and then take a, step, in the *direction* of the derivative, and *proportional* to it, but scaled by a tiny constant. So that's what I do, take tiny steps until x is as big as a, and then see what y is at that time. Well, that's the way I thought of it. In my code, t is never explicitly computed (it is 1e-7 \* the number of steps of the while loop), and I saved some characters by doing the calculations for x with a instead.
JS (ES6), 103 bytes ------------------- ```js t=(x,m,f)=>{for(r=i=s=u=1;i<1<<7+f;r+=s/(u=i++*(f?1:u)))s*=m;return r};e=(a,b)=>t(b,t(a,1-1/a,9)*b-b,0) ``` Examples : ``` e(1.234,5.678) = 3.299798925315965 e(4.5,4.5) = 869.8739233782269 e(4.5,-4.5) = 0.0011495918812070608 ``` Use Taylor series. `b^x = 1 + ln(b)*x/1! + (ln(b)*x)^2/2! + (ln(b)*x)^3/3! + (ln(b)*x)^4/4! + ...` with [natural logarithm approximation](http://en.wikipedia.org/wiki/Natural_logarithm#Derivative.2C_Taylor_series) : `ln(b) = (1-1/x) + (1-1/x)^2/2 + (1-1/x)^3/3 + (1-1/x)^4/4 + ...` I used 128 iterations to compute `b^x` (more iterations is difficult due to factorial) and 262144 iterations for `ln(b)`
35,732
### Challenge Challenge is writing a program that takes a **positive** numbers `a` and a **nonzero** number `b` and outputs `a^b` (a raised to the power b). You can only use `+ - * / abs()` as mathematical functions/operators. These can only be applied to scalar values, but not to whole lists or arrays. Examples: ``` 1.234 ^ 5.678 = 3.29980 4.5 ^ 4.5 = 869.874 4.5 ^-4.5 = 0.00114959 ``` Relevant: <http://xkcd.com/217/> ### Details You can write a function or a similar construct for using in console. If you cannot use console input you can assume that both numbers are saved in variables and ouptut via standard output or writing to a file. The output has to be correct to at least 4 significat digits. You can assume that both `a` and `b` are nonzero. A runtime of significantly more than 1 minute is not acceptable. The least number of bytes will win. Please explain your program and your algorithm. EDIT: Only **positive bases** have to be considered. You can assume `a>0`. **Be aware that both numbers do not have to be integers!!!**
2014/08/04
[ "https://codegolf.stackexchange.com/questions/35732", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24877/" ]
Haskell, 85 ~~90~~ ================== Standard exp-log algorithm. Now with different name, shaving off a few more characters: ```hs a%b|a>1=1/(1/a)%b|0<1=sum$scanl((/).((-b*foldr1(\n b->(1-a)*(b+1/n))c)*))1c c=[1..99] ``` `raise` is now called `(%)`, or `%` in infix notation, even making its use consume fewer bytes: `4.5%(-4.5)` The ungolfed version also uses just 172 bytes: ```hs raise a b | a > 1 = 1 / raise (1/a) b | otherwise = expo (-b* ln (1-a)) ln x = foldr1 (\n a -> x*a+x/n) [1..99] expo x = sum $ scanl ((/) . (x*)) 1 [1..99] ```
[golflua](http://mniip.com/misc/conv/golflua/) 120 ================================================== I use the fact that ``` a^b = exp(log(a^b)) = exp(b*log(a)) ``` and wrote my own `log` & `exp` functions. The values `a` and `b` need to be entered on newlines when run in the terminal: ``` \L(x)g=0~@ i=1,50 c=(x-1)/x~@j=2,i c = c*(x-1)/x$g=g+c/i$~g$\E(x)g=1;R=1e7~@i=1,R g=g*(1+x/R)$~g$a=I.r()b=I.r()w(E(b*L(a))) ``` Sample runs: ``` 4.5, 4.5 ==> 869.87104890175 4.5, -4.5 ==> 0.0011495904124065 3.0, 2.33 ==> 12.932794624815 9.0, 0.0 ==> 1 2.0, 2.0 ==> 3.9999996172672 ``` An ungolfed Lua version is, ``` -- returns log function L(x) g = 0 for i=1,50 do c=(x-1)/x for j=2,i do c = c*(x-1)/x end g = g + c/i end return g end -- returns exp function E(x) g=1;L=9999999 for i=1,L do g=g*(1+x/L) end return g end a=io.read() b=io.read() print(E(b*L(a))) print(a^b) ```
35,732
### Challenge Challenge is writing a program that takes a **positive** numbers `a` and a **nonzero** number `b` and outputs `a^b` (a raised to the power b). You can only use `+ - * / abs()` as mathematical functions/operators. These can only be applied to scalar values, but not to whole lists or arrays. Examples: ``` 1.234 ^ 5.678 = 3.29980 4.5 ^ 4.5 = 869.874 4.5 ^-4.5 = 0.00114959 ``` Relevant: <http://xkcd.com/217/> ### Details You can write a function or a similar construct for using in console. If you cannot use console input you can assume that both numbers are saved in variables and ouptut via standard output or writing to a file. The output has to be correct to at least 4 significat digits. You can assume that both `a` and `b` are nonzero. A runtime of significantly more than 1 minute is not acceptable. The least number of bytes will win. Please explain your program and your algorithm. EDIT: Only **positive bases** have to be considered. You can assume `a>0`. **Be aware that both numbers do not have to be integers!!!**
2014/08/04
[ "https://codegolf.stackexchange.com/questions/35732", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24877/" ]
Python, 77 ========== As with some other answers this is based on log and exp. But the functions are computed by numerically solving ordinary differential equations. ``` def f(a,b,y=1): if a<1:a=1/a;b=-b while a>1:a/=1e-7+1;y*=b*1e-7+1 return y ``` Does it satisfy the requirements? For the examples in the question, yes. For large a, it will take a very long time. For large a or b, it will become inaccurate. Examples: ``` a b f(a, b) pow(a, b) <1e-5 rel error? 1.234 5.678 3.2998 3.2998 OK 4.5 4.5 869.873 869.874 OK 4.5 -4.5 0.00114959 0.00114959 OK 0.5 0.5 0.707107 0.707107 OK 0.5 -0.5 1.41421 1.41421 OK 80 5 3.27679e+09 3.2768e+09 OK 2.71828 3.14159 23.1407 23.1407 OK ``` Update: flawr asked for more detail on the maths so here you go. I considered the following initial value problems: * x'(t) = x(t), with x(0) = 1. The solution is exp(t). * y'(t) = by(t), with y(0) = 1. The solution is exp(bt). If I can find the value of t such that x(t) = a, then I'll have y(t) = exp(bt) = a^b. The simplest way to numerically solve an initial value problem is [Euler's method](http://en.wikipedia.org/wiki/Euler_method). You compute the derivative the function is supposed to have, and then take a, step, in the *direction* of the derivative, and *proportional* to it, but scaled by a tiny constant. So that's what I do, take tiny steps until x is as big as a, and then see what y is at that time. Well, that's the way I thought of it. In my code, t is never explicitly computed (it is 1e-7 \* the number of steps of the while loop), and I saved some characters by doing the calculations for x with a instead.
[golflua](http://mniip.com/misc/conv/golflua/) 120 ================================================== I use the fact that ``` a^b = exp(log(a^b)) = exp(b*log(a)) ``` and wrote my own `log` & `exp` functions. The values `a` and `b` need to be entered on newlines when run in the terminal: ``` \L(x)g=0~@ i=1,50 c=(x-1)/x~@j=2,i c = c*(x-1)/x$g=g+c/i$~g$\E(x)g=1;R=1e7~@i=1,R g=g*(1+x/R)$~g$a=I.r()b=I.r()w(E(b*L(a))) ``` Sample runs: ``` 4.5, 4.5 ==> 869.87104890175 4.5, -4.5 ==> 0.0011495904124065 3.0, 2.33 ==> 12.932794624815 9.0, 0.0 ==> 1 2.0, 2.0 ==> 3.9999996172672 ``` An ungolfed Lua version is, ``` -- returns log function L(x) g = 0 for i=1,50 do c=(x-1)/x for j=2,i do c = c*(x-1)/x end g = g + c/i end return g end -- returns exp function E(x) g=1;L=9999999 for i=1,L do g=g*(1+x/L) end return g end a=io.read() b=io.read() print(E(b*L(a))) print(a^b) ```
24,950,412
I'm working on typing speed app and I need to know what's the Formula of calculating WPM (Words Per Minute) Edit: indeed i know: ``` wpm = correct_characters_in_60_seconds / 5 ``` but i have no idea what should i do with decimal numbers like 22.6 or 19.7 and... for example if user typed 158 keystrokes in 60 seconds so, `158/5 = 31.6` so do the result should be 32 WPM or 31 WPM? How? thanks.
2014/07/25
[ "https://Stackoverflow.com/questions/24950412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3237755/" ]
WPM (Word per minute) For the purpose of typing measurement, each word is standardized to be five characters or keystrokes long, including spaces and punctuation. For example, the phrase "I run" counts as one word, but "rhinoceros" and "let's talk" both count as two. So the formula is: ``` Number_of_keystroke / time_in_minute * percentages_of_accurate_word ``` or ``` Number_of_keystroke / time_in_second * 60 * percentages_of_accurate_word ``` When dealing with decimals you should round down when the decimal is >.5 , else round down Example: 5.5 -> 6 7.3 -> 7 3.49 -> 3 4.51 -> 5
Words per minute(WPM) should be rounded off to the closest decimal value. In your case 158/5 = 31.6 should be reported as 32 and not 31. However if the the value was 156/5 = 31.2 then it should be rounded off to 31 to approximate the closest decimal value and hence averaging the overall error. > > if WPM<=x.5 then WPM = x else WPM = x+1 > > >
48,883,287
I have a datafile in the following format ``` 1|col2|col3|105,230,3,44,59,62|col5 2|col2|col3|43,44|col5 3|col2|col3|1,2,3,4,5,6,7,8|col5 4|col2|col3|1,2,37|col5 ``` * Delimiter is "|" * 4th column is a comma separated set of numbers. * I need records that have the number "3" individually in their 4th column but numbers such as 43 or 33 shouldn't count. * "3" could be at the start of 4th column, in the middle of 4th column or at the end of 4th column So, desirable records from above given data are ``` 1|col2|col3|105,230,3,44,59,62|col5 3|col2|col3|1,2,3,4,5,6,7,8|col5 ``` I'm currently using the following command but I'm looking for a more efficient/organized one ``` awk -F"|" '$4 ~ /,3,/ || $4 ~ /^3,/ || $4 ~ /,3$/' ```
2018/02/20
[ "https://Stackoverflow.com/questions/48883287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4132504/" ]
Short GNU **`awk`** solution: ``` awk -F'|' '$4 ~ /\<3\>/' file ``` * `\<` and `\>` - stand for the *start* and *end* of the *word* respectively The output: ``` 1|col2|col3|105,230,3,44,59,62|col5 3|col2|col3|1,2,3,4,5,6,7,8|col5 ``` --- Or a more unified/portable one: ``` awk -F'|' '$4 ~ /(^|,)3(,|$)/' file ```
In case you want to have any values in 4th column which has `3` in it then print the line, if yes then following `awk` may help you on same: ``` awk -F"|" '{num=split($4, array,",");for(i=1;i<=num;i++){if(array[i]==3){print;next}}}' Input_file ```
48,883,287
I have a datafile in the following format ``` 1|col2|col3|105,230,3,44,59,62|col5 2|col2|col3|43,44|col5 3|col2|col3|1,2,3,4,5,6,7,8|col5 4|col2|col3|1,2,37|col5 ``` * Delimiter is "|" * 4th column is a comma separated set of numbers. * I need records that have the number "3" individually in their 4th column but numbers such as 43 or 33 shouldn't count. * "3" could be at the start of 4th column, in the middle of 4th column or at the end of 4th column So, desirable records from above given data are ``` 1|col2|col3|105,230,3,44,59,62|col5 3|col2|col3|1,2,3,4,5,6,7,8|col5 ``` I'm currently using the following command but I'm looking for a more efficient/organized one ``` awk -F"|" '$4 ~ /,3,/ || $4 ~ /^3,/ || $4 ~ /,3$/' ```
2018/02/20
[ "https://Stackoverflow.com/questions/48883287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4132504/" ]
In case you want to have any values in 4th column which has `3` in it then print the line, if yes then following `awk` may help you on same: ``` awk -F"|" '{num=split($4, array,",");for(i=1;i<=num;i++){if(array[i]==3){print;next}}}' Input_file ```
There is an idiomatic way to deal with splitting fields into sub-fields with GNU awk (although it is overkill in this context). The basic process is this: 1. Save the current record `rec = $0` 2. Save the current field separator `oFS = FS` 3. Choose a new field separator `FS=","` 4. Set `$0` to the field you are interested in `$0 = $4` 5. You can now address the sub-fields with dollar notation etc. 6. Restore the original field separator `FS = oFS` For example: *parse.awk* ```awk BEGIN { FS = "|" } { rec = $0 } { oFS = FS FS = "," $0 = $4 } /\<3\>/ { print rec } { FS = oFS } ``` Run it like this: ```none awk -f parse.awk infile ``` Output: ```none 1|col2|col3|105,230,3,44,59,62|col5 3|col2|col3|1,2,3,4,5,6,7,8|col5 ```
48,883,287
I have a datafile in the following format ``` 1|col2|col3|105,230,3,44,59,62|col5 2|col2|col3|43,44|col5 3|col2|col3|1,2,3,4,5,6,7,8|col5 4|col2|col3|1,2,37|col5 ``` * Delimiter is "|" * 4th column is a comma separated set of numbers. * I need records that have the number "3" individually in their 4th column but numbers such as 43 or 33 shouldn't count. * "3" could be at the start of 4th column, in the middle of 4th column or at the end of 4th column So, desirable records from above given data are ``` 1|col2|col3|105,230,3,44,59,62|col5 3|col2|col3|1,2,3,4,5,6,7,8|col5 ``` I'm currently using the following command but I'm looking for a more efficient/organized one ``` awk -F"|" '$4 ~ /,3,/ || $4 ~ /^3,/ || $4 ~ /,3$/' ```
2018/02/20
[ "https://Stackoverflow.com/questions/48883287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4132504/" ]
Short GNU **`awk`** solution: ``` awk -F'|' '$4 ~ /\<3\>/' file ``` * `\<` and `\>` - stand for the *start* and *end* of the *word* respectively The output: ``` 1|col2|col3|105,230,3,44,59,62|col5 3|col2|col3|1,2,3,4,5,6,7,8|col5 ``` --- Or a more unified/portable one: ``` awk -F'|' '$4 ~ /(^|,)3(,|$)/' file ```
There is an idiomatic way to deal with splitting fields into sub-fields with GNU awk (although it is overkill in this context). The basic process is this: 1. Save the current record `rec = $0` 2. Save the current field separator `oFS = FS` 3. Choose a new field separator `FS=","` 4. Set `$0` to the field you are interested in `$0 = $4` 5. You can now address the sub-fields with dollar notation etc. 6. Restore the original field separator `FS = oFS` For example: *parse.awk* ```awk BEGIN { FS = "|" } { rec = $0 } { oFS = FS FS = "," $0 = $4 } /\<3\>/ { print rec } { FS = oFS } ``` Run it like this: ```none awk -f parse.awk infile ``` Output: ```none 1|col2|col3|105,230,3,44,59,62|col5 3|col2|col3|1,2,3,4,5,6,7,8|col5 ```
30,983,202
I get output from Junos Switches in such format: ``` Physical interface: ge-0/0/7, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 42210774942 1163342 ``` I need only the interface name and dropped packets value in one line, something like this: ``` ge-0/0/7 - 1163342 ``` I tried many different combination of `sed` and `awk`. I tried to merge 3 lines to get only the columns I need, but it did not work. This is how I tried to merge lines: ``` cat file.txt.out | awk '{getline b; getline c;printf("%s %s %s\n",$0,b,c)}' ``` But it seems the resulting line is too long, so i was not able to get what is needed. Please help The output looks like this(but much longer): ``` Physical interface: ge-0/0/0, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 4582206 0 Physical interface: ge-0/0/1, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 14419826529 112564 Physical interface: ge-0/0/2, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 67593521901 1675707 Physical interface: ge-0/0/3, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 44283738671 977315 Physical interface: ge-0/0/4, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 98998665742 5065245 Physical interface: ge-0/0/5, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 56932179711 1446413 Physical interface: ge-0/0/6, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 34955222648 578513 ```
2015/06/22
[ "https://Stackoverflow.com/questions/30983202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4977702/" ]
It's extremely hard to guess with just one block of sample input, but this may be what you want: ``` $ awk -v RS= '{print $3, $NF}' file ge-0/0/7, 1163342 ``` If not, post a few blocks of your input file instead of just one so we can get a better idea what it is you're trying to parse. Given your newly posted sample input, this is what you need: ``` $ awk '(NR%3)==1{p=$3} (NR%3)==0{print p, $NF}' file ge-0/0/0, 0 ge-0/0/1, 112564 ge-0/0/2, 1675707 ge-0/0/3, 977315 ge-0/0/4, 5065245 ge-0/0/5, 1446413 ge-0/0/6, 578513 ```
Totally fragile: ``` $ cat test.txt Physical interface: ge-0/0/7, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 42210774942 1163342 $ echo $(grep -Po "Physical interface: \K[^,]*" test.txt) "-" \ $(awk '!/Phys/ && !/Drop/ && NF {print $NF}' test.txt) ge-0/0/7 - 1163342 ``` This works like this: * `grep -Po "Physical interface: \K[^,]*" test.txt` get all the text after `Physical interface:` and up to a comma. * `awk '!/Phys/ && !/Drop/ && NF {print $NF}' test.txt` in those lines not containing `Phys`, nor `Drop` nor being empty, print the last field. You can also use `printf` to have more control over the content your are printing: ``` printf "%s - %s\n" $(grep -Po "Physical interface: \K[^,]*" test.txt) $(awk '!/Phys/ && !/Drop/ && NF {print $NF}' test.txt) ```
30,983,202
I get output from Junos Switches in such format: ``` Physical interface: ge-0/0/7, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 42210774942 1163342 ``` I need only the interface name and dropped packets value in one line, something like this: ``` ge-0/0/7 - 1163342 ``` I tried many different combination of `sed` and `awk`. I tried to merge 3 lines to get only the columns I need, but it did not work. This is how I tried to merge lines: ``` cat file.txt.out | awk '{getline b; getline c;printf("%s %s %s\n",$0,b,c)}' ``` But it seems the resulting line is too long, so i was not able to get what is needed. Please help The output looks like this(but much longer): ``` Physical interface: ge-0/0/0, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 4582206 0 Physical interface: ge-0/0/1, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 14419826529 112564 Physical interface: ge-0/0/2, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 67593521901 1675707 Physical interface: ge-0/0/3, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 44283738671 977315 Physical interface: ge-0/0/4, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 98998665742 5065245 Physical interface: ge-0/0/5, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 56932179711 1446413 Physical interface: ge-0/0/6, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 34955222648 578513 ```
2015/06/22
[ "https://Stackoverflow.com/questions/30983202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4977702/" ]
Totally fragile: ``` $ cat test.txt Physical interface: ge-0/0/7, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 42210774942 1163342 $ echo $(grep -Po "Physical interface: \K[^,]*" test.txt) "-" \ $(awk '!/Phys/ && !/Drop/ && NF {print $NF}' test.txt) ge-0/0/7 - 1163342 ``` This works like this: * `grep -Po "Physical interface: \K[^,]*" test.txt` get all the text after `Physical interface:` and up to a comma. * `awk '!/Phys/ && !/Drop/ && NF {print $NF}' test.txt` in those lines not containing `Phys`, nor `Drop` nor being empty, print the last field. You can also use `printf` to have more control over the content your are printing: ``` printf "%s - %s\n" $(grep -Po "Physical interface: \K[^,]*" test.txt) $(awk '!/Phys/ && !/Drop/ && NF {print $NF}' test.txt) ```
Ok, after almost 2 days of struggling (I am a beginner in unix scripting) i have got this: ``` cat myfile | sed -n -e '/Physical/,$p' | egrep -v 'Dropped|master' | awk '{gsub(/Physical interface:|Enabled,|Physical link is|0 N4M-Q1/,"")}1' | sed '/^\s*$/d' | sed -e 's/ \+/ /g' | xargs -n 4 | awk '{ print $1" "$4 }' ``` Which produces such result: ``` ge-0/0/0, 0 ge-0/0/1, 112564 ge-0/0/2, 1675707 ge-0/0/3, 977315 ge-0/0/4, 5065245 ge-0/0/5, 1446413 ge-0/0/6, 578513 ge-0/0/7, 1163342 ge-0/0/8, 1297 ge-0/0/9, 1604987 ``` I realize that this soution might not be the most optimal, but at least it does what i need;) "Optimization" proposals are appreciated:)
30,983,202
I get output from Junos Switches in such format: ``` Physical interface: ge-0/0/7, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 42210774942 1163342 ``` I need only the interface name and dropped packets value in one line, something like this: ``` ge-0/0/7 - 1163342 ``` I tried many different combination of `sed` and `awk`. I tried to merge 3 lines to get only the columns I need, but it did not work. This is how I tried to merge lines: ``` cat file.txt.out | awk '{getline b; getline c;printf("%s %s %s\n",$0,b,c)}' ``` But it seems the resulting line is too long, so i was not able to get what is needed. Please help The output looks like this(but much longer): ``` Physical interface: ge-0/0/0, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 4582206 0 Physical interface: ge-0/0/1, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 14419826529 112564 Physical interface: ge-0/0/2, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 67593521901 1675707 Physical interface: ge-0/0/3, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 44283738671 977315 Physical interface: ge-0/0/4, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 98998665742 5065245 Physical interface: ge-0/0/5, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 56932179711 1446413 Physical interface: ge-0/0/6, Enabled, Physical link is Up Queue counters: Queued packets Transmitted packets Dropped packets 0 N4M-Q1 0 34955222648 578513 ```
2015/06/22
[ "https://Stackoverflow.com/questions/30983202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4977702/" ]
It's extremely hard to guess with just one block of sample input, but this may be what you want: ``` $ awk -v RS= '{print $3, $NF}' file ge-0/0/7, 1163342 ``` If not, post a few blocks of your input file instead of just one so we can get a better idea what it is you're trying to parse. Given your newly posted sample input, this is what you need: ``` $ awk '(NR%3)==1{p=$3} (NR%3)==0{print p, $NF}' file ge-0/0/0, 0 ge-0/0/1, 112564 ge-0/0/2, 1675707 ge-0/0/3, 977315 ge-0/0/4, 5065245 ge-0/0/5, 1446413 ge-0/0/6, 578513 ```
Ok, after almost 2 days of struggling (I am a beginner in unix scripting) i have got this: ``` cat myfile | sed -n -e '/Physical/,$p' | egrep -v 'Dropped|master' | awk '{gsub(/Physical interface:|Enabled,|Physical link is|0 N4M-Q1/,"")}1' | sed '/^\s*$/d' | sed -e 's/ \+/ /g' | xargs -n 4 | awk '{ print $1" "$4 }' ``` Which produces such result: ``` ge-0/0/0, 0 ge-0/0/1, 112564 ge-0/0/2, 1675707 ge-0/0/3, 977315 ge-0/0/4, 5065245 ge-0/0/5, 1446413 ge-0/0/6, 578513 ge-0/0/7, 1163342 ge-0/0/8, 1297 ge-0/0/9, 1604987 ``` I realize that this soution might not be the most optimal, but at least it does what i need;) "Optimization" proposals are appreciated:)
20,806,784
##I need to iterate over commas to break the characters between comma in xslt. There can be at the max 15 words separated by comma## ``` For example `Input <root> <child>A,B,C,D</child> </root> Output <root> <List>A</List> <List>B</List> <List>C</List> <List>D</List> ` ```
2013/12/27
[ "https://Stackoverflow.com/questions/20806784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1268935/" ]
Define a class in your CSS: ``` .stroked{ text-decoration: line-through; } ``` then just: ``` $(document).ready(function() { $(".button1").click(function() { $("ul li:nth-child(1)").toggleClass('stroked'); }); }); ``` Edit: as you are learning the basics of jQuery, consider caching your selectors [if their content is not changing through page lifecycle]: ``` $(document).ready(function() { var $li = $("ul li:nth-child(1)"); $(".button1").click(function() { $li.toggleClass('stroked'); }); }); ``` So you do not have to perform the selection on every click.
You should instead use [`.toggleClass()`](http://api.jquery.com/toggleClass/) ``` $(document).ready(function() { $(".button1").click(function() { $("ul li:nth-child(1)").toggleClass("test"); }); }); ``` CSS: ``` .test { text-decoration: line-through; } ```
20,806,784
##I need to iterate over commas to break the characters between comma in xslt. There can be at the max 15 words separated by comma## ``` For example `Input <root> <child>A,B,C,D</child> </root> Output <root> <List>A</List> <List>B</List> <List>C</List> <List>D</List> ` ```
2013/12/27
[ "https://Stackoverflow.com/questions/20806784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1268935/" ]
Define a class in your CSS: ``` .stroked{ text-decoration: line-through; } ``` then just: ``` $(document).ready(function() { $(".button1").click(function() { $("ul li:nth-child(1)").toggleClass('stroked'); }); }); ``` Edit: as you are learning the basics of jQuery, consider caching your selectors [if their content is not changing through page lifecycle]: ``` $(document).ready(function() { var $li = $("ul li:nth-child(1)"); $(".button1").click(function() { $li.toggleClass('stroked'); }); }); ``` So you do not have to perform the selection on every click.
You could use an if statement, if you wanted to keep it purely jQuery: ``` $(document).ready(function() { $(".button1").click(function() { if($("ul li:nth-child(1)").attr('text-decoration')){ $("ul li:nth-child(1)").removeAttr('text-decoration'); } Else{ $("ul li:nth-child(1)").css("text-decoration", "line-through"); } }); }); ``` otherwise, you can use `toggleClass` which is a little simpler to use, not to mention you could then use that class and the jQuery `toggleClass` to add/remove a strike-through anything
20,806,784
##I need to iterate over commas to break the characters between comma in xslt. There can be at the max 15 words separated by comma## ``` For example `Input <root> <child>A,B,C,D</child> </root> Output <root> <List>A</List> <List>B</List> <List>C</List> <List>D</List> ` ```
2013/12/27
[ "https://Stackoverflow.com/questions/20806784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1268935/" ]
Define a class in your CSS: ``` .stroked{ text-decoration: line-through; } ``` then just: ``` $(document).ready(function() { $(".button1").click(function() { $("ul li:nth-child(1)").toggleClass('stroked'); }); }); ``` Edit: as you are learning the basics of jQuery, consider caching your selectors [if their content is not changing through page lifecycle]: ``` $(document).ready(function() { var $li = $("ul li:nth-child(1)"); $(".button1").click(function() { $li.toggleClass('stroked'); }); }); ``` So you do not have to perform the selection on every click.
You could also use the `.css()` callback function: ``` $("ul li:nth-child(1)").css("text-decoration", function(_, td) { return td.indexOf("line-through") == -1 ? "line-through" : "none"; }); ```
20,806,784
##I need to iterate over commas to break the characters between comma in xslt. There can be at the max 15 words separated by comma## ``` For example `Input <root> <child>A,B,C,D</child> </root> Output <root> <List>A</List> <List>B</List> <List>C</List> <List>D</List> ` ```
2013/12/27
[ "https://Stackoverflow.com/questions/20806784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1268935/" ]
Define a class in your CSS: ``` .stroked{ text-decoration: line-through; } ``` then just: ``` $(document).ready(function() { $(".button1").click(function() { $("ul li:nth-child(1)").toggleClass('stroked'); }); }); ``` Edit: as you are learning the basics of jQuery, consider caching your selectors [if their content is not changing through page lifecycle]: ``` $(document).ready(function() { var $li = $("ul li:nth-child(1)"); $(".button1").click(function() { $li.toggleClass('stroked'); }); }); ``` So you do not have to perform the selection on every click.
Or you can do it simple like this: ``` if (condition) { $("#yourId").wrap("<strike>"); } else { $("#yourId").unwrap(); //to remove the strike } ```
20,806,784
##I need to iterate over commas to break the characters between comma in xslt. There can be at the max 15 words separated by comma## ``` For example `Input <root> <child>A,B,C,D</child> </root> Output <root> <List>A</List> <List>B</List> <List>C</List> <List>D</List> ` ```
2013/12/27
[ "https://Stackoverflow.com/questions/20806784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1268935/" ]
You should instead use [`.toggleClass()`](http://api.jquery.com/toggleClass/) ``` $(document).ready(function() { $(".button1").click(function() { $("ul li:nth-child(1)").toggleClass("test"); }); }); ``` CSS: ``` .test { text-decoration: line-through; } ```
You could use an if statement, if you wanted to keep it purely jQuery: ``` $(document).ready(function() { $(".button1").click(function() { if($("ul li:nth-child(1)").attr('text-decoration')){ $("ul li:nth-child(1)").removeAttr('text-decoration'); } Else{ $("ul li:nth-child(1)").css("text-decoration", "line-through"); } }); }); ``` otherwise, you can use `toggleClass` which is a little simpler to use, not to mention you could then use that class and the jQuery `toggleClass` to add/remove a strike-through anything
20,806,784
##I need to iterate over commas to break the characters between comma in xslt. There can be at the max 15 words separated by comma## ``` For example `Input <root> <child>A,B,C,D</child> </root> Output <root> <List>A</List> <List>B</List> <List>C</List> <List>D</List> ` ```
2013/12/27
[ "https://Stackoverflow.com/questions/20806784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1268935/" ]
You should instead use [`.toggleClass()`](http://api.jquery.com/toggleClass/) ``` $(document).ready(function() { $(".button1").click(function() { $("ul li:nth-child(1)").toggleClass("test"); }); }); ``` CSS: ``` .test { text-decoration: line-through; } ```
Or you can do it simple like this: ``` if (condition) { $("#yourId").wrap("<strike>"); } else { $("#yourId").unwrap(); //to remove the strike } ```
20,806,784
##I need to iterate over commas to break the characters between comma in xslt. There can be at the max 15 words separated by comma## ``` For example `Input <root> <child>A,B,C,D</child> </root> Output <root> <List>A</List> <List>B</List> <List>C</List> <List>D</List> ` ```
2013/12/27
[ "https://Stackoverflow.com/questions/20806784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1268935/" ]
You could also use the `.css()` callback function: ``` $("ul li:nth-child(1)").css("text-decoration", function(_, td) { return td.indexOf("line-through") == -1 ? "line-through" : "none"; }); ```
You could use an if statement, if you wanted to keep it purely jQuery: ``` $(document).ready(function() { $(".button1").click(function() { if($("ul li:nth-child(1)").attr('text-decoration')){ $("ul li:nth-child(1)").removeAttr('text-decoration'); } Else{ $("ul li:nth-child(1)").css("text-decoration", "line-through"); } }); }); ``` otherwise, you can use `toggleClass` which is a little simpler to use, not to mention you could then use that class and the jQuery `toggleClass` to add/remove a strike-through anything
20,806,784
##I need to iterate over commas to break the characters between comma in xslt. There can be at the max 15 words separated by comma## ``` For example `Input <root> <child>A,B,C,D</child> </root> Output <root> <List>A</List> <List>B</List> <List>C</List> <List>D</List> ` ```
2013/12/27
[ "https://Stackoverflow.com/questions/20806784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1268935/" ]
You could also use the `.css()` callback function: ``` $("ul li:nth-child(1)").css("text-decoration", function(_, td) { return td.indexOf("line-through") == -1 ? "line-through" : "none"; }); ```
Or you can do it simple like this: ``` if (condition) { $("#yourId").wrap("<strike>"); } else { $("#yourId").unwrap(); //to remove the strike } ```
13,924,318
I am trying to use libsndfile. I am also not very good with g++. The way to install libsndfile seems to be use "make install." I can really do that so I compiled it in a directory. I was trying to compile the tutorial here: <http://parumi.wordpress.com/2007/12/16/how-to-write-wav-files-in-c-using-libsndfile/> when I try the following: ``` g++ -Isrc/ test.c ``` I get: ``` /tmp/ccq5fhbT.o: In function SndfileHandle::SndfileHandle(char const*, int, int, int, int)': test.c:(.text._ZN13SndfileHandleC1EPKciiii[SndfileHandle::SndfileHandle(char const*, int, int, int, int)]+0xf4): undefined reference to sf_open' /tmp/ccq5fhbT.o: In function SndfileHandle::write(float const*, long)': test.c:(.text._ZN13SndfileHandle5writeEPKfl[SndfileHandle::write(float const*, long)]+0x27): undefined reference to sf_write_float' /tmp/ccq5fhbT.o: In function SndfileHandle::SNDFILE_ref::~SNDFILE_ref()': test.c:(.text._ZN13SndfileHandle11SNDFILE_refD1Ev[SndfileHandle::SNDFILE_ref::~SNDFILE_ref()]+0x20): undefined reference to sf_close' collect2: ld returned 1 exit status ``` When I try to do the following: ``` g++ -lsndfile -Isrc/ test.c ``` I get ``` /usr/bin/ld: cannot find -lsndfile collect2: ld returned 1 exit status ``` I am not sure what switches I need to give g++.
2012/12/18
[ "https://Stackoverflow.com/questions/13924318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742172/" ]
If you configure and install libsndfile with: ``` ./configure --prefix=$HOME/local make make install ``` you should then set/modify your LD\_LIBRARY\_PATH variable: ``` export $LD_LIBRARY_PATH=$HOME/local/lib ``` and then compile with ``` g++ -I $HOME/local/include -L $HOME/local/lib -lsndfile testsnd.c -o testsnd ```
In GNU/Linux Debian squeeze I have installed the libsndfile1 libraries and the program compiles without problem. ``` # apt-get install libsndfile1-dev $ g++ -w -o testsnd testsnd.c -lsndfile ``` You need to install the library with you package manager or from source code.
72,198,067
Master Data ----------- Group-Value pairs ``` 1 | 1 1 | 2 1 | 3 2 | 5 2 | 8 3 | 10 3 | 12 ``` Work Data --------- Group-Value pairs + desired result ``` 1 | 4 | 3 (3≤4, max in group 1) 1 | 2 | 2 (2≤2, max in group 1) 2 | 6 | 5 (5≤6, max in group 2) 3 | 7 | no result (both 10 and 12 > than 7) ``` --- The task is to find the maximum possible matched number from a group, the number should be less or equal to the given number. For `Group 1, value 4`: `=> filter Master Data (1,2,3) => find 3` Will have no problem with doing it once, need to do it with arrayformula. My attempts to solve it were using modifications of the `vlookup` formula, with wrong outputs so far. Samples and my working "arena": <https://docs.google.com/spreadsheets/d/11Cd2BGpGN-0h2bL0LQ_EpIDBKKT2hvTVHoxGC6i8uTE/edit?usp=sharing> Notes: no need to solve it in a single formula, because it may slow down the result.
2022/05/11
[ "https://Stackoverflow.com/questions/72198067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5372400/" ]
The TraMineRextras package has functions `sorti` and `sortv` that respectively return the sort index and the sort variable. To sorting the data, you need the `sorti` variable. Here is an example using the `actcal` data. ``` library(TraMineRextras) # actcal data set data(actcal) # using only sequence 11 to 20 actcal.seq <- seqdef(actcal[11:20,13:24]) sort.index <- sorti(actcal.seq, start="beg") actcal.seq[sort.index,] # 2103 A-A-A-A-A-A-A-A-A-A-A-A # 528 A-A-A-A-A-A-A-A-A-A-A-A # 4866 B-B-B-B-B-B-B-B-B-B-B-B # 5108 B-B-B-B-B-B-B-B-B-B-B-B # 5386 B-B-B-B-B-B-B-B-B-B-B-B # 3876 B-B-B-B-B-B-B-B-B-B-B-B # 5238 B-B-B-B-B-B-B-B-B-B-B-C # 3972 C-C-C-C-C-C-C-C-C-B-B-B # 4977 C-C-C-C-C-C-C-C-C-C-C-C # 6175 D-D-D-D-D-D-D-D-D-D-D-D ``` With `start="beg"`, you get the order corresponding to the `sortv="from.start"` argument of the plot function, and with `start="end"` the order corresponding to `"from.end"`. You can similarly use the `sort.index` with any table where rows match with sequences as `actcal[11:20,]` in the example above.
It's a little bit unclear which data frame you are alluding to, but I assume you are talking about your sequence data. The sorting is done in a two-step procedure: 1. Create a sort index using `order` 2. sort data using this index Below you find an example drawing on `{TraMineR}`'s example data `actcal`. ```r > library(TraMineR) > > # actcal data set > data(actcal) > > # We use only a sample of 10 cases > set.seed(1) > actcal <- actcal[sample(nrow(actcal),10),] > actcal.seq <- seqdef(actcal,13:24) [>] 4 distinct states appear in the data: 1 = A 2 = B 3 = C 4 = D [>] state coding: [alphabet] [label] [long label] 1 A A A 2 B B B 3 C C C 4 D D D [>] 10 sequences in the data set [>] min/max sequence length: 12/12 > > # here the sorting happens: > # 1) we create a sorting index with order > # 2) we sort the data according to the index > x <- as.data.frame(actcal.seq) > sortvar <- do.call(order, x[,ncol(x):1]) > sorted.data <- actcal.seq[sortvar,] > > # bonus: change rownumber to index position > # to ease comparison with seqplot output > rownames(sorted.data) <- 1:nrow(sorted.data) > > #Inspect data > #unsorted data > actcal.seq Sequence 3649 A-A-A-A-A-A-A-A-A-A-A-A 6274 D-D-D-D-D-D-D-D-D-D-D-D 4130 C-C-C-C-C-C-C-C-C-C-C-C 3236 B-B-B-B-B-B-B-B-B-B-B-B 2302 B-B-B-B-B-B-B-B-B-B-B-B 2172 A-A-A-A-A-A-A-A-A-A-A-A 5671 D-D-D-D-D-C-C-C-C-D-D-D 4039 B-B-B-B-B-B-B-B-B-B-B-B 153 D-D-D-D-D-D-D-D-D-D-D-D 5712 B-B-B-B-B-B-B-B-B-B-B-B > #sorted data > sorted.data Sequence 1 A-A-A-A-A-A-A-A-A-A-A-A 2 A-A-A-A-A-A-A-A-A-A-A-A 3 B-B-B-B-B-B-B-B-B-B-B-B 4 B-B-B-B-B-B-B-B-B-B-B-B 5 B-B-B-B-B-B-B-B-B-B-B-B 6 B-B-B-B-B-B-B-B-B-B-B-B 7 C-C-C-C-C-C-C-C-C-C-C-C 8 D-D-D-D-D-C-C-C-C-D-D-D 9 D-D-D-D-D-D-D-D-D-D-D-D 10 D-D-D-D-D-D-D-D-D-D-D-D > > #Compare to plot output > seqiplot(actcal.seq, sortv = "from.end") ``` [![enter image description here](https://i.stack.imgur.com/mtBMl.png)](https://i.stack.imgur.com/mtBMl.png)
5,218
What is the best way to accurately measure wavelength between crests from a pier?
2015/07/20
[ "https://earthscience.stackexchange.com/questions/5218", "https://earthscience.stackexchange.com", "https://earthscience.stackexchange.com/users/3207/" ]
One simple way is to measure the period $T$ by timing the arrival of each crest and estimate the wave speed $c$ from the depth of the water column $d$. Then one can compute a wavelength $\lambda$. Assuming the waves are shallow-water waves ($d/\lambda < 1/11$) and linear (modeled by a sine or cosine function), the error should be no more than 10% (is that accurate enough? It gets more complicated otherwise). Since we assumed these are shallow water waves they are nondispersive and the speed is simply $c = \sqrt{gd}$, where $g$ is the gravitational acceleration. Thus, the wavelength is $$\lambda = c\ T=\sqrt{gd}\ T\,.$$
Ideally you'd like to avoid having to estimate anything. Depending on the shape and orientation of the pier relative to the waves, you might be able to find some volunteers (at least 1 anyway) and space them out at approximately the right distance. Then get them to raise a hand when a crest passes them. Adjust their spacing until they are raising their hand at the same time. If the crests are simultaneous and there is only one trough between them, they are one wavelength apart. You might need to adjust for the angle of the pier, for example in this case, wavelength $\lambda$ is related to the inter-volunteer distance $d$ and pier angle $\theta$ as $\lambda = d \cos\theta$ ![measuring wavelength from a pier](https://i.stack.imgur.com/irgLR.png) Measure as many crests as you can, keeping track of the tide. As Isopycnal Oscillation explained in another answer, the wavelength with vary with water depth. Perhaps measure around high tide, and again around low tide. Take the means of your various sets of measurements. You'll need a longish tape measure, or phones with GPS, and a stopwatch, or phone with clock, if you want to measure periods as well (you might as well).
14,402,503
i am developing a new android application,and using a webview to view my website in one the website pages there is a link for login with facebook * after logging directly, it returns a blank and embty webview * i have seen couple of topics here regarding the same issue but it is not exactly like mine please note that if i am using normal desktop browser the issue is not there I assume that there is a property of the webview should be adjusted , below my webview code ``` webView1=(WebView)findViewById(R.id.webView1); webView1.setWebViewClient(new MyWebViewClient()); WebView webView1 = (WebView) findViewById(R.id.webView1); webView1.setWebChromeClient(new WebChromeClient()); webView1.getSettings().setAppCacheEnabled(true); webView1.getSettings().setDatabaseEnabled(true); webView1.getSettings().setDomStorageEnabled(true); webView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); webView1.getSettings().setGeolocationEnabled(true); webView1.loadUrl("http://www.myactivepoint.com/mobile/maplp.asp"); ``` i really approciate your support
2013/01/18
[ "https://Stackoverflow.com/questions/14402503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1990921/" ]
It seems you are looking for `Password store`. You can have a look into [vault 0.2](http://pypi.python.org/pypi/vault)
[PyCrypto](https://www.dlitz.net/software/pycrypto/) is a well known and mature library for this kind of thing, and should do what you are looking for.
14,402,503
i am developing a new android application,and using a webview to view my website in one the website pages there is a link for login with facebook * after logging directly, it returns a blank and embty webview * i have seen couple of topics here regarding the same issue but it is not exactly like mine please note that if i am using normal desktop browser the issue is not there I assume that there is a property of the webview should be adjusted , below my webview code ``` webView1=(WebView)findViewById(R.id.webView1); webView1.setWebViewClient(new MyWebViewClient()); WebView webView1 = (WebView) findViewById(R.id.webView1); webView1.setWebChromeClient(new WebChromeClient()); webView1.getSettings().setAppCacheEnabled(true); webView1.getSettings().setDatabaseEnabled(true); webView1.getSettings().setDomStorageEnabled(true); webView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); webView1.getSettings().setGeolocationEnabled(true); webView1.loadUrl("http://www.myactivepoint.com/mobile/maplp.asp"); ``` i really approciate your support
2013/01/18
[ "https://Stackoverflow.com/questions/14402503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1990921/" ]
PyCrypto.Blowfish should be very nice for that purpose: <https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.Blowfish.BlowfishCipher-class.html> Although you'd have to specify key manually on each startup of your "password server" obviously.
[PyCrypto](https://www.dlitz.net/software/pycrypto/) is a well known and mature library for this kind of thing, and should do what you are looking for.
14,402,503
i am developing a new android application,and using a webview to view my website in one the website pages there is a link for login with facebook * after logging directly, it returns a blank and embty webview * i have seen couple of topics here regarding the same issue but it is not exactly like mine please note that if i am using normal desktop browser the issue is not there I assume that there is a property of the webview should be adjusted , below my webview code ``` webView1=(WebView)findViewById(R.id.webView1); webView1.setWebViewClient(new MyWebViewClient()); WebView webView1 = (WebView) findViewById(R.id.webView1); webView1.setWebChromeClient(new WebChromeClient()); webView1.getSettings().setAppCacheEnabled(true); webView1.getSettings().setDatabaseEnabled(true); webView1.getSettings().setDomStorageEnabled(true); webView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); webView1.getSettings().setGeolocationEnabled(true); webView1.loadUrl("http://www.myactivepoint.com/mobile/maplp.asp"); ``` i really approciate your support
2013/01/18
[ "https://Stackoverflow.com/questions/14402503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1990921/" ]
It seems you are looking for `Password store`. You can have a look into [vault 0.2](http://pypi.python.org/pypi/vault)
PyCrypto.Blowfish should be very nice for that purpose: <https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.Blowfish.BlowfishCipher-class.html> Although you'd have to specify key manually on each startup of your "password server" obviously.
10,531,711
I am trying to get a method from the file Duality.java to be run in Min.Java when a button is clicked. Below are the two files and what I am currently trying to do, which is not working. How do I get the method duality() to run when the button is clicked within Min.java? Duality.java ``` package com.android.control; import android.util.Log; import com.map.AppName.R; public class duality { public void duality(){ Log.e("Did It Run","Yes it ran"); } } ``` Min.java ``` package com.android.control; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import com.map.AppName.R; public class Min extends LinearLayout { Button but; private final int ELEMENT_HEIGHT = 60; private final int ELEMENT_WIDTH = 80;; private final int TEXT_SIZE = 30; public Min( Context context, AttributeSet attributeSet ) { super(context, attributeSet); this.setLayoutParams( new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ) ); LayoutParams elementParams = new LinearLayout.LayoutParams( ELEMENT_WIDTH, ELEMENT_HEIGHT ); createBut( context ); addView( but, elementParams ); } private void createButton( Context context){ but = new Button( context ); but.setTextSize( TEXT_SIZE ); but.setText( "Go" ); but.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Duality duality = new duality(); } }); } } ```
2012/05/10
[ "https://Stackoverflow.com/questions/10531711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614460/" ]
You're only *constructing an instance* of the `duality` class - you're not calling the `duality()` method on it. This might be because you wanted that method to be a constructor - but it's not, because you specified a `void` return type, so it's just a conventional method. (By the way, it's conventional in Java to give classes names that start with uppercase characters. If you called your class `Duality`, there may be less chance that you'd get the two confused; though the problem with accidental non-constructors would still stand.)
Both `Min` and `duality` are in the `com.android.control` package so they should be able to see eachother without imports. It's recommended to capitalize class names. In fact, since your method has the same name as the class it might be conflicting with the constructor name. I suggest this: ``` public class Duality { public void duality(){ Log.e("Did It Run","Yes it ran"); } } ``` ... ``` but.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Duality d = new Duality(); d.duality(); } }); ```
10,531,711
I am trying to get a method from the file Duality.java to be run in Min.Java when a button is clicked. Below are the two files and what I am currently trying to do, which is not working. How do I get the method duality() to run when the button is clicked within Min.java? Duality.java ``` package com.android.control; import android.util.Log; import com.map.AppName.R; public class duality { public void duality(){ Log.e("Did It Run","Yes it ran"); } } ``` Min.java ``` package com.android.control; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import com.map.AppName.R; public class Min extends LinearLayout { Button but; private final int ELEMENT_HEIGHT = 60; private final int ELEMENT_WIDTH = 80;; private final int TEXT_SIZE = 30; public Min( Context context, AttributeSet attributeSet ) { super(context, attributeSet); this.setLayoutParams( new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ) ); LayoutParams elementParams = new LinearLayout.LayoutParams( ELEMENT_WIDTH, ELEMENT_HEIGHT ); createBut( context ); addView( but, elementParams ); } private void createButton( Context context){ but = new Button( context ); but.setTextSize( TEXT_SIZE ); but.setText( "Go" ); but.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Duality duality = new duality(); } }); } } ```
2012/05/10
[ "https://Stackoverflow.com/questions/10531711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614460/" ]
You're only *constructing an instance* of the `duality` class - you're not calling the `duality()` method on it. This might be because you wanted that method to be a constructor - but it's not, because you specified a `void` return type, so it's just a conventional method. (By the way, it's conventional in Java to give classes names that start with uppercase characters. If you called your class `Duality`, there may be less chance that you'd get the two confused; though the problem with accidental non-constructors would still stand.)
1. make sure that the class name and file name use same case combination in names. 2. if u want to call the constructor, remove the void from: public void duality() 3. if it is supposed to b a function and not constructor, call it using: object\_name.duality(); 4. u r calling createBut() and have given code for createButton().. is that a mistake in copy pasting?
2,906,433
I noticed that if I leave off the terminating double quote for a string constant in Visual Studio 2010, there is no error or even a warning, i.e. ``` Dim foo as String = "hi ``` However, the continuous integration tool we are using flags an error: ``` error BC30648: String constants must end with a double quote. ``` What's going on here? Is there some language rule in VB.Net that makes a terminating double quote optional "sometimes"? Is there some setting in Visual Studio that will make it flag this as an error, so I can avoid "breaking the build" in this way?
2010/05/25
[ "https://Stackoverflow.com/questions/2906433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16012/" ]
That's not according to spec as section 2.4.4 of the spec states: *A string literal is a sequence of zero or more Unicode characters beginning and ending with an ASCII double-quote character* <http://msdn.microsoft.com/en-us/library/aa711651%28v=VS.71%29.aspx> Normally Visual Studio will automatically add the ending double quote if you don't type one in. I wouldn't be surprised if it's related to this (maybe the testing never picked it up because they always got added or similar).
I noticed if you have this option on, "Pretty listing (reformatting) of code" Visual Studio will add the the terminating double quote for you, whether you want it or not. With that option off it allows the, what seems to be, invalid syntax.
2,906,433
I noticed that if I leave off the terminating double quote for a string constant in Visual Studio 2010, there is no error or even a warning, i.e. ``` Dim foo as String = "hi ``` However, the continuous integration tool we are using flags an error: ``` error BC30648: String constants must end with a double quote. ``` What's going on here? Is there some language rule in VB.Net that makes a terminating double quote optional "sometimes"? Is there some setting in Visual Studio that will make it flag this as an error, so I can avoid "breaking the build" in this way?
2010/05/25
[ "https://Stackoverflow.com/questions/2906433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16012/" ]
Actually, historically, the BASIC language never REQUIRED a closing quote. This dates back to the 70's. GW-Basic, BasicA, QBASIC, QuickBasic, even older Tandy and TRS-80 computers NEVER required a closing quote. This is nothing new. The reason for this is because BASIC is not a free flow language, like C or C#. This means that whenever a newline is found, BASIC knows that your string must end, quoted or not. Microsoft has purposely not enforced this rule in order to be compatible with older code.
I noticed if you have this option on, "Pretty listing (reformatting) of code" Visual Studio will add the the terminating double quote for you, whether you want it or not. With that option off it allows the, what seems to be, invalid syntax.
2,906,433
I noticed that if I leave off the terminating double quote for a string constant in Visual Studio 2010, there is no error or even a warning, i.e. ``` Dim foo as String = "hi ``` However, the continuous integration tool we are using flags an error: ``` error BC30648: String constants must end with a double quote. ``` What's going on here? Is there some language rule in VB.Net that makes a terminating double quote optional "sometimes"? Is there some setting in Visual Studio that will make it flag this as an error, so I can avoid "breaking the build" in this way?
2010/05/25
[ "https://Stackoverflow.com/questions/2906433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16012/" ]
Are you using MSBuild in your integrations tool? If you are, make sure you are pointing to the same MSBuild as Visual Studio is using. There is a good article I found here: [MSDN - MSBuild is now part of Visual Studio](http://blogs.msdn.com/b/visualstudio/archive/2013/07/24/msbuild-is-now-part-of-visual-studio.aspx) Instead of using MSBuild from something like **C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe** use the following: > > On 32-bit machines they can be found in: **C:\Program > Files\MSBuild\12.0\bin** > > > On 64-bit machines the 32-bit tools will be under: **C:\Program Files > (x86)\MSBuild\12.0\bin** > > > and the 64-bit tools under: **C:\Program Files > (x86)\MSBuild\12.0\bin\amd64** > > > This has worked for us.
I noticed if you have this option on, "Pretty listing (reformatting) of code" Visual Studio will add the the terminating double quote for you, whether you want it or not. With that option off it allows the, what seems to be, invalid syntax.
2,906,433
I noticed that if I leave off the terminating double quote for a string constant in Visual Studio 2010, there is no error or even a warning, i.e. ``` Dim foo as String = "hi ``` However, the continuous integration tool we are using flags an error: ``` error BC30648: String constants must end with a double quote. ``` What's going on here? Is there some language rule in VB.Net that makes a terminating double quote optional "sometimes"? Is there some setting in Visual Studio that will make it flag this as an error, so I can avoid "breaking the build" in this way?
2010/05/25
[ "https://Stackoverflow.com/questions/2906433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16012/" ]
Actually, historically, the BASIC language never REQUIRED a closing quote. This dates back to the 70's. GW-Basic, BasicA, QBASIC, QuickBasic, even older Tandy and TRS-80 computers NEVER required a closing quote. This is nothing new. The reason for this is because BASIC is not a free flow language, like C or C#. This means that whenever a newline is found, BASIC knows that your string must end, quoted or not. Microsoft has purposely not enforced this rule in order to be compatible with older code.
That's not according to spec as section 2.4.4 of the spec states: *A string literal is a sequence of zero or more Unicode characters beginning and ending with an ASCII double-quote character* <http://msdn.microsoft.com/en-us/library/aa711651%28v=VS.71%29.aspx> Normally Visual Studio will automatically add the ending double quote if you don't type one in. I wouldn't be surprised if it's related to this (maybe the testing never picked it up because they always got added or similar).
2,906,433
I noticed that if I leave off the terminating double quote for a string constant in Visual Studio 2010, there is no error or even a warning, i.e. ``` Dim foo as String = "hi ``` However, the continuous integration tool we are using flags an error: ``` error BC30648: String constants must end with a double quote. ``` What's going on here? Is there some language rule in VB.Net that makes a terminating double quote optional "sometimes"? Is there some setting in Visual Studio that will make it flag this as an error, so I can avoid "breaking the build" in this way?
2010/05/25
[ "https://Stackoverflow.com/questions/2906433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16012/" ]
Actually, historically, the BASIC language never REQUIRED a closing quote. This dates back to the 70's. GW-Basic, BasicA, QBASIC, QuickBasic, even older Tandy and TRS-80 computers NEVER required a closing quote. This is nothing new. The reason for this is because BASIC is not a free flow language, like C or C#. This means that whenever a newline is found, BASIC knows that your string must end, quoted or not. Microsoft has purposely not enforced this rule in order to be compatible with older code.
Are you using MSBuild in your integrations tool? If you are, make sure you are pointing to the same MSBuild as Visual Studio is using. There is a good article I found here: [MSDN - MSBuild is now part of Visual Studio](http://blogs.msdn.com/b/visualstudio/archive/2013/07/24/msbuild-is-now-part-of-visual-studio.aspx) Instead of using MSBuild from something like **C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe** use the following: > > On 32-bit machines they can be found in: **C:\Program > Files\MSBuild\12.0\bin** > > > On 64-bit machines the 32-bit tools will be under: **C:\Program Files > (x86)\MSBuild\12.0\bin** > > > and the 64-bit tools under: **C:\Program Files > (x86)\MSBuild\12.0\bin\amd64** > > > This has worked for us.
38,533,964
I have to parse a json object that can be a string, array, array of strings and array of object. I realised that it's not good from the beginning that one object can be many types, but I can't change the code from upstream so I'll have to deal it in my code instead. I'm building a pixel library for modern browser so I'm not using jQuery or lodash. I'm supporting most modern browser and IE >= 9 Here's the example of the data that can be returned ``` "author": { "@type": "Person", "name": "Author" } ``` Or ``` "author":[{"@type":"Person","name":"Author"}] ``` Or ``` "author": 'Author' ``` Or ``` "author": ['Author', 'Author1'] ``` And this is my code. ``` let obj = {}; try { const json = document.querySelector('div.json'); if (json) { let disc = JSON.parse(json.innerHTML); let authors = disc.author; if (typeof authors !== 'undefined' && Array.isArray(authors) && authors.length > 0) { authors = authors.map((author) => { if (typeof author === 'object' && author.name) { return author.name; } else { return author; } }); } if (typeof authors !== 'undefined' && !Array.isArray(authors) && typeof authors === 'object') { authors = [authors.name]; } if (typeof authors !== 'undefined' && typeof authors === 'string') { authors = authors.split(','); } obj.cAu: authors.join(','); } } catch (e) { } return obj; ``` My question is, is there a better way to do this in a more efficient way?
2016/07/22
[ "https://Stackoverflow.com/questions/38533964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/635162/" ]
After searching through the entire Sheets API, googling, and just general soul-searching, I had no choice but to include the Drive API and use it to do my bidding. Here's the solution I came up with. Hope this helps someone else out there! Used this script from Google for the client-side JS library in the `index.html` file: ```html <body> ... <script type="text/javascript" src="https://apis.google.com/js/client.js"></script> </body> ``` Then for the JS stuff: ```js // Cache the api's into variables. var sheets = gapi.client.sheets; var drive = gapi.client.drive; // 1. CREATE NEW SPREADSHEET sheets.spreadsheets.create({ properties: { title: 'new-sheet' } }).then(function(newSpreadSheet) { var id = newSpreadSheet.result.spreadsheetId; // 2. PUBLISH SPREADSHEAT VIA DRIVE API drive.revisions.update({ fileId: id, revisionId: 1 }, { published: true, // <-- This is where the magic happens! publishAuto: true }).then(function() { // 3. DISPLAY SPREADSHEET ON PAGE VIA IFRAME var iframe = [ '<iframe ', 'src="https://docs.google.com/spreadsheets/d/', id, '/pubhtml?widget=true&headers=false&embedded=true"></iframe>' ].join(''); // We're using jQuery on the page, but you get the idea. $('#container').html($(iframe)); }); }); ```
As you have concluded, it is not possible through the Sheets API today and is only possible through the Drive API (using the `PATCH https://www.googleapis.com/drive/v3/files/fileId/revisions/revisionId` request, documented at <https://developers.google.com/drive/v3/reference/revisions/update>).
28,659,623
i have a requirement where i have files starting with say :- M8585858 and UM966696. I have already written a code to read these files using the for loop like the one below :- ``` cd C:\Input\ echo M files .......... for %%f in (M*.*) do ( rem echo %%~nfAPSI set v=%%~nfAPSI ) echo %v% echo UM files .......... for %%f in (UM*.*) do ( set v=%%~nfAPSI ) set "v=%v:~1%" echo %v% cd D:\usr\src\IN\ cd echo Directory changed echo File in the input directory timeout 5 echo Enumerating files before copy.. dir C:\In java.exe -jar C:\abc.jar -rc4 -crypt C:\Input\ C:\Output\ %v% Echo Enumerating files after copy..... dir C:\Out echo End Of Batch File Execution ``` but now what happens is whenever a file with M966696 is dropped into the input folder C:\Input\ , the batch file deletes the first character 'M' and reads with 966696 ( which is incorrect ). i need to send the entire filename as public key. So, basically i am using the loops one below the other without conditions. Hence when it comes to the second loop, it deletes the first character. So, the ideal workaround is to include a condition with both M\* and UM\* related files. I tried using FINDSTR but it is not working or maybe I am not using it correctly - can anyone tell me how to use the if-else condition around the loops for the loops to run based on filenames?
2015/02/22
[ "https://Stackoverflow.com/questions/28659623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4588623/" ]
The following python code illustrates what I thought would be a solution: ```py import re words=['A','CAT','CATTLE','AT','LEAD'] exp=words[0] for i in range(1,len(words)): exp=exp+'|'+words[i] p = re.compile(exp) s = 'ACATTLEAD' p.findall(s) ``` unfortunately, the output is: ``` ['A', 'CAT', 'LEAD'] ``` CATTLE is missing. I searched around and it seems that any NFA constructed to match all possible words would run in n \* m complexity where n is the length of the text we are matching and m is the number of words that we are searching for. Frankly, I have no idea on how to achieve that in Python.
There are, but more often than not, for exact matches, the word list is turned into a finite automaton, deterministic or not. With natural languages, things sure get more interesting with number, cases, tenses, pre- and affixes, compound words, …
133,177
I'm trying to add a new line in checkbox note items in Google Keep app using Android Keyboard (AOSP); but instead, a new checkbox item is added when I do : * double tap on shift key → enter * drag from shift key to enter * long press enter key I can accomplish the purpose nicely in PC (Google Keep Chrome Extension) with Shift+Enter combination; but how to in Android !?
2016/01/02
[ "https://android.stackexchange.com/questions/133177", "https://android.stackexchange.com", "https://android.stackexchange.com/users/144268/" ]
This is not possible at the moment. Only thing I can think of is to use a clipboard app and copy-paste a soft linebreak into Google keep.
Android (AOSP) keyboard: When you hit the shift key (the one for the capital letters), automatically the key for the smiley (that is at the bottom right) becomes the key to start a new line. SwiftKey Keyboard: (when keyboard of the letters (alphabetical)). (from the keyboard of the letters .(a b c ..) simply hold for a moment the key for the smiley, at the bottom right.
45,939,570
I'm using Symfony 3.2 (PHP Framework) and Google API for Manage Google Spreadsheet using code. I use `google/apiclient`, and `asimlqt/php-google-spreadsheet-client` library for manage Google Sheets. As usually, I also created Application in [console.developers.google.com](https://console.developers.google.com/). Everything is working perfectly, but when I add new columns in Google Sheets after that this issue is raised. I deleted the Application from [console.developers.google.com](https://console.developers.google.com/) and re-create it also I create new spreadsheet - but same issue again. I'm following this [Document](https://www.twilio.com/blog/2017/03/google-spreadsheets-and-php.html) which mentions the issue but not how to fix it.
2017/08/29
[ "https://Stackoverflow.com/questions/45939570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3124813/" ]
I'm not familiar with gspread, which appears to be a third-party client for the Google Sheets API, but it looks like you should be using [`get_all_values`](https://github.com/burnash/gspread#getting-all-values-from-a-worksheet-as-a-list-of-lists) rather than `get_all_records`. That will give you a list of lists, rather than a list of dicts.
Python dictionaries are unordered. There is the [OrderedDict](https://docs.python.org/3.6/library/collections.html#collections.OrderedDict) in collections, but hard to say more about what the best course of action should be without more insight into why you need this dictionary ordered...
34,924,168
How can i execute code every second when only using the current time? (*no extra variables*, it doesn't have the be exactly every second, I'm quite happy with a variation between 800 to 1200 ms) I did try: ``` //code repeated every 30-100ms if ((System.currentTimeMillis() % 1000) == 0) { //execute code ``` But this doesn't work, cause the chance that currentTimeMillis can be exactly divided by 1000 is not very high. Any bright ideas on the subject? [edit] please note my "no extra variables" remark. Let me explain a bit better: i need to put this code in a place where i only have a long value indicating the unix time since 1970 (the value of currentTimeMillis). I can't remember anything, nor can i save extra variables that can be accessed the next time my code is executed. It's a special case.
2016/01/21
[ "https://Stackoverflow.com/questions/34924168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5411388/" ]
The only way I can think of to do this would be to check that we are in the time window, perform the action and then use `Thread.sleep` long enough to ensure we are out of the time window. ``` private static final long WINDOW = 200; void doItOncePerSecond(long time) throws InterruptedException { // Check the time. if ((time % 1000) / WINDOW == 0) { // Do your work. System.out.println("Now!! " + time + " - " + (time % 1000)); // Wait long enopugh to be out of the window. Thread.sleep(WINDOW - (time % 1000)); } } public void test() throws InterruptedException { System.out.println("Hello"); long start = System.currentTimeMillis(); long t; while ((t = System.currentTimeMillis()) - start < 10000) { doItOncePerSecond(t); Thread.sleep(100); } } ``` Beyond that you may need to persist a value in some other way - perhaps use a socket to yourself.
You can use java.util.Timer for this, but you can't do this scheduled operation without defining extra variable or it will be in infinity mode. You can try this: ``` new Timer().schedule(task, delay, period); ```
34,924,168
How can i execute code every second when only using the current time? (*no extra variables*, it doesn't have the be exactly every second, I'm quite happy with a variation between 800 to 1200 ms) I did try: ``` //code repeated every 30-100ms if ((System.currentTimeMillis() % 1000) == 0) { //execute code ``` But this doesn't work, cause the chance that currentTimeMillis can be exactly divided by 1000 is not very high. Any bright ideas on the subject? [edit] please note my "no extra variables" remark. Let me explain a bit better: i need to put this code in a place where i only have a long value indicating the unix time since 1970 (the value of currentTimeMillis). I can't remember anything, nor can i save extra variables that can be accessed the next time my code is executed. It's a special case.
2016/01/21
[ "https://Stackoverflow.com/questions/34924168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5411388/" ]
The only way I can think of to do this would be to check that we are in the time window, perform the action and then use `Thread.sleep` long enough to ensure we are out of the time window. ``` private static final long WINDOW = 200; void doItOncePerSecond(long time) throws InterruptedException { // Check the time. if ((time % 1000) / WINDOW == 0) { // Do your work. System.out.println("Now!! " + time + " - " + (time % 1000)); // Wait long enopugh to be out of the window. Thread.sleep(WINDOW - (time % 1000)); } } public void test() throws InterruptedException { System.out.println("Hello"); long start = System.currentTimeMillis(); long t; while ((t = System.currentTimeMillis()) - start < 10000) { doItOncePerSecond(t); Thread.sleep(100); } } ``` Beyond that you may need to persist a value in some other way - perhaps use a socket to yourself.
This does something every 1 second ``` while (true) { System.out.println("a second has passed"); Thread.sleep(1000); } ```
34,924,168
How can i execute code every second when only using the current time? (*no extra variables*, it doesn't have the be exactly every second, I'm quite happy with a variation between 800 to 1200 ms) I did try: ``` //code repeated every 30-100ms if ((System.currentTimeMillis() % 1000) == 0) { //execute code ``` But this doesn't work, cause the chance that currentTimeMillis can be exactly divided by 1000 is not very high. Any bright ideas on the subject? [edit] please note my "no extra variables" remark. Let me explain a bit better: i need to put this code in a place where i only have a long value indicating the unix time since 1970 (the value of currentTimeMillis). I can't remember anything, nor can i save extra variables that can be accessed the next time my code is executed. It's a special case.
2016/01/21
[ "https://Stackoverflow.com/questions/34924168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5411388/" ]
``` while(true) { //execute your code here Thread.sleep(1000); } ```
The only way I can think of to do this would be to check that we are in the time window, perform the action and then use `Thread.sleep` long enough to ensure we are out of the time window. ``` private static final long WINDOW = 200; void doItOncePerSecond(long time) throws InterruptedException { // Check the time. if ((time % 1000) / WINDOW == 0) { // Do your work. System.out.println("Now!! " + time + " - " + (time % 1000)); // Wait long enopugh to be out of the window. Thread.sleep(WINDOW - (time % 1000)); } } public void test() throws InterruptedException { System.out.println("Hello"); long start = System.currentTimeMillis(); long t; while ((t = System.currentTimeMillis()) - start < 10000) { doItOncePerSecond(t); Thread.sleep(100); } } ``` Beyond that you may need to persist a value in some other way - perhaps use a socket to yourself.
34,924,168
How can i execute code every second when only using the current time? (*no extra variables*, it doesn't have the be exactly every second, I'm quite happy with a variation between 800 to 1200 ms) I did try: ``` //code repeated every 30-100ms if ((System.currentTimeMillis() % 1000) == 0) { //execute code ``` But this doesn't work, cause the chance that currentTimeMillis can be exactly divided by 1000 is not very high. Any bright ideas on the subject? [edit] please note my "no extra variables" remark. Let me explain a bit better: i need to put this code in a place where i only have a long value indicating the unix time since 1970 (the value of currentTimeMillis). I can't remember anything, nor can i save extra variables that can be accessed the next time my code is executed. It's a special case.
2016/01/21
[ "https://Stackoverflow.com/questions/34924168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5411388/" ]
The best way to do this is to use `ScheduledExecutorService` ``` ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); Future future = service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS); ``` When you no longer need it, you can cancel execution ``` future.cancel(true); ```
The only way I can think of to do this would be to check that we are in the time window, perform the action and then use `Thread.sleep` long enough to ensure we are out of the time window. ``` private static final long WINDOW = 200; void doItOncePerSecond(long time) throws InterruptedException { // Check the time. if ((time % 1000) / WINDOW == 0) { // Do your work. System.out.println("Now!! " + time + " - " + (time % 1000)); // Wait long enopugh to be out of the window. Thread.sleep(WINDOW - (time % 1000)); } } public void test() throws InterruptedException { System.out.println("Hello"); long start = System.currentTimeMillis(); long t; while ((t = System.currentTimeMillis()) - start < 10000) { doItOncePerSecond(t); Thread.sleep(100); } } ``` Beyond that you may need to persist a value in some other way - perhaps use a socket to yourself.
34,924,168
How can i execute code every second when only using the current time? (*no extra variables*, it doesn't have the be exactly every second, I'm quite happy with a variation between 800 to 1200 ms) I did try: ``` //code repeated every 30-100ms if ((System.currentTimeMillis() % 1000) == 0) { //execute code ``` But this doesn't work, cause the chance that currentTimeMillis can be exactly divided by 1000 is not very high. Any bright ideas on the subject? [edit] please note my "no extra variables" remark. Let me explain a bit better: i need to put this code in a place where i only have a long value indicating the unix time since 1970 (the value of currentTimeMillis). I can't remember anything, nor can i save extra variables that can be accessed the next time my code is executed. It's a special case.
2016/01/21
[ "https://Stackoverflow.com/questions/34924168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5411388/" ]
The best way to do this is to use `ScheduledExecutorService` ``` ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); Future future = service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS); ``` When you no longer need it, you can cancel execution ``` future.cancel(true); ```
``` while(true) { //execute your code here Thread.sleep(1000); } ```
34,924,168
How can i execute code every second when only using the current time? (*no extra variables*, it doesn't have the be exactly every second, I'm quite happy with a variation between 800 to 1200 ms) I did try: ``` //code repeated every 30-100ms if ((System.currentTimeMillis() % 1000) == 0) { //execute code ``` But this doesn't work, cause the chance that currentTimeMillis can be exactly divided by 1000 is not very high. Any bright ideas on the subject? [edit] please note my "no extra variables" remark. Let me explain a bit better: i need to put this code in a place where i only have a long value indicating the unix time since 1970 (the value of currentTimeMillis). I can't remember anything, nor can i save extra variables that can be accessed the next time my code is executed. It's a special case.
2016/01/21
[ "https://Stackoverflow.com/questions/34924168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5411388/" ]
``` while(true) { //execute your code here Thread.sleep(1000); } ```
This does something every 1 second ``` while (true) { System.out.println("a second has passed"); Thread.sleep(1000); } ```
34,924,168
How can i execute code every second when only using the current time? (*no extra variables*, it doesn't have the be exactly every second, I'm quite happy with a variation between 800 to 1200 ms) I did try: ``` //code repeated every 30-100ms if ((System.currentTimeMillis() % 1000) == 0) { //execute code ``` But this doesn't work, cause the chance that currentTimeMillis can be exactly divided by 1000 is not very high. Any bright ideas on the subject? [edit] please note my "no extra variables" remark. Let me explain a bit better: i need to put this code in a place where i only have a long value indicating the unix time since 1970 (the value of currentTimeMillis). I can't remember anything, nor can i save extra variables that can be accessed the next time my code is executed. It's a special case.
2016/01/21
[ "https://Stackoverflow.com/questions/34924168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5411388/" ]
The best way to do this is to use `ScheduledExecutorService` ``` ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); Future future = service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS); ``` When you no longer need it, you can cancel execution ``` future.cancel(true); ```
This does something every 1 second ``` while (true) { System.out.println("a second has passed"); Thread.sleep(1000); } ```
34,924,168
How can i execute code every second when only using the current time? (*no extra variables*, it doesn't have the be exactly every second, I'm quite happy with a variation between 800 to 1200 ms) I did try: ``` //code repeated every 30-100ms if ((System.currentTimeMillis() % 1000) == 0) { //execute code ``` But this doesn't work, cause the chance that currentTimeMillis can be exactly divided by 1000 is not very high. Any bright ideas on the subject? [edit] please note my "no extra variables" remark. Let me explain a bit better: i need to put this code in a place where i only have a long value indicating the unix time since 1970 (the value of currentTimeMillis). I can't remember anything, nor can i save extra variables that can be accessed the next time my code is executed. It's a special case.
2016/01/21
[ "https://Stackoverflow.com/questions/34924168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5411388/" ]
The best way to do this is to use `ScheduledExecutorService` ``` ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); Future future = service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS); ``` When you no longer need it, you can cancel execution ``` future.cancel(true); ```
You can use java.util.Timer for this, but you can't do this scheduled operation without defining extra variable or it will be in infinity mode. You can try this: ``` new Timer().schedule(task, delay, period); ```
34,924,168
How can i execute code every second when only using the current time? (*no extra variables*, it doesn't have the be exactly every second, I'm quite happy with a variation between 800 to 1200 ms) I did try: ``` //code repeated every 30-100ms if ((System.currentTimeMillis() % 1000) == 0) { //execute code ``` But this doesn't work, cause the chance that currentTimeMillis can be exactly divided by 1000 is not very high. Any bright ideas on the subject? [edit] please note my "no extra variables" remark. Let me explain a bit better: i need to put this code in a place where i only have a long value indicating the unix time since 1970 (the value of currentTimeMillis). I can't remember anything, nor can i save extra variables that can be accessed the next time my code is executed. It's a special case.
2016/01/21
[ "https://Stackoverflow.com/questions/34924168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5411388/" ]
The only way I can think of to do this would be to check that we are in the time window, perform the action and then use `Thread.sleep` long enough to ensure we are out of the time window. ``` private static final long WINDOW = 200; void doItOncePerSecond(long time) throws InterruptedException { // Check the time. if ((time % 1000) / WINDOW == 0) { // Do your work. System.out.println("Now!! " + time + " - " + (time % 1000)); // Wait long enopugh to be out of the window. Thread.sleep(WINDOW - (time % 1000)); } } public void test() throws InterruptedException { System.out.println("Hello"); long start = System.currentTimeMillis(); long t; while ((t = System.currentTimeMillis()) - start < 10000) { doItOncePerSecond(t); Thread.sleep(100); } } ``` Beyond that you may need to persist a value in some other way - perhaps use a socket to yourself.
You can try this to get seconds and use it the way you would like to ... ``` long timeMillis = System.currentTimeMillis(); long timeSeconds = TimeUnit.MILLISECONDS.toSeconds(timeMillis); ```
34,924,168
How can i execute code every second when only using the current time? (*no extra variables*, it doesn't have the be exactly every second, I'm quite happy with a variation between 800 to 1200 ms) I did try: ``` //code repeated every 30-100ms if ((System.currentTimeMillis() % 1000) == 0) { //execute code ``` But this doesn't work, cause the chance that currentTimeMillis can be exactly divided by 1000 is not very high. Any bright ideas on the subject? [edit] please note my "no extra variables" remark. Let me explain a bit better: i need to put this code in a place where i only have a long value indicating the unix time since 1970 (the value of currentTimeMillis). I can't remember anything, nor can i save extra variables that can be accessed the next time my code is executed. It's a special case.
2016/01/21
[ "https://Stackoverflow.com/questions/34924168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5411388/" ]
The only way I can think of to do this would be to check that we are in the time window, perform the action and then use `Thread.sleep` long enough to ensure we are out of the time window. ``` private static final long WINDOW = 200; void doItOncePerSecond(long time) throws InterruptedException { // Check the time. if ((time % 1000) / WINDOW == 0) { // Do your work. System.out.println("Now!! " + time + " - " + (time % 1000)); // Wait long enopugh to be out of the window. Thread.sleep(WINDOW - (time % 1000)); } } public void test() throws InterruptedException { System.out.println("Hello"); long start = System.currentTimeMillis(); long t; while ((t = System.currentTimeMillis()) - start < 10000) { doItOncePerSecond(t); Thread.sleep(100); } } ``` Beyond that you may need to persist a value in some other way - perhaps use a socket to yourself.
This if statement would do it as per you request (between 800ms and 1200ms) but it is very inefficient and my previous answer or some of the other answers would be a lot better at doing what you want ``` if ((System.currentTimeMillis() % 1000) < 200 || (System.currentTimeMillis() % 1000) > 800) { } ``` or since you code is repeated roughly every 30-100 ms you can use ``` if ((System.currentTimeMillis() % 1000) < 100|| (System.currentTimeMillis() % 1000) > 900) { } ```
24,382,382
Recently I've written a custom DataGridViewColumn to host a progress bar. The column class itself has a property that I'd like to propagate to all the cells of the column. I use this code to implement it:- ``` <DefaultValue(5I)> _ Public Property BlockWidth() As Integer Get Return _blockWidth End Get Set(ByVal value As Integer) _blockWidth = value Me.ColumnCells.ForEach(Sub(cell) cell.BlockWidth = value) End Set End Property ``` And this:- ``` Private ReadOnly Property ColumnCells As IEnumerable(Of DataGridViewProgressBarCell) Get If Me.DataGridView IsNot Nothing Then Return Me.DataGridView.Rows. Cast(Of DataGridViewRow). Where(Function(r) TypeOf r.Cells.Item(Me.Index) Is DataGridViewProgressBarCell). Select(Function(r) DirectCast(r.Cells.Item(Me.Index), DataGridViewProgressBarCell)) Else Return New DataGridViewProgressBarCell() {} End If End Get End Property ``` Now this works at runtime. If I change the BlockWidth property of a column at runtime, all the cells of the column will change to reflect the property change but I cannot seem to get this to work at design time. At design time the cell doesn't change, the property change persists but the cell doesn't change. I've tried all manner of trickery and it refuses to work. Please can anyone tell me what I'm doing wrong ?
2014/06/24
[ "https://Stackoverflow.com/questions/24382382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050207/" ]
``` static readonly string scriptSuccessUpdate = "<script language=\"javascript\">\n" + "alert(\"Update Successful - Please surf to other pages to shop\");\n </script>"; ``` the last quote is diff please correct it
You Use **”** . Correct Code : static readonly string scriptSuccessUpdate = "\n" + "alert(\"Update Successful - Please surf to other pages to shop\");\n ";
24,382,382
Recently I've written a custom DataGridViewColumn to host a progress bar. The column class itself has a property that I'd like to propagate to all the cells of the column. I use this code to implement it:- ``` <DefaultValue(5I)> _ Public Property BlockWidth() As Integer Get Return _blockWidth End Get Set(ByVal value As Integer) _blockWidth = value Me.ColumnCells.ForEach(Sub(cell) cell.BlockWidth = value) End Set End Property ``` And this:- ``` Private ReadOnly Property ColumnCells As IEnumerable(Of DataGridViewProgressBarCell) Get If Me.DataGridView IsNot Nothing Then Return Me.DataGridView.Rows. Cast(Of DataGridViewRow). Where(Function(r) TypeOf r.Cells.Item(Me.Index) Is DataGridViewProgressBarCell). Select(Function(r) DirectCast(r.Cells.Item(Me.Index), DataGridViewProgressBarCell)) Else Return New DataGridViewProgressBarCell() {} End If End Get End Property ``` Now this works at runtime. If I change the BlockWidth property of a column at runtime, all the cells of the column will change to reflect the property change but I cannot seem to get this to work at design time. At design time the cell doesn't change, the property change persists but the cell doesn't change. I've tried all manner of trickery and it refuses to work. Please can anyone tell me what I'm doing wrong ?
2014/06/24
[ "https://Stackoverflow.com/questions/24382382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050207/" ]
``` static readonly string scriptSuccessUpdate = "<script language=\"javascript\">\n" + "alert(\"Update Successful - Please surf to other pages to shop\");\n </script>"; ``` the last quote is diff please correct it
This is because use of wrong quotes symbol: ``` static readonly string scriptSuccessUpdate = "<script language=\"javascript\">\n" + "alert(\"Update Successful - Please surf to other pages to shop\");\n </script>”; ``` You need to use this : ``` static readonly string scriptSuccessUpdate = "<script language='javascript'>alert('Update Successful - Please surf to other pages to shop')</script>"; ``` check out the correct way to use quotes. When to use **double quotes** `"` and when to use **single quote** `'` That was the only problem with your code.
24,382,382
Recently I've written a custom DataGridViewColumn to host a progress bar. The column class itself has a property that I'd like to propagate to all the cells of the column. I use this code to implement it:- ``` <DefaultValue(5I)> _ Public Property BlockWidth() As Integer Get Return _blockWidth End Get Set(ByVal value As Integer) _blockWidth = value Me.ColumnCells.ForEach(Sub(cell) cell.BlockWidth = value) End Set End Property ``` And this:- ``` Private ReadOnly Property ColumnCells As IEnumerable(Of DataGridViewProgressBarCell) Get If Me.DataGridView IsNot Nothing Then Return Me.DataGridView.Rows. Cast(Of DataGridViewRow). Where(Function(r) TypeOf r.Cells.Item(Me.Index) Is DataGridViewProgressBarCell). Select(Function(r) DirectCast(r.Cells.Item(Me.Index), DataGridViewProgressBarCell)) Else Return New DataGridViewProgressBarCell() {} End If End Get End Property ``` Now this works at runtime. If I change the BlockWidth property of a column at runtime, all the cells of the column will change to reflect the property change but I cannot seem to get this to work at design time. At design time the cell doesn't change, the property change persists but the cell doesn't change. I've tried all manner of trickery and it refuses to work. Please can anyone tell me what I'm doing wrong ?
2014/06/24
[ "https://Stackoverflow.com/questions/24382382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050207/" ]
This is because use of wrong quotes symbol: ``` static readonly string scriptSuccessUpdate = "<script language=\"javascript\">\n" + "alert(\"Update Successful - Please surf to other pages to shop\");\n </script>”; ``` You need to use this : ``` static readonly string scriptSuccessUpdate = "<script language='javascript'>alert('Update Successful - Please surf to other pages to shop')</script>"; ``` check out the correct way to use quotes. When to use **double quotes** `"` and when to use **single quote** `'` That was the only problem with your code.
You Use **”** . Correct Code : static readonly string scriptSuccessUpdate = "\n" + "alert(\"Update Successful - Please surf to other pages to shop\");\n ";
59,740
I'm preparing a present for a friend, which is a collection of photos and items from a couple of of travels we've done together. An idea I had was to somehow display our itinerary with notes and perhaps some pictures for each trip, like it is done here this one (although I would prefer it if the lines followed roads): [![enter image description here](https://i.stack.imgur.com/Ib83h.jpg)](https://i.stack.imgur.com/Ib83h.jpg) I've tried my maps by google maps and have found it useful but not perhaps as customisable (e.g. change line size and colour) and pretty as I would have hoped. Are there any other similar online services that I can use? I would want to print it out myself rather than order it by mail. Note: I'm not sure if this is on topic, reading the rules didn't clarify it for me. I'd of course be happy to migrate it to another SE
2015/12/10
[ "https://travel.stackexchange.com/questions/59740", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/37289/" ]
Although not technically an online tool, [ITN Converter](http://www.benichou-software.com/index.php?option=com_content&view=article&id=4&Itemid=3&lang=en) allows you create precise itineraries following roads traced on top of maps from Google Maps. With ITN converter you can create journeys and way-points to be uploaded in satellite navigation systems, as well as exportable Google Maps journeys. You can do all of this via the Editor feature: [![ITN Converter](https://i.stack.imgur.com/KCeAj.png)](https://i.stack.imgur.com/KCeAj.png) I don't remember if you can customise line colours and such, and can't test this feature since the Editor crashes when run from Wine on Linux. Try it out and let us know.
If you have an itinerary in GPX format (with routes and route points) you can create a printable PDF map on [Inkatlas](https://inkatlas.com). Smaller maps (6 pages or fewer) are free. Full disclosure: this is my project.
31,215
Suppose a doctor prescribes a family member (who lives in the same home) some test for an infectious disease, and then that family member tests positive. Is it a violation of medical ethics to fail to disclose this illness to other members of the household, given that the illness is highly contagious? <https://www1.nyc.gov/site/doh/providers/reporting-and-services/notifiable-diseases-and-conditions-reporting-central.page>
2022/06/09
[ "https://health.stackexchange.com/questions/31215", "https://health.stackexchange.com", "https://health.stackexchange.com/users/25276/" ]
Whether it's ethical or not is a moot question because in the US it would be illegal under federal law to do so unless the doctor has the patient's written permission to inform the others. The law that prohibits this is known as the Health Insurance Portability and Accountability Act of 1996 (HIPAA). Specifically, the Privacy Rule of HIPAA identifies Protected Health Information (PHI) as follows: > > **Protected Health Information.** The Privacy Rule protects all "individually identifiable health information" held or transmitted by > a covered entity or its business associate, in any form or media, > whether electronic, paper, or oral. The Privacy Rule calls this > information "protected health information (PHI)." > > > [Source](https://www.hhs.gov/hipaa/for-professionals/privacy/laws-regulations/index.html#:%7E:text=The%20Privacy%20Rule%20protects%20all,health%20information%20(PHI).%22) The specific restriction is as follows (*same link, emphasis is mine*): > > **Basic Principle.** A major purpose of the Privacy Rule is to define and limit the circumstances in which an individual’s protected heath > information may be used or disclosed by covered entities. **A covered > entity may not use or disclose protected health information, except > either: (1) as the Privacy Rule permits or requires; or (2) as the > individual who is the subject of the information (or the individual’s > personal representative) authorizes in writing.** > > > Nowhere in the Privacy Rule does it permit informing family or cohabitants about infectious diseases -- or any PHI at all -- without the patient's permission.
Failure of ethics for whom? * If the contagious **patient** does not disclose the risk for her/his family (and fails to protect them otherwise), endangering their health is a clear unethical violation. * For **medical staff**: at least depending on the jurisdiction, there are areas where all patient data is highly confidential unless the patients wants the medical staff to talk, with the exception of the patient directly endangering herself/himself or others. A classical examples is a patient in an altered mental state who cannot understand that driving quite is likely to kill himself or a child on the road, or a HIV positive patient who is not willing to inform and protect partners. This is always a balance of the thread to confidentiality vs. thread to life of the patient and third parties, and requires a real and direct danger that cannot be resolved otherwise. In these cases medical staff is allowed (and required) to prevent immanent danger, and if necessary break confidentiality - as much as really necessary. In addition, there are common obligations to tell about serious infections (depending on the disease for clinical practitioneer and/or diagnostic lab, either anonymously or by name), to allow health care authorities to monitor outbreaks and possibly take countermeasures for the endangered public. In cases of doubt and when time allows, fellow team members (e.g. your supervising professor, clinic attorney) or a medical ethics board my be involved in the decision. Regarding your example: if the disease causes substantial harm and is likely to be transmitted, it would be unethical (and unlawful depending on the jurisdiction) to force the family to suffer.
10,154,739
I have a label that appears after a gesture and I want to fade the label out. The following code works, but if I do several gestures in a row, the last ones don't finish the fade and display but then stop abruptly. Here is my code: ``` - (void) gestureLabelAppear:(NSString *)theLabelText { myLabel = [[UILabel alloc] initWithFrame:CGRectMake(gestureEndPoint.x, gestureEndPoint.y, 200, 20)]; myLabel.center=CGPointMake(gestureEndPoint.x, gestureEndPoint.y); myLabel.textAlignment = UITextAlignmentCenter; myLabel.text =theLabelText; [self.view addSubview:myLabel]; [self fadeOutLabels]; } -(void)fadeOutLabels { [UIView animateWithDuration:3.0 delay:0.0 options:UIViewAnimationCurveEaseInOut animations:^ { myLabel.alpha = 0.0; } completion:^(BOOL finished) { [myLabel removeFromSuperview]; NSLog(@"removed label"); }]; } ``` Any suggestions on how to fix?
2012/04/14
[ "https://Stackoverflow.com/questions/10154739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1203475/" ]
You can use a Linq query to check if a game exists before saving. Assuming in my example a field Name is enough to identify a game review you can do like that ``` [HttpPost] public ActionResult Create(tblGame tblgame, HttpPostedFileBase image1, HttpPostedFileBase image2) { try { if (ModelState.IsValid) { var mygame = db.tblGames.Where(x => x.GameName == tblgame.GameName).SingleOrDefault(); if (mygame != null) { if (image1 != null) { string image = image1.FileName; tblgame.Image = image; var image1Path = Path.Combine(Server.MapPath("~/Content/UploadImages"), image); image1.SaveAs(image1Path); } if (image2 != null) { string Image2 = image2.FileName; tblgame.Image2 = Image2; var image2Path = Path.Combine(Server.MapPath("~/Content/UploadImages"), Image2); image2.SaveAs(image2Path); } db.tblGames.Add(tblgame); db.SaveChanges(); //All ok, we redirect to index or to Edit method. (PRG pattern) return RedirectToAction("Index"); } else { //otherwise we add a generic error to the model state ModelState.AddModelError("", "A game review already exists"); } } } catch { //return View("Upload_Image_Failed"); ModelState.AddModelError("", "The upload of the images as failed"); } //if we arrive here, the model is returned back to the view with the errors added ViewBag.ConsoleNameIDFK = new SelectList(db.tblConsoles, "ConsoleName", "ConsoleName", tblgame.ConsoleNameIDFK); return View(tblgame); } ```
From the code you provided, you should change your `Create` action method: ``` [HttpPost] public ActionResult Create(tblGame tblgame, // tblGame is the new game being created HttpPostedFileBase image1, HttpPostedFileBase image2) { try { if (ModelState.IsValid) { /* Go to DB and check if there's a Game already there that matches this one just being added. What's the property you want to check against? That's something you must provide. I just wrote GameName to show you how to do this... */ var game = db.tblGames.Single(g => g.GameName == tblGame.GameName); /* OK, can proceed adding this game... since there's no game in the DB that matches this one being added. */ if (game == null) { // Continue saving the new game } else /* Abort and display a message to user informing that there's a game already. */ { // TODO } } } } ```
10,154,739
I have a label that appears after a gesture and I want to fade the label out. The following code works, but if I do several gestures in a row, the last ones don't finish the fade and display but then stop abruptly. Here is my code: ``` - (void) gestureLabelAppear:(NSString *)theLabelText { myLabel = [[UILabel alloc] initWithFrame:CGRectMake(gestureEndPoint.x, gestureEndPoint.y, 200, 20)]; myLabel.center=CGPointMake(gestureEndPoint.x, gestureEndPoint.y); myLabel.textAlignment = UITextAlignmentCenter; myLabel.text =theLabelText; [self.view addSubview:myLabel]; [self fadeOutLabels]; } -(void)fadeOutLabels { [UIView animateWithDuration:3.0 delay:0.0 options:UIViewAnimationCurveEaseInOut animations:^ { myLabel.alpha = 0.0; } completion:^(BOOL finished) { [myLabel removeFromSuperview]; NSLog(@"removed label"); }]; } ``` Any suggestions on how to fix?
2012/04/14
[ "https://Stackoverflow.com/questions/10154739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1203475/" ]
From the code you provided, you should change your `Create` action method: ``` [HttpPost] public ActionResult Create(tblGame tblgame, // tblGame is the new game being created HttpPostedFileBase image1, HttpPostedFileBase image2) { try { if (ModelState.IsValid) { /* Go to DB and check if there's a Game already there that matches this one just being added. What's the property you want to check against? That's something you must provide. I just wrote GameName to show you how to do this... */ var game = db.tblGames.Single(g => g.GameName == tblGame.GameName); /* OK, can proceed adding this game... since there's no game in the DB that matches this one being added. */ if (game == null) { // Continue saving the new game } else /* Abort and display a message to user informing that there's a game already. */ { // TODO } } } } ```
> > I have had extermly hard time trying to see if game allreday exsits as > i have code that makes users unique. I need this code otherwise I > could have had a statment that checks the database for all games and > throw an error if a game exsisted with this code i have added its a > bit hard for me that is why i have come here. > > > With each user having their own unique game list, you would have a table called GameMapping something like this which maps each user to a game. ID | UserID | GameID ID is your auto-incremented, primary key. UserID would be a foreign key which links to the users primary ID, and GameID is a foreign key linking to a specific game. ``` var user = GetUser(); // not sure what you use to identity users, but that logic would go here var game = Db.Games.Where(g => g.Name == tblGame.Name).First(); Db.GameMapping .Where(g => g.UserID == user.ID) // filter out all records for that user .Select(g => g.GameID) // select just the game IDs .Contains(game.ID) // see if the game id they want to add is in that list ``` --- Here is an alternative LINQ query which does the same check. ``` if (Db.GameMapping.Where(gm => gm.UserID == User.ID && gm.GameID == game.ID).Count() > 0) // user already has that game else // they do not ``` --- It looks like the growth of your project is starting to introduce errors and become a bit overwhelming. What I would strongly suggest before implementing this game checking code in your project is to setup a small unit test first. Create a new project separate from your big project, add your database library and create a very small test where you enter in a game, and a user, and see if this code works as you expect it. Once you know your implementation is solid, then integrate it into the bigger project. When you break the project into smaller pieces and test each piece you greatly reduce the complexity of debugging the entire thing. Good Luck.
10,154,739
I have a label that appears after a gesture and I want to fade the label out. The following code works, but if I do several gestures in a row, the last ones don't finish the fade and display but then stop abruptly. Here is my code: ``` - (void) gestureLabelAppear:(NSString *)theLabelText { myLabel = [[UILabel alloc] initWithFrame:CGRectMake(gestureEndPoint.x, gestureEndPoint.y, 200, 20)]; myLabel.center=CGPointMake(gestureEndPoint.x, gestureEndPoint.y); myLabel.textAlignment = UITextAlignmentCenter; myLabel.text =theLabelText; [self.view addSubview:myLabel]; [self fadeOutLabels]; } -(void)fadeOutLabels { [UIView animateWithDuration:3.0 delay:0.0 options:UIViewAnimationCurveEaseInOut animations:^ { myLabel.alpha = 0.0; } completion:^(BOOL finished) { [myLabel removeFromSuperview]; NSLog(@"removed label"); }]; } ``` Any suggestions on how to fix?
2012/04/14
[ "https://Stackoverflow.com/questions/10154739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1203475/" ]
You can use a Linq query to check if a game exists before saving. Assuming in my example a field Name is enough to identify a game review you can do like that ``` [HttpPost] public ActionResult Create(tblGame tblgame, HttpPostedFileBase image1, HttpPostedFileBase image2) { try { if (ModelState.IsValid) { var mygame = db.tblGames.Where(x => x.GameName == tblgame.GameName).SingleOrDefault(); if (mygame != null) { if (image1 != null) { string image = image1.FileName; tblgame.Image = image; var image1Path = Path.Combine(Server.MapPath("~/Content/UploadImages"), image); image1.SaveAs(image1Path); } if (image2 != null) { string Image2 = image2.FileName; tblgame.Image2 = Image2; var image2Path = Path.Combine(Server.MapPath("~/Content/UploadImages"), Image2); image2.SaveAs(image2Path); } db.tblGames.Add(tblgame); db.SaveChanges(); //All ok, we redirect to index or to Edit method. (PRG pattern) return RedirectToAction("Index"); } else { //otherwise we add a generic error to the model state ModelState.AddModelError("", "A game review already exists"); } } } catch { //return View("Upload_Image_Failed"); ModelState.AddModelError("", "The upload of the images as failed"); } //if we arrive here, the model is returned back to the view with the errors added ViewBag.ConsoleNameIDFK = new SelectList(db.tblConsoles, "ConsoleName", "ConsoleName", tblgame.ConsoleNameIDFK); return View(tblgame); } ```
> > I have had extermly hard time trying to see if game allreday exsits as > i have code that makes users unique. I need this code otherwise I > could have had a statment that checks the database for all games and > throw an error if a game exsisted with this code i have added its a > bit hard for me that is why i have come here. > > > With each user having their own unique game list, you would have a table called GameMapping something like this which maps each user to a game. ID | UserID | GameID ID is your auto-incremented, primary key. UserID would be a foreign key which links to the users primary ID, and GameID is a foreign key linking to a specific game. ``` var user = GetUser(); // not sure what you use to identity users, but that logic would go here var game = Db.Games.Where(g => g.Name == tblGame.Name).First(); Db.GameMapping .Where(g => g.UserID == user.ID) // filter out all records for that user .Select(g => g.GameID) // select just the game IDs .Contains(game.ID) // see if the game id they want to add is in that list ``` --- Here is an alternative LINQ query which does the same check. ``` if (Db.GameMapping.Where(gm => gm.UserID == User.ID && gm.GameID == game.ID).Count() > 0) // user already has that game else // they do not ``` --- It looks like the growth of your project is starting to introduce errors and become a bit overwhelming. What I would strongly suggest before implementing this game checking code in your project is to setup a small unit test first. Create a new project separate from your big project, add your database library and create a very small test where you enter in a game, and a user, and see if this code works as you expect it. Once you know your implementation is solid, then integrate it into the bigger project. When you break the project into smaller pieces and test each piece you greatly reduce the complexity of debugging the entire thing. Good Luck.
49,365,968
Please, I need help with are problem, I changing the syntax Swift 3 for swift 4 and now i have many problems for identification of all my bugs.The Error its on the function savePhoto in the last line., completionHandler: { \_ in ``` func takePhoto(_ previewLayer: AVCaptureVideoPreviewLayer, location: CLLocation?, completion: (() -> Void)? = nil) { guard let connection = stillImageOutput?.connection(with: AVMediaType.video) else { return } connection.videoOrientation = Helper.videoOrientation() queue.async { self.stillImageOutput?.captureStillImageAsynchronously(from: connection) { buffer, error in guard let buffer = buffer, error == nil && CMSampleBufferIsValid(buffer), let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer), let image = UIImage(data: imageData) else { DispatchQueue.main.async { completion?() } return } self.savePhoto(image, location: location, completion: completion) } } } func savePhoto(_ image: UIImage, location: CLLocation?, completion: (() -> Void)? = nil) { PHPhotoLibrary.shared().performChanges({ let request = PHAssetChangeRequest.creationRequestForAsset(from: image) request.creationDate = Date() request.location = location }, completionHandler: { _ in DispatchQueue.main.async { completion?() } }) } ```
2018/03/19
[ "https://Stackoverflow.com/questions/49365968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9028796/" ]
Rewrite it to: ``` }, completionHandler: { (_, _) in ``` As per [documentation](https://developer.apple.com/documentation/photos/phphotolibrary/1620743-performchanges), completion handler in `performChanges(_:completionHandler:)` accepts two parameters, not just one. `_ in`, what you have used, is a placeholder for a single parameter only.
As you can clearly see in the error message the `completionHandler` passes **two** parameters rather than just one. So you have to write ``` }, completionHandler: { (_, _) in ``` but you are strongly encouraged to handle the result and a potential error. Ignoring errors causes bad user experience.
9,146,366
``` $arr = array('a' => 1, 'b' => 2); $xxx = &$arr['a']; unset($xxx); print_r($arr); // still there :( ``` so unset only breaks the reference... Do you know a way to unset the element in the referenced array? Yes, I know I could just use `unset($arr['a'])` in the code above, but this is only possible when I know exactly how many items has the array, and unfortunately I don't. This question is kind of related to [this one](https://stackoverflow.com/a/9145419/376947) (this is the reason why that solution doesn't work)
2012/02/05
[ "https://Stackoverflow.com/questions/9146366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
I may be wrong but I think the only way to unset the element in the array would be to look up the index that matches the value referenced by the variable you have, then unsetting that element. ``` $arr = array('a' => 1, 'b' => 2); $xxx = &$arr['a']; $keyToUnset = null; foreach($arr as $key => $value) { if($value === $xxx) { $keyToUnset = $key; break; } } if($keyToUnset !== null) unset($arr[$keyToUnset]); $unset($xxx); ``` Well, anyway, something along those lines. However, keep in mind that this is not super efficient because each time you need to unset an element you have to iterate over the full array looking for it. Assuming you have control over how $xxx is used, you may want to consider using it to hold the key in the array, instead of a reference to the element at the key. That way you wouldn't need to search the array when you wanted to unset the element. But you would have to replace all sites that use $xxx with an array dereference: ``` $arr = array('a' => 1, 'b' => 2); $xxx = 'a'; // instead of $xxx, use: $arr[$xxx]; // to unset, simply unset($arr[$xxx]); ```
When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. And with respect to the code above - I do not think there is need in separate key ``` foreach($arr as $key => $value) { if($value === $xxx) { unset($arr[$key]); break; } } ```
9,146,366
``` $arr = array('a' => 1, 'b' => 2); $xxx = &$arr['a']; unset($xxx); print_r($arr); // still there :( ``` so unset only breaks the reference... Do you know a way to unset the element in the referenced array? Yes, I know I could just use `unset($arr['a'])` in the code above, but this is only possible when I know exactly how many items has the array, and unfortunately I don't. This question is kind of related to [this one](https://stackoverflow.com/a/9145419/376947) (this is the reason why that solution doesn't work)
2012/02/05
[ "https://Stackoverflow.com/questions/9146366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
I may be wrong but I think the only way to unset the element in the array would be to look up the index that matches the value referenced by the variable you have, then unsetting that element. ``` $arr = array('a' => 1, 'b' => 2); $xxx = &$arr['a']; $keyToUnset = null; foreach($arr as $key => $value) { if($value === $xxx) { $keyToUnset = $key; break; } } if($keyToUnset !== null) unset($arr[$keyToUnset]); $unset($xxx); ``` Well, anyway, something along those lines. However, keep in mind that this is not super efficient because each time you need to unset an element you have to iterate over the full array looking for it. Assuming you have control over how $xxx is used, you may want to consider using it to hold the key in the array, instead of a reference to the element at the key. That way you wouldn't need to search the array when you wanted to unset the element. But you would have to replace all sites that use $xxx with an array dereference: ``` $arr = array('a' => 1, 'b' => 2); $xxx = 'a'; // instead of $xxx, use: $arr[$xxx]; // to unset, simply unset($arr[$xxx]); ```
The simple answer: ``` $arr = array('a' => 1, 'b' => 2); $xxx = 'a'; unset($arr[$xxx]); print_r($arr); // gone :) ``` i.e.. You probably don't ever really need a reference. Just set `$xxx` to the appropriate key.
9,146,366
``` $arr = array('a' => 1, 'b' => 2); $xxx = &$arr['a']; unset($xxx); print_r($arr); // still there :( ``` so unset only breaks the reference... Do you know a way to unset the element in the referenced array? Yes, I know I could just use `unset($arr['a'])` in the code above, but this is only possible when I know exactly how many items has the array, and unfortunately I don't. This question is kind of related to [this one](https://stackoverflow.com/a/9145419/376947) (this is the reason why that solution doesn't work)
2012/02/05
[ "https://Stackoverflow.com/questions/9146366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. And with respect to the code above - I do not think there is need in separate key ``` foreach($arr as $key => $value) { if($value === $xxx) { unset($arr[$key]); break; } } ```
The simple answer: ``` $arr = array('a' => 1, 'b' => 2); $xxx = 'a'; unset($arr[$xxx]); print_r($arr); // gone :) ``` i.e.. You probably don't ever really need a reference. Just set `$xxx` to the appropriate key.
18,547,829
Im trying to send bulk of emails containing passwords to the students taking an exam in a particular subject.Now, Im having an error "SMTP Error: Could not connect to SMTP host. Mailer Error () SMTP Error: Could not connect to SMTP host." What could possibly be the problem? my code as follows: ``` <?php //error_reporting(E_ALL); error_reporting(E_STRICT); //date_default_timezone_set('America/Toronto'); require_once('PHPMailer-phpmailer-5.2.0/class.phpmailer.php'); include("PHPMailer-phpmailer-5.2.0/class.smtp.php"); //optional, gets called from within class.phpmailer.php if not already loaded $mail = new PHPMailer(); $mail->IsSMTP(); // telling the class to use SMTP $mail->Host = "localhost"; $mail->SMTPAuth = true; // enable SMTP authentication $mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent $mail->Host = "mail.yahoo.com"; // sets the SMTP server*/ $mail->Port = 26; $mail->Username = "***********@yahoo.com"; // SMTP account username $mail->Password = "****************"; // SMTP account password $mail->From = "*************@yahoo.com"; $mail->FromName = "Exam System"; //$mail->IsHTML(true); while ($row_email = mysql_fetch_array ($email)) { $mail->Subject = "Subject: ".$row_email['subject_description'].""; $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test $mail->Body = "This is your password for ".$row_email['exam_title']." : ".$row_email['pass_password'].""; $mail->AddAddress($row_email['stud_email']); if(!$mail->Send()) { echo "Mailer Error (" . str_replace("@", "&#64;", $row_email['stud_email']) . ') ' . $mail->ErrorInfo . '<br />'; } else { echo "Message sent to :" . $row_email['stud_email'] . ' (' . str_replace("@", "&#64;", $row_email['stud_email']) . ')<br />'; } // Clear all addresses and attachments for next loop $mail->ClearAddresses(); $mail->ClearAttachments(); } mysql_free_result($email); ?> ```
2013/08/31
[ "https://Stackoverflow.com/questions/18547829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2691911/" ]
The compiler is also confused about first line; you can't take the address of a type. As for following void pointers, you've got the right idea: cast it to the type of pointer you wish to treat it as.
Here is a fixed version which actually compiles and works without errors: ``` #include <string.h> #include <stdio.h> typedef struct { char Buf[20]; char Str[20]; } Sample; typedef struct { char Data[20]; int i; } Test; typedef struct { void *New; int j; } Datastruct; int main() { Datastruct d; Sample s; d.New = &s; strcpy(((Sample*)d.New )->Buf,"adam"); printf("Datastruct->New->Buf\n"); Test t; d.New = &t; strcpy(((Test*)d.New)->Data,"Eve"); printf("Datastruct->New->Data\n"); return 0; } ``` In your original you were confusing `->` with `.` and types (e.g. `Datastruct`) with variables of that type.
17,846,610
I'm creating a `HashMap` inline with double braces inside a function: ``` public void myFunction(String key, String value) { myOtherFunction( new JSONSerializer().serialize( new HashMap<String , String>() {{ put("key", key); put("value", value.); }} ) ); } ``` and I'm receiving these errors: ``` myClass.java:173: error: local variable key is accessed from within inner class; needs to be declared final put("key", key); ^ myClass.java:174: error: local variable value is accessed from within inner class; needs to be declared final put("value", value); ^ 2 errors ``` How can method parameters be inserted into an `Object` double brace initialized?
2013/07/24
[ "https://Stackoverflow.com/questions/17846610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Declare your parameters as `final`: ``` public void myFunction(final String key, final String value) ``` Also, you might want to take a look at [Efficiency of Java "Double Brace Initialization"?](https://stackoverflow.com/q/924285/758280)
Compiler will complain if you use non final local variables in inner classes, fix it with this: ``` public void myFunction(final String key, final String value) { myOtherFunction( new JSONSerializer().serialize( new HashMap<String , String>() {{ put("key", key); put ("value", value.); }} ) ); } ```
32,730,007
When using the Dialog module in Electron and .showSaveDialog() to save a file, is there a way to make the filename in the Save As window populate with the actual filename?
2015/09/23
[ "https://Stackoverflow.com/questions/32730007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5100015/" ]
This can be accomplished with the `defaultPath` property in [`dialog.showSaveDialog()`](https://github.com/atom/electron/blob/master/docs/api/dialog.md). It should be noted that, since it's the `defaultPath`, you must specify the full file path, not just the name+extension: ``` dialog.showSaveDialog( { defaultPath: '/Users/username/Documents/my-file.txt' }, function (fileName) { // do your stuff here }); ```
According to [Electron Docs](https://www.electronjs.org/docs/api/dialog#dialogshowsavedialogbrowserwindow-options), `defaultPath` String (optional) - Absolute directory path, absolute file path, or file name to use by default. This means if you just pass the file name in the `defaultPath` like the following without using the absolute path, it will still work. ```js dialog.showSaveDialog({ defaultPath: `HelloWorld.txt`, }); ```
13,045,279
I have a form on one page that submits to another page. There, it checks if the input `mail` is filled. If so then do something and if it is not filled, do something else. I don't understand why it always says that it is set, even if I send an empty form. What is missing or wrong? `step2.php`: ``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" value="continue"/> </form> ``` `step2_check.php`: ``` if (isset($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "N0, mail is not set"; } ```
2012/10/24
[ "https://Stackoverflow.com/questions/13045279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016409/" ]
Use `!empty` instead of `isset`. isset return true for `$_POST` because `$_POST` array is superglobal and always exists (set). Or better use `$_SERVER['REQUEST_METHOD'] == 'POST'`
You can simply use: ``` if($_POST['username'] and $_POST['password']){ $username = $_POST['username']; $password = $_POST['password']; } ``` Alternatively, use [empty()](http://php.net/manual/en/function.empty.php) ``` if(!empty($_POST['username']) and !empty($_POST['password'])){ $username = $_POST['username']; $password = $_POST['password']; } ```
13,045,279
I have a form on one page that submits to another page. There, it checks if the input `mail` is filled. If so then do something and if it is not filled, do something else. I don't understand why it always says that it is set, even if I send an empty form. What is missing or wrong? `step2.php`: ``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" value="continue"/> </form> ``` `step2_check.php`: ``` if (isset($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "N0, mail is not set"; } ```
2012/10/24
[ "https://Stackoverflow.com/questions/13045279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016409/" ]
Most form inputs are always set, even if not filled up, so you must check for the emptiness too. Since `!empty()` is already checks for both, you can use this: ``` if (!empty($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "No, mail is not set"; } ```
``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail" required="required"/> <br /> <input type="password" name="password" required="required"/><br /> <input type="submit" value="continue"/> </form> <?php if (!empty($_POST["mail"])) { echo "Yes, mail is set"; }else{ echo "N0, mail is not set"; } ?> ```
13,045,279
I have a form on one page that submits to another page. There, it checks if the input `mail` is filled. If so then do something and if it is not filled, do something else. I don't understand why it always says that it is set, even if I send an empty form. What is missing or wrong? `step2.php`: ``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" value="continue"/> </form> ``` `step2_check.php`: ``` if (isset($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "N0, mail is not set"; } ```
2012/10/24
[ "https://Stackoverflow.com/questions/13045279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016409/" ]
Check to see if the FORM has been submitted first, then the field. You should also sanitize the field to prevent hackers. ``` form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" id="SubmitForm" name= "SubmitForm" value="continue"/> </form> ``` step2\_check: ``` if (isset($_POST["SubmitForm"])) { $Email = sanitize_text_field(stripslashes($_POST["SubmitForm"])); if(!empty($Email)) echo "Yes, mail is set"; else echo "N0, mail is not set"; } } ```
``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail" required="required"/> <br /> <input type="password" name="password" required="required"/><br /> <input type="submit" value="continue"/> </form> <?php if (!empty($_POST["mail"])) { echo "Yes, mail is set"; }else{ echo "N0, mail is not set"; } ?> ```
13,045,279
I have a form on one page that submits to another page. There, it checks if the input `mail` is filled. If so then do something and if it is not filled, do something else. I don't understand why it always says that it is set, even if I send an empty form. What is missing or wrong? `step2.php`: ``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" value="continue"/> </form> ``` `step2_check.php`: ``` if (isset($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "N0, mail is not set"; } ```
2012/10/24
[ "https://Stackoverflow.com/questions/13045279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016409/" ]
Use `!empty` instead of `isset`. isset return true for `$_POST` because `$_POST` array is superglobal and always exists (set). Or better use `$_SERVER['REQUEST_METHOD'] == 'POST'`
[From php.net](http://us2.php.net/isset), isset > > Returns TRUE if var exists and has value other than NULL, FALSE > otherwise. > > > empty space is considered as set. You need to use empty() for checking all null options.
13,045,279
I have a form on one page that submits to another page. There, it checks if the input `mail` is filled. If so then do something and if it is not filled, do something else. I don't understand why it always says that it is set, even if I send an empty form. What is missing or wrong? `step2.php`: ``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" value="continue"/> </form> ``` `step2_check.php`: ``` if (isset($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "N0, mail is not set"; } ```
2012/10/24
[ "https://Stackoverflow.com/questions/13045279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016409/" ]
Check to see if the FORM has been submitted first, then the field. You should also sanitize the field to prevent hackers. ``` form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" id="SubmitForm" name= "SubmitForm" value="continue"/> </form> ``` step2\_check: ``` if (isset($_POST["SubmitForm"])) { $Email = sanitize_text_field(stripslashes($_POST["SubmitForm"])); if(!empty($Email)) echo "Yes, mail is set"; else echo "N0, mail is not set"; } } ```
To answer the posted question: isset and empty together gives three conditions. This can be used by Javascript with an ajax command as well. ``` $errMess="Didn't test"; // This message should not show if(isset($_POST["foo"])){ // does it exist or not $foo = $_POST["foo"]; // save $foo from POST made by HTTP request if(empty($foo)){ // exist but it's null $errMess="Empty"; // #1 Nothing in $foo it's emtpy } else { // exist and has data $errMess="None"; // #2 Something in $foo use it now } } else { // couldn't find ?foo=dataHere $errMess="Missing"; // #3 There's no foo in request data } echo "Was there a problem: ".$errMess."!"; ```
13,045,279
I have a form on one page that submits to another page. There, it checks if the input `mail` is filled. If so then do something and if it is not filled, do something else. I don't understand why it always says that it is set, even if I send an empty form. What is missing or wrong? `step2.php`: ``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" value="continue"/> </form> ``` `step2_check.php`: ``` if (isset($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "N0, mail is not set"; } ```
2012/10/24
[ "https://Stackoverflow.com/questions/13045279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016409/" ]
Most form inputs are always set, even if not filled up, so you must check for the emptiness too. Since `!empty()` is already checks for both, you can use this: ``` if (!empty($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "No, mail is not set"; } ```
If you send the form empty, `$_POST['mail']` will still be sent, but the value is empty. To check if the field is empty you need to check ``` if(isset($_POST["mail"]) && trim($_POST["mail"]) != "") { .. } ```
13,045,279
I have a form on one page that submits to another page. There, it checks if the input `mail` is filled. If so then do something and if it is not filled, do something else. I don't understand why it always says that it is set, even if I send an empty form. What is missing or wrong? `step2.php`: ``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" value="continue"/> </form> ``` `step2_check.php`: ``` if (isset($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "N0, mail is not set"; } ```
2012/10/24
[ "https://Stackoverflow.com/questions/13045279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016409/" ]
Add the following attribute to the input text form: `required="required"`. If the form is not filled, it will not allow the user to submit the form. Your new code will be: ```html <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail" required="required"/> <br /> <input type="password" name="password" required="required"/><br /> <input type="submit" value="continue"/> ``` ```php if (isset($_POST["mail"])) { echo "Yes, mail is set"; } ```
``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail" required="required"/> <br /> <input type="password" name="password" required="required"/><br /> <input type="submit" value="continue"/> </form> <?php if (!empty($_POST["mail"])) { echo "Yes, mail is set"; }else{ echo "N0, mail is not set"; } ?> ```
13,045,279
I have a form on one page that submits to another page. There, it checks if the input `mail` is filled. If so then do something and if it is not filled, do something else. I don't understand why it always says that it is set, even if I send an empty form. What is missing or wrong? `step2.php`: ``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" value="continue"/> </form> ``` `step2_check.php`: ``` if (isset($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "N0, mail is not set"; } ```
2012/10/24
[ "https://Stackoverflow.com/questions/13045279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016409/" ]
Use `!empty` instead of `isset`. isset return true for `$_POST` because `$_POST` array is superglobal and always exists (set). Or better use `$_SERVER['REQUEST_METHOD'] == 'POST'`
To answer the posted question: isset and empty together gives three conditions. This can be used by Javascript with an ajax command as well. ``` $errMess="Didn't test"; // This message should not show if(isset($_POST["foo"])){ // does it exist or not $foo = $_POST["foo"]; // save $foo from POST made by HTTP request if(empty($foo)){ // exist but it's null $errMess="Empty"; // #1 Nothing in $foo it's emtpy } else { // exist and has data $errMess="None"; // #2 Something in $foo use it now } } else { // couldn't find ?foo=dataHere $errMess="Missing"; // #3 There's no foo in request data } echo "Was there a problem: ".$errMess."!"; ```
13,045,279
I have a form on one page that submits to another page. There, it checks if the input `mail` is filled. If so then do something and if it is not filled, do something else. I don't understand why it always says that it is set, even if I send an empty form. What is missing or wrong? `step2.php`: ``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" value="continue"/> </form> ``` `step2_check.php`: ``` if (isset($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "N0, mail is not set"; } ```
2012/10/24
[ "https://Stackoverflow.com/questions/13045279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016409/" ]
Use `!empty` instead of `isset`. isset return true for `$_POST` because `$_POST` array is superglobal and always exists (set). Or better use `$_SERVER['REQUEST_METHOD'] == 'POST'`
Maybe you can try this one: ``` if (isset($_POST['mail']) && ($_POST['mail'] !=0)) { echo "Yes, mail is set"; } else { echo "No, mail is not set"; } ``` ---
13,045,279
I have a form on one page that submits to another page. There, it checks if the input `mail` is filled. If so then do something and if it is not filled, do something else. I don't understand why it always says that it is set, even if I send an empty form. What is missing or wrong? `step2.php`: ``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" value="continue"/> </form> ``` `step2_check.php`: ``` if (isset($_POST["mail"])) { echo "Yes, mail is set"; } else { echo "N0, mail is not set"; } ```
2012/10/24
[ "https://Stackoverflow.com/questions/13045279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1016409/" ]
Lets Think this is your HTML Form in step2.php > > step2.php > > > ``` <form name="new user" method="post" action="step2_check.php"> <input type="text" name="mail"/> <br /> <input type="password" name="password"/><br /> <input type="submit" value="continue"/> </form> ``` I think you need it for your database, so you can assign your HTML Form Value to php Variable, now you can use Real Escape String and below must be your > > step2\_check.php > > > ``` if(isset($_POST['mail']) && !empty($_POST['mail'])) { $mail = mysqli_real_escape_string($db, $_POST['mail']); } ``` Where $db is your Database Connection.
You can try, ``` <?php if (isset($_POST["mail"])) { echo "Yes, mail is set"; }else{ echo "N0, mail is not set"; } ?> ```