qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
4,919,437
Does `dbms_output.put_line` decrease the performance in `plsql` code?
2011/02/07
[ "https://Stackoverflow.com/questions/4919437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/606147/" ]
Yes, it's another piece of code that needs to be executed, but unless the output is actually turned on, I think the overhead is quite minimal. Here's an AskTom question with more details: [Is there a performance impact for dbms\_output.put\_line statements left in packages?](http://asktom.oracle.com/pls/asktom/f?p=100:11:0%3a%3a%3a%3aP11_QUESTION_ID:1468572900346293780)
72,038,470
WHy does the value of `calendar.SelectedDate` include a time (eg.: 22-04-2022 00:00:00) when the user has picked a date? In fact, I am interested in picking both a date and time but apparently, from what I've read, it seems like you can't pick a time from the calendar element in the program UI and I don't understand why when it also returns time in the value of `Selected.Date` Is there an option to extend the calendar element to also include a timer-picker that isn't too complicated? Code that that that returns returns `dd-mm-yyyy 00:00:00` ``` { post.date = calendar.SelectedDate.ToString(); DateLabel.Content = $"Date and time for post: {post.date}"; } ```
2022/04/28
[ "https://Stackoverflow.com/questions/72038470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18750341/" ]
WPF calendar has the default DateTime property. Neither only Date nor only Time it has `Nullable<DateTime>` default property, so it always along with Time. You would avoid it by setting below code ``` post.date = calendar.SelectedDate.Value.Date.ToShortDateString(); ```
46,117,380
I have an express app that I start in terminal with following command to enable debug logs in it: ``` DEBUG=custom:* npm start (on Ubuntu) SET DEBUG=custom:* & npm start (on Windows) ``` On production server, I start app with PM2 using following command: ``` pm2 start bin/www -i 0 ``` But this does not enable the `debug` logs in my code, so the debug statements are not added to the logs, only `console.error()` are added to the log files. How can I pass the `DEBUG=custom:*` option while starting my app with PM2?
2017/09/08
[ "https://Stackoverflow.com/questions/46117380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3801947/" ]
You can parse it yourself with a function, here's an example: ``` function getTextWithInputValues(id) { var element = document.getElementById(id); if (!element) { return null; } var elementText = element.innerHTML; // Get the entire text from your element var elementInputs = element.getElementsByTagName('input'); // fetch all inputs from your element // replace all input fields with their respective values Object.getOwnPropertyNames(elementInputs).forEach( (input) => { var inputText = elementInputs[input].outerHTML; if (elementText.search(inputText) > 0) { elementText = elementText.replace(inputText, elementInputs[input].value); } } ); return elementText; } ``` You can test it right here by opening a console, paste this code in, then type in something in the search box on the top of the page (don't click search, just type in something), then when you call the function in the console like `getTextWithInputValues('search')` it will output something like ``` <svg ......</svg> your-text-here <button .....</button> ``` Hope this helps.
25,349,941
I'm struggling for about 3 hours for now to fasten my Project Euler #12 code. I achieved to save a few seconds for the case that numbers has over 130 divisors, my first program went to 2.33 seconds now it does it in 1.169 seconds. However I never had the patience to wait for the 500 divisors number. How can I fasten my code? I tried the case to get the divisors from n and n+1 but it just slowed my program even more... Here is my code. ``` static bool isPrime(int num) { if (num % 2 == 0 && num != 2) return false; else for (int i = num; i < Math.Sqrt(num) + 1; i++) { if (num % i == 0) return false; } return true; } static void Main(string[] args) { Stopwatch time = new Stopwatch(); time.Start(); int trianglenumber = 0; int divizori = 0; for (int i = 3; i < Int32.MaxValue; i+=2) { if (isPrime(i) != false) { int tempnumber = 0; tempnumber = (i * (1 + i)) / 2; for (int k = 1; k < tempnumber + 1; k++) { if (tempnumber % k == 0) { divizori++; } } if (500 < divizori) { trianglenumber = tempnumber; break; } divizori = 0; } } time.Stop(); double timp = time.ElapsedMilliseconds ; Console.WriteLine(trianglenumber); Console.Write("Runtime: " + timp/1000 + " seconds"); Console.ReadKey(); } ```
2014/08/17
[ "https://Stackoverflow.com/questions/25349941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3899440/" ]
The **big** slow down is in your isPrime() method. Take a look at counting factors by prime factorization. You'll see that counting 500 factors is MUCH quicker this way. <http://www.mathsisfun.com/prime-factorization.html> Also, how you're getting your triangular numbers should be much simpler. ``` 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... ``` Notice the difference between each sequential set of numbers.... 1 + **2** = 3 3 + **3** = 6 6 + **4** = 10 10+ **5** = 15 15+ **6** = 21 and so on...take a look at that middle number. Just for reference, my version of this using the prime factorization method takes roughly 6ms to find the answer....pretty quick.
932,278
Let say $$f(x) := \left\{\begin{array}{l l}x+1 & \text{ if } -2\leq x<0 \\ x-1 & \text{ if }0\leq x\leq 2\end{array}\right.$$ How can we find out $f\circ f$?
2014/09/15
[ "https://math.stackexchange.com/questions/932278", "https://math.stackexchange.com", "https://math.stackexchange.com/users/176196/" ]
**Hint:** First, verify that $f(x) \subset [-2,2]$ to be sure that the composition $f \circ f$ is well defined. Then you should carefully separate the cases. Here's an example for the first steps: If $-2 \leq x < 0$ then $f(x) = x+1$ and so $f(x) < 0$ for $-2 \leq x < -1$, it follows that $f\circ f(x) = ((x+1)+1)$ for $-2 \leq x < -1$. Now if $-2 \leq x < 0$ then $f(x) = x+1$ and so $f(x) \geq 0$ for $-1 \leq x < 0$ thus ... Can you continue from here? **EDIT:** To be more precise, let $y = f(x)$, then $$f \circ f(x) = f(y) = \left\{\begin{array}{l l}y+1 & \text{ if } -2\leq y<0 \\ y-1 & \text{ if }0\leq y\leq 2\end{array}\right.=\left\{\begin{array}{l l}f(x)+1 & \text{ if } -2\leq f(x)<0 \\ f(x)-1 & \text{ if }0\leq f(x)\leq 2\end{array}\right.$$ So we have to separate the cases when $-2\leq f(x)<0$ and $0\leq f(x)\leq 2$. By definition of $f$ we know that $f(x) < 0$ for every $x \in [-2,-1)$ and $x \in [0,1)$. In particular this implies that if $x \in [-2,-1)$, then $f(x) = x+1 < 0$ and thus $$f \circ f(x) = f(x)+1 = (x+1)+1 = x+2.$$ Stays to study the case $x \in [0,1)$ and $f(x) \geq 0$.
66,144,093
This happens in Android Studio Beta. Used to work in the other builds as I recall. Now, I either have to generate a new key every time I generate the apk or manually enter my password due to this error. My password is ASCII. Simple characters A thru Z and a thru z. It takes the key just fine, but the next time I try to build this is what I get. Digging back one error up in the output I see this: Execution failed for task ':app:packageRelease'. > > A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable > com.android.ide.common.signing.KeytoolException: Failed to read key key0 from store "C:\AndroidRelated\KeyStoreForCompanyA\KeyStore.jks": keystore password was incorrect > > > I have it remember my password from build to build though. Note that if I change this manually to what I know is correct, then it will build. Just a bug in Android Studio Beta maybe or is this overridden somewhere other than the Generate Signed Bundle or SDK dialog?
2021/02/10
[ "https://Stackoverflow.com/questions/66144093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/443654/" ]
**Solved**! Step; 1. Clean your project 2. Generate signed yours bundle/.apk file 3. Uncheck the "Remember password" 4. Manually put your password at "Key store password" and "Key password" 5. Click Next and you Done!. *Android studio update bring this bug.*
661,104
I have a Java applet consisting of a wizard-like form with three steps. At the final step, the user can click a "finish" button. I want that button to cause the web browser to navigate to a specific URL. **Question:** Is there a way to cause the browser to navigate to a specific URL, in such a way that it will work across all modern browsers? My specific browser requirements are FF3+, IE7+, Safari 3+, and Opera 9+. I am using Java 1.5.
2009/03/19
[ "https://Stackoverflow.com/questions/661104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2405/" ]
From the applet you can simply get the applet context and call [showDocument(url)](http://java.sun.com/javase/6/docs/api/java/applet/AppletContext.html#showDocument(java.net.URL)). This will navigate away from the current page to the specified URL: ``` getAppletContext().showDocument(url); ``` Additionally you can pass a [target](http://java.sun.com/javase/6/docs/api/java/applet/AppletContext.html#showDocument(java.net.URL,%20java.lang.String)) parameter. To visit a relative URL you can use: ``` URL url = new URL(getCodeBase().getProtocol(), getCodeBase().getHost(), getCodeBase().getPort(), "/next.html"); getAppletContext().showDocument(url); ``` These work in every major browser since Java version 1.1.
44,251,180
So after a bit of stringy business, I was able to get a large chunk of substring from a haystack of string closer to my target after searching the first occurrence of `"getflashmedia"` ``` var_dump($str) = string(1735) "getflashmedia" src="http://www.exampleURL.com/media-name.mp4"></object> .../*a haystack of code as string*/" ``` I want to get the URL inside `src` but this is varying in length, so I can't really use the `substr()` function
2017/05/29
[ "https://Stackoverflow.com/questions/44251180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4169959/" ]
Use a regular expression, I'd recommend the following: `src="(.*?)"`. This expression matches `src="` literally, then starts capturing and stops when it finds another `"`. ``` <?php $input = 'getflashmedia" src="http://www.exampleURL.com/media-name.mp4"></object>'; preg_match_all('/src="(.*?)"/', $input, $matches); print_r($matches[1]); ``` Output: ``` Array ( [0] => http://www.exampleURL.com/media-name.mp4 ) ``` This will get every link, from every src attribute in the input string. If you only need the first, use `preg_match()`.
5,469,736
I want paste button only when I select copy option. When copy option is not selected the paste button should not come on the screen. How can I do it?
2011/03/29
[ "https://Stackoverflow.com/questions/5469736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
> > Where is the best place to start? > > > Here: <http://www.asp.net/mvc/mvc3>
7,800,882
I have two services IServiceA and IServiceB. The concrete implementation of IServiceB looks like this: ``` public class ServiceB : IServiceB { public ServiceB(string path, IServiceA serviceA) { ... } } ``` So I need to pass in a string and a ServiceA. I'm kinda stuck how I would do that. I have this right now: ``` var path = _config.Path; container.RegisterType<IServiceA, ServiceA>(); container.RegisterType<IServiceB, ServiceB>( new InjectionConstructor(path, container.Resolve<IServiceA>()); ``` This is obviously wrong as I'm actually instantiating a ServiceA and registering a single Instance with all ServiceB's. How can I tell Unity to always resolve a "fresh" ServiceA? I tried just removing the IServiceA from RegisterType, and that throws an exception telling me there is no `ctor(string)`, which is correct since it's a `ctor(string,IServiceA)`.
2011/10/17
[ "https://Stackoverflow.com/questions/7800882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
It's not particularly well documented, but this appears to work: ``` container.RegisterType<IServiceA, ServiceA>(); container.RegisterType<IServiceB, ServiceB>( new InjectionConstructor(path, new ResolvedParameter<IServiceA>())); ``` I would recommend testing it before using it in production.
15,868
I have designed a hybrid(keywords and data in same excel sheet) framework using `WebDriver`+`Java`+`TestNG`+`Maven`. I am using `PageFactory`, `Singleton Pattern` . I am using different type of HTML locators in my framework like `id`, `css`, `xpath`. I run tests on UNIX environment. I was told that using id instead of `xpath` is faster. But how do we measure it, because when I use `xpath` and when I use `id` in both cases test gives output in same time. Apart from avoid using `xpath`, what are other points to take care of to make project improve lot in case of speedy execution.
2015/11/30
[ "https://sqa.stackexchange.com/questions/15868", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/7741/" ]
This may not be a full answer to your question but I think it fits to the topic: I was wondering about the "id is faster than xpath" and start searching. [This SO-Question/Answer](https://stackoverflow.com/questions/16788310/what-is-the-difference-between-css-selector-xpath-which-is-betteraccording-t) gives an answer which sounds quite logical. But then I found these two Blogs from *Elemental Selenium*: * [XPATH vs CSS](http://elementalselenium.com/tips/32-xpath-vs-css) * [Css Vs. X Path, Under a Microscope](http://elementalselenium.com/tips/33-xpath-vs-css-revisited) which shows that XPATH is faster than CSS. In the second one the author describes that he used the `benchmark` lib from ruby for his measurements. > > For benchmarking I used the library that's available in Ruby's standard lib called 'benchmark' > > > But as you see the numbers of his comparion you see they don't diverge so much, so I think it's better to use CSS because of the compatibility as not all browsers implementing XPATH the same way. (And yes that's not part of your question)
59,081,148
First a question: I am a complete newbie. Is it correct that postgresql installs with some default passwords without asking to change it during installation? What are those passwords? I am just playing with an app and if I know the default passwords, everything will be okay. As you could tell I don't have the default passwords. Somewhere I read that postgres user allows login with no password. Do I then leave the password field in the app config file empty? I used the following command from the postgresql command line: ``` ALTER ROLE postgres WITH PASSWORD 'new_password'; ``` I get the following error: ``` ALTER: command not found. ``` Could you tell me what is going on? I have postgresql 11.6 & 12.1.
2019/11/28
[ "https://Stackoverflow.com/questions/59081148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4732120/" ]
If you have an object to log, I recommend just pass it directly to `console.log()`. `JSON.stringify()` might be adding carriage returns, which could be interpreted as multiple lines to log. ``` console.log({key1: 'val1', key2: 'val2'}) ``` Just make sure that the object doesn't contain references to other very complex objects (especially self-referential objects), otherwise it could cause problems with evaluating the final string at runtime.
14,850,855
**CODE :** **.htaccess:** ``` RewriteEngine On RewriteRule ^(.*)/*$ base.php?request=$1 [NC,L] ``` **base.php** ``` <?php echo "this is base.php <br/> and Get Vaiables <br> "; print_r($_GET); ?> ``` *for the request:* ``` localhost/blahblahproject/hello ``` **EXPECTED RESULT:** > > this is base.php > > and Get Vaiables > > Array ( [request] => hello ) > > > **Current RESULT:** > > this is base.php > > and Get Vaiables > > Array ( [request] => base.php ) > > >
2013/02/13
[ "https://Stackoverflow.com/questions/14850855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2067797/" ]
Change your .htaccess rule to this: ``` RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/?$ /base.php?request=$1 [QSA,L] ```
6,537,541
I've followed the Google app script tutorial [here](http://www.youtube.com/user/GoogleDocsCommunity#p/c/0/5VmEPo6Rkq4) which is a very simple script with two functions. `showDialog` (which presents a dialog box with a text field and submit button ) and `respondToSubmit(e)` which handles the submit button and adds the entered data to the spreadsheet. It works fine. What doesn't seem to work is the debugger on the callback. So I place a breakpoint in both functons and start the `showDialog` function. The debugger kicks in and stops execution at the breakpoint. I click continue so I can interact with the newly opened dialog box. However when I click the submit button the debugger does not start again. The `respondtoSubmit(e)` function is executed. The debugger just does not stop on the breakpoint(s). Is there a problem with debugging callbacks like this or can you only debug one function at a time?
2011/06/30
[ "https://Stackoverflow.com/questions/6537541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/516286/" ]
As of right now, the debugger has some unexpected behaviours. Mostly, it seems to only respect breakpoints during calls from the script editor, so to debug your event handler you must call it from the debugger, not the UI. If you need to peek into variables such as the event object passed to the function, for example, try adding this line to your handler where you'd normally put a breakpoint: `Logger.log(Utilities.jsonStringify(e));` Then view the log from the script editor after execution.
7,333,873
I am buidling an app in CakePHP. I have 2 models: - Project - User The Project model has various belongsTo relations to the user model, one for the creator, one for the last editor and one for the manager. This works fine. Then I add a virtual field to the User model, called 'name', which is CONCAT(first\_name, ' ', last\_name). It combines the first name and last name into a general name field, which is used througout the app. After this, I get SQL errors saying that the first\_name column is ambiguous. This is because in the query, the alias for Creator, Manager, etc is not used in the CONCAT field. Any ideas on how to avoid this?
2011/09/07
[ "https://Stackoverflow.com/questions/7333873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/565907/" ]
Showing the exact queries should help resolve this problem. But if you are joining 2 tables, and they both have a column with the same name. you have to reference the column with TableName.ColumnName, like this. ``` Select Table1.Column1 AS someColumn, Table2.Column1 AS SomeOtherColumn FROM Table1 INNER JOIN Table2 ON Table1.ID = Table2.Table1ID WHERE Table1.ID = 3 ``` You can shorten this up by giving your tables aliases, As follows. ``` Select T1.Column1 AS someColumn, T2.Column1 AS SomeOtherColumn FROM Table1 AS T1 INNER JOIN Table2 AS T2 ON T1.ID = T2.Table1ID WHERE T1.ID = 3 ```
31,541,814
There are topics online that are discussing this problem however, I couldn't find any tidy explanation of the problem or any solid answers for the question. What I am trying to achieve is connecting Laravel 5.1 to MySQL Database of MAMP. --- In my ***config>app.php:*** ``` 'default' => env('DB_CONNECTION', 'mysql'), 'mysql' => [ 'driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, ], ``` In my ***.env:*** ``` DB_HOST=localhost DB_DATABASE=test DB_USERNAME=root DB_PASSWORD=root ``` I also have ***.env.example:*** (which I believe has no functionality) ``` DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret ``` I also have `create_users_table.php` and `create_password_resets_table.php` in my ***database>migrations*** (even though I did not run any migration:make) --- MAMP is directing and running the server successfully as it loads the project on localhost. --- Here is my MAMP settings: [![](https://i.imgur.com/T3KczgP.png "source: imgur.com")](https://imgur.com/T3KczgP) [![](https://i.imgur.com/wbySSkJ.png "source: imgur.com")](https://imgur.com/wbySSkJ) And the `test` database is created (with tables in it which I have previously created and used in my other projects, not Laravel.) [![](https://i.imgur.com/4V2r913.png "source: imgur.com")](https://imgur.com/4V2r913) --- Even though everything seems correct to me, when trying to submit Auth form, I am getting this error: > > ### PDOException in Connector.php line 50: > could not find driver > > > 1. in Connector.php line 50 > 2. at PDO->\_\_construct ('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', 'root', 'root', array('0', '2', '0', false, false)) in Connector.php line 50 > 3. at Connector->createConnection('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', array('driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8\_unicode\_ci', 'unix\_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, 'name' => 'mysql'), array('0', '2', '0', false, false)) in MySqlConnector.php line 22 > > > and so on... > > >
2015/07/21
[ "https://Stackoverflow.com/questions/31541814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4705339/" ]
It was pretty simple for me, I added :8889 to the localhost in the .env file. DB\_HOST=localhost:8889 This is because in the MAMP preferences, :8889 is the default port.
21,328,507
I want to generate sequential outcomes for a 3X5 slot machine. I have 5 reels of different length, e.g: ``` reel1 = [1,2,3,4,5], reel2 = [2,3,4,5,6,7], reel3 = [3,4,5,6,7,8,9], reel4 = [4,5,6,7,8,9,0,1], reel5 = [0,1,2]. ``` Right now I'm using Python for loop to generate the result, but I think it may not be an effective way as in total I need 5 for loops and if the reel length is very long, then it will take quite long time to do sequential generation. I think there may be a more effective way to do this using Python. Anyone have any ideas?~
2014/01/24
[ "https://Stackoverflow.com/questions/21328507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2774993/" ]
If you want random outcomes, you can use [`random.choice`](http://docs.python.org/2.7/library/random.html#random.choice): ``` from random import choice reels = [reel1, reel2, ...] outcome = [choice(reel) for reel in reels] ``` If you want all outcomes, use [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product): ``` from itertools import product for outcome in product(*reels): # use outcome ``` --- With your clarification that you want sets of three numbers, I would generate the positions up-front: ``` reelpos = [] for reel in reels: reelpos.append(list(zip(reel, reel[1:] + reel[:1], reel[2:] + reel[:2]))) ``` You can then apply `choice` or `product` to `reelpos`, which looks like: ``` [[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 1), (5, 1, 2)], [(2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 2), (7, 2, 3)], [(3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 3), (9, 3, 4)], [(4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 0), (9, 0, 1), (0, 1, 4), (1, 4, 5)], [(0, 1, 2), (1, 2, 0), (2, 0, 1)]] ```
1,191,444
I'd like to ask if there's a way to make chrome extension ONLY activated in incognito mode. I only want the extension activated in incognito mode and disabled in normal browsing. I do hope there's a way and thanks in advance.
2017/03/23
[ "https://superuser.com/questions/1191444", "https://superuser.com", "https://superuser.com/users/710152/" ]
You can't do exactly this. Closest way is to create a separate Chrome Profile and install extensions there.
5,862,229
I have an application that displays the contents of messages in an MSMQ message queue. There is a problem with MSMQ on Windows 7 not preserving the true object type of the data in the message body. In the example, I send a byte[], and then later when I receive it, it's no longer a byte array, but the wrapped XML container document. In Windows XP I have never had this problem, and the Message.Body property has always correctly been set to a byte[]. Here is the compression code: ``` public void SendWithCompression(string Message) { try { // Compress the message data in memory. byte[] UncompressedData = Encoding.UTF8.GetBytes(Message); byte[] CompressedData = null; MemoryStream s = new MemoryStream(); using (GZipStream z = new GZipStream(s, CompressionMode.Compress)) { z.Write(UncompressedData, 0, UncompressedData.Length); } CompressedData = s.ToArray(); if (_Transaction != null) { _Transaction.Begin(); base.Send(CompressedData, _Transaction); _Transaction.Commit(); } else { base.Send(CompressedData); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } ``` --- Here is the message contents for a test message. It ends up as an XML document that wraps the encoded binary data.: `<?xml version="1.0"?>..<base64Binary>H4sIAAAAAAAEAO29B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Ih63edMefTsvy2rv8V3+4/8ByygBlxMAAAA=</base64Binary>` --- Here is the decompression code it uses: ``` String Data; //Get message and format XML System.Messaging.Message m = MessagesList[ListIndex].Tag; m.Formatter = new XmlMessageFormatter(new Type[] { typeof(string), // Send raw plain strings typeof(byte[]), // Array of binary data typeof(XmlNode) // Xml document }); m.BodyStream.Position = 0; Data = m.Body.ToString(); if (m.Body.GetType() == typeof(byte[])) { try { // The message body is an array of binary data. // Assume it is a GZIP stream of compressed data. byte[] CompressedData = (byte[])m.Body; byte[] UncompressedData = null; // Decompress it. MemoryStream s = new MemoryStream(CompressedData); using (GZipStream z = new GZipStream(s, CompressionMode.Decompress)) { UncompressedData = MyExtensions.ReadRemainingBytes(z); } // Turn the bytes back into a string. Data = Encoding.UTF8.GetString(UncompressedData); } catch { Data = "Unknown binary data: " + BitConverter.ToString((byte[])m.Body, 0); } } if (m.Body.GetType() == typeof(XmlElement)) { XmlElement el = (XmlElement)m.Body; if (el.Name == "string") Data = el.InnerText; else Data = el.OuterXml; } ``` --- I would like to point out that I am setting the Formatter of the message, which is the first step to getting the body to automatically "box" and "unbox" in the queue. In Windows XP, m.Body.GetType() == byte[], like expected. But, in Windows 7, m.Body.GetType() == XmlElement, i.e. the wrapper XML. It no longer "unboxes" the message. Do we need to do something differently? We have worked around it once for sending strings, as you can see at the end of the receive function, but I would like to find a real answer for why this code behaves differently on Windows 7.
2011/05/02
[ "https://Stackoverflow.com/questions/5862229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735072/" ]
Use the Message.BodyStream property if you want to send an array of bytes: ``` System.Messaging.MessageQueue queue = new MessageQueue(queueFormatName, false, true, QueueAccessMode.Send); System.Messaging.Message msg = new System.Messaging.Message(); msg.BodyStream = new MemoryStream(buffer); queue.Send(msg, MessageQueueTransactionType.Single); ```
9,997,550
I have seen several post regarding making a build in Jenkins fail if the unit test execution fail (e.g. this [one](https://stackoverflow.com/questions/6681880/how-to-make-jenkins-display-fail-if-one-of-the-ant-tests-fail)). It turns out that by default Jenkins reports builds with failing tests as `unstable` and some people do not like that. This, however, will be perfectly fine for me. I just want to be able to easily differentiate builds with passing tests from such with failing tests. And here is the catch: **I am developing for Android** so my build is configured following [this page](https://wiki.jenkins-ci.org/display/JENKINS/Building+an+Android+app+and+test+project). Basically the tests are run with the following command: ``` ant all clean emma debug install test ``` As result coverage report is generated and published in Jenkins. All posts I have read about configuring the Jenkins result according to tests results were dealing with ant task manipulation. However, if we look at the android `build.xml` the Android tests are run with adb command: `adb shell am instrument ...`. I don't know how to configure this command to print the tests results. It can be configured to print the coverage report. I have already done that, but was never able to make the build fail according to the coverage report. I hope somebody else also faced the same problem and managed to solve it. Any guidance will be most appreciated.
2012/04/03
[ "https://Stackoverflow.com/questions/9997550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108032/" ]
You have two options: Either use the `AsyncTask`'s method `get(long timeout, TimeUnit unit)` like that: ``` task.get(1000, TimeUnit.MILLISECONDS); ``` This will make your main thread wait for the result of the `AsyncTask` at most 1000 milliseconds (as per @user1028741 comment: actually there is also infinetly waiting method - [`AsyncTask#get()`](http://developer.android.com/reference/android/os/AsyncTask.html#get%28%29) which might also do the work for you in some cases). Alternatively you can show a progress dialog in the async task until it finishes. See this [thread](https://stackoverflow.com/a/4538370/1108032) (No need for me to copy past the code). Basically a progress dialog is shown while the async task runs and is hidden when it finishes. You have even third option:" if `Thread` is sufficient for your needs you can just use its `join` method. However, if the task is taking a long while you will still need to show a progress dialog, otherwise you will get an exception because of the main thread being inactive for too long.
16,377
My cat catches a lot of mice and birds. It always leaves the heart, perfectly intact. My question is, what about the tails of the mice, the feathers of the birds? I sometimes find some feathers but never all of them. Does the cat eat it, and why does it leave the heart?
2017/02/10
[ "https://pets.stackexchange.com/questions/16377", "https://pets.stackexchange.com", "https://pets.stackexchange.com/users/-1/" ]
Cats are very picky with what they eat. Although hearts have a lot of good nutrients for cats, if a cat doesnt like the texture or taste, it might just reject it. Cats most likely won't eat the feathers or the tails, as they are harder to digest, but might occasionally eat a few. Although this is unrelated, and not a current issue for you, it will prevent future stress. Remember to get your cat regularily checked up on by the vet. Mice and birds can carry diseases.
21,289,637
Hello I am trying to insert into a database and I am getting the error: ``` SQL Exception: java.sql.SQLException: Parameter index out of range (6 > number of parameters, which is 5). ``` The code causing this is: ``` PreparedStatement st = connection.prepareStatement("INSERT INTO Members VALUES ('?','?','?','?','?','?','?','?','?','?','?','?','?','?'','?','?','?','?','?'"); st.setString(1, username); st.setString(2, id); st.setString(3, firstName); st.setString(4, lastName); st.setString(5, address); st.setString(6, phone); st.setString(7, email); st.setInt(8, age); st.setString(9, String.valueOf(sex)); st.setDouble(10, height); st.setInt(11, kgs); st.setDouble(12, stone); st.setInt(13, targetWeightKgs); st.setDouble(14, bmi); st.setString(15, medicalHistory); st.setString(16, extraHistory); st.setBoolean(17, smoker); st.setBoolean(18, usernameCompleted); st.setString(19, myNotes); st.executeUpdate(); ```
2014/01/22
[ "https://Stackoverflow.com/questions/21289637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3211740/" ]
You should not quote your `?` placeholders, even if they represent string data. Quoted question marks will be intrepreted as literal `'?'` strings. It's probably interpreted as 5 parameters because your 6th to last parameter has two `'` characters, so your last 5 `?`s are interpreted as outside of single-quotes. Try ``` connection.prepareStatement("INSERT INTO Members VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); ``` **UPDATE** There was a closing ")" missing in the insert statement, that I have now added.
30,746,586
I have some scala futures. I can easily run them in parallel with `Future.sequence`. I can also run them one-after-another with something like this: ``` def serFut[A, B](l: Iterable[A])(fn: A ⇒ Future[B]) : Future[List[B]] = l.foldLeft(Future(List.empty[B])) { (previousFuture, next) ⇒ for { previousResults ← previousFuture next ← fn(next) } yield previousResults :+ next } ``` (Described [here](http://www.michaelpollmeier.com/execute-scala-futures-in-serial-one-after-the-other-non-blocking/)). Now suppose that I want to run them *slightly* in parallel - ie with the constraint that at most `m` of them are running at once. The above code does this for the special case of `m=1`. Is there a nice scala-idiomatic way of doing it for general `m`? Then for extra utility, what's the most elegant way to implement a kill-switch into the routine? And could I change `m` on the fly? My own solutions to this keep leading me back to procedural code, which feels rather wimpy next to scala elegance.
2015/06/10
[ "https://Stackoverflow.com/questions/30746586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/662694/" ]
You should accumulate the results in a dictionary. You should use the values of 'a' and 'b' to form a key of this dictionary Here, I have used a `defaultdict` to accumulate the entries ``` l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}] l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}] from collections import defaultdict D = defaultdict(dict) for lst in l1, l2: for item in lst: key = item['a'], item['b'] D[key].update(item) l3 = D.values() print l3 ``` output: ``` [{'a': 1, 'c': 3, 'b': 2, 'e': 101, 'd': 4}, {'a': 5, 'c': 7, 'b': 6, 'e': 100, 'd': 8}] ```
58,947,053
I am confused about what is business logic. I assume that it is written in Controller but then I search it on internet but i found that many person say that it refers to model. I am highly confused. And somee community meembers give me suggestions that my question is same but you are doing mistake. I am confused by the answers in those questions. Someone says model is business logic but I assume that Controller is business logic. So Please understand my doubt.
2019/11/20
[ "https://Stackoverflow.com/questions/58947053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12302811/" ]
You can use `array_filter` with `callback` to return only type which is checkbox. ``` $filtered = array_filter($array, function($v){return $v['type'] == 'checkbox' && $v['is_active'] == 1;}); ``` Working example :- <https://3v4l.org/idAR4>
11,424
Me and my sister in law bought a house. We asked her help to acquire the loan. She signed the mortgage loan for a 5 year contract, and we got the house. Me and my wife paid all the expenses and down payment for the house, my sister in law never gave a single cent for acquiring the house. The title stated she has 5% share and 95% for me. We all live in the same house and she is paying me 600 a month because she came to live with us with her two kids and with the 600 everything is inclusive down to utilities. Something went wrong and now she wants her name out of the mortgage and she is claiming her 5% share. Me and my wife are paying the mortgage and never had any default, we pay property taxes, insurance and all the utilities, my wife maintains the house and we renovated the house significantly without any help from her. Do I have the right to refuse her demand to remove her name since I believe I cannot stand alone yet on the mortgage?
2016/07/07
[ "https://law.stackexchange.com/questions/11424", "https://law.stackexchange.com", "https://law.stackexchange.com/users/-1/" ]
I can't help with the relationship issues: here are the legal issues. 1. She legally owns 5% of the house and you own 95% 2. I presume that the loan agreement is a contract between you, her and the lender so removing her name from the loan is at the discretion of the lender, not you or her. I would be very surprised if the lender would allow this without totally refinancing the loan. 3. Whatever arrangements you had with your sister are *probably* not enforceable because the presumption is that arrangements between family members are *not* legally enforceable contracts. Unless you can provide evidence that both of you intended to create legally binding obligations for what you assert (like a signed document) then what you say is just hot air. Legally, neither of you have the power to get her name off the loan. As a co-owner she is entitled to live in the property rent free. Each of you is jointly (i.e. together) and severally (i.e. individually) liable for making the loan repayments - in what proportion that should be done is a matter for you two to sort out - the lender doesn't care who pays so long as they get paid. <https://www.law.cornell.edu/wex/tenancy_in_common>
950,794
I am running Gnome Shell with a 4k monitor and there are a few applications that I use that don't scale at all with the high resolution. Here is an example of LMMS, an application that hasn't yet been ported Qt 5, so it doesn't have high dpi scaling capabilities: [![Screenshot](https://i.stack.imgur.com/Af0Vr.jpg)](https://i.stack.imgur.com/Af0Vr.jpg) (Click images to enlarge) Is there any way to scale a specific X window without changing the display resolution? My current solution is to half the dimensions of my display resolution, but this degrades the resolution of every other application that supports proper dpi scaling: [![Screenshot](https://i.stack.imgur.com/fJVFL.jpg)](https://i.stack.imgur.com/fJVFL.jpg)
2015/08/04
[ "https://superuser.com/questions/950794", "https://superuser.com", "https://superuser.com/users/61024/" ]
I finally managed to find a solution that scales old applications without any noticeable visual or performance degradation. Thanks to kaueraal, you can now scale old applications using `run_scaled`. You can obtain the script from either his [GitHub page](https://github.com/kaueraal/run_scaled) or as part of the `xpra` package if you are running Arch Linux. Here is an example of two applications running side by side: * Firefox with HiDPI support on the left * LMMS running with `run_scaled` on the right [![enter image description here](https://i.stack.imgur.com/VwIjQ.jpg)](https://i.stack.imgur.com/VwIjQ.jpg) I discovered this script through the [Arch Linux Wiki](https://wiki.archlinux.org/index.php?title=HiDPI&oldid=468803#Unsupported_applications).
57,059,368
I have a pointer `uvw(:,:)` which is two-dimensional, and I got a 1d buffer array `x(:)`. Now I need to point `uvw(1,:)=>x(1:ncell)` and `uvw(2,:)=>x(ncell+1:ncell*2)` etc. I made a very simple example. I know that array of pointers does not work, but does anybody have an idea how this can be worked around? PS: For a pragmatic reason I do not want to wrap my uvw with a declared type. ( i am changing some bit of code, and need uvw as 2D pointer. Currently is an array, and my idea is to avoid changing the way uvw is being used as it being used thousands of times) ``` program test real, allocatable,target :: x(:) real, pointer :: ptr(:,:) allocate(x(100) ) x = 1. ptr(1,:) => x(1:10) end program ``` The error message says: > > `error #8524: The syntax of this data pointer assignment is incorrect: > either 'bound spec' or 'bound remapping' is expected in this context. > [1] > > > ptr(1,:) => x(1:10) > > > ----^` > > >
2019/07/16
[ "https://Stackoverflow.com/questions/57059368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8889824/" ]
You are trying to perform *pointer bounds remapping*, but you have the incorrect syntax and approach. Pointer bounds remapping is a way to have the shape of the pointer different from that of the target. In particular, the rank of the pointer and target may differ. However, in such an assignment it is necessary to explicitly specify the lower and upper bounds of the remapping; it isn't sufficient to use `:` by itself. Also, you'll need to assign the whole pointer in one go. That is, you can't have "the first ten elements point to this slice, the next ten to this slice" and so on in multiple statements. The assignment statement would be ``` ptr(1:10,1:10) => x ``` Note, that this also means that you can't actually have what you want. You are asking for the elements `ptr(1,1:10)` to correspond to `x(1:10)` and `ptr(2,2:10)` to correspond to `x(11:20)`. That isn't possible: the array elements must match in order: `ptr(1:10,1)` being the first ten elements of `ptr` must instead be associated with the first ten elements `x(1:10)`. The corrected pointer assignment above has this.
30,893,505
I've been making a game with Corona SDK. I'm trying display an image in the middle of the screen, but it displays in the random location. Image that I'm trying to display is circle.png. Please help me if you can. Here is the code: local composer = require( "composer" ) ``` strong textlocal scene = composer.newScene() local widget = require "widget" widget.setTheme ("widget_theme_ios") local score local scoreEarn = 1 local lives = {} local livesCount = 1 local balls = {} local ballsCount = 0 local ballsSendSpeed = 65 local ballsTravelSpeed = 3500 local ballsIncrementSpeed = 1.5 local ballsMaxSendSpeed = 30 local timer_Counter local onGameOver, gameOverBox, gameoverBackground, btn_returnToMenu -- ------------------------------------------------------------------------------- -- "scene:create()" function scene:create( event ) local sceneGroup = self.view -- Initialize the scene here. -- Example: add display objects to "sceneGroup", add touch listeners, etc. local function ballTap(event) end local function ballDrag() end local function ballSend () end local function ballsCollision () end local function onCollision (event) end local function circleDamage () end function gameOver () end local background = display.newImageRect(sceneGroup, "images/gamescreen/background.png", 1600, 1200) background.x = _CX background.y = _CY local cirlce = display.newImageRect(sceneGroup, "images/gamescreen/circle.png", 184, 179) cirlce.x = _CX cirlce.y = _CY end -- "scene:show()" function scene:show( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Called when the scene is still off screen (but is about to come on screen). elseif ( phase == "did" ) then -- Called when the scene is now on screen. -- Insert code here to make the scene come alive. -- Example: start timers, begin animation, play audio, etc. end end -- "scene:hide()" function scene:hide( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Called when the scene is on screen (but is about to go off screen). -- Insert code here to "pause" the scene. -- Example: stop timers, stop animation, stop audio, etc. elseif ( phase == "did" ) then -- Called immediately after scene goes off screen. end end -- "scene:destroy()" function scene:destroy( event ) local sceneGroup = self.view -- Called prior to the removal of scene's view ("sceneGroup"). -- Insert code here to clean up the scene. -- Example: remove display objects, save state, etc. end -- ------------------------------------------------------------------------------- -- Listener setup scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) -- ------------------------------------------------------------------------------- return scene ```
2015/06/17
[ "https://Stackoverflow.com/questions/30893505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5019687/" ]
Just try this , ``` local cirlce = display.newImageRect(sceneGroup, "images/gamescreen/circle.png", 184, 179) cirlce.x = display.viewableContentWidth/2 cirlce.y = display.viewableContentHeight/2 ```
2,188,179
The scalar product equation $$ {\bf v\cdot w}=s\\v\_1w\_1+v\_2w\_2+\cdots+v\_nw\_n = s$$ is a linear equation if we look at $\bf v$ and $\bf w$ separately. But can we somehow make it simultaneously linear? In 2D special case $s=0$ we can "cheat" by setting $$\cases{v\_1=-w\_2\\v\_2=w\_1} \Leftrightarrow \cases{v\_1+w\_2=0\\v\_2-w\_1=0}$$ which is simultaneously linear assuming we have a vectorization $${\bf q} = \left[\begin{array}{c}\bf v\\\bf w\end{array}\right] = \left[\begin{array}{c}v\_1\\v\_2\\w\_1\\w\_2\end{array}\right]$$ we can write the equations $$\left[\begin{array}{cccc|c}1&0&0&1&0\\0&1&-1&0&0\end{array}\right] \text{or with matrices : } \\\phantom{a}\\{\bf M}= \left[\begin{array}{cccc}1&0&0&1\\0&1&-1&0\end{array}\right], {\bf Mq=0}$$
2017/03/15
[ "https://math.stackexchange.com/questions/2188179", "https://math.stackexchange.com", "https://math.stackexchange.com/users/213607/" ]
Your proposal does not give you the set of solutions $$ \{ (\mathbf{v}, \mathbf{w}) \, | \, \mathbf{v} \cdot \mathbf{w} = 0 \} $$ but only a linear subspace which is contained in the set of solutions. Namely, if $v\_1 = -w\_2$ and $v\_2 = w\_1$ then indeed $$ v\_1 w\_1 + v\_2 w\_2 = -w\_2 w\_1 + w\_1 w\_2 = 0 $$ but not all the solution have this form (consider for example $\mathbf{v} = (1,0)$ and $\mathbf{w} = (0,2)$). In general, the set of solutions is a non-affine subspace of $\mathbb{R}^n \times \mathbb{R}^n$ so you can't expect to describe it as the solution set of a linear system of equations.
82,435
When I train a neural network, I observe an increasing validation loss, while at the same time, the validation accuracy is also increased. I have read explanations related to the phenomenon, and it seems an increasing validation loss and validation accuracy signifies an overfitted model. However, I have not really grokked the reasons why an increasing validation loss and validation accuracy signifies an overfitting. Could you please give the explanations behind this phenomenon?
2020/10/01
[ "https://datascience.stackexchange.com/questions/82435", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/103610/" ]
Consider a simple example where the cost function to be a parabola $y=x^2$ which is convex(ideal case) with a one global minima at $x=0$ Here your $y$ is the independent variable and $x$ is the dependent variable, analogus to the weights of model that you are trying to learn. This is how it would look like. [![enter image description here](https://i.stack.imgur.com/5zcMe.png)](https://i.stack.imgur.com/5zcMe.png) Let's apply gradient descent to this particular cost function(parabola) to find it's minima. From calculus it is clear that $dy/dx = 2\*x$. So that means that the gradients are positive in the $1^{st}$ quadrant and negative in the $2^{nd}$. That means for every **positive** small step in x that we take, we move away from origin in the $1^{st}$ quadrant and move towards the origin in the $2^{nd}$ quadrant(step is still positive). In the update rule of gradient descent the '-' negative sign basically negates the gradient and hence always moves towards the local minima. * $1^{st}$ quadrant -> gradient is positive, but if you use this as it is you move away from origin or minima. So, the negative sign helps here. * $2^{nd}$ quadrant -> gradient is negative, but if you use this as it is you move away from origin or minima(addition of two negative values). So, the negative sign helps here. Here is a small python code to make things clearer- ```py import numpy as np import matplotlib.pyplot as plt x = np.linspace(-4, 4, 200) y = x**2 plt.xlabel('x') plt.ylabel('y = x^2') plt.plot(x, y) # learning rate lr = 0.1 np.random.seed(20) x_start = np.random.normal(0, 2, 1) dy_dx_old = 2 * x_start dy_dx_new = 0 tolerance = 1e-2 # stop once the value has converged while abs(dy_dx_new - dy_dx_old) > tolerance: dy_dx_old = dy_dx_new x_start = x_start - lr * dy_dx_old dy_dx_new = 2 * x_start plt.scatter(x_start, x_start**2) plt.pause(0.5) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/APPGu.png)](https://i.stack.imgur.com/APPGu.png)
54,439,733
The actual problem is to use option tag in select block in horizontal way and divide option values using optgroup. So the expected result would be: `Showing elements on the page 10 | 20 | 30`, where 10,20,30 are selectable and table will show selected amount of elements The solution I came to is: HTML: ``` <div class="styled-select"> <select size="3"> <optgroup label="|"> <option value="10">10</option> </optgroup> <optgroup label="|"> <option value="20">20</option> </optgroup> <optgroup label="|"> <option value="30">30</option> </optgroup> </select> </div> ``` CSS: ``` .styled-select { display:inline-block; overflow:hidden; margin-top:30px; overflow-x:hidden; height:25px; } .styled-select select { margin: -1px -20px -5px -5px; } optgroup { position:relative; display:inline-block; width:32px; padding-left:5px; padding-right: 0px; } optgroup:nth-child(1) { visibility:hidden; } .styled-select select option{ visibility:visible; position:absolute; display:inline-block; width:15px; margin-left:12px !important; padding-top:-10px !important; margin-top:-16px !important; text-align: center; } .styled-select select option::before{ content: none; padding-left: 0 !important; padding-right: 0 !important; margin: 0 0 0 0; } ``` Result you can see here: <https://jsfiddle.net/834gwtz7/4/> If you have any suggestions, how to do it in more elegant way, please help!
2019/01/30
[ "https://Stackoverflow.com/questions/54439733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10989864/" ]
The Go Cloud Development Kit Pub/Sub API is still a work in progress (it's one of our newer APIs). As of 2019-01-30, there is a [pull request](https://github.com/google/go-cloud/pull/1207) out for review that adds support, so stay tuned!
44,971,813
Code: ``` int x = 2; int* pointerone = &x; int* pointertwo = pointerone; ``` So the address of `pointerone` is assigned to `pointertwo`, but is the copy constructor being called and the object that holds the address is copied into the address object of the other pointer, like all the default copy constructors on other types performing a shallow copy. If it is as I expect, how does the copy constructor of a pointer look like?
2017/07/07
[ "https://Stackoverflow.com/questions/44971813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There are no constructors involved here. In fact this code is pure C code. ``` int x = 2; // pointerone points to the memory address of x int* pointerone = &x; // pointertwo points to the same address than pointerone, // therefore it points also to the memory address of x int* pointertwo = pointerone; ``` That's all. And even in C++, pointers don't have constructors, exactly as the `int` type doesn't have a constructor.
21,289,707
I'm using Backbone together with require.js and jQuery. What I'm trying to do is to simply bind an event to a container which should show (mouseover) or hide (mouseout) a video. The event fires but unfortunately too many times (I've several children inside `.intro-content`). I tried using `ev.stopPropagation()` (as seen in the code) and `ev.stopImmediatePropagation` but this doesn't prevent the bubbling. What am I doing wrong? View: ``` define([ 'jquery', 'underscore', 'backbone', 'global' ], function($, _, Backbone, Global){ var VideoView = Backbone.View.extend({ el: $('#splitlayout'), events: { 'mouseover .side-left .intro-content': 'checkVideoState', 'mouseout .side-left .intro-content': 'checkVideoState' }, render: function(){ this.playVideo('video', '0GsrOOV0gQM'); this.delegateEvents(); }, initialize: function() { _.bindAll(this); this.render(); }, checkVideoState: function(ev) { ev.stopPropagation(); if(!$('#video').hasClass('active') && ev.type == 'mouseover') { this.showVideo(); } else if($('#video').hasClass('active') && ev.type == 'mouseout') { this.hideVideo(); } }, showVideo: function() { console.log('test'); $('#video').addClass('active'); player.playVideo(); }, hideVideo: function() { console.log('test'); $('#video').removeClass('active'); player.pauseVideo(); }, playVideo: function(container, videoId) { var self = this; if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') { window.onYouTubeIframeAPIReady = function() { self.loadPlayer(container, videoId); }; $.getScript('//www.youtube.com/iframe_api'); } else { self.loadPlayer(container, videoId); } }, loadPlayer: function(container, videoId) { player = new YT.Player(container, { videoId: videoId, playerVars: { controls: 0, loop: 1, modestbranding: 0, rel: 0, showinfo: 0 }, events: { 'onReady': this.onPlayerReady } }); }, onPlayerReady: function() { player.setPlaybackQuality('hd720'); player.seekTo(8,false); player.pauseVideo(); } }); return VideoView; }); ```
2014/01/22
[ "https://Stackoverflow.com/questions/21289707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/529585/" ]
You're definitely along the right lines, but you can simplify your loop and use [.each()](http://api.jquery.com/jquery.each/) function to iterate over all of the `$('.content-block')` elements on your page. You're alos only setting the random colour once, so you can move that into the each function: ``` $('.content-block').each(function(i, el) { var randomColor = Math.floor(Math.random()*background.length); $(el).addClass(background[randomColor]); }); ``` I've also just realised that you might want each `$('.content-block')` to be a different colour from the other. In which case, you want to remove the colour from `colors` each time you've assigned a colour: ``` function getRandomColour() { var randomNumber = Math.floor(Math,random()*colors.length(); var randomColour = colors[randomNumber]; var colourPosition = colors.indexOf(randomColour); colours.splice(colourPosition, 1); // Remove colour from array return randomColour; } $('.content-block').each(function(i, el) { $(el).addClass(background[randomColor]); }); ```
302,220
I saw that a chatroom event is going to be held. What is special about chatroom events? Aren't they just the same as the usual chatting? I went to the FAQ and the Help Center, but I see no useful information there.
2015/08/11
[ "https://meta.stackoverflow.com/questions/302220", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/5133585/" ]
Chatroom events are just easy ways for moderators of a room to communicate a scheduled function. They can be created with any purpose in mind, much like their real life counterparts. In the StackOverflow Python chat, we typically schedule our [room meetings as events](https://chat.stackoverflow.com/rooms/info/6/python?tab=schedule) so that everyone is reminded of the occurrence outside of having pinned messages in the starred/pinned messages area of the interface. Finally, the StackOverflow dev team was nice enough to make the events exportable, meaning it's easy to get "official" reminders in whatever calendar solution the user chooses.
33,067,964
I need to write a program in C++ where the user can do some computation, and when the computation is done, the program will ask the user if he wants to do another computation. I know how to write this in Python: ``` more = "y" while (more == "y"): // computation code print "Do you want to do another computation? y/n " more = input() ``` I created a char variable and used it in the head of the loop, but I don't know how to implement the "input" function in C++. I tried using the cin.get(char\_variable) function but the program seems to skip it entirely.
2015/10/11
[ "https://Stackoverflow.com/questions/33067964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906984/" ]
You can use `cin >> char_variable;` to get the value. Don't forget: ``` #include <iostream> using namespace std; ```
4,631,569
How would you go about opening an .xml file that is within a .jar and edit it? I know that you can do... ``` InputStream myStream = this.getClass().getResourceAsStream("xmlData.xml"); ``` But how would you open the xmlData.xml, edit the file, and save it in the .jar? I would find this useful to know and don't want to edit a file outside of the .jar... **and the application needs to stay running the entire time!** Thank you!
2011/01/08
[ "https://Stackoverflow.com/questions/4631569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/516664/" ]
Jar files are just .zip files with different file suffix, and naming convention for contents. So use classes from under `java.util.zip` to read and/or write contents. Modifying contents is not guaranteed (or even likely) to effect running system, as class loader may cache contents as it sees fit. So it might be good to know more about what you are actually trying to achieve with this. Modifying contents of a jar on-the-fly sounds like complicated and error-prone approach...
11,268
Does this website have "specific rules" for MODs to follow, or can they just make up their own set of rules as they feel like it? I ask this because I have posted many answers and get different MODs telling me this and that... examples: I post an answer with just links to the "relevant" tutorials so I can avoid "plagiarism." A MOD posts saying I need to post a relevant "tutorial"... ok... I post a tutorial from a website and another MOD tells me that I need to post a link to the tutorial otherwise it can be seen as plagiarism... ok... I post an answer with full tutorial and link to the source website where I got the tutorial, and a MOD tells me that I need to "blockquote" when I post stuff from other sources... OK... And lastly, a MOD tells me that most of my answers are from other sources.... SO WHAT! If it has already been answered and I find the answer and re-post it here on this website... is that my fault that people don't know how to use the search engines to their advantage? What the hell is going on with all the MODs on this website... it's like no matter what a low ranking user posts they feel the need to "bash" on them. And I won't even get started on the "high ranked" users feeling that they need to comment on a users post saying that what they said does not help the OP solve their question... when in fact it CLEARLY does give the OP something else to check as they DID NOT try this or that way according to their question posted. It's just getting ridiculous @Admin... your staff needs an overhaul or a good stern company meeting.
2016/02/26
[ "https://meta.superuser.com/questions/11268", "https://meta.superuser.com", "https://meta.superuser.com/users/562173/" ]
This site does have "specific rules" which the moderators follow, in the form of the [Moderator Agreement](https://superuser.com/legal/moderator-agreement). The site also has specific rules as well as general guidelines for all users (including but not limited to moderators) to follow, which are documented in the [site help pages](https://superuser.com/help). The help pages have a specific entry on [how to reference material written by others](https://superuser.com/help/referencing), as well as general guidance on [how to write a good answer](https://superuser.com/help/how-to-answer). Between the two of those, your concerns about how to best refer to external material should be answered. > > Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline. > > > When you find a useful resource that can help answer a question (from another site or in an answer on Super User) make sure you do all of the following: > > > > > * Provide a link to the original page or answer > * Quote only the relevant portion > * Provide the name of the original author > > > Do not copy the complete text of external sources; instead, use their words and ideas to support your own. And always give proper credit to the author and site where you found the text, including a direct link to it. > > > In short, you should provide more than just a bare link, so that other people can understand the general idea of what the link provides, and so that the information is preserved should the link go dead. But you shouldn't just copy an entire article verbatim, or make it appear as if you wrote it yourself – hence the use of block quote formatting and attribution. Please note this is general feedback based on your meta question; I haven't looked over any of the specific answers you posted. --- > > It's just getting ridiculous @Admin... your staff needs an overhaul or a good stern company meeting. > > > Moderators are not staff. We are volunteers democratically elected by the community. The Stack Exchange staff are not typically involved with day-to-day moderation of the sites, as there are over 100 sites in the network. If you do need to contact the SE staff [you can do so through the help center](https://superuser.com/contact).
6,234,333
I want to display "goodbye" for 1 second, fade it out, replace it with "hello", and then fade back in. Why doesn't this snippetwork? (jQuery is loaded): ``` <div id="foo">x</div> <script type="text/javascript"> $('#foo').fadeOut().html('goodbye').fadeIn().delay(1000).fadeOut().html('hello').fadeIn(); </script> ``` I'm using the queue correctly, so these commands occur in order (not asynchronously), right? Full version: <http://test.barrycarter.info/stacked1.html> EDIT: Thanks to everyone who answered! I appreciate the alternate suggestions. I guess my real question was "why doesn't my code work?" I'm learning jQuery, and figuring out where my code goes wrong would really help me!
2011/06/04
[ "https://Stackoverflow.com/questions/6234333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You want to make the `fadeIn` part of the callback function of `fadeOut`. So... ``` $('#foo').fadeOut('slow', function(){ $('#foo').fadeIn('slow').html('Hello'); }); ``` Change `slow` to `1000` for 1 second or whatever is desired. <http://jsfiddle.net/qK26W/>
42,038,334
Excuse me if this has been answered previously, but I can't seem to find an answer. How do I convert a string of numbers (e.g "50") into a single char with an ASCII value of the same number, in this case '2'. Is there a way to do this conversion? Alternatively, could I do the same by converting the string to an int first?
2017/02/04
[ "https://Stackoverflow.com/questions/42038334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7501819/" ]
Here for some languages: C/C++ ``` int i = 65; char c = i; printf("%c", c); // prints A ``` JS ``` var c = String.fromCharCode(66); console.log(c); // prints B ``` C#/Java ``` char c = (char)67; // For Java use System.out.println(c) Console.WriteLine(c) // prints C ``` Python ``` c = chr(68) # for Python 2 use c = str(unichr(68)) print(c) # Prints D ```
69,372,101
I want to do something like this: ``` ArrayList<String> strings = new ArrayList<>(); //build a collection of Strings callMethod(strings); ``` The "callMethod" is legacy (in a legacy project), so I cannot change it. It's signature is this: ``` private void callMethod(String... input){ // and so forth... ``` How do I pass the collection of Strings to the callMethod method?
2021/09/29
[ "https://Stackoverflow.com/questions/69372101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17031679/" ]
Just convert the list to an array of Strings ([varargs turns into an array under the hood](https://docs.oracle.com/javase/specs/jls/se17/html/jls-8.html#jls-8.4.1): *"If the formal parameter is a variable arity parameter, then the declared type is an array type specified by §10.2."*): ``` callMethod(strings.toArray(new String[0])); ```
55,744,147
Calendars have a owner and have a `ManyToMany` field 'assistants' i have a Calendar who has 2 assistants one of which is its owner. I think these 3 lines of code in the django shell can explain the weird behaviour quite well. ```py In [17]: Calendar.objects.filter(assistants=customer).exclude(owner=customer) Out[17]: <QuerySet []> In [20]: Calendar.objects.filter(owner=customer) Out[20]: <QuerySet [<Calendar: aliz cal>, <Calendar: yassi has a calendar>]> In [19]: Calendar.objects.filter(owner=customer) | Calendar.objects.filter(assistants=customer).exclude(owner=customer) Out[19]: <QuerySet [<Calendar: aliz cal>, <Calendar: aliz cal>, <Calendar: yassi has a calendar>]> ``` Of course expected the result of queryset join to be the actual union of them.
2019/04/18
[ "https://Stackoverflow.com/questions/55744147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2696242/" ]
Assuming this is for django 1.11+: `|` does not represent a union. It represents an OR-combination (which maintains **all** joins; hence aliz showing up twice) of two querysets . `qs1.filter(x=1) | qs2.exclude(x=1)` translates to: ``` SELECT STUFF FROM TABLES_AND_JOINS WHERE (x = 1 OR NOT (x = 1)) ``` While `qs1.filter(x=1).union(qs2.exclude(x=1))` translates to: ``` SELECT STUFF FROM TABLE1 WHERE x = 1 UNION SELECT STUFF FROM TABLE2 WHERE NOT x = 1 ``` Use `str(qs.query)` to see the SQL.
14,042,251
I am trying to make buttons with different gradients programmatically. I use ShapeDrawable and it works like a charm. ``` RoundRectShape rs = new RoundRectShape(new float[] { 12f, 12f, 12f, 12f, 12f, 12f, 12f, 12f }, null, null); ShapeDrawable sd = new ShapeDrawable(rs); ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() { @Override public Shader resize(int width, int height) { LinearGradient lg = new LinearGradient(0, 0, 0, height, new int[] { Color.parseColor("#feccb1"), Color.parseColor("#f17432"), Color.parseColor("#e86320"), Color.parseColor("#f96e22") }, new float[] { 0, 0.50f, 0.50f, 1 }, Shader.TileMode.REPEAT); return lg; } }; sd.setShaderFactory(sf); myBtn.setBackgroundDrawable(sd); ``` However I would like to add a **shadow** to the button, **not the button text** programmatically. Any help would be appreciated.
2012/12/26
[ "https://Stackoverflow.com/questions/14042251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1005194/" ]
> > However I would like to add a shadow to the button, not the button > text programmatically. > > > I guess you want the shadow behind the current drawable you built. If yes then make a [`LayerDrawable`](http://developer.android.com/reference/android/graphics/drawable/LayerDrawable.html) along with another `Drawable`(placed first) that will act as the shadow: ``` RoundRectShape rss = new RoundRectShape(new float[] { 12f, 12f, 12f, 12f, 12f, 12f, 12f, 12f }, null, null); ShapeDrawable sds = new ShapeDrawable(rss); sds.setShaderFactory(new ShapeDrawable.ShaderFactory() { @Override public Shader resize(int width, int height) { LinearGradient lg = new LinearGradient(0, 0, 0, height, new int[] { Color.parseColor("#e5e5e5"), Color.parseColor("#e5e5e5"), Color.parseColor("#e5e5e5"), Color.parseColor("#e5e5e5") }, new float[] { 0, 0.50f, 0.50f, 1 }, Shader.TileMode.REPEAT); return lg; } }); LayerDrawable ld = new LayerDrawable(new Drawable[] { sds, sd }); ld.setLayerInset(0, 5, 5, 0, 0); // inset the shadow so it doesn't start right at the left/top ld.setLayerInset(1, 0, 0, 5, 5); // inset the top drawable so we can leave a bit of space for the shadow to use b.setBackgroundDrawable(ld); ```
18,425,419
Hoping someone could let me know if this is possible as I have searched and couldn't come up with the desired effect I wanted. I basically want to have the border hover to be centred so when you mouse over the links the border-bottom is centred. I would like the border width to be a fixed size around 20px and centered. As you can see its really basic so far and the jsfiddle is here: <http://jsfiddle.net/pCQLN/3/> I want something like shown in the below image: --- ![enter image description here](https://i.stack.imgur.com/z1VGe.jpg) --- Thank you for any time you can spare! Here's my code; HTML ``` <div id="wrap"> <div id="nav"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Projects</a></li> <li><a href="#">Blog</a></li> </ul> </div> </div> ``` CSS ``` #wrap { width:40em; height:3em; margin:0 auto; } #nav { float:right; width:75%; } #nav ul { display:inline; list-style: none; float: right; } #nav li { float: left; width:50px padding-right:1em; } #nav a { text-align:center; text-decoration:none; color: #888; font-size:1em; float: left; } #nav a:hover { color:#212121; display:block; width:20px; margin:0 auto; border-bottom:3px solid #000; } ```
2013/08/25
[ "https://Stackoverflow.com/questions/18425419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1722242/" ]
Use [`:after`](https://developer.mozilla.org/en-US/docs/Web/CSS/%3a%3aafter) pseudo selector in combination with `hover` pseudo selector. ``` #nav a:hover:after{ content: ""; color:#212121; display:block; width:20px; margin:0 auto; border-bottom:3px solid #000; } ``` [**Working Fiddle**](http://jsfiddle.net/venkateshwar/pCQLN/6/)
408,115
I'm looking for an elementary proof of the fact that $\ell(nP) = \dim L(nP) = n$, where $L(nP)$ is the linear (Riemann-Roch) space of certain rational functions associated to the divisor $nP$, where $n > 0$ is an integer and $P$ is a point on a curve of genus 1. This fact is used to prove that every elliptic curve is isomorphic to a curve given by a Weierstrass equation. See for instance Silverman, The Arithmetic of Elliptic Curves, p. 59, Proposition 3.1.(a). I know that it's a corollary to the Riemann-Roch theorem (it follows from the corollary that says if $\deg D > 2g - 2$ then $\ell(D) = \deg D + 1 - g$). The proof of the full Riemann-Roch theorem still looks a little intimidating to me, so I'm hoping someone can provide a more elementary proof of this special case, perhaps by making the relevant simplifications in the proof of the Riemann-Roch theorem. Thanks in advance.
2013/06/01
[ "https://math.stackexchange.com/questions/408115", "https://math.stackexchange.com", "https://math.stackexchange.com/users/23180/" ]
Let $X$ be an elliptic curve over $k$, and $P \in X$. We have to prove that for $D=nP$ we have $$ l(D)=\deg(D)=n $$ If $D$ satisfies the above equation, and $E$ is a divisor such that $E \geq D$, then we have $l(E)=\deg(E)$ (cf. [Fulton](http://www.math.lsa.umich.edu/~wfulton/CurveBook.pdf), Corollary 8.3.1). Hence it is enough to show that $l(P)=1$. Clearly $l(P) > 0$, since $k \subset L(P)$. On the other hand, $l(P) > 1$ would imply that there exists $x \in k(X)$ such that $x$ has a simple pole at $P$, and no other poles. But this would imply that the map $$ x: X \rightarrow \Bbb{P}^1 $$ is an isomorphism, which is a contradiction. Thus $l(P)=1$.
24,618,610
is my 2nd day with this problem. I receive this at LogCat: > > > > > > Error parsing data org.json.JSONException: Value Array of type java.lang.String cannot be converted to JSONArray > > > > > > > > > i'm doing query's to my database, and put the info that matters to me on an array like this: ``` 07-07 21:01:00.686: E/getpostresponse(17902): result= Array 07-07 21:01:00.686: E/getpostresponse(17902): ( 07-07 21:01:00.686: E/getpostresponse(17902): [0] => Array 07-07 21:01:00.686: E/getpostresponse(17902): ( 07-07 21:01:00.686: E/getpostresponse(17902): [0] => 7 07-07 21:01:00.686: E/getpostresponse(17902): [1] => mouse 07-07 21:01:00.686: E/getpostresponse(17902): [2] => Barcelona 07-07 21:01:00.686: E/getpostresponse(17902): [3] => Abbey IV Ale Yeast 07-07 21:01:00.686: E/getpostresponse(17902): [4] => 0000-00-00 00:00:00 07-07 21:01:00.686: E/getpostresponse(17902): [5] => Ale 07-07 21:01:00.686: E/getpostresponse(17902): [6] => 11 07-07 21:01:00.686: E/getpostresponse(17902): [7] => 20 07-07 21:01:00.686: E/getpostresponse(17902): [8] => prueba 07-07 21:01:00.686: E/getpostresponse(17902): [9] => Admiral 07-07 21:01:00.686: E/getpostresponse(17902): [10] => Ahtanum 07-07 21:01:00.686: E/getpostresponse(17902): [11] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [12] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [13] => 80 07-07 21:01:00.686: E/getpostresponse(17902): [14] => 20 07-07 21:01:00.686: E/getpostresponse(17902): [15] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [16] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [17] => Amber Dry Extract 07-07 21:01:00.686: E/getpostresponse(17902): [18] => Biscuit Malt 07-07 21:01:00.686: E/getpostresponse(17902): [19] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): ) 07-07 21:01:00.686: E/getpostresponse(17902): [1] => Array 07-07 21:01:00.686: E/getpostresponse(17902): ( 07-07 21:01:00.686: E/getpostresponse(17902): [0] => 8 07-07 21:01:00.686: E/getpostresponse(17902): [1] => mouse 07-07 21:01:00.686: E/getpostresponse(17902): [2] => Barcelona 07-07 21:01:00.686: E/getpostresponse(17902): [3] => Abbey IV Ale Yeast 07-07 21:01:00.686: E/getpostresponse(17902): [4] => 0000-00-00 00:00:00 07-07 21:01:00.686: E/getpostresponse(17902): [5] => Ale 07-07 21:01:00.686: E/getpostresponse(17902): [6] => 50 07-07 21:01:00.686: E/getpostresponse(17902): [7] => 8 07-07 21:01:00.686: E/getpostresponse(17902): [8] => prueba2 07-07 21:01:00.686: E/getpostresponse(17902): [9] => Ahtanum 07-07 21:01:00.686: E/getpostresponse(17902): [10] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [11] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [12] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [13] => 100 07-07 21:01:00.686: E/getpostresponse(17902): [14] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [15] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [16] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [17] => Black (Patent) Malt 07-07 21:01:00.686: E/getpostresponse(17902): [18] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [19] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): ) 07-07 21:01:00.686: E/getpostresponse(17902): [2] => Array 07-07 21:01:00.686: E/getpostresponse(17902): ( 07-07 21:01:00.686: E/getpostresponse(17902): [0] => 9 07-07 21:01:00.686: E/getpostresponse(17902): [1] => mouse 07-07 21:01:00.686: E/getpostresponse(17902): [2] => Valencia 07-07 21:01:00.686: E/getpostresponse(17902): [3] => Abbey Ale 07-07 21:01:00.686: E/getpostresponse(17902): [4] => 0000-00-00 00:00:00 07-07 21:01:00.686: E/getpostresponse(17902): [5] => Lager 07-07 21:01:00.686: E/getpostresponse(17902): [6] => 33 07-07 21:01:00.686: E/getpostresponse(17902): [7] => 4 07-07 21:01:00.686: E/getpostresponse(17902): [8] => prueba3 07-07 21:01:00.686: E/getpostresponse(17902): [9] => Admiral 07-07 21:01:00.686: E/getpostresponse(17902): [10] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [11] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [12] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [13] => 100 07-07 21:01:00.686: E/getpostresponse(17902): [14] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [15] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [16] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [17] => Aromatic Malt 07-07 21:01:00.686: E/getpostresponse(17902): [18] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): [19] => vacio 07-07 21:01:00.686: E/getpostresponse(17902): ) 07-07 21:01:00.686: E/getpostresponse(17902): ) ``` Here is my PHP code: ``` $resut = array(); $result = $db->cervezas($user);//this function returns the array print_r($result); //$json_data = array(); // while($row=mysql_fetch_array($result)){ // array_push($json_data, $row); // } //$json_data = json_encode($json_data); $json_data = json_encode($result); echo $json_data; ``` And i give you the Java code too. The code run after call an Asyntask: ``` public boolean cervezastatus(){ ArrayList<NameValuePair> postparameters2send= new ArrayList<NameValuePair>(); postparameters2send.add(new BasicNameValuePair("tipo","agua")); SharedPreferences prefe=getSharedPreferences("datos",Context.MODE_PRIVATE); String user = prefe.getString("user",""); postparameters2send.add(new BasicNameValuePair("user",user)); String URL_connect="http://"+IP_Server+"/pide_cerveza.php"; jdata=post.getserverdata(postparameters2send, URL_connect); if (jdata != null) { for (int i=0;i<jdata.length();i++){ try { Cerveza cerveza2 = new Cerveza(); cerveza2.setIdcerveza(jdata.getJSONObject(i).getInt("idcerveza")); cerveza2.setUsuario(jdata.getJSONObject(i).getString("usuario")); cerveza2.setAgua(jdata.getJSONObject(i).getString("agua")); cerveza2.setLevadura(jdata.getJSONObject(i).getString("levadura")); cerveza2.setFecha(jdata.getJSONObject(i).getString("fecha")); cerveza2.setTipo(jdata.getJSONObject(i).getString("tipo")); cerveza2.setIbu(jdata.getJSONObject(i).getInt("ibu")); cerveza2.setCantidad(jdata.getJSONObject(i).getDouble("cantidad")); cerveza2.setNombre(jdata.getJSONObject(i).getString("nombre")); cerveza2.setLupulo(jdata.getJSONObject(i).getString("lupulo")); cerveza2.setLupulo1(jdata.getJSONObject(i).getString("lupulo1")); cerveza2.setLupulo2(jdata.getJSONObject(i).getString("lupulo2")); cerveza2.setLupulo3(jdata.getJSONObject(i).getString("lupulo3")); cerveza2.setLupulo_porc(jdata.getJSONObject(i).getDouble("lupulo_porc")); cerveza2.setLupulo1_porc(jdata.getJSONObject(i).getDouble("lupulo1_porc")); cerveza2.setLupulo2_porc(jdata.getJSONObject(i).getDouble("lupulo2_porc")); cerveza2.setLupulo3_porc(jdata.getJSONObject(i).getDouble("lupulo3_porc")); cerveza2.setGrano(jdata.getJSONObject(i).getString("grano")); cerveza2.setGrano1(jdata.getJSONObject(i).getString("grano1")); cerveza2.setGrano2(jdata.getJSONObject(i).getString("grano2")); cerveza2.setGrano3(jdata.getJSONObject(i).getString("grano3")); cerveza_lista.add(cerveza2); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (jdata!=null && jdata.length() > 0){ Log.e("no es null","dentro del if"); JSONObject json_data; //creamos un objeto JSON try { json_data = jdata.getJSONObject(1); String cervezaArray=json_data.getString("Nombre");//accedemos al valor Log.e("longitud", "long= "+jdata.length()); Log.e("pruebaebeba","psaiaiaia= "+cervezaArray); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; }else{ //json obtenido invalido verificar parte WEB. Log.e("JSON ", "ERROR"); return false; } } ``` EDIT: My logcat log without print\_r($result) ``` 07-07 22:52:20.506: E/getpostresponse(17902): result= [["7","mouse","Barcelona","Abbey IV Ale Yeast","0000-00-00 00:00:00","Ale","11","20","prueba","Admiral","Ahtanum","vacio","vacio","80","20","vacio","vacio","Amber Dry Extract","Biscuit Malt","vacio"],["8","mouse","Barcelona","Abbey IV Ale Yeast","0000-00-00 00:00:00","Ale","50","8","prueba2","Ahtanum","vacio","vacio","vacio","100","vacio","vacio","vacio","Black (Patent) Malt","vacio","vacio"],["9","mouse","Valencia","Abbey Ale","0000-00-00 00:00:00","Lager","33","4","prueba3","Admiral","vacio","vacio","vacio","100","vacio","vacio","vacio","Aromatic Malt","vacio","vacio"]] 07-07 22:52:20.506: E/DEspues de recibir jdata(17902): fail 07-07 22:52:20.516: W/System.err(17902): org.json.JSONException: Value ["7","mouse","Barcelona","Abbey IV Ale Yeast","0000-00-00 00:00:00","Ale","11","20","prueba","Admiral","Ahtanum","vacio","vacio","80","20","vacio","vacio","Amber Dry Extract","Biscuit Malt","vacio"] at 0 of type org.json.JSONArray cannot be converted to JSONObject 07-07 22:52:20.516: W/System.err(17902): at org.json.JSON.typeMismatch(JSON.java:100) 07-07 22:52:20.516: W/System.err(17902): at org.json.JSONArray.getJSONObject(JSONArray.java:514) 07-07 22:52:20.516: W/System.err(17902): at test.Droidlogin.HiScreen.cervezastatus(HiScreen.java:302) 07-07 22:52:20.516: W/System.err(17902): at test.Droidlogin.HiScreen$asynccerveza.doInBackground(HiScreen.java:200) 07-07 22:52:20.516: W/System.err(17902): at test.Droidlogin.HiScreen$asynccerveza.doInBackground(HiScreen.java:1) 07-07 22:52:20.516: W/System.err(17902): at android.os.AsyncTask$2.call(AsyncTask.java:288) 07-07 22:52:20.516: W/System.err(17902): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 07-07 22:52:20.516: W/System.err(17902): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 07-07 22:52:20.516: W/System.err(17902): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 07-07 22:52:20.516: W/System.err(17902): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 07-07 22:52:20.516: W/System.err(17902): at java.lang.Thread.run(Thread.java:841) 07-07 22:52:20.516: W/System.err(17902): org.json.JSONException: Value ["8","mouse","Barcelona","Abbey IV Ale Yeast","0000-00-00 00:00:00","Ale","50","8","prueba2","Ahtanum","vacio","vacio","vacio","100","vacio","vacio","vacio","Black (Patent) Malt","vacio","vacio"] at 1 of type org.json.JSONArray cannot be converted to JSONObject 07-07 22:52:20.516: W/System.err(17902): at org.json.JSON.typeMismatch(JSON.java:100) 07-07 22:52:20.516: W/System.err(17902): at org.json.JSONArray.getJSONObject(JSONArray.java:514) 07-07 22:52:20.516: W/System.err(17902): at test.Droidlogin.HiScreen.cervezastatus(HiScreen.java:302) 07-07 22:52:20.516: W/System.err(17902): at test.Droidlogin.HiScreen$asynccerveza.doInBackground(HiScreen.java:200) 07-07 22:52:20.516: W/System.err(17902): at test.Droidlogin.HiScreen$asynccerveza.doInBackground(HiScreen.java:1) 07-07 22:52:20.516: W/System.err(17902): at android.os.AsyncTask$2.call(AsyncTask.java:288) 07-07 22:52:20.516: W/System.err(17902): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 07-07 22:52:20.516: W/System.err(17902): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 07-07 22:52:20.516: W/System.err(17902): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 07-07 22:52:20.516: W/System.err(17902): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 07-07 22:52:20.516: W/System.err(17902): at java.lang.Thread.run(Thread.java:841) 07-07 22:52:20.526: W/System.err(17902): org.json.JSONException: Value ["9","mouse","Valencia","Abbey Ale","0000-00-00 00:00:00","Lager","33","4","prueba3","Admiral","vacio","vacio","vacio","100","vacio","vacio","vacio","Aromatic Malt","vacio","vacio"] at 2 of type org.json.JSONArray cannot be converted to JSONObject 07-07 22:52:20.526: W/System.err(17902): at org.json.JSON.typeMismatch(JSON.java:100) 07-07 22:52:20.526: W/System.err(17902): at org.json.JSONArray.getJSONObject(JSONArray.java:514) 07-07 22:52:20.526: W/System.err(17902): at test.Droidlogin.HiScreen.cervezastatus(HiScreen.java:302) 07-07 22:52:20.526: W/System.err(17902): at test.Droidlogin.HiScreen$asynccerveza.doInBackground(HiScreen.java:200) 07-07 22:52:20.526: W/System.err(17902): at test.Droidlogin.HiScreen$asynccerveza.doInBackground(HiScreen.java:1) 07-07 22:52:20.526: W/System.err(17902): at android.os.AsyncTask$2.call(AsyncTask.java:288) 07-07 22:52:20.526: W/System.err(17902): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 07-07 22:52:20.526: W/System.err(17902): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 07-07 22:52:20.526: W/System.err(17902): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 07-07 22:52:20.526: W/System.err(17902): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 07-07 22:52:20.526: W/System.err(17902): at java.lang.Thread.run(Thread.java:841) 07-07 22:52:20.526: E/no es null(17902): dentro del if 07-07 22:52:20.526: W/System.err(17902): org.json.JSONException: Value ["8","mouse","Barcelona","Abbey IV Ale Yeast","0000-00-00 00:00:00","Ale","50","8","prueba2","Ahtanum","vacio","vacio","vacio","100","vacio","vacio","vacio","Black (Patent) Malt","vacio","vacio"] at 1 of type org.json.JSONArray cannot be converted to JSONObject 07-07 22:52:20.526: W/System.err(17902): at org.json.JSON.typeMismatch(JSON.java:100) 07-07 22:52:20.526: W/System.err(17902): at org.json.JSONArray.getJSONObject(JSONArray.java:514) 07-07 22:52:20.526: W/System.err(17902): at test.Droidlogin.HiScreen.cervezastatus(HiScreen.java:336) 07-07 22:52:20.526: W/System.err(17902): at test.Droidlogin.HiScreen$asynccerveza.doInBackground(HiScreen.java:200) 07-07 22:52:20.526: W/System.err(17902): at test.Droidlogin.HiScreen$asynccerveza.doInBackground(HiScreen.java:1) 07-07 22:52:20.526: W/System.err(17902): at android.os.AsyncTask$2.call(AsyncTask.java:288) 07-07 22:52:20.526: W/System.err(17902): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 07-07 22:52:20.526: W/System.err(17902): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 07-07 22:52:20.526: W/System.err(17902): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 07-07 22:52:20.536: W/System.err(17902): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 07-07 22:52:20.536: W/System.err(17902): at java.lang.Thread.run(Thread.java:841) ``` EDIT 2: My function ``` public function cervezas($user){ //Obtenemos el idusuario en funcion al nombre de usuario que nos pasan $iduser_aux = mysql_query("SELECT idusuario FROM usuarios WHERE username='".$user."'")or die("query failed"); $id_user_res = mysql_fetch_row($iduser_aux); $iduser = $id_user_res[0]; //Creamos vector inicializando todos los valores a "". Este será el vector a devolver al final. /* 0->idcerveza, 1->usuario, 2->agua, 3->levadura, 4->fecha, 5->tipo, 6->ibu, 7->cantidad, 8->nombre, 9->lupulo, 10->lupulo1, 11->lupulo2, 12->lupulo3, 13->lupulo_porc, 14->lupulo1_porc, 15->lupulo2_porc, 16->lupulo3_porc, 17->grano, 18->grano1, 19->grano2, 20->grano3 */ $array = array( array("vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio"), array("vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio"), array("vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio", "vacio"), ); //Seleccionamos todas las cerverzas que ha creado un usuario. Puede ser 0,1 o muchas $cervezas_aux = mysql_query("SELECT c.idcerveza, (SELECT username FROM usuarios WHERE idusuario='".$iduser."') usuario, (SELECT Ciudad FROM agua WHERE idagua=c.idagua) agua, (SELECT Nombre FROM levadura WHERE idlevadura=c.idlevadura) levadura, c.fecha, c.tipo, c.ibu, c.cantidad, c.nombre FROM cerveza c WHERE idusuario='".$iduser."'")or die("Query failed"); //$cervezas = mysql_fetch_array($cervezas_aux); $t=0; $i=0; while($row = mysql_fetch_object($cervezas_aux)){ //echo $row->idcerveza; $array[$t][0] = $row->idcerveza;//Metemos idcerveza en el array $array[$t][1] = $row->usuario;//Metemos usuario en el array $array[$t][2] = $row->agua; $array[$t][3] = $row->levadura;//Metemos levadura en el array $array[$t][4] = $row->fecha;//Metemos fecha en el array $array[$t][5] = $row->tipo;//Metemos tipo en el array $array[$t][6] = $row->ibu;//Metemos ibu en el array $array[$t][7] = $row->cantidad;//Metemos cantidad en el array $array[$t][8] = $row->nombre;//Metemos nombre en el array //$t++; // } //$i=0; //foreach((array) $cervezas_aux as $cerveza ){ //Como solo nos falta por meter el lupulo, porcentaje y grano, debemos consultar primero cuanto hay de cada tipo $lupulo_cont = mysql_query("SELECT COUNT(l.idlupulo) FROM cerveza c, lupulo_has_cerveza l WHERE c.idcerveza = l.idcerveza AND l.idcerveza = '".$array[$t][0]."' ")or die("Query failed1"); $count_lupulo = mysql_fetch_row($lupulo_cont); $grano_cont = mysql_query("SELECT COUNT(g.idgrano) FROM cerveza c, cerveza_has_grano g WHERE c.idcerveza = g.idcerveza AND g.idcerveza = '".$array[$t][0]."' ")or die("Query failed2"); $count_grano = mysql_fetch_row($grano_cont); if($count_lupulo[0] >= 1 && $count_grano[0] >= 1){ $lupulos = mysql_query("SELECT (SELECT Nombre FROM lupulo WHERE idlupulo = l.idlupulo) lupulo, l.porcentaje FROM cerveza c, lupulo_has_cerveza l WHERE c.idcerveza = l.idcerveza AND l.idcerveza = '".$array[$t][0]."' "); $cont_l = 1; //foreach((array) $lupulos as $z=>$lupulo ){ while($lu = mysql_fetch_object($lupulos)){ if($count_lupulo[0] == 1){ $array[$i][9] = $lu->lupulo; $array[$i][13] = $lu->porcentaje; }else if($count_lupulo[0] == 2){ if($cont_l == 1){ $array[$i][9] = $lu->lupulo; $array[$i][13] = $lu->porcentaje; $cont_l++; }else{ $array[$i][10] = $lu->lupulo; $array[$i][14] = $lu->porcentaje; $cont_l = 1; } }else if($count_lupulo[0] == 3){ if($cont_l == 1){ $array[$i][9] = $lu->lupulo; $array[$i][13] = $lu->porcentaje; $cont_l++; }else if($cont_l == 2){ $array[$i][10] = $lu->lupulo; $array[$i][14] = $lu->porcentaje; $cont_l++; }else{ $array[$i][11] = $lu->lupulo; $array[$i][15] = $lu->porcentaje; $cont_l = 1; } }else if($count_lupulo[0] == 4){ if($cont_l == 1){ $array[$i][9] = $lu->lupulo; $array[$i][13] = $lu->porcentaje; $cont_l++; }else if($cont_l == 2){ $array[$i][10] = $lu->lupulo; $array[$i][14] = $lu->porcentaje; $cont_l++; }else if($cont_l == 3){ $array[$i][11] = $lu->lupulo; $array[$i][15] = $lu->porcentaje; $cont_l++; }else{ $array[$i][12] = $lu->lupulo; $array[$i][16] = $lu->porcentaje; $cont_l = 1; } } } $granos = mysql_query("SELECT (SELECT Nombre FROM grano WHERE idgrano = g.idgrano) grano FROM cerveza c, cerveza_has_grano g WHERE c.idcerveza = g.idcerveza AND g.idcerveza = '".$array[$t][0]."' "); $cont_g = 1; //foreach((array) $granos as $j=>$grano ){ while($gr = mysql_fetch_object($granos)){ if($count_grano[0] == 1){ $array[$i][17] = $gr->grano; }else if($count_grano[0] == 2){ if($cont_g == 1){ $array[$i][17] = $gr->grano; $cont_g++; }else{ $array[$i][18] = $gr->grano; $cont_g = 1; } }else if($count_grano[0] == 3){ if($cont_g == 1){ $array[$i][17] = $gr->grano; $cont_g++; }else if($cont_g == 2){ $array[$i][18] = $gr->grano; $cont_g++; }else{ $array[$i][19] = $gr->grano; $cont_g = 1; } }else if($count_grano[0] == 4){ if($cont_g == 1){ $array[$i][17] = $gr->grano; $cont_g++; }else if($cont_g == 2){ $array[$i][18] = $gr->grano; $cont_g++; }else if($cont_g == 3){ $array[$i][19] = $gr->grano; $cont_g++; }else{ $array[$i][20] = $gr->grano; $cont_g = 1; } } } } $i++; $t++; } //print_r($array); return $array; } ``` EDIT 3: I change array declaration: $array = array(); instead of $array = array( array("vacio", "vacio", ...). And now i recieve a result like JSON Format: ``` result= [{"0":"7","1":"mouse","2":"Barcelona","3":"Abbey IV Ale Yeast","4":"0000-00-00 00:00:00","5":"Ale","6":"11","7":"20","8":"prueba","9":"Admiral","13":"80","10":"Ahtanum","14":"20","17":"Amber Dry Extract","18":"Biscuit Malt"},{"0":"8","1":"mouse","2":"Barcelona","3":"Abbey IV Ale Yeast","4":"0000-00-00 00:00:00","5":"Ale","6":"50","7":"8","8":"prueba2","9":"Ahtanum","13":"100","17":"Black (Patent) Malt"},{"0":"9","1":"mouse","2":"Valencia","3":"Abbey Ale","4":"0000-00-00 00:00:00","5":"Lager","6":"33","7":"4","8":"prueba3","9":"Admiral","13":"100","17":"Aromatic Malt"}] ``` But still throwing me error because there are missing keys. But format is right(I think). If i do this: ``` $array[$t][9] = $vacio; $array[$t][10] = $vacio; $array[$t][11] = $vacio; $array[$t][12] = $vacio; $array[$t][13] = $vacio; $array[$t][14] = $vacio; $array[$t][15] = $vacio; $array[$t][16] = $vacio; $array[$t][17] = $vacio; $array[$t][18] = $vacio; $array[$t][19] = $vacio; $array[$t][20] = $vacio; ``` The array format change again to an Array format. Please, i need your help. I don't know what can i do anymore. Thank you.
2014/07/07
[ "https://Stackoverflow.com/questions/24618610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480270/" ]
To begin with, you probably want the `-directory` option rather than the `-path` option. It can be abbreviated to `-dir`. Also, you wanted the files matching `*.tcl`, not every file (`*`). ``` foreach dir [glob -type d *] { glob -dir $dir *.tcl } ``` Second, the `foreach` command does not collect the results of the script it runs, so you need to do that yourself: ``` set files [list] foreach dir [glob -type d *] { lappend files {*}[glob -dir $dir *.tcl] } ``` Now the `files` variable should hold the file names you want. If you're using an older version of Tcl (before 8.5), you need to write it like this: ``` set files [list] foreach dir [glob -type d *] { set files [concat $files [glob -dir $dir *.tcl]] } ``` Documentation: [concat](http://www.tcl.tk/man/tcl/TclCmd/concat.htm), [foreach](http://www.tcl.tk/man/tcl/TclCmd/foreach.htm), [glob](http://www.tcl.tk/man/tcl/TclCmd/glob.htm), [lappend](http://www.tcl.tk/man/tcl/TclCmd/lappend.htm), [set](http://www.tcl.tk/man/tcl/TclCmd/set.htm)
4,555,055
I have a repository method that accepts an order by parameter in the form: ``` public IEnumerable<TEntity> Get<TEntity>(Expression<Func<TEntity,string>> orderBy) ``` Now that works fine when trying to sort by a property of type string, ``` var entities = rep.Get(x => x.Name); ``` but what if i want to sort by double or int or any other type. Doing something like `var entities = rep.Get(x => x.Price);` obviously throws a compile error saying I can't convert double to string. How can I make this more generic so I can sort by any property in my entity, or at least the properties where the type implements IComparable or something similar?
2010/12/29
[ "https://Stackoverflow.com/questions/4555055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2849/" ]
``` public IEnumerable<TEntity> Get<TEntity, TOrderBy>(Expression<Func<TEntity,TOrderBy>> orderBy) ```
53,676,235
My software builds use `-Xlint -Werror` so I routinely run across compiler warnings that break my build. Every once in a while I run across a warning that I need to suppress, but it's always difficult to figure out which `Xlint` option suppresses the warning I am seeing. I'll give you a concrete example. I recently ran across: ``` [WARNING] module-info.java:[16,106] module not found: org.bitbucket.cowwoc.requirements.guava ``` I searched the JDK 11 source-code and discovered this warning message declared at `/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties` as: ``` # 0: symbol compiler.err.module.not.found=\ module not found: {0} ``` Now, it turns out that this is suppressed by `-Xlint:-module` but that's not obvious from the documentation. `-Xlint:-export` could made sense as well. I've also run across warnings in the past that couldn't be suppressed at all (these were subsequently fixed). Instead of resorting to trial and error, **is there a deterministic way to figure out which `Xlint` option corresponds to each warning message**? Is there some sort of mapping file somewhere in the JDK source codes? **UPDATE**: I am using Maven 3.6.0, maven-compiler-plugin 3.8.0, JDK 11.0.1
2018/12/07
[ "https://Stackoverflow.com/questions/53676235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14731/" ]
One way to do that, if somehow you're not able to access the [online documentation](https://docs.oracle.com/en/java/javase/11/tools/javac.html#GUID-AEEC9F07-CB49-4E96-8BC7-BCC2C7F725C9) could be using the command ``` javac --help-extra ``` This would list out the possible warnings that you could enable/disable. For example from ***`javac 12-ea`*** : [![enter image description here](https://i.stack.imgur.com/W44GG.png)](https://i.stack.imgur.com/W44GG.png)
31,929,963
On my html page I have a button, and a number being displayed. I want the number to increase by 1 every time the button is pressed. This is the code that I have so far, but for some it doesn't work. mypage.html ```html <form method='get' action='#'> <input type="submit" value="add" name="add"/> </form> <h1>{{ p }}</h1> ``` views.py ```python p = 1 def mypage(request): global p my_dictionary = { "p" : p, } if request.GET.get('add'): p = p+1 my_dictionary = { "p" : p, } return render(request, "mypage.html", my_dictionary) ```
2015/08/10
[ "https://Stackoverflow.com/questions/31929963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5131031/" ]
On every request a new instance of the python script is run which would result in your global variable not being retained. You should store the count in a database and recall the value on every request. There are options other than a database but the basic idea of needing some sort of persistent storage still exists. Alternatively, you can have the requester keep track of the count and provide the current count in the request. You would then add one to the value provided in the request. This would require some additional code on the front end to maintain the count, and even then, if the user closes the browser the count will be reset. As dm03514 pointed out, you can can also use sessions like so: ``` if 'p' in request.session: request.session['p'] = request.session['p'] + 1 else: request.session['p'] = 1 ```
196,904
Without warning, a wizard casts *telepathy* targeting a friend who is on a different continent. > > You create a telepathic link between yourself and a willing creature with which you are familiar. > > > How is it decided whether the target is willing? Does the wizard get 6 seconds to quickly introduce herself? Does the target "feel" a "friend request/phone call" and envision the caster in their head and then decide whether to let them in/answer? I wondered if the spell assumes the target is willing until the target decides otherwise, but there is no option for the target to end the spell.
2022/03/18
[ "https://rpg.stackexchange.com/questions/196904", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/46827/" ]
### Short answer, you will need to establish an agreement ahead of time. As the check occurs before the connection is ever established. This is apparently not a spell used for cold calling. As explained by @Fie (emphasis theirs) > > according to the spell targetting rules in XGE (pp. 85–6), the validity of the target (i.e. whether the creature is willing) must be determined *before* the spell has any effect (including the target recognising you as the creature it ***is* communicating** with). > > > Meaning that though you are familiar with the target, they must be willing to receive your message before they receive it. A short conversation among friends can be had, "Hey, is it ok if I use telepathy to communicate with you in the future?" to establish that willingness in some regard ahead of time. If the target for some reason becomes unwilling, the spell will fail without contact ever being established and the target not realizing you attempted to reach them. Perhaps they are busy at the moment, but that doesn't stop them from later being willing once more. **The Willingness check will occur before connection is made on casting the spell.** Alternatively, there may be a discussion on the hypothetical, * "if A somehow knew that it was B calling, would they accept the call?" willingness being applied that way, as they are willing in this case. But it is unclear if the question instead is, * "are they willing to accept an unknown call before knowing who sent the request?" which might not be the same willingness. Could be stated more clearly in either case. Curious though, the duration *is 24 hours* without an off switch *other than* moving to another plane of existence. Once the spell succeeds, the willingness of the creature to continue the link is seemingly **no longer** considered.
66,273,005
I am trying to integrate my spring boot application with docusign for sending the documents and getting it signed from the users. I am not able to do it because I am not getting as how to get the JWT token to call the API's. I have downloaded the java code example from the docusign and configured accordingly. I am able to call the API's from the postman properly, But when I call any API from my application by rest template it gives me 302 redirect found. Is there any example project with java available for this ? Am I missing something.
2021/02/19
[ "https://Stackoverflow.com/questions/66273005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6057802/" ]
I have figured out the solution myself. It's the issue with the session management and security in the example code. If I call any API from rest template there is no session at the beginning and it requires a JWT. So I need to pass a session Id in the header which is active and holds the value of the current user.
1,679,371
I have an ID (number format) that has trailing decimals in the source data. I need to retain the rounded number (see example attached) and have the trailing decimals removed from the data. The decimals are causing upload issues/error into a system that I use. I have tried formatting to number and removing decimal places, =INT, =ROUND, etc and I can get the cell view to reflect what I want but when I click on the cell, the formula bar still appears to retain the trailing decimals. How do I remove these? Thanks in advance! [![Example](https://i.stack.imgur.com/n3kOe.jpg)](https://i.stack.imgur.com/n3kOe.jpg)
2021/10/01
[ "https://superuser.com/questions/1679371", "https://superuser.com", "https://superuser.com/users/-1/" ]
All of IP addresses 1 - 7 may well exist only between your laptop and the 4G modem. As the whole path is wired, there's no way to set up a MITM in between; unless there's another way to access your firewall. The 4G modem requires connection to a service provider, and it will only connect to the provider who provided the SIM Card, so a MITM in between the modem and the service provider is also extremely unlikely. Tunnels in this context have nothing to do with caching, they're just a way to route traffic in a specific way. To quote [Wikipedia](https://en.wikipedia.org/wiki/IP_tunnel): > > An IP tunnel is an Internet Protocol (IP) network communications channel between two networks. It is used to transport another network protocol by encapsulation of its packets. > > > Usually tunnels are used because it simplifies the routing one way or another. In this context something may be internally configured to use a tunnel, for example the Ethernet-over-USB interface that connects the modem to the firewall. Can't say much more than that without knowing more of the setup; the hardware and the configuration. Connection refused has nothing to do with port 80, only the fact that your client isn't authorized to connect to that tunnel.
24,399,292
I have made a client-server application which can connect over the internet. I have hard coded in my client the server's IP which is fixed. My question is that I want a way that will not take a lot of processing and memory. I want my client to check if internet is available and then try to connect to the server if its up and running. If not then to wait and try again. Keeping in mind that the app is supposed to always run on your computer 24/7 and connect when possible just like skype does, in the sense that its always on and when you have the internet available and server reachable , it connects. My client's code that connects to the server: ``` private void connectToServer() throws Exception { showMessage("Attempting Connection... \n"); try{ connection = new Socket(InetAddress.getByName(serverIP), 6789); showMessage("Ok dude you are Connected to:" + connection.getInetAddress().getHostName());} catch(IOException e){ int x = 0; while (true){ try { showMessage("Sorry Your IP was not found, \nAutomatic detection:"); showMessage("Now trying again"); connection = new Socket(InetAddress.getByName(serverIP),6789); break; } catch (UnknownHostException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); showMessage("\nConnection not established, trying again\n"); } /*x++; if(x>10) break;*/ } //throw new Exception(); } } ``` This does work but takes a lot of processing and memory ! I know that by adding thread.sleep(5000), I am going to add them eventually etc... But this doesn't solve the memory problem. My program would be running for a long time and this doesn't stop the inevitable. Is there a better way? THANKS P.S : showMessage() is just my function that displays the output on my GUI The way I checked memory was using Window's Task Manager ! (the memory increases drastically)
2014/06/25
[ "https://Stackoverflow.com/questions/24399292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3677907/" ]
An array of T when used in most expressions will decay to a pointer of type "pointer to T" and have the value equal to the address of the first element of the array. If `Str` is declared as: ``` char Str[3][5]; ``` Then `Str` will decay to `char (*)[5]`, and have the value of `&Str[0]`. If passing to a function, you can declare the function as follows: ``` void foo (char (*str)[5], size_t n); ``` And within `foo()`, you would access `str` as you would access `Str` itself.
48,479,065
I have a code given below. when I run the code, all x1,x2 and x3 having same values.As per logic x1 should have random numbers, x2 also random numbers , x3 should have 0s and 1s. ``` import numpy as np def reluDerivative(x): yy=x; yy[yy<=0] = 0 yy[yy>0] = 1 return yy x1=np.random.uniform(-1, 1,10) x2=x1 x3=reluDerivative(x1) ```
2018/01/27
[ "https://Stackoverflow.com/questions/48479065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7425709/" ]
You should think of python variables as **labels**, hence when you do `x2=x1` you are just creating a new label for the same data in memory, this differs in behaviour for mutable and immutable objects, for example: ``` x1 = [] x2 = x1 x2.append(10) print(x2) print(x1) ``` will result on printing: ``` [10] [10] ``` Because both `x2` and `x1` are labeling the same list. This is the behaviour for mutable objects, for immutable objects: ``` x1 = 10 x2 = x1 x2 += 5 print(x2) print(x1) ``` will print: ``` 15 10 ``` Because in this case `x2` is re-assigned to label the new created `15` due to the `+` operation. The solution is just to copy the data from the original object (for your numpy object): ``` x2 = np.copy(x1) ```
65,838,713
I was looking to download kdiff for windows from <https://download.kde.org/stable/kdiff3/> and I noticed the latest package is kdiff3-1.8.5-windows-64-cl.exe while the next-latest is kdiff3-1.8.4-windows-64.exe Does the -cl signify anything like a library I need or stability or ??? There is 0 documentation that I can find on how to download and install anything later than 0.9.98. Couldn't find any clue on the project site <https://invent.kde.org/sdk/kdiff3> about the -cl and I couldnt figure out how to ask there ... Loading up a new computer and reluctant to add something that seems a little like it might have special requirements or caveats. thanks!
2021/01/22
[ "https://Stackoverflow.com/questions/65838713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2407039/" ]
It was built using the MSVC command line compiler (cl.exe) that comes with Visual Studio. See: <https://learn.microsoft.com/en-us/cpp/build/reference/compiler-options?view=msvc-160>
10,751,076
I'm new to django and for practice I'm trying to program my own version of the all familiar 'todo list' app. I have some page that displays all todo list items the user has entered, along with a button to edit each one. The edit button sends the user to another page with a form to enter in the changes to the item. It's possible for the user to change everything about the item. Obviously request.POST gives me all the information the user just put into the form, but I want this information to rewrite the info of the item they originally clicked on. So how do I write the view code to find out what that original item was? I guess I could format my form submit button to: > > `<button type="submit" name="save" value={{ item.pk }}>Save</button>` > > > and get the primary key that way but lets say I had passed two items to the edit page and I wanted to give the user the ability to combined them. Again, I *could* figure out what those items were by doing: > > `<button type="submit" name="save" value='{{ item1.pk }} {{ item2.pk }}'>Save</button>` > > > then > > `request['save'].split(' ')` > > > this seems kinda stupid though. Is there some other, less brute force, way? like a: > > request.tell\_me\_all\_items\_passed\_to\_the\_template > > > kind of thing?
2012/05/25
[ "https://Stackoverflow.com/questions/10751076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1322179/" ]
In case someone else has the same question **So instead of doing this:** *template* ``` <form method="post" action="/list/saving/"> <!--- form fields ---> <button type="submit" name="save" value='{{ item.pk }}'>Save</button> </form> ``` *url.py* ``` (r'^list/saving/$', save) ``` *views.py* ``` def save(request): .... item = Item.objects.get(pk=request.POST['save']) .... ``` **do this:** *template* ``` <form method="post" action="{% url todolist.views.save item.pk %}"> <!--- form fields ---> <button type="submit" name="save">Save</button> </form> ``` *url.py* ``` (r'^list/saving/(\d+)/$', save) ``` *views.py* ``` def save(request, pk): .... item = Item.objects.get(pk=pk) .... ``` [More info on url reversing](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#url)
356,472
What do the matching "L" shapes (near `.5` and `20`) mean in this forumla? ![fomula with unknown symbols](https://i.stack.imgur.com/MoxWg.png) The document where I found this formula can be found here: <http://www.cs.cmu.edu/~hcwong/Pdfs/icip02.ps>
2013/04/09
[ "https://math.stackexchange.com/questions/356472", "https://math.stackexchange.com", "https://math.stackexchange.com/users/13360/" ]
The bracketing symbol means Floor (see <http://en.wikipedia.org/wiki/Floor_and_ceiling_functions>) The definition of Floor is $\lfloor x \rfloor$ = Largest integer less than x. This is very similar to rounding down as $\lfloor 2.3 \rfloor = \lfloor 2.999 \rfloor = 2$. However, the subtlety is that for negative numbers it acts slightly differently, as $\lfloor -1.5 \rfloor = -2$ which might not be what you expect at first.
4,346,191
hey :) ok im looking for a way to create a large number of panels in wxpython and append a hold to them in a list but am not sure how best to do this. for example for i in list: wx.Panel(self, -1, pos, size) #create the panel somehow store a hold to it e.g ============================== anotherlist.append(a) #where a is the hold to the panel when i say hold i mean say the variable name is x, so x = wx.Panel. i would call x the hold cos x can be used for any manipulation of the widget, e.g x.SetPosition etc.. i was thinking maybe using a class something(wx.Panel) that creates the panel and saves the id of the panel.. problem is having the id i have no idea how to access the widget. say the panels id is -206. how do i do something like widgetid(-206).SetBackgroundColour("RED")
2010/12/03
[ "https://Stackoverflow.com/questions/4346191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527204/" ]
Some people solve these sorts of things by creating the ids at the beginning of the file: ``` panelOneId = wx.NewId() panelTwoId = wx.NewId() ``` And then doing something like myPanel = wx.FindWindowById(panelOneId). Of course, if all you're doing is setting panel attributes, it might just behoove you to create a helper method like this: ``` #---------------------------------------------------------------------- def createPanel(self, sizer, id, bg): """""" panel = wx.Panel(self, id=id) panel.SetBackgroundColour(bg) sizer.Add(panel) ``` You can also use wx.FindWindowByName, if you've given the panels unique name parameters.
49,152,669
I have an android app that gets my devices location and adds a marker. It also tracks the location and the marker moves. I want to add a marker on the map each time the location changes, so I can then draw a Polyline between them at a later date. I am not using firebase or a DBHelper. Just looking for a simple way to do it. This is the onLocationChanged function ``` @Override public void onLocationChanged(Location location) { LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude()); LocationMarker.setPosition(myCoordinates); mMap.moveCamera(CameraUpdateFactory.newLatLng(myCoordinates)); float zoomLevel = 12.0f; mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myCoordinates, zoomLevel)); ``` } This is my onCreate function ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tracking); mOptions = new MarkerOptions().position(new LatLng(0, 0)).title("My Current Location") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission(); } // Gets map fragment and allows map to display location SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(map); mapFragment.getMapAsync(this); } ``` Is it possible to store the lat and long into an array and use the array to plot the points? I've been trying to get my head around it but there isn't a definitive
2018/03/07
[ "https://Stackoverflow.com/questions/49152669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9385851/" ]
I get the feeling that the reasons the other answers may not be working for you is that you are looking for how to SET the config, as opposed to retrieving it. If you don't have it already, you'll need to install the Firebase CLI, as per the steps in <https://firebase.google.com/docs/cli/> . with it installed, you can set up your config like so: `firebase functions:config:set algolia.app_id="YOUR_APP_ID_HERE"` You can set multiple variables at once by just separating them with spaces like so: `firebase functions:config:set algolia.api_id="YOUR_API_ID_HERE" algolia.search_key="YOUR_SEARCH_KEY_HERE"` To check you have the right config in there, you can also run: `firebase functions:config:get` Which should print out, in JSON format, the current config you have set.
676,518
C#: In the keydown event of a textbox, how do you detect currently pressed modifiers + keys? I did the following, but I'm not too familiar with these operators so I'm not sure if and what I'm doing wrong. ``` private void txtShortcut_KeyDown(object sender, KeyEventArgs e) { if (e.Modifiers == (Keys.Alt || Keys.Control || Keys.Shift)) { lbLogger.Items.Add(e.Modifiers.ToString() + " + " + "show non-modifier key being pressed here"); } } ``` 1) How would I check if e contains any modifier keys?
2009/03/24
[ "https://Stackoverflow.com/questions/676518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
according to msdn [linkt](http://support.microsoft.com/kb/839201) ``` private void txtShortcut_KeyDown(object sender, KeyEventArgs e) { if (e.Alt || e.Control || e.Shift)) { lbLogger.Items.Add(e.ToString() + " + " + "show non-modifier key being pressed here"); } } ```
3,003,349
The problem was this: radius is $2$, tangent to the $x$ axis, passes through $(1, -1)$. I don't know how to solve this, and my math teacher didnt teach this yet.
2018/11/18
[ "https://math.stackexchange.com/questions/3003349", "https://math.stackexchange.com", "https://math.stackexchange.com/users/617065/" ]
Given the conditions you gave, there is only two circle that works: their center is $\left(\begin{array}{cc} 1-\sqrt{3}\\ -2 \end{array}\right)$ and $\left(\begin{array}{cc} 1+\sqrt{3}\\ -2 \end{array}\right)$, their radius is $2$. So their respective equation are: $(x - 1+\sqrt{3})^2 + (y+2)^2 = 4$ and $(x-1-\sqrt{3})^2 + (y+2)^2 = 4$.
72,645,549
When I try to use `:syntax on` I get the following error: `E484: Can't open file C:\Program Files (x86)\Vim\vim82\gvim.exe\syntax\snytax.vim` When I explore the directory, I find that there is a syntax.vim at the directory: `C:\Program Files (x86)\Vim\vim82\syntax\syntax.vim` How do I get gVim to recognize that this is where it should look for the syntax files? I am using windows 10.
2022/06/16
[ "https://Stackoverflow.com/questions/72645549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9994156/" ]
I had the same problem. You have to set ~~$VIMRUNTIME~~ (Not this variable, as Stun Brick points out in the comment below.) as an environment variable. If you are using Windows 10, search on your compuer, "Edit the system environment variables" and you can set it.
56,854,614
[![enter image description here](https://i.stack.imgur.com/CGEth.png)](https://i.stack.imgur.com/CGEth.png)When I install redux-thunk it shows an error and you can see attached image for more info - npm ERR! Error: EPERM: operation not permitted, rename 'C:\Users\siddharth.vyas\Desktop\react-native\_Proj\AwesomeProject\node\_modules.staging\redux-thunk-069b38d0' -> 'C:\Users\siddharth.vyas\Desktop\react-native\_Proj\AwesomeProject\node\_modules\redux-thunk' And I have also try to install "redux-thunk" with the administrator but shows the same error. Pakage.json - "dependencies": { "axios": "^0.19.0", "react": "16.8.3", "react-native": "0.59.9", "react-native-loading-spinner-overlay": "^1.0.1", "react-redux": "^7.1.0", "redux": "^4.0.1", "redux-axios-middleware": "^4.0.0" }, "devDependencies": { "@babel/core": "7.4.5", "@babel/runtime": "7.4.5", "babel-jest": "24.8.0", "jest": "24.8.0", "metro-react-native-babel-preset": "0.54.1", "react-test-renderer": "16.8.3" },
2019/07/02
[ "https://Stackoverflow.com/questions/56854614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8039805/" ]
try removing node\_modules and do `npm install`. If it doesn't work, delete node\_modules, add "redux-thunk": "^2.3.0" to your dependencies, then run `npm install -i`
67,719
I'm currently following a tutorial to rig a character. All goes well until I go to Pose Mode to see if my rig moves (I can do that before or after doing the automatic weight things, it changes nothing). [![Pose Mode](https://i.stack.imgur.com/3kqsV.png)](https://i.stack.imgur.com/3kqsV.png) What happens is most strange: I select a bone and press `G`. The usual box with the colour arrows appear, I try to grab and move one of them and it turns into a `><` like that. [![Cursor Change](https://i.stack.imgur.com/9h0im.png)](https://i.stack.imgur.com/9h0im.png) So far I've only seen that whilst scaling in edit mode and it does nothing, same with rotating. I verified I do not have any lock on location or rotation for the chosen bone or it's neighbours. I also dont have the `ctrl` + `.` or snap to center turned on, I checked all I could in the manual and here and found nothing. I've spent the afternoon on this and it's driving me nuts. I haven't found anywhere on the net anyone who talked about a dead scale `><` cursor dragging and replacing the wheel and grab and scale box. I am following the free rig the biker tutorial on Digital Tutors and so far so good, I checked everything. I'm nearing nervous breakdown.
2016/11/21
[ "https://blender.stackexchange.com/questions/67719", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/32816/" ]
Judging from your second screenshot, I'd suppose you've got `Manipulate Center Points` activated. While this is useful on multiple selected objects or bones, when bones are **not** connected, it leads to the behavior you describe in your Question. See the GIF below on how to deactivate this feature: [![Manipulate Center Points](https://i.stack.imgur.com/e5R3T.gif)](https://i.stack.imgur.com/e5R3T.gif) The purpose of this feature is to **Translate** objects by using **Rotate** or **Scale** functions. In your case, as the bone is already a child of another bone, Translation channels are automatically locked already. That's why nothing happens.
19,097,562
Which is a better approach to building a complex object (eager loading). A single call to a stored procedure that returns multiple result sets or multiple calls to stored procedures with one result set each? I'm building my DAL using T4/text templates in .NET so I'm leaning towards to latter. Thanks!
2013/09/30
[ "https://Stackoverflow.com/questions/19097562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57106/" ]
For a pass to install, the following criteria have to be met: * The link must be https * The URL must return a valid `.pkpass` bundle * The `Content-Type` header must be `application/vnd.apple.pkpass` Unfortunately, these requirements are not yet documented, but they are mentioned in the WWDC session [What's new in Passbook](https://developer.apple.com/wwdc/videos/?id=302)
10,617,363
I have ``` SharedPreferences myPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); ``` and ``` myPreferences.getBoolean("checkbox", true) ``` So, how can my main activity know when user change preferences state? For example if user don't wont to get notifications any more. Thanks.
2012/05/16
[ "https://Stackoverflow.com/questions/10617363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159613/" ]
You could either re-read all the preferences in `Activity.onResume()`, or as long as your main activity launches the preferences activity (e.g. from a menu), you could launch with `startActivityForResult(Intent, int)` and re-read all the preferences in `onActivityResult(int, int, Intent)`. I have also found it sufficient to re-check each relevant preference before starting the appropriate behavior (i.e. before issuing the `Notification` for your example).
41,063,941
I am writing a Rule Engine based on ANTLR 4 for C# (I am using the [Sam Harwell alternative](https://github.com/tunnelvisionlabs/antlr4cs)) but I can't get my grammar correctly parsing my inputs about two rules very similar. There are probably several others mistakes, but I am stuck with this one for the moment. Also, I am new to ANTLR (except my old days in school ^^), so do not hesitate to give me some tips/explanations :). My goal are to interprete binary and numeric assignments such as: * `Fact := Fact1 OR Fact2` Behind the scene I want it to match the `bin_assign` rule. * `Fact := 8 * 4` Behind the scene I want it to match the `num_assign` rule. But my parser always matchs `num_assign` and failed matching the operator (because it is expecting a NUM\_OP or a EOF). You will see that those two rules start the same way with the FACT token. But my intuition tells me it is not the cause of the issue (as I say, I'm new to ANTLR, it is just my intuition). I wrote those two rules to avoid `Fact := 1 + true` being a right statment. Here are my grammars: 1. Common lexer rules: ``` lexer grammar Common; /* * Lexer Rules */ FACT: [a-zA-Z](([a-zA-Z0-9] | '.' | '_')*[a-zA-Z0-9])?; ASSIGN: ':='; LITERAL: '\'' .*? '\'' | '"' .*? '"'; WS : [ \t\r\n]+ -> skip; ``` 2. Numeric grammar: ``` grammar NumericGrammar; import Common; /* * Parser Rules */ num_stat: num_stat NUM_OP num_stat # ArithmeticStat | '(' num_stat ')' # ArithmeticBrakedStat | DIGIT # DigitStat | FACT # ArithmeticFactStat ; num_assign: FACT NUM_ASSIGN num_stat # ArithmeticAssign ; /* * Lexer Rules */ DIGIT: INT | FLOAT; INT: ([1-9][0-9]*)?[0-9]; FLOAT: INT(','|'.')[0-9]+; NUM_OP: MULT | DIV | ADD | SUB; MULT: '*'; DIV: '/'; ADD: '+'; SUB: '-'; NUM_ASSIGN: MULT_ASSIGN | DIV_ASSIGN | ADD_ASSIGN | SUB_ASSIGN | ASSIGN; MULT_ASSIGN: '*='; DIV_ASSIGN: '\\='; ADD_ASSIGN: '+='; SUB_ASSIGN: '-='; ``` 3. Binary grammar : ``` grammar BinaryGrammar; import NumericGrammar; /* * Parser Rules */ bin_stat: bin_stat BIN_OP bin_stat # BinaryStat | '(' bin_stat ')' # BinaryBrakedStat | NOT bin_stat # NegateStat | num_stat COMPARE_OP num_stat # CompareStat | FACT EQUALITY_OP (LITERAL | DIGIT) # LiteralComparisonStat | num_stat IN SET # IntervalComparisonStat | BOOL # BoolStat | FACT # BinaryFactStat ; bin_assign: FACT ASSIGN bin_stat # BinAssign ; /* * Lexer Rules */ BOOL: TRUE | FALSE; TRUE: '1' | 'true' | 'True' | 'YES' | 'Yes' | 'yes'; FALSE: '0' | 'false' | 'False' | 'NO' | 'No' | 'no'; BIN_OP: AND | OR | EQUALITY_OP; COMPARE_OP: EQUALITY_OP | GT | GTE | LT | LTE; AND: 'AND' | 'And' | 'and' | '&' | '&&'; OR: 'OR' | 'Or' | 'or' | '|' | '||'; EQUALITY_OP: EQUALITY | UNEQUALITY; EQUALITY: '=' | '=='; UNEQUALITY: '<>' | '!=' | '=/=' | '=\\='; GT: '>'; GTE: '>='; LT: '<'; LTE: '<='; NOT: '!' | 'NOT' | 'not'; IN: 'IN' | 'in'; SET: ('[' | ']') (INT | FLOAT) ';' (INT | FLOAT) ('[' | ']'); ``` 4. Final grammar: ``` grammar Test; import BinaryGrammar; /* * Parser Rules */ r: (IF bin_stat THEN)? assign EOF; assign: bin_assign | num_assign; /* * Lexer Rules */ IF: 'if' | 'IF' | 'If'; THEN: 'then' | 'THEN' | 'Then'; ``` Here a screenshot of the execution if needed:[![bad matching](https://i.stack.imgur.com/dPdX7.png)](https://i.stack.imgur.com/dPdX7.png)
2016/12/09
[ "https://Stackoverflow.com/questions/41063941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2183236/" ]
Using inconsistent naming of tokens makes analysis of the rules harder for you (parser/lexer won't mind). So it is just suggestion for easier (manual) reading the rules -- when I read my grammar, when I see two rules with different tokens all in caps (terminal) I know for sure they are different at that point. In your case you have to check that token if it is really terminal and if not, how it can unfold.
7,244,836
I have tabbar application, in first tab I have a webView, so when user open the website and going to download some song mp3 format, it push another View which takes the title from the user. after giving the title I just change the tabbarSelectController to one title for song and the downloading begins and shown on the tabbar at selected Index 1. when i change the tab to selected Index 0 and select another song for downloading and again back to selectedIndex 1 first downloading stop and 2nd downloading resume. so i want to download multiple songs and don't have much idea how to do that in this scenario because user add songs dynamically I have seen ASINtworkQueue as well but don't get the idea of how that works
2011/08/30
[ "https://Stackoverflow.com/questions/7244836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/868703/" ]
You may start using: m2e ( maven to eclipse integration ) -> <http://www.eclipse.org/m2e/> Eclipse WTP ( web tools platform ) -> <http://www.eclipse.org/webtools/> WTP will allow you to run Tomcat from eclipse and m2e will take care of converting your Maven build into Eclipse project and integrating it with WTP.
21,420,252
I have a live video stream from FFMpeg, and I am having a hard time viewing the stream using my own custom Java application. Before someone tells me to use VLC or something like that I do want to use my own application. The stream I am trying to read is a H.264 encoded Mpeg-ts stream streamed over UDP. I do know how to decode the H.264 frames, but I am simply wondering about how to receive the Mpeg-ts stream.
2014/01/29
[ "https://Stackoverflow.com/questions/21420252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1618141/" ]
Try this on: `d = collections.OrderedDict({ i:'*'*i for i in range(8) })` **EDIT** `pprint.pprint(list(d.items()))`
3,225,907
Is there an example for $\sum a\_nx^n$ with radius $R>0$ such that $a\_n \neq 0$ for some $n$ ($a\_n$ is not always $0$) but for all $x \in (-R,R)$ we have $\sum a\_nx^n=0$
2019/05/14
[ "https://math.stackexchange.com/questions/3225907", "https://math.stackexchange.com", "https://math.stackexchange.com/users/547001/" ]
Since the power series $g$ is convergent in the radius, it is infinitely times differentiable there. Since it is uniformly 0 there, it must have each of its derivatives be 0. Therefore, the constant term of $\frac{d^n}{dx^n}g$ must be 0 for all $n$. This implies that $a\_n=0$ for all $n$.
44,988,957
I am using geom\_smooth and it gives me default legend line color blue that I cannot use in the plot. Is there a way of changing the default color for geom\_smooth legend line? for example, I wand to change the legend colour to black for line type in the following plot ``` library(reshape2) library(ggplot2) d1<-melt(mtcars,id=c("mpg","cyl")) p<-ggplot(d1,aes(x=mpg,y=value,factor=variable,color=cyl)) p1<-p+geom_smooth(aes(linetype = as.factor(cyl)),se = F,stat = "smooth",method = "glm",size=.5, inherit.aes = T)+ scale_linetype_manual("line type",labels = rp, values=c(1,5,4,3)) ``` [![enter image description here](https://i.stack.imgur.com/84k2E.png)](https://i.stack.imgur.com/84k2E.png)
2017/07/08
[ "https://Stackoverflow.com/questions/44988957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4057644/" ]
Per my comment, if you add an override to your legend you can change how the color displays. This should work: ``` p1<-p+geom_smooth(aes(linetype = as.factor(cyl)),se = F,stat = "smooth",method = "glm",size=.5, inherit.aes = T)+ scale_linetype_manual("line type",labels = c("100 yr", "50 yr", "25 yr"), values=c(1,5,4,3)) + guides(linetype = guide_legend(override.aes= list(color = "black"))) ``` And the resulting plot is: [![enter image description here](https://i.stack.imgur.com/023d7.png)](https://i.stack.imgur.com/023d7.png)
36,912
I want to type "xy-plane" in a document so that it "looks right" when I print the document. (1) `xy-plane` does not look right to me. (2) `$xy-$plane` looks bad. (3) `$xy$-plane` looks ok, but I feel uneasy. What is the accepted convention for typing "xy-plane" in a (La)TeX document?
2011/12/02
[ "https://tex.stackexchange.com/questions/36912", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/7764/" ]
Here "x" and "y" are variables, so they have to go in math mode; the hyphen must go outside math mode. So ``` $xy$\nobreakdash-plane ``` Note that `\nobreakdash` is provided by the **amsmath** package; it disallows a break after the hyphen. Possible variation: ``` $x\,y$\nobreakdash-plane ``` where the two letters are slightly separated. Be consistent. You can define ``` \newcommand{\plane}[2]{$#1#2$\nobreakdash-plane} ``` and use it as `\plane{x}{y}`, if it appears with different letters. Or ``` \newcommand{\xyplane}{$x\,y$\nobreakdash-plane} ``` and use it as `\xyplane{}`. (I've used both variations, take your pick.)
2,353,902
I'm struggling in finding a closed form for, > > $$ \int\_0^\infty Ae^{-bx}\sin\left(\frac{2\pi}{T}x\right) \,dx $$ > > > *My Attempt:* Let $H = \int Ae^{-bx}\sin\left(\frac{2\pi}{T}x\right)\,dx$. First I integrate by parts, splitting $f=e^{-bx}$ and $dg=\sin\left(\frac{2\pi}{T}x\right)\,dx$. Then another IBP using $u=e^{-bx}$ and $dv = \cos\left(\frac{2\pi}{T}x\right)\,dx$ and simplify, \begin{align} \frac{2\pi}{A\cdot T} H &= -e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac 1 b \int \cos\left(\frac{2\pi}{T}x\right)e^{-bx}\,dx \\ \frac{2\pi}{A\cdot T} H &= -e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac 1 b \left[ e^{-bx}\frac{T}{2\pi}\sin\left(\frac{2\pi}{T}x\right) + \frac{T}{2\pi b}\int e^{-bx}\sin\left(\frac{2\pi}{T}x\right)\,dx \right] \\ \left(\frac{2\pi}{A\cdot T} - \frac{T}{2\pi b^2}\right)H &= e^{-bx}\cos\left(\frac{2\pi}{T}x\right) - \frac{T}{2\pi b} e^{-bx} \sin\left(\frac{2\pi}{T}x\right) \\ H &= -e^{-bx} \left(\cos\left(\frac{2\pi}{T}x\right) + \frac{T}{2\pi b}\sin\left(\frac{2\pi}{T}x\right) \right) \cdot \left( \frac{A\cdot T 2\pi b^2}{(2\pi b)^2 - A\cdot T^2}\right) + c\\ \end{align} First off, is this horrid looking expression correct? If so, can it be simplified further? Now I come to evaluate $H|\_0^\infty$. $H$ appears to be defined at $x=0$, so I really just need to find $\lim\_{x\to \infty^+} H$. Here is where I'm stuck. The denominator grows exponentially for $b\ge 1$, and $T$ and $A$ don't seem to have any effect on the limit. How should I evaluate this limit?
2017/07/10
[ "https://math.stackexchange.com/questions/2353902", "https://math.stackexchange.com", "https://math.stackexchange.com/users/274085/" ]
If you differentiate $f(x)$, you should end up with $f'(x) = 4x^3 - 12x^2-4x+12$ which you can factor as $f'(x) = 4\cdot[x^2(x-3) -(x-3)]=4(x^2-1)(x-3)$. Assess whether each of the roots of $f'(x)$ corresponds to a minimum or a maximum of $f$, or neither. Deduce that $f$ has two global minima which are positive at $x = 3$ and $x=-1$. Since $f(x)\to+\infty$ as $|x|\to+\infty$, conclude that $f$ has no real roots. --- **Edit:** The factorization of $f'(x)$: \begin{align\*} 4x^3-12x^2-4x+12 &= (4x-12)x^2-4(x-3) \\ &= 4(x-3)x^2-4(x-3) \\ &= 4\cdot[x^2(x-3)-(x-3)]. \end{align\*}
8,871,253
In my project I have a simple `UIView` with a `UIScrollView` subview. I am trying to calculate the height based on the content within the `UIScrollView` with the following code: ![enter image description here](https://i.stack.imgur.com/HkZYE.png) file.h ``` @interface ScrollViewController : UIViewController { IBOutlet UILabel* topLabel; IBOutlet UILabel* bottomLabel; IBOutlet UIScrollView * scroller; } @property(nonatomic,retain) IBOutlet UIScrollView *scroller; ``` file.m ``` - (void)viewDidLoad { [scroller setScrollEnabled:YES]; CGFloat scrollViewHeight = 0.0f; for (UIView* view in scroller.subviews) { scrollViewHeight += view.frame.size.height; } // print value 88.000000 NSLog(@"%f", scrollViewHeight); [scroller setContentSize:CGSizeMake(320, scrollViewHeight)]; [super viewDidLoad]; } ``` I don't know why the code doesn't work.
2012/01/15
[ "https://Stackoverflow.com/questions/8871253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1021610/" ]
JMS provides a mechanism for you to set expiry on messages. Look at the below two references 1. [setJMSExpiration(long expiration)](https://docs.oracle.com/javaee/1.3/api/javax/jms/Message.html#setJMSExpiration%28long%29): per message 2. [ActiveMQ: How do I set the message expiration](https://activemq.apache.org/how-do-i-set-the-message-expiration.html): per destionation/per message
1,167,966
> > Evaluate the integral $\int\_0^1 nx(1-x^2)^n \, dx$ ($n$ is constant here) > > > I actually have the solution which is: $$\int\_0^1 nx(1-x^2)^n = \left( \frac{-n}{2(n+1)} (1-x^2)^{n+1}\right)|\_0^1 = \frac{n}{2(n+1)}$$ It's unclear to me this was calculated. I'd be glad for reasoning. Thanks.
2015/02/27
[ "https://math.stackexchange.com/questions/1167966", "https://math.stackexchange.com", "https://math.stackexchange.com/users/188391/" ]
if you write $f(x) = 1-x^2$, your integral can be rewriten as $$\int\_0^1 nx(1-x^2)^n = \int\_0^1 -\frac{n}{2} f'(x)f(x)^n dx $$ $$ = \int\_0^1 -\frac{n}{2(n+1)} \left( f(x)^{n+1} \right)' dx$$ $$ = \left[-\frac{n}{2(n+1)} f^{n+1}(x)\right]\_0^1$$
66,140,459
I have the React class below that shows a list of users(zoomers). Each `zoomer` has a property called `isHidden`. When the page first loads, I want it to just show zoomers who have the `isHidden = false`. I made a checkbox control that, when checked, should show all zoomers, including even the hidden ones. When it's not checked, I don't want it to show any zoomer with `isHidden = true`. So when I run the web app, and load this React component, it initially shows me no users at all...hidden or not hidden. And when I click the checkbox, it reloads and just shows me the hidden users. So it's not really doing what I am want it to do and I'm not sure why. I was hoping someone could please show me the way. Here is my code: ``` export default class ZoomerGrid extends React.PureComponent { constructor(props) { super(props); this.state = { zoomers: List(), showHidden: false }; } toggleShowHidden = e => { const { value } = e.target; this.setState({ showHidden: true }); } render() { let zoomersShowHidden = this.state.zoomers.toJS(); zoomersShowHidden = zoomersShowHidden.filter(x => x.isHidden = this.state.showHidden); return ( <div> Show Hidden Zoomers? <input type="checkbox" name="test" onChange={this.toggleShowHidden} value="false" /> {zoomersShowHidden.map((zoomer) => <ZoomerTile key={zoomer.id} zoomer={zoomer} />)} </div> ); } } Thanks! ```
2021/02/10
[ "https://Stackoverflow.com/questions/66140459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/880874/" ]
UPDATED FOR TS4.5+ ------------------ Now that TypeScript supports [tail recursion elimination on conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html#tail-recursion-elimination-on-conditional-types) we can write `Kebab<T>` in a straightforward way that should handle strings up to ~1000 characters: ``` type Kebab<T extends string, A extends string = ""> = T extends `${infer F}${infer R}` ? Kebab<R, `${A}${F extends Lowercase<F> ? "" : "-"}${Lowercase<F>}`> : A ``` This works by iterating character-by-character, and inserting a `"-"` before each character which is not already lowercase (so caseless characters like numbers will not get a dash before them), and then lowercasing each character. Non-tail-recursive character-by-character iteration in TypeScript 4.5+, or any recursive type in TypeScript 4.4 and below hits recursion limits for modestly long strings, sometimes even strings of only twenty or so characters, and weird workarounds were required to handle longer strings. But now we can handle string literals longer than I imagine anyone would reasonably need: ``` type Testing = Kebab<"itWasTheBestOfTimesItWasTheWorstOfTimesItWasTheAgeOfWisdomItWasTheAgeOfFoolishnessItWasTheEpochOfBeliefItWasTheEpochOfIncredulityItWasTheSeasonOfLightItWasTheSeasonOfDarknessItWasTheSpringOfHopeItWasTheWinterOfDespair"> // type Testing = "it-was-the-best-of-times-it-was-the-worst-of-times-it-was-the-age-of-wisdom-it-was-the-age-of-foolishness-it-was-the-epoch-of-belief-it-was-the-epoch-of-incredulity-it-was-the-season-of-light-it-was-the-season-of-darkness-it-was-the-spring-of-hope-it-was-the-winter-of-despair" ``` --- Now we can use [key remapping](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#key-remapping-in-mapped-types) (also a TS4.1 feature) to easily convert from an object with camelCase keys to one with kebab-case keys: ``` type KebabKeys<T> = { [K in keyof T as K extends string ? Kebab<K> : K]: T[K] }; ``` --- Finally, let's try it out on your example: ``` export interface CssPropertiesCamel { alignContent: number | string | null; alignItems: number | string | null; alignSelf: number | string | null; alignmentBaseline: number | string | null; } type CssPropertiesKebab = KebabKeys<CssPropertiesCamel>; /* type CssPropertiesKebab = { "align-content": number | string | null; "align-items": number | string | null; "align-self": number | string | null; "alignment-baseline": number | string | null; } */ export interface CssProperties extends CssPropertiesCamel, CssPropertiesKebab { } ``` Looks good! We've turned `CssPropertiesCamel` into `CssPropertiesKebab`, and then `CssProperties` can just be a merged version of those two types. [Playground link to code](https://www.typescriptlang.org/play?#code/C4TwDgpgBA0hBGBDeAeAKlCAPYEB2AJgM5RHABOAlngOYA0UAgpjvsaRdTVALxQBE-AHy8AUFAlQM2XIRIADACQBvagDMI5KADEAvivWaoAJV3yoAfnGS4SVMYZLljfcu0tZ7ADIB7AO6aAMaIRBAo2iIWAvxQAFwCALT8rr4B5MGh4UJmIrHWEoyioqCQUhBkXLywCMgo-JTAAOohaAAWEABC5cAA8mpolAC25QCSTS3tjT7kZH0Dw0RjzURtEIw0EH2NlEQEPoNLE2sbfdo+PgA2O6145YvjK+0AomA+ga19XVcQaoePEC83h9fnhAuQIAQAK5XUB-VYAZQgIR8eD6XkoNFawDh7URyNRagAIohyABrW5Ee7LBFgKi0PoACR8kBxEG2eFw5D6hPKYEQlHIwlEAHphVAStA0N1Knx6sAEn4QglgO0EvBugkfGplUNygkGgqlSqIArpmRNdrgLqiPr5YqbcaEogNhaFTs9oNbYaHarnSatQk1OcrkQbncvfblaqIK93q71d9tQbI46Y0DXdQwRDoQ0QBGjarQvjXVdMfLkwWTUWiCjXQQSeTwxWfVXaVxXa1mSbm1GTX5qJy67z+YKihLqnY4CAiOgRHxlFAANowKDUKCkiAgLVSKAhWAeNgkMh07hRWy1GC5WAAXXiaGX16gugA3EVsK9yMBVxzNGpEIFoAAYUpAAFcgu0-ShykAxBhguKBlHyXdSzwQCUVkYB4jwSFBnVLQAB8OBPKBCOwi4LlfSRkIxPAxggQYiCwnC8JIojKlI6EKKQxAUMRC41CY3CjEI492KgMiuKoniaOGDkOhCCArluQSWJEzhaFYiTX10IpinAIDQPAyBIPKc94CqMypxnYCiDAiCrWg2DFKEV9hQAKnFfSoBsuzjIcogzKqRCqP4aSaDwBJAnQ-BgH4FThLYjSOPIyjJFClDbXoog4vE5iEtEpLcpSpD0pohJQn4nLsKEgjEu4ZLJLSsK8Fk+UkAq6gICqvLaoK+qiq43QoDc4U3ywD8vwHX9-wM2yjM0fyDzkbzDPsqCiBguCGB8+aTICmpzIXHSiiAA)
59,101,674
So I was having issues with flutter http package when it came to making a post request so I used dart HttpClient. I made a post request according to what was described somewhere but I am having issues getting response. Here is my code ``` Future<HttpClientResponse> submit() async { print('start'); Map<String, dynamic> data = { 'title' : 'My first post' }; String jsonString = json.encode(data); // encode map to json String paramName = 'param'; // give the post param a name String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString); List<int> bodyBytes = utf8.encode(formBody); // utf8 encode HttpClientRequest request = await HttpClient().postUrl(Uri.parse('https://jsonplaceholder.typicode.com/posts')); // it's polite to send the body length to the server request.headers.set('Content-Length', bodyBytes.length.toString()); request.headers.set('Content-Type', 'application/json'); request.add(bodyBytes); print('done'); return await (request.close()); } ``` How do I get the response from this request?
2019/11/29
[ "https://Stackoverflow.com/questions/59101674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8390502/" ]
> > Should I follow the documentation of StandardScaler such that the test dataset MUST be transformed only using ".transform()" without fit() function? Or it depends on the dataset such that I can use the "fit\_transform()" function for both training and testing datasets? > > > The moment you are re-training your scaler for the testing set you will have a different dependincy of your input features. The original algorithm will be fitted based on the fitting of your training sacling. And if you re-train it this will be overwritten, and you are faking your input of the test data for the algorithm. So the answer is **MUST** only be transformed.
56,082,728
I'm writing automated test cases using Javascript to perform GUI actions. I'm writing a function to handle some basic "initialization" operations on the software under test but I wanted to have the option to not necessarily put every argument into the parameters. So I had a function that basically did this: ``` function initializeApp(arg1,arg2,arg3,arg4) { action1(arg1); action2(arg2); action3(arg3); action4(arg4); } ``` But lets say that I didn't want to perform action 4, right now the code contained inside the "action4" block would not be able to handle there not being input for arg4 and would crash. So the hamfisted way I thought about getting around this issue was to create a bunch of `if` and `else if` statements that would essentially skip over different code blocks if that argument was undefined. Here's an example: ``` function testIES(configFile, recordFile, overwrite, scriptFile) { if (arg1 == undefined) { action2(arg2); action3(arg3); action4(arg4); } else if (arg2 == undefined) { action1(arg1); action3(arg3); action4(arg4); } else if (arg3 == undefined) { action1(arg1); action2(arg2); action4(arg4); } else if (arg4 == undefined) { action1(arg1); action2(arg2); action3(arg3); } } ``` However, this approach has an obvious flaw in that I'd need to come up with every combination of "actions" if I wanted to be able to leave out more than 1 argument. It would also not be very user friendly if anyone else wanted to do it because they'd have to know not to leave out more than one argument. So is my best option simply coming up with all the different combinations? Or is there a better way? Surely there's a better way.
2019/05/10
[ "https://Stackoverflow.com/questions/56082728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4227893/" ]
There was an error in the code: the encoding declared was not actually used when opening the file. I created an issue in the module, and [this pull request to fix it](https://github.com/Tux/CSV/pull/15)
3,380,694
I need some help understanding the correct way to mix variables with strings like this. I have tried every configuration I can think of and I keep getting an error. ``` <?php include('connect.php'); foreach($_GET['item'] as $key=>$value) { mysql_query("UPDATE userprojectlist SET category_display_order = '$key' WHERE category_id = '$value' "); } ?> Notice: Undefined index: item in updatedb.php on line 3 Warning: Invalid argument supplied for foreach() in pdatedb.php on line 3 ```
2010/08/01
[ "https://Stackoverflow.com/questions/3380694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340688/" ]
Is `item` an array in the url like `item[]`? If it's not that's the reason you get that error, you cannot iterate through a non-iterator object! Also get rid of the single quotes around the values if they are numeric and use string concatenation, ``` "UPDATE userprojectlist SET category_display_order = " . $key . " WHERE category_id = " . $value . ";" ```
2,377,603
There is a question having several parts. I solved the part (a) but I have problems with other parts. Let $f\in L^{1}(\mathbb{R}^{n}),$ with $f\geq 0\;$ a.e. in $\mathbb{R}^{n}$ and let $g:\mathbb{R}^{n}\to [0,+\infty)$ be the function defined by $$ g(x):=\int\_{B(x,\vert x\vert/2)}f(y)dy,$$ where $\vert \cdot\vert$ denotes the Euclidean norm and $B(x,r)=\{y\in \mathbb{R}^{n}:\vert y-x\vert <r\}$ for every $x\in \mathbb{R}^{n}$ and every $r\geq 0.$ (a) Prove that $g$ is continuous. (b) Prove that $g(x)\to 0$ as $\vert x\vert\to \infty. $ (c) Prove that $g$ has a maximum point in $\mathbb{R}^{n}.$ Please write only hint and not a whole solution, I have to be accustomed to solve the mathematics problems. A small useful hint will be accepted. Also, if you have seen this problem in other books, please let me know.
2017/07/31
[ "https://math.stackexchange.com/questions/2377603", "https://math.stackexchange.com", "https://math.stackexchange.com/users/277958/" ]
Note that the zero element of $\mathbb{Z}\oplus \mathbb{Z} / I $ is $I=0+I.$ Let $$((x\_1,y\_1)+I)((x\_2,y\_2)+I)=0+I$$ Then $$(x\_1x\_2,y\_1y\_2)\in I$$ Thus $$7\mid y\_1y\_2$$ As $7$ is prime, therefore $7 \mid y\_1$ or $7 \mid y\_2$. Hence, $(x\_1,y\_1) \in I$ or $(x\_2,y\_2)\in I$. So, $(x\_1,y\_1)+I = 0 + I$ or $(x\_2,y\_2)+I=0+I$. So, $\mathbb{Z}\oplus \mathbb{Z} / I $ is an integral domain.
67,273,304
I'm creating a bunch of emails using Word 2013 mail merge (not sure about the English term; I'm working with German version). Outlook is set to *offline mode*, so that I can modify the mails before sending out. So far, everything is working. I want to add an attachment to each of the emails and am trying to write some Outlook VBA script to do so. The following code is failing with code 80070005 (insufficient permission) at the `.Attachment.Add...` statement **but** only if the mail does not have an attachement yet. If there is an attachment, it will add the attachment to this **and** the next mail, then fails again with 80070005. I repeated running the script and it adds the attachment to one more mail at each run. What might cause the 80070005? ``` Sub addAttachmentsToMailsInOutbox() Dim olNs As Outlook.NameSpace Dim olOutbox As Outlook.MAPIFolder Dim olItem As Object Dim olEmail As Outlook.MailItem Set olNs = GetNamespace("MAPI") Set olOutbox = olNs.GetDefaultFolder(olFolderOutbox) For Each olItem In olOutbox.Items If olItem.Class = olMail Then Set olEmail = olItem With olEmail .Attachments.Add ("d:\temp\test.txt") .Save End With End If Next MsgBox ("done") End Sub ``` *Note* that this is the smallest working -- well failing -- example. I tried other code I found on the internet, but all show that strange behaviour.
2021/04/26
[ "https://Stackoverflow.com/questions/67273304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3220554/" ]
The suggestion from @HackSlash didn't work either, but it prompted another idea: Separate the modifications into two loops, and voilà, this works: ``` Sub addAttachmentsToMailsInOutbox() Dim olNs As Outlook.NameSpace Dim olOutbox As Outlook.MAPIFolder Dim olItem As Object Set olNs = GetNamespace("MAPI") Set olOutbox = olNs.GetDefaultFolder(olFolderOutbox) For Each olItem In olOutbox.Items If olItem.Class = olMail Then With olItem .BodyFormat = olFormatHTML .Save End With End If Next For Each olItem In olOutbox.Items If olItem.Class = olMail Then With olItem .Attachments.Add ("d:\temp\test.txt") .Save End With End If Next MsgBox ("done") End Sub ``` If more than one file needs to be attached, simply repeat the line `.Attachments.Add(....)` for each file.
73,368,464
i git yolov7(<https://github.com/WongKinYiu>) with `yolov7.pt` and try to run `detect.py`(i just want to run the example). it seems to be normal. but the output image has no mask.Why? here is my code and log: ``` (PyTorch) E:\yolov7>python detect.py --weights yolov7.pt --source inference\images\bus.jpg Namespace(weights=['yolov7.pt'], source='inference\\images\\bus.jpg', img_size=640, conf_thres=0.25, iou_thres=0.45, device='', view_img=False, save_txt=False, save_conf=False, nosave=False, classes=None, agnostic_nms=False, augment=False, update=False, project='runs/detect', name='exp', exist_ok=False, no_trace=False) YOLOR v0.1-103-g6ded32c torch 1.11.0 CUDA:0 (NVIDIA GeForce GTX 1650, 4095.6875MB) Fusing layers... RepConv.fuse_repvgg_block RepConv.fuse_repvgg_block RepConv.fuse_repvgg_block Model Summary: 306 layers, 36905341 parameters, 6652669 gradients Convert model to Traced-model... traced_script_module saved! model is traced! E:\anaconda\envs\PyTorch\lib\site-packages\torch\functional.py:568: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at C:\cb\pytorch_1000000000000\work\aten\src\ATen\native\TensorShape.cpp:2228.) return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined] Done. (151.6ms) Inference, (9.3ms) NMS The image with the result is saved in: runs\detect\exp4\bus.jpg Done. (3.713s) ``` and here is my result:[output image](https://i.stack.imgur.com/OrM6E.jpg)
2022/08/16
[ "https://Stackoverflow.com/questions/73368464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19570683/" ]
Your code should be throwing errors I think? You're trying to declare result twice, but as the second time is within the forEach loop, it's actually a different variable, and is created and destroyed for each loop. Assuming your fetch works, this *should* work: ``` const data = ['item1','item2','item3'] let result = [] data.forEach(async (item)=>{ const res = await fetch(`https://websitename.com/${item}`) result = [...result,...res] } console.log(result) ```
49,427,419
I'm using $mdDialog to show popup alerts. I want to refresh the the page whenever I close the Pop up container. ``` $scope.updateCustomer = function(){ HomeService.updateCustomer($scope.update) .then (function success(response){ $mdDialog.show( $mdDialog.alert() .parent(angular.element(document.querySelector('#popupContainer'))) .clickOutsideToClose(true) .textContent("Username has been changed successfully!") .ariaLabel('') .ok('Ok') ); }, function error(response){ $mdDialog.show( $mdDialog.alert() .parent(angular.element(document.querySelector('#popupContainer'))) .clickOutsideToClose(true) .textContent("Something is wrong!") .ariaLabel('') .ok('Ok') ); }); } ``` How to refresh the page when I close the pop up container?
2018/03/22
[ "https://Stackoverflow.com/questions/49427419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9048829/" ]
This was the working answer for my problem... ``` $scope.updateCustomer = function(){ HomeService.updateCustomer($scope.update) .then (function success(response){ $mdDialog.show( $mdDialog.alert() .parent(angular.element(document.querySelector('#popupContainer'))) .clickOutsideToClose(true) .textContent("Username has been changed successfully!") .ariaLabel('') .ok('Ok') .onRemoving(window.location.reload()) ); }, function error(response){ $mdDialog.show( $mdDialog.alert() .parent(angular.element(document.querySelector('#popupContainer'))) .clickOutsideToClose(true) .textContent("Something is wrong!") .ariaLabel('') .ok('Ok') ); }); } ```
84,684
Do we need to make changes for Salesforce Fast deploy to deploy our code via ANT migration tool ? OR does Salesforce take care of it automatically ? I would like to find some documentation which states that we don't have to make any changes for fast deploy.
2015/07/23
[ "https://salesforce.stackexchange.com/questions/84684", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/13059/" ]
If you will go through [this](http://releasenotes.docs.salesforce.com/en-us/winter15/release-notes/rn_quick_deployment.htm) article, it is clearly written : When deploying to non-production environments (sandbox), Apex tests aren’t required and aren’t run automatically. ***When using Metadata API (including the Force.com Migration Tool), Quick Deploy is supported in sandbox only for validations that explicitly enable the execution of tests (for example, via the runAllTests parameter for the Migration Tool)***. For change sets, Quick Deploy is not supported in sandbox because there is no option to enable test runs for change sets. So it seems like, using Metadata API(ANT), it is supported only in sandbox(with runAllTests paramater enabled)
73,720,590
It appears that starting with Android 11, you are now required to include a `AndroidWindowSplashScreenAnimatedIcon` preference in your Cordova `config.xml` that includes a path to a path to a png/xml file and the `<splash>` tags are no longer supported. This appears to mean that we are now required to use an icon for the Splash loading in the app. Do we have the ability to still use a full-screen image that we had done with previous versions of Android? When using `cordova-res` it would generate some individual files for different screen sizes/densities, so I wasn't sure if there was a similar tool to help create an individual screen image for the project.
2022/09/14
[ "https://Stackoverflow.com/questions/73720590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278584/" ]
Gmail does not support svg image format, so for displaying it you should host somewhere png version of appstore badge to display it inside of the email. The easiest way to host this image is Amazon s3 bucket.
845,593
How to I extract a subdirectory in a tarball into the current directory? Example, the tarball from [wordpress](http://wordpress.org/download/): ``` wordpress/ wordpress/wp-trackback.php wordpress/wp-config-sample.php wordpress/wp-settings.php wordpress/wp-rss2.php wordpress/readme.html wordpress/index.php ... ``` How do I extract everything under `wordpress/` into the current directory? In otherwords, it will not create a `wordpress` directory. I've tried this with no luck: ``` tar xvfz latest.tar.gz wordpress -C ./ ``` I know I can extract it normally and move it back, but I figure there has to be a way to do it in one shot.
2009/05/10
[ "https://Stackoverflow.com/questions/845593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16742/" ]
Why don't you untar normally, then just: ``` mv wordpress/.* . mv wordpress/* . rmdir wordpress ``` But alas, there's: ``` tar --strip-components=1 -zxvf wordpress.tgz ```
1,134,725
![enter image description here](https://i.stack.imgur.com/Yc7wb.png) Everything's explained in the above image. Basically, I need a sidebar div whose width expands according to the content inside of it and a `mainContent` that expands to the rest of the width of the window.
2009/07/15
[ "https://Stackoverflow.com/questions/1134725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139089/" ]
This seems to do it. @stefanw has a point, though. The side bar will expand to the width of its text, and that means the text will not wrap. I think that is probably not what you want. Or maybe it is, if what you are putting in there is not vary wide, but isn't fixed either? ``` <html> <head> <style type="text/css"> #overallWrapper div { background: #CCC; border: 1px solid black; padding: 15px; height: 100%; } #sideBar { float: left; } </style> </head> <body> <div id="overallWrapper"> <div id="sideBar"> I need this to expand to the width of this text... </div> <div id="content"> This should take the rest of the room, whatever's left... </div> </div> </body> </html> ``` You could remove the overallWrapper, if you want.
31,081,750
I created this xslt mapping using Contivo but it's not working for the XML below. Would someone be able to identify what is wrong, please? I spent some time already working on it but was not able to figure out what is wrong. Here is the XSLT: ``` <?xml version="1.0" encoding="UTF-8"?> <!-- IMPORTANT: If this transform will be run using Xalan, then version 2.5.1 or higher is required. --> <!-- Copyright (c) 2008 Contivo, Inc. All Rights Reserved.--> <!-- NOTE: DataPower supports the Xalan:nodeset() function. --> <!-- This transform was created by Analyst version 3.11.2.2. --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xalan="http://xml.apache.org/xalan" xmlns:func="http://exslt.org/functions" xmlns:ctvf="http://www.contivo.com/xslt/extensions" xmlns:date="http://exslt.org/dates-and-times" xmlns:dp="http://www.datapower.com/extensions" xmlns:tns="http://schemas.datacontract.org/2004/07/Inventory.Data.Models" xmlns:xs2="http://integration.com/interfaces/queryDirectInventory/v1/queryDirectInventory.xsd" extension-element-prefixes="func ctvf date dp" exclude-result-prefixes="xalan tns s"> <xsl:variable name='_root' select='/'/> <xsl:template match='/'> <xsl:variable name="__MappingResults"> <xsl:value-of select="ctvf:trim($_root//tns:InventoryInquiryApiResponse[1]/tns:InventoryInquiryApiResult[1]/tns:SkuAvailabilities[1]/tns:SkuAvailabilityResponse[1]/tns:AvailabilityIndicator[1])"/> <e> <xsl:attribute name="n">xs2:queryDirectInventoryResponse</xsl:attribute> <xsl:attribute name="m">t</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <e> <xsl:attribute name="n">xs2:availabilityList</xsl:attribute> <xsl:attribute name="m">t</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <e> <xsl:attribute name="n">xs2:availabilityList</xsl:attribute> <xsl:attribute name="m">t</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <xsl:attribute name="m">l</xsl:attribute> <xsl:for-each select="$_root//tns:InventoryInquiryApiResponse[1]/tns:InventoryInquiryApiResult[1]/tns:SkuAvailabilities[1]/tns:SkuAvailabilityResponse"> <e> <xsl:attribute name="n">xs2:availabilityList</xsl:attribute> <xsl:attribute name="m">f</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <e> <xsl:attribute name="n">xs2:availabilityInd</xsl:attribute> <xsl:attribute name="m">f</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <xsl:value-of select="ctvf:trim(string(./tns:AvailabilityIndicator[1]))"/> </e> <e> <xsl:attribute name="n">xs2:availableQuantity</xsl:attribute> <xsl:attribute name="m">f</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <xsl:value-of select="ctvf:testForNullNumber(./tns:AvailableQuantity[1], &quot;&quot;)"/> </e> <e> <xsl:attribute name="n">xs2:zipCode</xsl:attribute> <xsl:attribute name="m">f</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <xsl:value-of select="ctvf:trim(./tns:PostalCode[1])"/> </e> <e> <xsl:attribute name="n">xs2:itemId</xsl:attribute> <xsl:attribute name="m">f</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <xsl:value-of select="ctvf:trim(./tns:Sku[1])"/> </e> <e> <xsl:attribute name="n">xs2:statusMessageInfo</xsl:attribute> <xsl:attribute name="m">f</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <e> <xsl:attribute name="n">xs2:statusMessageCode</xsl:attribute> <xsl:attribute name="m">t</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <xsl:value-of select="ctvf:trim(./tns:StatusMessage[1])"/> </e> <e> <xsl:attribute name="n">xs2:statusMessageText</xsl:attribute> <xsl:attribute name="m">f</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <xsl:value-of select="ctvf:convertNumber(ctvf:trim(string(./tns:StatusMessageCode[1])))"/> </e> </e> </e> </xsl:for-each> <e> <xsl:attribute name="n">xs2:availabilityList</xsl:attribute> <xsl:attribute name="m">t</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <xsl:attribute name="m">e</xsl:attribute> <e> <xsl:attribute name="n">xs2:statusMessageInfo</xsl:attribute> <xsl:attribute name="m">f</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> <xsl:attribute name="m">e</xsl:attribute> <e> <xsl:attribute name="n">xs2:statusMessageCode</xsl:attribute> <xsl:attribute name="m">t</xsl:attribute> <xsl:attribute name="d">f</xsl:attribute> </e> </e> </e> </e> </e> </e> </xsl:variable> <xsl:apply-templates select='xalan:nodeset($__MappingResults)' mode="eliminateEmptyTags"/> </xsl:template> <xsl:template match="a" mode="eliminateEmptyTags"> <xsl:if test='@v != "" or @m = "t"'> <xsl:attribute name="{@n}"> <xsl:value-of select='@v' /> </xsl:attribute> </xsl:if> </xsl:template> <xsl:template match="e" mode="eliminateEmptyTags"> <xsl:choose> <xsl:when test='@m = "f"'> <xsl:if test='descendant-or-self::*[text() != ""][@d = "f"][1]/text() != "" or descendant-or-self::a[@v != ""][@d = "f"][1]/@v != ""'> <xsl:choose> <xsl:when test='@n !=""'> <xsl:element name="{@n}"> <xsl:apply-templates select='a' mode="eliminateEmptyTags"/> <xsl:value-of select='text()' /> <xsl:for-each select='./namespace::*'> <xsl:copy/> </xsl:for-each> <xsl:apply-templates select='e' mode="eliminateEmptyTags"/> </xsl:element> </xsl:when> <xsl:otherwise> <xsl:apply-templates select='e' mode="eliminateEmptyTags"/> </xsl:otherwise> </xsl:choose> </xsl:if> </xsl:when> <xsl:when test='@m = "l"'> <xsl:choose> <xsl:when test='child::e[@m != "e"]/descendant-or-self::*[text() != ""][@d = "f"][1]/text() != "" or child::e[@m != "e"]/descendant-or-self::a[@v != ""][@d = "f"][1]/@v != ""'> <xsl:apply-templates select='e[@m != "e"]' mode="eliminateEmptyTags"/> </xsl:when> <xsl:otherwise> <xsl:apply-templates select='e[@m = "e"]' mode="eliminateEmptyTags"/> </xsl:otherwise> </xsl:choose> </xsl:when> <xsl:otherwise> <xsl:choose> <xsl:when test='@n !=""'> <xsl:element name="{@n}"> <xsl:apply-templates select='a' mode="eliminateEmptyTags"/> <xsl:value-of select='text()' /> <xsl:for-each select='./namespace::*'> <xsl:copy/> </xsl:for-each> <xsl:apply-templates select='e' mode="eliminateEmptyTags"/> </xsl:element> </xsl:when> <xsl:otherwise> <xsl:apply-templates select='e' mode="eliminateEmptyTags"/> </xsl:otherwise> </xsl:choose> </xsl:otherwise> </xsl:choose> </xsl:template> <!--=========================================================================--> <xsl:template name="trimAll"> <xsl:param name="trimMe"/> <xsl:choose> <xsl:when test="contains($trimMe, ' ')"> <xsl:call-template name="trimAll"> <xsl:with-param name="trimMe"> <xsl:value-of select='concat(substring-before($trimMe, " "), substring-after($trimMe, " "))'/> </xsl:with-param> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select='$trimMe'/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name="trimLeft"> <xsl:param name="trimMe"/> <xsl:choose> <xsl:when test="starts-with($trimMe, ' ')"> <xsl:call-template name="trimLeft"> <xsl:with-param name="trimMe" select='substring-after($trimMe, " ")'/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select='$trimMe'/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name="trimRight"> <xsl:param name="trimMe"/> <xsl:choose> <xsl:when test="substring($trimMe, string-length($trimMe), 1) = ' '"> <xsl:call-template name="trimRight"> <xsl:with-param name="trimMe" select='substring($trimMe, 1, string-length($trimMe) - 1)'/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select='$trimMe'/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template name="trimBoth"> <xsl:param name="trimMe"/> <xsl:variable name="result"> <xsl:call-template name="trimRight"> <xsl:with-param name="trimMe" select='$trimMe'/> </xsl:call-template> </xsl:variable> <xsl:variable name="resultb"> <xsl:call-template name="trimLeft"> <xsl:with-param name="trimMe" select='$result'/> </xsl:call-template> </xsl:variable> <xsl:value-of select='$resultb'/> </xsl:template> <!--=========================================================================--> <func:function name="ctvf:testForNullNumber"> <xsl:param name="node"/> <xsl:param name="defaultValue"/> <xsl:choose> <xsl:when test="local-name($node) = ''"> <func:result select="$defaultValue"/> </xsl:when> <xsl:when test="string-length(normalize-space(string($node))) = 0"> <func:result select="$defaultValue"/> </xsl:when> <xsl:otherwise> <func:result select="number($node)"/> </xsl:otherwise> </xsl:choose> </func:function> <!--=========================================================================--> <func:function name="ctvf:convertNumber"> <xsl:param name="val"/> <xsl:variable name="strVal" select="string($val)"/> <xsl:choose> <xsl:when test="$strVal = 'NaN'"> <func:result select="''"/> </xsl:when> <xsl:otherwise> <func:result select="$strVal"/> </xsl:otherwise> </xsl:choose> </func:function> <!--=========================================================================--> <func:function name="ctvf:trim"> <xsl:param name="param" select="''"/> <xsl:variable name="in" select="string($param)"/> <xsl:variable name="len" select="string-length($in)"/> <xsl:choose> <xsl:when test="$len &gt; 0 and (ctvf:isWhitespace(substring($in, 1, 1)) or ctvf:isWhitespace(substring($in, $len)))"> <xsl:variable name="first" select="ctvf:doTrimGetFirst($in, 1, $len)"/> <func:result select="substring($in, $first, ctvf:doTrimGetLast($in, $len, $len) - $first + 1)"/> </xsl:when> <xsl:otherwise> <func:result select="$in"/> </xsl:otherwise> </xsl:choose> </func:function> <func:function name="ctvf:isWhitespace"> <xsl:param name="char"/> <func:result select="$char = '&#x20;' or $char = '&#x9;' or $char = '&#xD;' or $char = '&#xA;'"/> </func:function> <func:function name="ctvf:doTrimGetFirst"> <xsl:param name="in"/> <xsl:param name="index"/> <xsl:param name="len"/> <xsl:choose> <xsl:when test="($index &lt;= $len) and ($index &lt;= 350) and ctvf:isWhitespace(substring($in, $index, 1))"> <func:result select="ctvf:doTrimGetFirst($in, $index + 1, $len)"/> </xsl:when> <xsl:otherwise> <func:result select="$index"/> </xsl:otherwise> </xsl:choose> </func:function> <func:function name="ctvf:doTrimGetLast"> <xsl:param name="in"/> <xsl:param name="index"/> <xsl:param name="len"/> <xsl:choose> <xsl:when test="($index &gt;= 1) and ($len - $index &lt;= 350) and ctvf:isWhitespace(substring($in, $index, 1))"> <func:result select="ctvf:doTrimGetLast($in, $index - 1, $len)"/> </xsl:when> <xsl:otherwise> <func:result select="$index"/> </xsl:otherwise> </xsl:choose> </func:function> </xsl:stylesheet> ``` Here is XML: ``` <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header /> <s:Body> <InventoryInquiryApiResponse xmlns="http://tempuri.org/"> <InventoryInquiryApiResult xmlns:a="http://schemas.datacontract.org/2004/07/Inventory.Data.Models" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <a:SkuAvailabilities> <a:SkuAvailabilityResponse> <a:AvailabilityIndicator>true</a:AvailabilityIndicator> <a:AvailableQuantity>1</a:AvailableQuantity> <a:PostalCode>12065</a:PostalCode> <a:Sku>sku</a:Sku> <a:StatusMessage>OK</a:StatusMessage> <a:StatusMessageCode>200</a:StatusMessageCode> </a:SkuAvailabilityResponse> </a:SkuAvailabilities> </InventoryInquiryApiResult> </InventoryInquiryApiResponse> </s:Body> </s:Envelope> ```
2015/06/26
[ "https://Stackoverflow.com/questions/31081750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2929206/" ]
There could be (and probably are) various things wrong with your XSL. The first thing that jumps to the eye (**after** removing the undeclared `s` prefix from the `exclude-result-prefixes` list) is that you're not using the correct namespaces of the source XML. For example, in your very first selection: ``` <xsl:value-of select="ctvf:trim($_root//tns:InventoryInquiryApiResponse[1]/tns:InventoryInquiryApiResult[1]/tns:SkuAvailabilities[1]/tns:SkuAvailabilityResponse[1]/tns:AvailabilityIndicator[1])"/> ``` you are using the same `tns:` prefix for all your location steps - but in your XML, both `InventoryInquiryApiResponse` and `InventoryInquiryApiResult` are in the `xmlns="http://tempuri.org/"` namespace, which isn't even declared in your stylesheet. So you are starting off with your `$__MappingResults` variable being empty. AFAICS, this mistake is repeated throughout your stylesheet, so that none of your instructions are selecting anything.
50,823,950
So, I wanted to move a dataframe to a database into a table but I am encountering a few problems. I made the dataframe using the pandas library and wanted to upload the data into a table in my database. Relevant snippets of my Code and the error details are as follows: ``` #CONNECTION TO SQL DATABASE db=sql.connect(host="localhost",user="root",passwd="password",db="database_name") cur=db.cursor() #CONVERTING DATAFRAME(df_final) INTO TABLE df_final.to_sql(con=db, name='finaltable', if_exists='replace', chunksize=5000) ``` Error details: ``` Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\M ySQLdb\cursors.py", line 238, in execute query = query % args TypeError: not all arguments converted during string formatting During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p andas\io\sql.py", line 1400, in execute cur.execute(*args) File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\M ySQLdb\cursors.py", line 240, in execute self.errorhandler(self, ProgrammingError, str(m)) File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\M ySQLdb\connections.py", line 52, in defaulterrorhandler raise errorclass(errorvalue) _mysql_exceptions.ProgrammingError: not all arguments converted during string fo rmatting During handling of the above exception, another exception occurred: Traceback (most recent call last): File "pt.py", line 77, in <module> df_final.to_sql(con=db, name='finaltable', if_exists='replace', chunksize=50 00) File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p andas\core\generic.py", line 2127, in to_sql dtype=dtype) File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p andas\io\sql.py", line 450, in to_sql chunksize=chunksize, dtype=dtype) File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p andas\io\sql.py", line 1502, in to_sql table.create() File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p andas\io\sql.py", line 561, in create if self.exists(): File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p andas\io\sql.py", line 549, in exists return self.pd_sql.has_table(self.name, self.schema) File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p andas\io\sql.py", line 1514, in has_table return len(self.execute(query, [name, ]).fetchall()) > 0 File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p andas\io\sql.py", line 1412, in execute raise_with_traceback(ex) File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p andas\compat\__init__.py", line 403, in raise_with_traceback raise exc.with_traceback(traceback) File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\p andas\io\sql.py", line 1400, in execute cur.execute(*args) File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\M ySQLdb\cursors.py", line 240, in execute self.errorhandler(self, ProgrammingError, str(m)) File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\lib\site-packages\M ySQLdb\connections.py", line 52, in defaulterrorhandler raise errorclass(errorvalue) pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_ma ster WHERE type='table' AND name=?;': not all arguments converted during string formatting ```
2018/06/12
[ "https://Stackoverflow.com/questions/50823950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9071346/" ]
So apparently my approach has gone obsolete due to updates and therefore for the connection bit, I used 'create\_engine' from 'sqlalchemy' library instead of 'mysqldb.connect()' to access the database: ``` #relevant import: from sqlalchemy import create_engine #accessing database: engine = create_engine("mysql://root:PASSWORD@host/database_name") con = engine.connect() #uploading dataframe to database: df.to_sql(con=con, name='final_table', if_exists='replace', chunksize=10000) ```
39,070,962
I have learning Image Slider Using ViewPager. For that, I want the images to be dynamic. Glide is easy but I think I am not using it properly. Here's what I am trying to do. ``` //Initialize by default Images private static final Integer[] IMAGES = {R.drawable.image1,R.drawable.image2}; // Load images into Drawables using Glide Glide.with(this) .load("https://google.com/someImage1.jpg") .error(R.drawable.image1) .into(R.drawable.image1); Glide.with(this) .load("https://google.com/someImage2.jpg") .error(R.drawable.image2) .into(R.drawable.image2); // Set Again IMAGES[0]= R.drawable.image1; IMAGES[1]= R.drawable.image2; ``` But `.into(java.lang.Integer`) is not defined and I know that. But I want something that would solve my problem. I have slider view. In that I need to pass the Images as drawables or something like that. Image loading would be carried by Adapter. I can't load directly as far as I know. Is there any way to load glide images in `drawable`. Also what is the best way to catch or store the images locally, so that if there is no internet connection, still the slider works smoothly. Here is my Adapater ``` public class MainPageSlideImageAdapter extends PagerAdapter { private ArrayList<Integer> IMAGES; private LayoutInflater inflater; private Context context; public MainPageSlideImageAdapter(Context context,ArrayList<Integer> IMAGES) { this.context = context; this.IMAGES=IMAGES; inflater = LayoutInflater.from(context); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public int getCount() { return IMAGES.size(); } @Override public Object instantiateItem(ViewGroup view, int position) { View imageLayout = inflater.inflate(R.layout.main_page_slidingimages, view, false); assert imageLayout != null; final ImageView imageView = (ImageView) imageLayout .findViewById(R.id.image); imageView.setImageResource(IMAGES.get(position)); view.addView(imageLayout, 0); return imageLayout; } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public void restoreState(Parcelable state, ClassLoader loader) { } @Override public Parcelable saveState() { return null; } } ```
2016/08/22
[ "https://Stackoverflow.com/questions/39070962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2254802/" ]
you must provide the view in `.into()` please view the sample sample layout ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ImageView android:id="@+id/myImage" android:layout_width="100dp" android:layout_height="100dp"/> </LinearLayout> ``` **Update** ``` @Override public Object instantiateItem(ViewGroup view, int position) { View imageLayout = inflater.inflate(R.layout.main_page_slidingimages, view, false); assert imageLayout != null; final ImageView imageView = (ImageView) imageLayout .findViewById(R.id.image); Glide.with(this) .load(IMAGES.get(position)) .error(R.drawable.image2) .into(imageView); //imageView.setImageResource(); view.addView(imageLayout, 0); return imageLayout; } ```
155,607
> > Let a small pressure-sensing device be suspended inside a fluid-filled vessel. ... We find by experiment that at a given point in a fluid at rest, the **pressure has the same value no matter how the pressure sensor is placed.** > > > Why is it so?
2014/12/29
[ "https://physics.stackexchange.com/questions/155607", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/-1/" ]
Suppose we had a fluid where the pressure depended on direction: ![enter image description here](https://i.stack.imgur.com/zNkSH.gif) For the sake of argument let's suppose that $P\_1 > P\_2$. In that case we could take a tube with one end normal to direction $1$ and the other normal to direction $2$: ![enter image description here](https://i.stack.imgur.com/OqivP.gif) Because the pressure at the ends is different, fluid will flow round the tube and we have a perpetual motion device. Or rather, the fluid would flow until the pressures equalised and $P\_1 = P\_2$. But the tube is just a conceptual aid, and we can take it away: ![enter image description here](https://i.stack.imgur.com/Eo8ad.gif) In this case fluid would simply flow in the cycle shown until the pressures equalised. So in any fluid that can flow freely the pressure $P\_1$ must equal $P\_2$. The argument applies to any directions, and the conclusion is that the pressure must be independant of direction. There are possible exceptions. For example some [structured fluids](https://www.google.co.uk/search?q=structured%20fluid) are anisotropic and may have different viscosity in different directions, or may have an anisotropic yield stress. In these cases it could be the case that the pressure would not be the same in all directions. But then, as Sofia says in a comment, the equations of motion for such a fluid would not be spherically symmetric.
73,402,356
``` def openFood(): with open("FoodList.txt") as f: lines = f.readlines() for line in lines: if 'Food' in line: print(f.next()) openFood() ``` I want it where when it sees a certain header like 'Food' It will print the line below it. I cant seem to make it work. The text file will be like ``` Food Apple Cal 120 Protein 12 Fat 13 Carb 23 ```
2022/08/18
[ "https://Stackoverflow.com/questions/73402356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19730199/" ]
Just use the index. ``` def openFood(): with open("FoodList.txt") as f: lines = f.readlines() for i in range(len(lines)-1): if 'Food' in lines[i]: print(lines[i+1]) openFood() ```
37,657,006
I'm playing w/ this [Valo theme](http://demo.vaadin.com/valo-theme/#!common) sample. In it, when browser screen is widely open i see the menu items as small icon following w/ some text in a singel line. Ok. When i make the browser screen more narrow the menu item look is changing. Now i see larger icon w/ the line of text below it. How can i see such look from the origin? it seems such behavior is related to so called "responsive" design. it is a really cool thing but in this particular case i would like to handle it more precisely. Thanks in advance.
2016/06/06
[ "https://Stackoverflow.com/questions/37657006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053031/" ]
The easiest way is to modify styles via CSS in your theme that imports the Valo theme. The menu item icons are font icons, so you can just increase the `font-size` via CSS. Inspecting styles of the Valo theme demo with Firefox, I identified the following CSS for the responsive enlargement of the icon: ``` .tests-valo .v-ui.valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-item { font-size: 26px; ... } ``` More information on responsiveness can be found in [Vaadin docs](https://vaadin.com/docs/-/part/framework/themes/themes-responsive.html). **EDIT** according to the comment: New line of caption is done by the `display` style. ``` .tests-valo .v-ui.valo-menu-responsive[width-range~="801px-1100px"] .valo-menu-part .valo-menu-item [class*="caption"] { display: block; ... } ```
66,781,577
I need to print input from the user in reverse order using a function. As a condition, just words (no floats/ int) should be allowed & at least **four** words need to be entered. e.g.: How can I help you --> you help I can How It should'nt be possible to input: "4 5 6 7" or "There are 2 dogs" Here's my current code, however I didn't integrate that only strings are allowed so far: ``` def phrase(): while True: user_input = input("Please insert a phrase: ") words = user_input.split(" ") n = len(words) if n >= 4: words = words[-1::-1] phrase_reverse = " ".join(words) print(phrase_reverse) else: print("Please only insert words and at least 4 ") continue break phrase() ``` I tried with `if n<4 and words == str:`, `if n<4 and words != string` etc.. However, that didn't work. Could you please help me solving this issue? Maybe my code is wrong in general.
2021/03/24
[ "https://Stackoverflow.com/questions/66781577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15469758/" ]
try to do this ```r df <- structure(list(animals = c("E1", "E1", "E1", "E2", "E2", "E2"), period = structure(c(18690, 18697, 18704, 18690, 18697, 18704), class = "Date"), weight1 = c(704, 734, 653, 851, 911, 829), weight2 = c(0, 235, 325, 0, 148, 200)), row.names = c(NA, -6L), class = c("data.table", "data.frame")) library(dplyr) df %>% group_by(animals) %>% mutate(across(starts_with("weight"), cumsum)) #> # A tibble: 6 x 4 #> # Groups: animals [2] #> animals period weight1 weight2 #> <chr> <date> <dbl> <dbl> #> 1 E1 2021-03-04 704 0 #> 2 E1 2021-03-11 1438 235 #> 3 E1 2021-03-18 2091 560 #> 4 E2 2021-03-04 851 0 #> 5 E2 2021-03-11 1762 148 #> 6 E2 2021-03-18 2591 348 ``` Created on 2021-03-24 by the [reprex package](https://reprex.tidyverse.org) (v1.0.0) **or** `vars <- names(df)[3:4]` `df %>% group_by(animals) %>% mutate(across(all_of(vars), cumsum))`
2,915,307
I am working on the design and implementation of an iPhone application ( a newbie, but I am getting the hang of it) where a person can download specific contact information about teachers based on their majors. The information is currently on different edu websites. And I have exported the information into SQLite databases. Is it possible to develop the application that when it is first initiated, it can give the user the option of which particular SQLite database they want for their application? Or if not, would it be better to merge all the DBs into one DB, and allow the user the option of downloading specific information from the SQLite db. I see that the db's can be downloaded into an app, but have yet to find a solution where there can be an option to download from different SQLite dbs. Thanks!
2010/05/26
[ "https://Stackoverflow.com/questions/2915307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/351199/" ]
Mark, By setting some variable to the database name via an NSString, you should be able to open up any database you want that is bundled with the app when it's submitted. For instance, declare variable: `NSString *databaseName;` set database name: `databaseName = @"teachersDBNumber1.sql";` and then when you open it up using the file path, you get the file path for whatever `databaseName` is set to. If you want to open a different one, just set databaseName to a new string like `databaseName = @"teachersDBNumber2.sql";` find the path for it and then open it up. You should be able to find a number of good SQLite db tutorials out there for how to open it, read the data, etc.
15,116,283
Is it possible to setup WebAPI to Self Host like Nancy. Such that it hosts an > > /api/... > > > section serving up json and xml responses and hosts a > > /content/... > > > section serving up \*.jpg and \*.html and \*.js I'm trying to create a self hosting Single Page Application with WebAPI as the backend, and the only thing I have seen that comes close is Nancy. Is this possible with WebAPI self hosting?
2013/02/27
[ "https://Stackoverflow.com/questions/15116283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51841/" ]
Try this: ``` #if __has_feature(objc_arc) /* ARC is used */ #endif ```
13,707,879
I have an Internet Explorer Add-On that generates some files in LocalAppDataFolder\Microsoft\Windows\Temporary Internet Files\CompanyName\AddOnName\ I have a WIX installer for the application that I would like to have delete the CompanyName\AddOnName\ folders on both install and uninstall. I have never used WIX before, and I'm more of a MacOS guy, so all of this stuff is a bit foreign to me. Here is a portion of what I have right now (in my Product.wxs file): ``` <Feature Id="ProductFeature" Title="Company IE Add-On" Level="1" ConfigurableDirectory="INSTALLFOLDER"> <ComponentRef Id="INSTALLFOLDER" /> <ComponentGroupRef Id="ProductComponents" /> <ComponentRef Id="dataDirectory"/> </Feature> <Fragment> <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="ProgramFilesFolder"> <Directory Id="INSTALLFOLDER" Name="Company IE Add-On" > <Component Id="INSTALLFOLDER" Guid="THERE IS A GUID HERE"> <RemoveFolder On="both" Id="INSTALLFOLDER"/> <RegistryValue Root="HKLM" Key="Software\[Manufacturer]\[ProductName]" Type="string" Value="Company IE Add-On" /> </Component> </Directory> </Directory> <Directory Id="LocalAppDataFolder"> <Directory Id="Microsoft"> <Directory Id="Windows"> <Directory Id="TempInetFiles" Name="Temporary Internet Files"> <Directory Id="CompanyName"> <Directory Id="AddOnName"> <Component Id="dataDirectory" Guid="E5938D44-5315-43D4-94EC-313F6CDB290B" NeverOverwrite="no" Permanent="no"> <RemoveFolder Id="AddOnName" On="both"/> </Component> </Directory> </Directory> </Directory> </Directory> </Directory> </Directory> </Directory> </Fragment> ``` But this is giving me errors like "Component dataDirectory installs to user profile. It must use a registry key under HKCU as its KeyPath, not a file." And "The directory CompanyName is in the user profile but is not listed in the RemoveFile table." Any help would be greatly appreciated. Thanks.
2012/12/04
[ "https://Stackoverflow.com/questions/13707879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506949/" ]
You need to manually initialize the whole array and all levels if multi-leveled: ``` point[] p1 = new point[5]; // Now the whole array contains only null elements for (int i = 0; i < 5; i++) p1[i] = new point(); p1[0].x = 1; // Will be okay ```
965,610
I have converted a GWT Eclipse based project to GWT-Maven but when I run the command ``` mvn clean gwt:compile ``` I get an awful lot of errors that specify: ``` [class name].java' is removed due to invalid reference(s): ``` My pom.xml dependencies are: * dom4j-1.6.1 * commons-httpclient-3.1 * gwt-servlet-1.6.4 * gwt-user-1.6.4 * junit-4.3.1 * gwtext-2.0.5 * GWTx-20070605 What do these errors mean and how do I go about diagnosing the source of the problem?
2009/06/08
[ "https://Stackoverflow.com/questions/965610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71561/" ]
That's because the removed class refers to a method that is implemented as part of the GWT JRE emulation library : <http://library.igcar.gov.in/readit2007/tutori/tools/gwt-windows-1.4.10/doc/html/jre.html> If your software makes use of reflection it is very probably the cause.
19,801,679
I have been working on this issue for several days now and have been unable to find a solution. I will try to be as specific as I can, so that you understand the problem, and include code where necessary. I have a normal view with a Html.BeginForm (as seen in the first code example) with different controls inside, as well as ValidationMessageFors for some of them. In the model (the second example) we have a couple validation attributes for some of the properties, just like any other MVC setup. The issue is that locally when the page is run, the data-val-required attribute, as well as others, are all added to the html, but when deployed to the production server, these attributes are never added, and so the validation doesn't work. Examples 3 and 4 show this. Example 5 shows the script file declarations. --- Example 1: ``` @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.DocumentID); @Html.HiddenFor(model => model.TempFilePath); @Html.HiddenFor(model => model.FileName); <div style="height: 27px; width: 769px; background-color: #b3b3b3; padding-top: 7px; padding-right: 14px; padding-left: 14px; border-bottom: 1px solid #808080;"> <span style="font-size: 11.5pt; font-weight: bold; float: left;">@ViewBag.Title</span> </div> <br /> <div style="margin-left: 15px; margin-right: 15px;"> @Html.ValidationSummary(true) <h4>Document Name</h4> @Html.TextBoxFor(model => model.Name, new { id = "DocumentNameEdit" }) @Html.ValidationMessageFor(model => model.Name, "*", new { @style = "font-size:16pt;" }) <br /> <h4>Description</h4> @Html.TextAreaFor(model => model.Description, new { id = "DocumentDescriptionEdit" }) @Html.ValidationMessageFor(model => model.Description, "*", new { @style = "font-size:16pt;" }) <br /> <input type="button" id="btnSaveDocument" value="Save" /> <input type="button" id="btnClose" value="Close" /> </div> } ``` Example 2: ``` public class DocumentModel { public DocumentModel() { Statuses = new List<SelectListItem>() { new SelectListItem() {Text="Visible", Value="3"}, new SelectListItem() {Text="Hidden", Value="4"} }; } public string DocumentID { get; set; } [StringLength(255, ErrorMessage = "Please enter no more than 255 characters for the Name.")] [Required(ErrorMessage="Name is Required") ] public string Name { get; set; } [StringLength(2000, ErrorMessage = "Please enter no more than 2000 characters for the Description.")] [Required(ErrorMessage = "Description is Required")] public string Description { get; set; } public string FileName { get; set; } public int? Status { get; set; } public string FolderID { get; set; } public string TempFilePath { get; set; } public List<dm_LIST_Folders_Result> FolderList { get; set; } public List<SelectListItem> Statuses { get; set; } } ``` Example 3 (local): ``` <form method="post" action="/DPS/Documents/CreateEdit" novalidate="novalidate"> <input type="hidden" value="TheCode" name="__RequestVerificationToken"> <input type="hidden" value="" name="DocumentID" id="DocumentID"> <input type="hidden" value="" name="TempFilePath" id="TempFilePath"> <input type="hidden" value="" name="FileName" id="FileName"> <div style="height: 27px; width: 769px; background-color: #b3b3b3; padding-top: 7px; padding-right: 14px; padding-left: 14px; border-bottom: 1px solid #808080;"> <span style="font-size: 11.5pt; font-weight: bold; float: left;">Add New Document</span> </div> <br> <div style="margin-left: 15px; margin-right: 15px;"> <h4>Document Name</h4> <input type="text" value="" name="Name" id="DocumentNameEdit" data-val-required="Name is Required" data-val-length-max="255" data-val-length="Please enter no more than 255 characters for the Name." data-val="true"> <span style="font-size:16pt;" data-valmsg-replace="false" data-valmsg-for="Name" class="field-validation-valid">*</span> <br> <h4>Description</h4> <textarea rows="2" name="Description" id="DocumentDescriptionEdit" data-val-required="Description is Required" data-val-length-max="2000" data-val-length="Please enter no more than 2000 characters for the Description." data-val="true" cols="20"></textarea> <span style="font-size:16pt;" data-valmsg-replace="false" data-valmsg-for="Description" class="field-validation-valid">*</span> <br> <input type="button" value="Save" id="btnSaveDocument"> <input type="button" value="Close" id="btnClose"> </div> </form> ``` Example 4 (Production) ``` <form method="post" action="/DM/DPS/Documents/CreateEdit" novalidate="novalidate"> <input type="hidden" value="TheCode" name="__RequestVerificationToken"> <input type="hidden" value="" name="DocumentID" id="DocumentID"> <input type="hidden" value="" name="TempFilePath" id="TempFilePath"> <input type="hidden" value="" name="FileName" id="FileName"> <div style="height: 27px; width: 769px; background-color: #b3b3b3; padding-top: 7px; padding-right: 14px; padding-left: 14px; border-bottom: 1px solid #808080;"> <span style="font-size: 11.5pt; font-weight: bold; float: left;">Add New Document</span> </div> <br> <div style="margin-left: 15px; margin-right: 15px;"> <h4>Document Name</h4> <input type="text" value="" name="Name" id="Name"> <br> <h4>Description</h4> <textarea rows="2" name="Description" id="Description" cols="20"></textarea> <br> <input type="button" value="Save" id="btnSaveDocument"> <input type="button" value="Close" id="btnClose"> </div> </form> ``` Example 5: ``` @Scripts.Render("~/bundles/jquery") <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script> <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script> ``` --- Just to save on time, here is what I have tried: 1. Adding requestValidationMode="2.0" to the web.config. 2. Adding HtmlHelper.ClientValidationEnabled = true; to the view. 3. Adding HtmlHelper.UnobtrusiveJavaScriptEnabled = true; to the view. 4. Getting the most recent version of jquery and the validate plugin. When it comes to jquery, the most recent is 1.\* series, since we have to support ie8 and can't use 2.\*. 5. Checking if the FormContext is null and creating a new one if it is. 6. Checking if the scripts are being loaded. The answer is yes. 7. Including unobtrusive.ajax. Doesn't help. 8. Setting ClientValidationEnabled to true and UnobtrusiveJavaScriptEnabled to true. A final note: this is on a Server 2012 machine running IIS 8. This is not a partial view. Hopefully one of you have run into this. Everywhere I look online says to do one of those 7 options, and none have helped. Edit: After looking into things for quite a bit more (couple days since original posting) I have found that the window.mvcClientValidationMetadata property is being set to the correct rullings in the javascript, but the hookups are missing, so when validation is run, the fields aren't actually validated.
2013/11/06
[ "https://Stackoverflow.com/questions/19801679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2679383/" ]
``` > df[ sapply(df$Col1,function(x) any(2:3 %in% x)) , ] Col1 Col2 1 1, 2, 3 1 2 2, 3 2 3 3 3 ```
17,214,150
I have been trying to test my controllers as per this tutorial -> [Zend Framework 2.1 Unit testing](http://framework.zend.com/manual/2.1/en/tutorials/unittesting.html#testing-actions-with-post) I have tried every possible variation of the code to send POST or GET data along with the dispatch but the only thing I get back from running the test is "Undefined Index" when I try to access that data from the $\_POST array in the controller. I am using PHPUnit 3.7.17, Everything else works perfectly except for POST and GET data, I have tried the following code: ``` public function testIndexActionCanBeAccessed() { $this->getRequest() ->setMethod("POST") ->setPost(new \Zend\Stdlib\Parameters(array('argument' => 'value'))); $response = $this->dispatch('/app/api/index'); $this->assertResponseStatusCode(200); } ``` AND ``` public function testIndexActionCanBeAccessed() { $post_data = array("argument" => "value"); $response = $this->dispatch("/app/api/index", "POST", $post_data); $this->assertResponseStatusCode(200); } ``` I can't find any help on the web how to fix this issue. Can anyone help out? Any ideas?
2013/06/20
[ "https://Stackoverflow.com/questions/17214150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/393897/" ]
``` $p = new Parameters(); $p->set('username','foo'); $p->set('password','bar'); $this->getRequest()->setMethod('POST'); $this->getRequest()->setPost($p); $this->dispatch('/login'); ``` This works for me. The Parameters() constructor doesn't seem to be what you're expecting it to be. The docs say it takes an array, but I could only get it to work this way. The Stdlib\Parameters() constructor doesn't seem to do anything with the array passed in.
18,983,906
Why is time taken to access an element in a non-homogeneous list considered as constant or How is a non-homogeneous list stored in memory in case of python? In case of a homogeneous list, knowing the type and position, the memory location can be determined but how is it done in case of a non homogeneous list so fast as to consider it as a function of constant time? Going through this page [Does Python use linked lists for lists? Why is inserting slow?](https://stackoverflow.com/questions/12274060/does-python-use-linked-lists-for-lists-why-is-inserting-slow) I assume it stores elements in contiguous memory locations.
2013/09/24
[ "https://Stackoverflow.com/questions/18983906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2216108/" ]
If all you need to do is check the value of a boolean, that's just a conditional statement: ``` public JsonResult ResolveProfileSelectionRequired(ResolveProfileSelectionRequiredModel model) { if (model.NewTransferee) { // do something } else { // do something else } } ``` It's not entirely clear what your goal is though, since your current `return` statement depends on the output of the method that you only want to call conditionally. All code paths will need to return *something*. Maybe like this?: ``` public JsonResult ResolveProfileSelectionRequired(ResolveProfileSelectionRequiredModel model) { if (model.NewTransferee) { var resolved = SqlDataProvider.ResolveProfileSelectionRequiredJobException(model); return resolved ? Json("Success") : Json("Failed"); } else { return Json("Success"); } } ``` Again, I can't know without knowing more about your intended behavior for this action. It's worth noting that this isn't really an "MVC" thing. At its simplest, this action method is just a method which receives an argument of type `ResolveProfileSelectionRequiredModel`. The conditional statement is just plain C#. All code paths returning a value is plain C#. The only thing "MVC" about this method is that it's returning a `JsonResult`. --- **Edit:** I just noticed... The value you're looking for is on the `CreateTransferee` model, but your controller is receiving a `ResolveProfileSelectionRequiredModel`? Is that value on the `ResolveProfileSelectionRequiredModel`? They seem to be very similar. If it's not on that model, you can either add it to that model or use @Raidri's approach to add it as an explicit parameter to the controller action.