qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
8,928,533
Why in jQuery `core.js` isn't `extend` defined as like this: ``` jQuery.extend = jQuery.fn.extend = function() { ... } ``` and not as a prototype like: ``` jQuery.prototype.extend = jQuery.fn.prototype.extend = function() { ... } ``` Presumably with the former, objects created from jQuery will not have the extend function.
2012/01/19
[ "https://Stackoverflow.com/questions/8928533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/415600/" ]
Because `jQuery.fn === jQuery.prototype` It is defined on the prototype. jQuery just decided it would be "cute" to alias the prototype to `.fn` Which is why ``` $().extend({ "lulz": "baz" }, { "more-lulz": "no wai" })["more-lulz"] === "no wai"; // true ```
Well, because `fn` is nothing than a shortcut to the `prototype` property : ``` console.log($.prototype === $.fn); ``` Maybe John Resig got bored of typing `prototype` for every method and set up a nice alias `fn` (which is indeed shorter and in my opinion more suggestive).
77,946
For Barcelona, Google Maps has driving, public transport and walking directions. However, the button for cycling directions is grayed out. Is this feature only available in certain places?
2015/05/11
[ "https://webapps.stackexchange.com/questions/77946", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/-1/" ]
It is likely that the area does not support this method of navigation in Google Maps. Looking at the location you mention Google Maps is reporting that "Cycling is not available". You could try out [OpenCycleMaps](http://www.opencyclemap.org/) powered by [OpenStreetMaps](https://www.openstreetmap.org/)
Try this - looks like is built on Google anyhow, <http://com-shi-va.lameva.barcelona.cat/en/bicycle>
173,264
Are there Virtual Machine Servers that you can install Virtual Machines on and then the clients can just fire up the OS (Windows, Mac, Linux) through the web browser? That would be very efficient.
2010/08/22
[ "https://serverfault.com/questions/173264", "https://serverfault.com", "https://serverfault.com/users/39101/" ]
VMware's ESX pretty much does this by default although this feature has now been removed from ESXi and will not be available in future releases after V4.1 once the ESXi variant becomes the only one that VMware will update in future. Web based access to a remote guest console is trivially easy to provide for ESX but as others have said there are some serious security issues with this that limit its practical use.
VirtualBox can be scripted, so it would be possible to include a web front-end command interface. Microsoft's Virtual Server 2005 was ran exclusively from a web front-end, bit it has largely been supplanted by Hyper-V. Hyper-V is scriptable via Powershell, I believe, so a web front-end would be possible but I think it would require making calls in a web-friendly language to then make Powershell calls. VMware does have APIs for VBScript and Perl, and possibly Powershell.  I'm not sure, but they may only apply to ESX. -Waldo
3,799,810
I have an instance on my stage that I dragged from my library at design time. This instance links to a custom class who's constructor takes an argument. ``` package { import flash.display.MovieClip; import flash.media.Sound; public class PianoKey extends MovieClip { var note:Sound; public function PianoKey(note:Sound) { this.note = note; } } } ``` Obviously, trying to run the the code as is yields the following argument count error: > > ArgumentError: Error #1063: Argument > count mismatch on PianoKey(). Expected > 1, got 0. > > > Is there any way to set arguments on an instance that has been manually dragged to the stage?
2010/09/26
[ "https://Stackoverflow.com/questions/3799810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46914/" ]
Why not just use VIM? You know exactly what it can do and how it can be extended, and it appears to be what you want anyway. You will not be satisfied by any emulation as it will fall short, and with your current mindset you will not like having to learn a new editor. It is, however, what I will recommend you to do. The things modern Java IDE's can do are miles above what VIM can do because they know your source intimately. You will benefit the most from an IDE if you use its default configuration, and I do not know any which wants to look like vi/vim. When THAT is said, you might find <http://ideavim.sourceforge.net/> interesting. IDEA is the only common place Java IDE left which makes money...
I've been using the viplugin for eclipse (http://www.viplugin.com/viplugin/) It's quite good, fights a little bit with refactoring, but most of the main editing commands work. I still have to use vim for complex regex work, but I only have to do that about twice a year. Unfortunately it's commercial (€15) and development seems to have slowed a lot. It seems to be currently more feature complete than vrapper, but I haven't tried that.
1,358,694
How to remove a blank page that gets added automatically after \part{} or \chapter{} in a book document class? I need to add some short text describing the \part. Adding some text after the part command results in at least 3 pages with an empty page between the part heading and the text: 1. Part xx 2. (empty) 3. some text How to get rid of that empty page? P.S. [Latex: How to remove blank pages coming between two chapters IN Appendix?](https://stackoverflow.com/questions/491904/latex-how-to-remove-blank-pages-coming-between-two-chapters-in-appendix) is similar but it changes the behavior for the rest of the text while I need to remove the empty page for this one \part command only.
2009/08/31
[ "https://Stackoverflow.com/questions/1358694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025531/" ]
A solution that works: Wrap the part of the document that needs this modified behavior with the code provided below. In my case the portion to wrap is a \part{} and some text following it. ``` \makeatletter\@openrightfalse \part{Whatever} Some text \chapter{Foo} \@openrighttrue\makeatother ``` The wrapped portion should also include the chapter at the beginning of which this behavior needs to stop. Otherwise LaTeX may generate an empty page before this chapter. Source: folks at the #latex IRC channel on irc.freenode.net
I believe that in the book class all \part and \chapter are set to start on a recto page. from book.cls: ``` \newcommand\part{% \if@openright \cleardoublepage \else \clearpage \fi \thispagestyle{plain}% \if@twocolumn \onecolumn \@tempswatrue \else \@tempswafalse \fi \null\vfil \secdef\@part\@spart} ``` you should be able to renew that command, and something similar for the \chapter.
17,406
I want to convert `.txt` files to `.pdf`. I'm using this: ``` ls | while read ONELINE; do convert -density 400 "$ONELINE" "$(echo "$ONELINE" | sed 's/.txt/.pdf/g')"; done ``` But this produces one "error" -- if there's a very long line in the text file, it doesn't get wrapped. ### Input text ![Screenshot of the input file](https://i.stack.imgur.com/J03Hd.png) ### Output PDF ![Screenshot of the output PDF](https://i.stack.imgur.com/CUbzw.png) -- Also, it would also be great if the output PDF could contain text, instead of images of text. I have many-many-many TXT files. So don't want to do it by hand. I need an automatic solution, like the one I mentioned above.
2011/07/26
[ "https://unix.stackexchange.com/questions/17406", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/6960/" ]
You can print text to a PostScript file using Vim and then convert it to a PDF, as long as Vim was compiled with the `+postscript` feature. For this you use the `:hardcopy > {filename}` command. For example you can open `example.txt` and execute ``` :hardcopy > example.ps ``` which will produce a file `example.ps` containing all the text in `example.txt`. The header of each page in the PostScript file will contain the original filename and the page number. Then you can convert the PostScript file into a PDF by using the following command ``` ps2pdf example.ps ``` which will create `example.pdf`. You can do the same directly from a terminal (without interacting with Vim) by using the following command ``` vim example.txt -c "hardcopy > example.ps | q"; ps2pdf example.ps ``` This opens `example.txt` in Vim and executes the command passed to the `-c` option, which in this case is a `hardcopy` command followed by a quit (`q`) command. Then it executes `ps2pdf` to produce the final file. For more options see the help files with `:help :hardcopy`.
I am adding this `a2ps` as another alternative. `a2ps` produces postscript file, then could be converted into pdf using `ps2pdf`. Both `a2ps` and `ps2pdf` should be in the major Linux distros repository. ``` a2ps input.txt -o output.ps ps2pdf output.ps output.pdf ```
39,654,620
By default IDE genarate a apk like `app-debug.apk` or `app-release.apk` file but I need to generate specific name of the **Apk** of the App. For Example: My application name is **iPlanter** so i need to generate **`iPlanter-debug.apk`** or **`iPlanter-release.apk`** instead of `app-debug.apk` or `app-release.apk` respectively. Thanks,
2016/09/23
[ "https://Stackoverflow.com/questions/39654620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5315735/" ]
This will help you. This code will create app name like iPlanter-release.apk or iPlanter-debug.apk ``` buildTypes { applicationVariants.all { variant -> variant.outputs.each { output -> project.ext { appName = 'iPlanter' } def newName = output.outputFile.name newName = newName.replace("app-", "$project.ext.appName-") output.outputFile = new File(output.outputFile.parent, newName) } } } ``` **Update:** ``` applicationVariants.all { variant -> variant.outputs.all { outputFileName = "iPlanter_${variant.versionName}(${variant.versionCode}).apk" } } ``` It set name like > > iPlanter\_0.0.1(25).apk > > >
Try this code: ``` defaultConfig{ applicationVariants.all { variant -> changeAPKName(variant, defaultConfig) } } def changeAPKName(variant, defaultConfig) { variant.outputs.each { output -> if (output.zipAlign) { def file = output.outputFile output.packageApplication.outputFile = new File(file.parent, "Your APK NAME") } def file = output.packageApplication.outputFile output.packageApplication.outputFile = new File(file.parent, "Your APK NAME") } } ```
21,696,293
As soon as the page load, href link should get trigger(Manual click should not happen).Plz help ``` <a href="www.google.com" id="info">Information</a> <script> $(document).ready(function(){ $("#info").click(function(){ }); $(window).load(function(){ $("#info").trigger("click"); }); }); </script> ```
2014/02/11
[ "https://Stackoverflow.com/questions/21696293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2721624/" ]
Use this ``` <script> $(document).ready(function(){ $("#info").on("click",function(){ var url = $(this).attr('href'); $(location).attr('href',url); }); $("#info").trigger("click"); }); </script> ``` Jsffidle demo <http://jsfiddle.net/waseemmachloy/tBGX3/2/>
Simply ``` $(function(){ $("#info")[0].click(); }); ```
1,258,335
I m using Zend\_Log to create and Log messages. It works well for storing Log messages in to a stream (a new defined file name), well i want to store these messages in to Buffer array. For this i visit : <http://framework.zend.com/wiki/display/ZFPROP/Zend_Log+Rewrite#Zend_LogRewrite-1.Overview> but fail to get their points............. Thanks : Rob Knight But i want some thing like; If i write $logger->info('Informational message'); in any line of my .php file, the message which will show, must contain the Message Text along with Line Number. Let suppose i write $logger->info('Name Already Exists'); at line number 116 of my test.php file. Then the result Log must be like : INFO: "Name Already Exists", Line: 116, File: test.php
2009/08/11
[ "https://Stackoverflow.com/questions/1258335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Here's a shot at it. With this method, you don't need to write any global utility functions. You can use the Zend\_Log interface for all your method calls. In your bootstrap, initialize your logger. Make sure to include the file and line event types in your formatter. Then, create the Logger with a custom writer, which will set the values of the file and line event types at runtime. ``` $format = '%file% %line% %message%' . PHP_EOL; $formatter = new Zend_Log_Formatter_Simple($format); $writer = new My_Log_Writer_Stream('file://' . $traceLogPath); $writer->setFormatter($formatter); $log = new Zend_Log($writer); ``` In the custom writer, go through the backtrace and find the first class that isn't related to your logging libraries. There is probably a more elegant way to write this piece, but it seems to work in my environment (I'll vote you up for any good suggestions). When you have found the desired item in the backtrace, add it to the event array and then call the parent's write method. If you have initialized the formatter correctly, it will write the event values to the log string. ``` class My_Log_Writer_Stream extends Zend_Log_Writer_Stream { protected function _write($event) { $backtrace = debug_backtrace(); foreach($backtrace as $traceItem) { $class = $traceItem['class']; if(!is_subclass_of($class, 'Zend_Log') && !is_subclass_of($class, 'Zend_Log_Writer_Abstract') && $class !== 'Zend_Log' && $class !== 'Zend_Log_Writer_Abstract') { break; } } $event['file'] = $traceItem['file']; $event['line'] = $traceItem['line']; parent::_write($event); } ```
You're gonna have to write your own writer for this functionality I think. You can use debug\_backtrace to see where the $logger->info() for the line and file info. <http://de2.php.net/manual/en/function.debug-backtrace.php>
325,296
I would wager there must be a term of art describing what a fish does as it breathes, normally, underwater. Any thoughts?
2016/05/12
[ "https://english.stackexchange.com/questions/325296", "https://english.stackexchange.com", "https://english.stackexchange.com/users/174975/" ]
This punishment, while potentially useful, is burdened with an overly restrictive [precondition](http://www.oxforddictionaries.com/us/definition/american_english/precondition) for activation. It means > > A condition that must be fulfilled before other things can happen or be done. > > > Also, you may consider [sine qua non](http://dictionary.cambridge.org/dictionary/english/sine-qua-non) > > a necessary condition without which something is not possible. > > >
In safety, there are regulatory limits for exposures to various hazards, such as noise and ionizing radiation. In many cases, there are also **action levels**, which are typically some percentage, e.g., 10% or 50%, of the regulatory limits. When an exposure reaches an action level, that triggers an investigation or intervention to determine the cause of the exposure, the goal being to take measures to reduce the level of exposure before it gets too close to, or exceeds, the exposure limit -- at that point the damage has been done and cannot be undone. Perhaps the term you are looking for is **action level**. I agree that if you need one word, **criterion** or **threshold** could work, but both leave out the concept of a staged or phased two-level approach.
4,571,155
How do i manually initiate values in array on heap? If the array is local variable (in stack), it can be done very elegant and easy way, like this: ``` int myArray[3] = {1,2,3}; ``` Unfortunately, following code ``` int * myArray = new int[3]; myArray = {1,2,3}; ``` outputs an error by compiling ``` error: expected primary-expression before ‘{’ token error: expected `;' before ‘{’ token ``` Do i have to use cycle, or not-so-much-elegant way like this? ``` myArray[0] = 1; myArray[1] = 2; myArray[2] = 3; ```
2010/12/31
[ "https://Stackoverflow.com/questions/4571155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335717/" ]
This is interesting: [Pushing an array into a vector](https://stackoverflow.com/questions/4541556/pushing-an-array-into-a-vector/4541707#4541707) However, if that doesn't do it for you try the following: ``` #include <algorithm> ... const int length = 32; int stack_array[length] = { 0 ,32, 54, ... } int* array = new int[length]; std::copy(stack_array, stack_array + length, &array[0]); ```
`{1,2,3}` is a very limited syntax, specific to POD structure initialization (apparently C-style array was considered one too). The only thing you can do is like `int x[] = {1,2,3};` or `int x[3] = {1,2,3};`, but you can't do neither `int x[3]; x={1,2,3};` nor use `{1,2,3}` in any other place. If you are doing C++, it is preferable to use something like std::vector instead of C-style arrays, as they are considered dangerous - for example you can't know their size and must delete them with a `delete[]`, not a normal `delete`. With std::vector you will still have the same initialization problem, though. If I used such initialization a lot, I would most probably create a macro assigning to a dummy local variable and then copying memory to the destination. EDIT: You could also do it like this (std::vector still preferable): ``` int* NewArray(int v1, int v2, int v3) { /* allocate and initialize */ } int* p = NewArray(1,2,3); ``` but then you'll have to override the function with different number of arguments, or use va\_arg which is, again, unsafe. EDIT2: My answer is only valid for C++03, as other people mentioned C++0x has some improvements to this.
12,393,428
I am a relatively new web apps programmer. I have done differents web apps when HTML 5 were becoming (let's say) the new HTML standard. So I want to know whether it is a good idea to migrate some of those apps to HTML 5. By the way, I never have used HTML 5 in any web application. What things do I have to keep in mind before do a migration or starts new web applications? I mean: browsers, frameworks, javascript libraries, etc. Thanks in advance!
2012/09/12
[ "https://Stackoverflow.com/questions/12393428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1464529/" ]
After much experience running unit tests across multiple environments I recommend not referencing `nunit.framework` that comes with MonoDevelop (or Xamarin Studio). If you only ever run your tests within that IDE it is fine. However, if you run your tests from a command line, a different environment or on a build box then you should have control over your version of NUnit. Thus, if you create a new NUnit Library from the New Project dialog, you should remove the provided `nunit.framework` reference and replace it with your own. Also note that NUnit test runners are very sensitive to the assembly version. So you should keep all of the NUnit binaries together in your source tree. (NUnit-2.6.1/bin weighs in at 7 MB) It is also worth noting that there are other ways to run the tests, such as the [NAnt `<nunit2>` Task](http://nant.sourceforge.net/release/latest/help/tasks/nunit2.html), which will be sensitive to the NUnit version. Thus, having downloaded NUnit 2.6.1\* to the packages directory under my solution directory, the command would be: ``` mono packages/NUnit-2.6.1/bin/nunit-console.exe TryTesting/bin/Debug/TryTesting.dll ``` \*Footnote: I've not been able to use NUnit 2.6.2 due to a NotImplementedException.
I had a similar problem. I removed explicit reference (.dll) and I installed NUnit by Nuget package. Works for me.
38,770,799
i had write a html file which will request some information from user and send it to another php file. The php file will establish the connection to database and insert the value to database. My database name = testdb table name = table1 I had do some testing on both file by calling an alert message, the alert messages was able to display in the html file,it's seen like the request from the html file cant send to the php file,so the code for inserting data to database can't execute My Html form as show below ``` <form id="firstPrize" method="POST" action="firstPrize.php"> <label> Number 1</label> <input type="text" name="num1"><br> <label> Number 2</label> <input type="text" name="num2"><br> <label> Number 3</label> <input type="text" name="num3"><br> <label> Number 4</label> <input type="text" name="num4"><br><br><Br> <input type="button" value="enter" name="btnSubmit" onclick="show()"> </form> ``` firstPrize.php sample code ``` <?php $host = "localhost"; $user = "root"; $password = ""; mysql_connect($host,$user,$password); mysql_select_db("testdb") or die(mysql_error()); Session_Start(); echo("yeah"); if(isset($_POST["btnSubmit"])) { $num1 = $_POST["num1"]; $num2 = $_POST["num2"]; $num3 = $_POST["num3"]; $num4 = $_POST["num4"]; mysql_query("insert into table1(num1,num2,num3,num4) values ('num1','num2','num3','num4')"); ?> ```
2016/08/04
[ "https://Stackoverflow.com/questions/38770799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5157127/" ]
First, your `if` statement is missing a closing `}`. Second, your SQL query is not inserting the variables you've set above. You've got variables like `$num1`, but then you are inserting the value just `'num'` in your SQL insert. You have to change `'num1', 'num2'...` to `'$num1', '$num2'...` Third, please do some research on PHP Data Objects (PDO) or MYSQLi (reference links at bottom of post). `mysql_` is **deprecated** and completely vulnerable to malicious injection. **Edit:** In addition, please see [fred -ii-](https://stackoverflow.com/users/1415724/fred-ii)'s comments below for some sound advice on better `INSERT` queries. It's safe practice to verify that the values are of the type you're expecting prior to running them against your database. [fred -ii-](https://stackoverflow.com/users/1415724/fred-ii) says: > > What if one of those values happens to contain an injection such as '123? > > > *[Use]*... (int)$\_POST["num1"] and check to see firsthand if the input entered is an integer. There are a few functions that will do that. > > > --- Use error reporting and error checking against your query during testing and assuming that you are able to use the MySQL\_ API. References: * <http://php.net/manual/en/function.error-reporting.php> * <http://php.net/manual/en/function.mysql-error.php> Otherwise, you will need to resort to either using the MySQLi\_ or PDO API. References: * <http://php.net/manual/en/book.mysqli.php> * <http://php.net/manual/en/book.pdo.php>
As you clearly mentioned in your question, > > " I had do some testing on both file by calling an alert message, the > alert messages was able to display in the html file, **it's seen like the > request from the html file cant send to the php file ,so the code for inserting data to database can't execute** ~@Heart Break KID " > > > For That, **1)** Change ``` <input type="button" value="enter" name="btnSubmit" onclick="show()"> ``` To ``` <input type="submit" value="enter" name="btnSubmit" onclick="show()"> ``` here, `type='submit'` is required to submit form data.. **2)** Closing curly brackets are not available. Close `if` condition. ``` if(isset($_POST["btnSubmit"])) { // Your query. } ``` Now, data will go to next page. But, read this question [How can I prevent SQL-injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) [The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead](https://stackoverflow.com/questions/13944956/the-mysql-extension-is-deprecated-and-will-be-removed-in-the-future-use-mysqli) ***UPDATED CODE*** (using mysqli) **Html form** ``` <form id="firstPrize" method="POST" action="firstPrize.php"> <label> Number 1</label> <input type="text" name="num1"><br> <label> Number 2</label> <input type="text" name="num2"><br> <label> Number 3</label> <input type="text" name="num3"><br> <label> Number 4</label> <input type="text" name="num4"><br><br><Br> <input type="submit" value="enter" name="btnSubmit" onclick="show()"> </form> ``` **firstPrize.php** ``` <?php $host = "localhost"; $user = "root"; $password = ""; $connect = mysqli_connect($host, $user, $password, "testdb"); session_start(); if(isset($_POST["btnSubmit"])) { $num1 = $_POST["num1"]; $num2 = $_POST["num2"]; $num3 = $_POST["num3"]; $num4 = $_POST["num4"]; $stmt = mysqli_prepare($connect, "INSERT INTO table1(num1,num2,num3,num4) VALUES (?, ?, ?, ?)"); mysqli_stmt_bind_param($stmt, 'ssss', $num1, $num2, $num3, $num4); $query123 = mysqli_stmt_execute($stmt); } ?> ```
6,895
I'm thinking of writing a novel where my character narrates flashbacks through the hardest times of his life written in past tense, leading up to the present tense. I was considering switching to present tense only directly before and throughout the climax of the book so that the reader can understand the character's actions. By writing the beggining of the book as a series of flashbacks I can skip through many years without boring the reader. Then, when he has described the events up to the present day, he will describe his current location and condition and proceed to initiate the climax. So would this kind of switch be ok for a book written in first person point of view? By the way, I'm not a pro writer at all this was just an idea that I had and would like to try.
2012/12/25
[ "https://writers.stackexchange.com/questions/6895", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/4518/" ]
I think that beginning with a series of flashbacks might be difficult for the reader to follow if there was no sense of what they are moving towards. This might not be exactly what you are doing, but in any case my advice would be to consider an *[in medias res](http://en.wikipedia.org/wiki/In_medias_res)* structure. Instead of narrating consecutive flashbacks leading up to the present, begin with a moment just before the climax in present tense, and then revert to flashbacks. This introduces the narrator, introduces the conflict, and gives some context to the flashbacks. It also gives the reader added motivation to figure out what links the flashbacks. The key when using flashbacks of any kind, though, is in the effectiveness of the narrative transitions into and out of the present.
One can debate the validity of the flashback technique, as Lauren Ipsum and Tylerharms do in the comments on another answer. Like many techniques, it can be done well and it can be done lamely. (Oh, how I hate movies that start out with a character brooding over the scene of the disaster -- whether it's the end of his marriage or the end of the world or whatever -- and then he stares soulfully at the camera and says, "Let me remember, how did it all begin ..." Lame lame lame!!) What's the difference between a good use of flashbacks and a lame use of flashbacks? I wish I knew simple criteria I could give. One point: Make it clear to the reader what's the present and what's a flashback. I've read many books where I got really confused because it wasn't clear what was what. I'd be halfway through a scene before I realized it was a flashback. I recall one book where I was halfway through the book before I realized that it was all a flashback from the first scene. Whether that's a simple, "Twenty years ago ..." or something more artistic, make it obvious.
2,272,996
What is the easiest way to simulate a database table with an index in a key value store? The key value store has NO ranged queries and NO ordered keys. The things I want to simulate (in order of priority): 1. Create tables 2. Add columns 3. Create indexes 4. Query based on primary key 5. Query based on arbitrary columns
2010/02/16
[ "https://Stackoverflow.com/questions/2272996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190822/" ]
Use a hashtable or dictionary. If you want unique key values you could use a GUID or hashcode.
The key-value store should support ordering the keys and ranged access to the keys. Then you should create two dictionaries: ``` id -> payload ``` and ``` col1, id -> NULL ``` , where `payload` should contain all the data the database table would contain, and the keys of the second dictionary should contain the values of `(col1, id)` from each entry of the first dictionary.
26,322,873
ternery search tree requires O(log(n)+k) comparisons where n is number of strings and k is the length of the string to be searched and binary search tree requires log(n) comparisons then why is TST faster than BST ?
2014/10/12
[ "https://Stackoverflow.com/questions/26322873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2745366/" ]
``` ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(\W|_)).{5,}$ ``` You can use the above regex with lookahead and you can *easily* append any other criteria if required in future. You're basically checking if each of your criteria is present by lookaheads. ``` if(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(\W|_)).{5,}$/.test(pwd)){ // valid password } ``` [**DEMO**](http://regex101.com/r/cG9vB7/2)
Below regular expression should work for you... ``` var pattern = /^(?=.{5,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W])/ ``` **HTML Code** ``` <input type="text" id="pass" /> <input type="button" id="btnpass" value="Test" /> ``` **jQuery code** ``` var pattern = /^(?=.{5,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W])/ $("#btnpass").click(function(){ var checkval = pattern.test($("#pass").val()); if(!checkval) { alert("Invalid password"); } }); ``` <http://jsfiddle.net/ty72wn1g/4/>
548,408
> > How can I configure `biber`/`biblatex` so that `{\"u}` is printed as `{\"u}` in the `bbl` file, not as `ü`? > > > I uses `biblatex`+`biber`. Because they're stuck in the past, arXiv require a `bbl` file of version `2.8`. I have an old version of `biber`, namely `2.7`, which outputs a `bbl` files with version `2.8`. My issue is with international (non-English) letters. I have some letters like `ü`/etc in my bibliography. When I preview on arXiv, these letters simply aren't printed. (They are in the `bbl` file as `ü`/etc.) So I went through my *entire* reference set (managed with Zotero) and replaced `ü` with `\"u` and so on. (That was fun use of time `;)`!) However, when I run `biber`, even though in the `bib` file the information is stored as `\"u`, the created `bbl` file coerces this to `ü` -- which then does not get printed by arXiv. Ideally, `biber` would take `ü` as an input and output `{\"u}`, but this seems a bit too much to ask... (Actually, ideally arXiv would be more modern, but that's also a bit too much to ask!) As I said, I am using `biber 2.7`. I combine this with `biblatex 3.3`.
2020/06/08
[ "https://tex.stackexchange.com/questions/548408", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/81928/" ]
It's difficult to fit such big objects in a table without making line breaks. Here's my suggestion: the laws' names on a line by themselves, in italic type; then the mathematical law and its description. Some spacing between rows will help in dividing the four parts. With `tabularx` the second column takes all the space left free by the first column. With `>{$\displaystyle}l<{$}` the first column is typeset flush left, in display style like when in displays (don't use `$$` in general, but the proper environments). Finally, I added a command for the differential; since it *may* happen that you're required to make the “d” upright, it's better having it in the code as a command, so you can just change the definition. ```latex \documentclass[11pt]{article} \usepackage{amsmath} \usepackage{booktabs,array,tabularx} \usepackage{esvect} \newcommand{\diff}{\mathop{}\!d} \begin{document} \begin{center}\bfseries\Large MAXWELL’S EQUATIONS \end{center} Maxwell’s equations summarize electromagnetism and form its foundation, including optics. \bigskip \noindent \begin{tabularx}{\textwidth}{@{} >{$\displaystyle}l<{$} X @{}} \multicolumn{2}{@{}l@{}}{\itshape Gauss’ law for electricity} \\ \addlinespace[2pt] \oint \vec{E}\cdot \diff\vec{A}= \frac{q_{\mathrm{enc}}}{\varepsilon_0} & Relates net electric flux to net enclosed electric charge\\ \addlinespace \multicolumn{2}{@{}l@{}}{\itshape Gauss’ law for magnetism} \\ \addlinespace[2pt] \oint \vec{B}\cdot \diff\vec{A}=0 & Relates net magnetic flux to net enclosed magnetic charge\\ \addlinespace \multicolumn{2}{@{}l@{}}{\itshape Faraday’s law} \\ \addlinespace[2pt] \oint \vec{E}\cdot \diff\vec{s}= -\frac{\diff\Phi_B}{\diff t} & Relates induced electric field to changing magnetic flux\\ \addlinespace \multicolumn{2}{@{}l@{}}{\itshape Ampère--Maxwell law} \\ \addlinespace[2pt] \oint \vec{B}\cdot d\vec{s}= \mu_0\varepsilon_0\frac{\diff\Phi_E}{\diff t}+\mu_0i_{\mathrm{enc}} & Relates induced magnetic field to changing electric flux and to current\\ \end{tabularx} \end{document} ``` Instead of `\overrightarrow` that adds a too big arrow, it's better to use `\vec` or make the vector's symbols bold. Note also that `_\textrm{enc}` and similar only works by chance. It should better be `_{\mathrm{enc}}`. A stylistic remark: you want to center something which is large in size and boldface, not to boldface something that's centered. [![enter image description here](https://i.stack.imgur.com/cRjZA.png)](https://i.stack.imgur.com/cRjZA.png) If you also do `\usepackage{bm}` and add ``` \renewcommand{\vec}[1]{\bm{#1}} ``` the output would become [![enter image description here](https://i.stack.imgur.com/vdARs.png)](https://i.stack.imgur.com/vdARs.png)
Another solution only for fun! ``` \documentclass[12pt]{article} \usepackage{amsmath,palatino} \usepackage{longtable,array} \renewcommand\arraystretch{2.5} \begin{document} \begin{longtable}{|m{0.3\linewidth}|>{\centering$\displaystyle}m{0.3\linewidth}<{$}|m{0.4\linewidth}|}\hline Gauss' law & \vec{\nabla} \cdot \vec{B} = 0 & Relates net electric flux to net enclosed electric charge.\\\hline Gauss' law & \vec{\nabla} \cdot \vec{D} = \rho_{\text{enc}} & Relates net magnetic flux to net enclosed magnetic charge.\\\hline Faraday's law & \vec{\nabla} \times \vec{E} = - \frac{\partial B}{\partial\, t} & Relates induced electric field to changing magnetic flux. \\\hline Ampere-Maxwell law & \vec{\nabla} \times \vec{H} = \vec{J} + \frac{\partial \vec{D}}{\partial\, t} & Relates induced magnetic field to changing electric flux and to current. \\\hline \end{longtable} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/gWw85.png)](https://i.stack.imgur.com/gWw85.png)
1,522,444
I've been trying to redirect System.out PrintStream to a JTextPane. This works fine, except for the encoding of special locale characters. I found a lot of documentation about it (see for ex. [mindprod encoding page](http://mindprod.com/jgloss/encoding.html)), but I'm still fighting with it. Similar questions were posted in StackOverFlow, but the encoding wasn't addressed as far as I've seen. First solution: ``` String sUtf = new String(s.getBytes("cp1252"),"UTF-8"); ``` Second solution should use java.nio. I don't understand how to use the Charset. ``` Charset defaultCharset = Charset.defaultCharset() ; byte[] b = s.getBytes(); Charset cs = Charset.forName("UTF-8"); ByteBuffer bb = ByteBuffer.wrap( b ); CharBuffer cb = cs.decode( bb ); String stringUtf = cb.toString(); myTextPane.text = stringUtf ``` Neither solution works out. Any idea? Thanks in advance, jgran
2009/10/05
[ "https://Stackoverflow.com/questions/1522444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Try this code: ``` public class MyOutputStream extends OutputStream { private PipedOutputStream out = new PipedOutputStream(); private Reader reader; public MyOutputStream() throws IOException { PipedInputStream in = new PipedInputStream(out); reader = new InputStreamReader(in, "UTF-8"); } public void write(int i) throws IOException { out.write(i); } public void write(byte[] bytes, int i, int i1) throws IOException { out.write(bytes, i, i1); } public void flush() throws IOException { if (reader.ready()) { char[] chars = new char[1024]; int n = reader.read(chars); // this is your text String txt = new String(chars, 0, n); // write to System.err in this example System.err.print(txt); } } public static void main(String[] args) throws IOException { PrintStream out = new PrintStream(new MyOutputStream(), true, "UTF-8"); System.setOut(out); System.out.println("café résumé voilà"); } } ```
As you rightfully assume the problem is most likely in: ``` String s = Character.toString((char)i); ``` since you encode with UTF-8, characters may be encoded with more than 1 byte and thus adding each byte you read as a character won't work. To make it work you can try writing all bytes into a ByteBuffer and using a CharsetDecoder (Charset.forName("UTF-8).newDecoder(), "UTF-8" to match the PrintStream) to convert them into characters which you add the panel. I haven't tried it to make sure it works, but I think it is worth a try.
36,846
If the stock market crashes 20%, do bonds suffer or is there little to no correlation between the two markets?
2014/09/10
[ "https://money.stackexchange.com/questions/36846", "https://money.stackexchange.com", "https://money.stackexchange.com/users/2239/" ]
It depends. Very generally when yields go up stocks go down and when yields go down stocks go up (as has been happening lately). If we look at the yield of the 10 year bond it reflects future expectations for interest rates. If the rate today is very low but expectations are that the short term rates will go up that would be reflected in a higher yield simply because no one would buy the longer term bond if they could simply wait out and get a better return on shoter term investments. If expectations are that the rate is going down you get what's called an inverted yield curve. The inverted yield curve is usually a sign of economic trouble ahead. Yields are also influenced by inflation expectations as @rhaskett is alluding in his answer. So. If the stock market crashes because the economy is doing poorly and if interest rates are relatively high then people would expect the rates to go down and therefore bonds will go up! However, if there's rampant inflation and the rates are going up we can expect stocks and bonds to move in opposite directions. Another interpretation of that is that one would expect stock prices to track inflation pretty well because company revenue is going to go up with inflation. If we're just talking about a bump in the road correction in a healthy economy I wouldn't expect that to have much of an immediate effect though bonds might go down a little bit in the short term but possibly even more in the long term as interest rates eventually head higher. Another scenario is a very low interest rate environment (as today) with a stock market crash and not a lot of room for yields to go further down. Both stocks and bonds are influenced by current interest rates, interest rate expectations, current inflation, inflation expectations and stock price expectation. Add noise and stir.
It depends on **why** the stocks crashed. If this happened because interest rates shot up, bonds will suffer also. On the other hand, stocks could be crashing because economic growth (and hence earnings) are disappointing. This pulls **down** interest rates and lifts bonds.
45,333,609
I'm inserting data into the influxDb using batch points via Java API (used http API under the hood) after some time the exception is raised. ``` java.lang.RuntimeException: {"error":"partial write: max-values-per-tag limit exceeded (100010/100000): ``` According to the Influx docs - [docs](https://www.influxdata.com/influxdb-1-1-released-with-up-to-60-performance-increase-and-new-query-functionality/) this parameter prevent high cardinality data from being written before it can be fixed into the Influx. I can set it to 0 to remove Exception. But I don't clear understand what is "high cardinality data". What's wrong to have "high cardinality data" to be inserted into InfluxDb. I'm going to insert millions unique values and need them to be indexed. Do I need to review my data design ?
2017/07/26
[ "https://Stackoverflow.com/questions/45333609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/359376/" ]
They are using in memory index for "tags", the more different tags values you have (the higher aardinality of the data) the more memory influx requires. <https://github.com/influxdata/influxdb/issues/7151>
InfluxDB may require high amounts of memory for high cardinality data (~10KB of memory per time series) and memory requirements may grow exponentially with the number of unique time series. See [these official docs](https://docs.influxdata.com/influxdb/v1.7/guides/hardware_sizing/#when-do-i-need-more-ram) for details. There are other time series databases exist, which require lower amounts of RAM for high cardinality data. For instance, [this benchmark](https://medium.com/@valyala/insert-benchmarks-with-inch-influxdb-vs-victoriametrics-e31a41ae2893) compares memory usage and performance of InfluxDB and VictoriaMetrics - an alternative TSDB, which understands [Influx line protocol](https://docs.influxdata.com/influxdb/v1.7/write_protocols/line_protocol_tutorial/).
1,969,620
I'm looking at some 3rd party code and am unsure exactly what one line is doing. I can't post the exact code but it's along the lines of: ``` bool function(float x) { float f = doCalculation(x); return x > 0 ? f : std::numeric_limits<float>::infinity(); } ``` This obviously throws a warning from the compiler about converting float->bool, but what will the actual behaviour be? How does Visual C++ convert floats to bools? At the very least I should be able to replace that nasty infinity...
2009/12/28
[ "https://Stackoverflow.com/questions/1969620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
I think it is a mistake. That function should return a float. This seem logical to me. The conversion float to bool is the same as float != 0. However, strict comparing two floating points is not always as you'd expect, due to precision.
I think it would be better to use **isnan()**. isnan() returns true if f is not-a-number. But it will return true for e.g. 0.0 ... ``` #include <cmath> bool function(float x) { float f = doCalculation(x); return isnan(f) ? false : true; } ``` as mentioned that will not catch the case where f is 0.0 - or very close to it. If you need this you could check with: ``` bool near0 = std::abs(f) > std::numeric_limits<float>::epsilon(); ``` EDIT: here an improved example including a test driver: ``` #include <cmath> #include <limits> #include <iostream> #include <vector> // using namespace std; bool fn(float f) { if (isnan(f)) return false; // it is not-a-number return std::abs(f) > std::numeric_limits<float>::epsilon(); } // testdriver int main(void) { std::vector<float> t; t.push_back(0.0); t.push_back(0.1); t.push_back(-0.1); t.push_back( 0.0 + std::numeric_limits<float>::epsilon()); t.push_back( 0.0 - std::numeric_limits<float>::epsilon()); t.push_back( 0.0 - 2*std::numeric_limits<float>::epsilon()); t.push_back( 0.0 + 2*std::numeric_limits<float>::epsilon()); t.push_back( 1.0 * std::numeric_limits<float>::epsilon()); t.push_back(-0.1 * std::numeric_limits<float>::epsilon()); t.push_back( 0.1 * std::numeric_limits<float>::epsilon()); for (unsigned int i=0; i<t.size(); i++) { std::cout << "fn(" << t[i] << ") returned " << fn(t[i]) << std::endl; } } ``` testresults: ``` fn(0) returned 0 fn(0.1) returned 1 fn(-0.1) returned 1 fn(1.19209e-07) returned 0 fn(-1.19209e-07) returned 0 fn(-2.38419e-07) returned 1 fn(2.38419e-07) returned 1 fn(1.19209e-07) returned 0 fn(-1.19209e-08) returned 0 fn(1.19209e-08) returned 0 ```
21,174,359
I'm trying to add fields dynamically to a web page so that a user can enter in additional amenities to a form. By clicking on the add amenity button I can add the fields just fine. However I cannot manage to get the values out of the input fields dynamically. The objective is to display what they type after they leave the field (using `(':text').blur(myFunction);`). This works for every other field I've used it on but for some reason I can't get the value to dynamically pull after I leave an 'amenity' field. ``` $('#new_amenity').on('click', function (event) { amenity++; $(this).prev().after('<br/><input type="text" value="" class="' + amenity + '" placeholder="Amenity" id="amenity" />'); event.preventDefault(); }); ``` Below is the code that I've tried to use to assign to the array. ``` //inside myfunction(); for(var i=1; $('#amenity').hasClass('.' + i);i++){ amenities[i]=$('.'+i).val(); } //outside of function $(":text").blur(myfunction); ```
2014/01/16
[ "https://Stackoverflow.com/questions/21174359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3192152/" ]
I've just made this ugly example. And it worked, it retrieves all messages including those that have been seen. ``` Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); Session session = Session.getDefaultInstance(props, null); try { Store store = App.session.getStore("imaps"); store.connect("imap-mail.outlook.com", "email", "password"); Folder folder = App.store.getFolder("Inbox"); folder.open(Folder.READ_ONLY); Message[] msgs = folder.getMessages(); for (Message msg : msgs) { System.out.println(msg.getSubject()); } }catch(MessagingException e) { System.out.println(e); } ``` Of course you will have to properly retrieve just the mails you need, otherwise if you have an old email account this code will start a very heavy process. I hope this could be helpfull.
``` import java.util.*; import javax.mail.*; public class ReadingEmail { public static void main(String[] args) { Properties props = new Properties(); props.setProperty("mail.store.protocol", "imaps"); try { Session session = Session.getInstance(props, null); Store store = session.getStore(); store.connect("imap.gmail.com", "example@gmail.com", "Password"); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); Message msg = inbox.getMessage(inbox.getMessageCount()); Address[] in = msg.getFrom(); for (Address address : in) { System.out.println("FROM:" + address.toString()); } Multipart mp = (Multipart) msg.getContent(); BodyPart bp = mp.getBodyPart(0); System.out.println("SENT DATE:" + msg.getSentDate()); System.out.println("SUBJECT:" + msg.getSubject()); System.out.println("CONTENT:" + bp.getContent()); } catch (Exception mex) mex.printStackTrace(); } } } ```
3,369,107
I am currently reading Folland's Real Analysis. On page 145 of his book, he claims the following: > > **Claim**: If $X$ is a noncompact, locally compact Hausdorff space, then the closure of the image of the embedding $e:X\hookrightarrow I^\mathcal F$ associated to $\mathcal F=C\_c(X)\cap C(X,I)$ is the one-point compactification of $X$. > > > A few remarks: * The "associated embedding" refers to the map $X\to I^\mathcal F$ obtained by mapping $X\ni x\mapsto \hat x\in I^{\mathcal F}$, where $\hat x$ is given by $\hat x(f)=f(x)$ for $f\in \mathcal F$. * $C\_c(X)$ is the set of all continuous, compactly supported, complex valued functions on $X$. * $C(X,I)$ is the set of all continuous functions from $X$ to $I=[0,1]$. I understand that this is indeed an embedding, because Urysohn's lemma guarantees that $\mathcal F$ separates points and closed sets and we know Theorem 1 below. I also understand that $\overline{e(X)}\setminus X$ contains at least one point because $\overline {e(X)}$ is a compact space containing the noncompact subspace $X$. What I do not understand is that why $\overline {e(x)}\setminus X$ consists of precisely one point. I managed to prove the above claim. (See below. Any comment on the proof is welcome.) But it's a bit lengthy. Folland states the above claim as if it's very trivial, so I must be missing something. Can someone help me? Thanks in advance. --- **Theorem 1**: Let $X$ be a completely regular space, and suppose that $\mathcal F\subset C(X,I)$ is a collection that separates points and closed sets (that is, if $E\subset X$ is a closed set and $x\in X\setminus E$, then there is some $f\in \mathcal F$ such that $f(x)\not\in \overline{f(E)}$). Then the map $X\hookrightarrow I^{\mathcal F}$ defined as above is an embedding. --- **My attempt**: I first proved the following: > > Lemma 1: Let $X$ be a completely regular space, let $Y$ be a compact > Hausdorff space, and let $\phi\in C(X,Y)$. Suppose that $\mathcal{F}\subset C(X,I)$ separates > points and closed sets, and the collection > $\mathcal{G}=(\phi^{\*})^{-1}(\mathcal{F})\subset C(Y,I)$ also > separates points and closed sets. Then $\phi$ has a > unique continuous extension $\tilde{\phi}:\hat{X}\to Y$, where $\hat{X}$ is the compactification of $X$ associated to $\mathcal F$. If $\phi$ > is a compactification of $X$, then $\tilde{\phi}$ is a quotient map. > > > Here $\phi^\*$ is the pullback $\phi^\*(g)=g\circ \phi$. (Proof of Lemma 1.)The map $\phi:X\to Y$ defines the pullback $\phi^{\*}:\mathcal{G}\to\mathcal{F}$ given by $\phi^{\*}(g)=g\circ\phi$, and then $\phi^{\*}$ defines the pullback $\Phi=\phi^{\*\*}:I^{\mathcal{F}}\to I^{\mathcal{G}}$ given by $\Phi(F)=F\circ\phi^{\*}$. It is easy to check that the diagram $$\require{AMScd} \begin{CD} X@>>> I^{\mathcal F} \\ @VV\phi V & @V\Phi VV\\ Y@>>> I^{\mathcal G} \end{CD} $$commutes. (The horizontal maps are the embeddings.) For each $g\in\mathcal{G}$, the corresponding coordinate function of $\Phi$ is given by $\pi\_{g}\circ\Phi=\pi\_{g\circ\phi}:I^{\mathcal{F}}\to I$. Because $\pi\_{g\circ\phi}$ just a projection, it follows that $\pi\_{g}\circ\Phi$ is continuous. Therefore $\Phi$ is continuous. Now by the closed map lemma, $Y$ is closed in $I^{\mathcal{G}}$, so $Y=\overline{Y}$. Thus we have $\Phi(\hat{X})=\overline{\Phi(X)}\subset Y$, where the equality follows again from the closed map lemma. So $\Phi$ restricts to a map $\tilde{\phi}:\overline{X}\to Y$ which extends $\phi$. Because $X$ is dense in $\hat{X}$ and $Y$ is Hausdorff, this is a unique extension. If $\phi$ is a compactification of $X$, then $\overline{\Phi(X)}=Y$ , so $\tilde{\phi}$ is surjective and hence is a quotient map by the closed map lemma. $\blacksquare $ > > Lemma 2:In the situation of lemma 1, if every function $f\in\mathcal{F}$ has a > continuous extension to $Y$, then $\tilde{\phi}:\hat{X}\to Y$ > is a homeomorphism. > > > (Proof.) In view of the preceding proposition, it suffices to show that $\tilde{\phi}$ is injective. So suppose that $F,F'\in\hat{X}$ are distinct elements of $\hat{X}$. Then there is some $f\in\mathcal{F}$ such that $F(f)\neq F'(f)$. If $g:Y\to I$ denotes the continuous extension of $f$, then $\tilde{\phi}(F)(g)=F(g\circ\phi)=F(f)$, and similarly, $\tilde{\phi}(F')(g)=F'(f)$. Therefore $\tilde{\phi}(F)\neq\tilde{\phi}(F')$, proving that $\tilde{\phi}$ is injective. $\blacksquare$ Now we can prove our claim. Suppose $X$ is a locally compact Hausdorff space, and let $\phi:X\to X^{\*}=X\cup {\infty}$ be the one-point compactification of $X$. By the Urysohn's lemma, the collection $\mathcal{F}=C\_{c}(X,I)\cap C(X)$ separates points and closed sets. The collection $\mathcal{G}=(\phi^{\*})^{-1}(\mathcal{F})$ consists of continuous functions $g:X^{\*}\to I$ with $\operatorname{supp}\_{g}\subset X$. Because $X^{\*}$ is normal, given a point $x\in X^{\*}$ and a closed set $A\subset X^{\*}$ disjoint from $X$, there exists a closed set $B\subset X^{\*}$ containing a neighborhood of $x$, and then the Urysohn's lemma shows that there is some $g\in\mathcal{G}$ that is equal to 0 on $A$ and $1$ on $B$. So $\mathcal{G}$ separates points and closed sets. Moreover, any function in $\mathcal{F}$ extends continuously to $X^{\*}$ (by declaring ). Thus by above lemmas, $\hat{X}$ is homeomorphic to $X^{\*}$.
2019/09/25
[ "https://math.stackexchange.com/questions/3369107", "https://math.stackexchange.com", "https://math.stackexchange.com/users/544921/" ]
Your proof is correct, although you should explicitly define $\hat X$ is and restate lemma 1 as > > Lemma 1: Let $X$ be a completely regular space, and let $Y$ be a compact > Hausdorff space. Suppose that $\mathcal{F}\subset C(X,I)$ separates > points and closed sets. Then any $\phi\in C(X,Y)$ such that the collection > $\mathcal{G}=(\phi^{\*})^{-1}(\mathcal{F})\subset C(Y,I)$ also > separates points and closed sets, has a > unique continuous extension $\tilde{\phi}:\hat{X}\to Y$. If $\phi$ > is a compactification of $X$, then $\tilde{\phi}$ is a quotient map. > > > However, your approach is too complicated. Let $X^+$ denote the one-point compactification of $X$ and write $X^+ \setminus X = \{\infty\}$. Then each $f \in C\_c(X)$ has a (trivally unique) extension $f^+ : X^+ \to \mathbb C$ (take $f^+(\infty) = 0$). Clearly if $f \in C(X,I)$, then $f^+ \in C(X^+,I)$. Let $j : \mathcal F \to C(X^+,I), j(f) = f^+$. If $i : X \to X^+$ denotes inclusion, then the diagram $$\require{AMScd} \begin{CD} X@> \epsilon >> I^{\mathcal F} \\ @VVi V @AA j^\*A \\ X^+@>>\epsilon^+ > I^{\mathcal C(X^+,I)} \end{CD} $$ commutes because for $x \in X$ and $f \in \mathcal F$ we have $$\big(j^\*(\epsilon^+(i(x)))\big)(f) = \big(\epsilon^+(i(x))j\big)(f) = \epsilon^+(i(x))(j(f)) = \epsilon^+(i(x))(f^+) = f^+(i(x)) = f(x) =\epsilon(x)(f) .$$ $X' = (j^\*\epsilon^+)(X^+)$ is compact, thus $\overline{\epsilon (X)} \subset X'$. But $X' = (j^\*\epsilon^+)(X^+) = (j^\*\epsilon^+)(X \cup \{\infty\}) = \epsilon(X) \cup \{ (j^\*\epsilon^+)(\infty) \}$.
Simply use the fact mentioned in the preceding sentence (on p.145): Y consists of e(X) together with the single point of $I^{\mathcal{F}}$ all of whose coordinates are zero. To prove the aforementioned fact, just observe that if $y \in Y \setminus e(X)$, then $y \notin K$ for all compact subsets $K \subseteq e(X)$.
32,640,250
I'm having an issue where my gameObject barely jumps at all. I think it has something to do with `moveDirection` because the jumping works when I comment out `p.velocity = moveDirection`. Any suggestions on how to fix this? ``` using UnityEngine; using System.Collections; public class Controller : MonoBehaviour { public float jumpHeight = 8f; public Rigidbody p; public float speed = 1; public float runSpeed = 3; public Vector3 moveDirection = Vector3.zero; // Use this for initialization void Start () { p = GetComponent<Rigidbody>(); p.velocity = Vector3.zero; } // Update is called once per frame void Update () { if (Input.GetKeyDown (KeyCode.Space)) { p.AddForce(new Vector3(0, jumpHeight, 0), ForceMode.Impulse); } Move (); } void Move () { if(Input.GetKey(KeyCode.D)) { transform.Rotate(Vector3.up, Mathf.Clamp(180f * Time.deltaTime, 0f, 360f)); } if(Input.GetKey(KeyCode.A)) { transform.Rotate(Vector3.up, -Mathf.Clamp(180f * Time.deltaTime, 0f, 360f)); } moveDirection = new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical")); moveDirection = transform.TransformDirection(moveDirection); if(Input.GetKey(KeyCode.LeftShift)) { moveDirection *= runSpeed; } else { moveDirection *= speed; } p.velocity = moveDirection; } } ```
2015/09/17
[ "https://Stackoverflow.com/questions/32640250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5348182/" ]
You would just have to use the **createdRow** ``` $('#data-table').DataTable( { createdRow: function( row, data, dataIndex ) { // Set the data-status attribute, and add a class $( row ).find('td:eq(0)') .attr('data-status', data.status ? 'locked' : 'unlocked') .addClass('asset-context box'); } } ); ```
**To set the Id attribute on the row `<tr>` use:** ``` //.... rowId: "ShipmentId", columns: [...], //.... ``` **To set a class name on the `<tr>` use this calback** ``` createdRow: function (row, data, dataIndex) { $(row).addClass('some-class-name'); }, ``` ref: <https://datatables.net/reference/option/createdRow> **To set a class on the `<td>` use** ``` "columns": [ { data:"", className: "my_class", render: function (data, type, row) { return "..."; } }, { data:"", className: "my_class", render: function (data, type, row) { return "..."; } }, //... ] ``` Something similar for 'columnDefs' ref: <https://datatables.net/reference/option/columns.className>
39,387,688
i want to remove all unselected option of Particular select box by j-query and java script simple code example : if i select test- 1 option of first select box, than all unselected option remove of first select box , and this condition apply on all select box ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <select class="mymultiSelect" onchange="myfun()"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <select class="mymultiSelect" onchange="myfun()"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <select class="mymultiSelect" onchange="myfun()"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <select class="mymultiSelect" onchange="myfun()"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <select class="mymultiSelect" onchange="myfun()"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <script> function myfun(){ var foo = []; $('.mymultiSelect :selected').each(function(i, selected){ if($(selected).val() != 0) { foo[i] = $(selected).val(); alert(foo[i]); } }); } </script> ```
2016/09/08
[ "https://Stackoverflow.com/questions/39387688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5935830/" ]
Try something like this : ```js $(function() { $('.mymultiSelect').on('change', function() { $(this).find('option').not(':selected').remove(); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="mymultiSelect"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <select class="mymultiSelect"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <select class="mymultiSelect"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <select class="mymultiSelect"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <select class="mymultiSelect"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> ```
Im not quite sure I understand correctly. My code uses the value that is selected and removes it from all the other selects. I hope this works for you. ```js $(function() { $('.mymultiSelect').on('change', function() { $('.mymultiSelect').not($(this)).find('option[value="'+$(this).val()+'"]').remove(); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="mymultiSelect"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <select class="mymultiSelect"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <select class="mymultiSelect"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <select class="mymultiSelect"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> <select class="mymultiSelect"> <option value="0">-select-</option> <option value="1">test - 1</option> <option value="2">test - 2</option> <option value="3">test - 3</option> <option value="4">test - 4</option> </select> ```
42,227,537
I am reading a book on compiler design and implementation. In the part about storage management the author writes a function to allocate memory. He wants the function to be suitably aligned for any type. He claims that the size of the union below is the minimum alignment on the host machine. I don't quite understand what that means. From the book: "... its fields are those that are most likely to have the strictest alignment requirements." ``` union align { long l; char *p; double d; int (*f) (void); }; ``` Could somebody explain what 'strictest alignment requirements' means and how does this give the minimum alignment on the host machine ?
2017/02/14
[ "https://Stackoverflow.com/questions/42227537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/904194/" ]
The alignment of a union is chosen to be the same as the alignment of the member with the greatest alignment requirements. Its size chosen to be as big as the biggest member, plus some additional padding at the end to ensure that the alignment doesn't break when it is laid out sequentially in an array. So in that sense, `union align` will have the same alignment as either `l`, `p`, `d` or `f` (whichever has the greatest alignment requirements). For example, if the `f` member which is of type `int (*)(void)` has an alignment requirement of `8`, the whole union will be aligned on an 8-byte boundary, even if `long` requires only `4`. I am not quite certain whether the standard guarantees that the greatest alignment requirement from these 4 types will be the "minimum alignment on the host machine". It may be just a good exercise in order to understand the way in which the compiler works with regard to storage management.
Consider a machine that, due to memory bus limitations, can read 16-bit values only from even addresses. A 16-bit value on such a machine would have an "alignment requirement" of 2. Do **not** rely on `union` trickery. Since C11, there are: * [`max_align_t`](http://en.cppreference.com/w/c/types/max_align_t) which is synonymous to the largest (standard) scalar type for a platform(1), i.e. a type with the alignment as served by `malloc()`. * [`_Alignof`](http://en.cppreference.com/w/c/language/_Alignof), which gives the alignment requirements for a given type. * [`alignas`](http://en.cppreference.com/w/c/language/_Alignas), which allows to modify the alignment of types. (1): The largest such type would *usually* be `long double`, a type suspiciously absent from your book's example... Note that a compiler might support "extension" types which require special handling. For example, having a 256-byte SSE data type, but having `malloc()` "only" do 128-byte alignment.
57,432
I am replacing the toilet in my house, and after removing the old toilet, I can see that the flange is not bolted to the floor. Also, it sits up off the finished floor about a quarter inch. Do I need to add any supports underneath to fill the gap, and do I need to drill holes and bolt it down to the subfloor before installing the new toilet?
2015/01/08
[ "https://diy.stackexchange.com/questions/57432", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/31453/" ]
We would usually screw it down during the rough in. Having said that I personally see nothing wrong with cementing it to the exit pipe below. Although not my first choice I have seen installs last many many years without screwing in the flange. For example for basement bathrooms I would just attach the flange via cement. Also if you have the PVC cemented together the screws are really doing nothing, other than backing up the cement in case of failure.
If your pipe is already installed with a flange and studs, it's probably attached correctly. A sub floor was probably installed during the last remodeling. You just need to check for rot around the pipe flange.
39,786,337
I wish to convert a JS object into x-www-form-urlencoded. How can I achieve this in angular 2? ``` export class Compentency { competencies : number[]; } postData() { let array = [1, 2, 3]; this.comp.competencies = array; let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); let options = new RequestOptions({ headers: headers, method: 'post' }); return this.http.post(this.postUrl, JSON.stringify(this.comp), options) .map(res => res.json().data.competencies) .catch(this.handleError); } ```
2016/09/30
[ "https://Stackoverflow.com/questions/39786337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6897022/" ]
```js let o = { a:1, b:'2', c:true }; let s = new URLSearchParams(Object.entries(o)).toString(); console.log(s); ```
Assume have an object named postdata as below: ```js const postdata = { 'a':1, 'b':2, 'c':3 }; ``` and, you want convert it into x-www-form-urlencoded format, like: `a=1&b=2&c=3` with [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams) it's very easy to do it. ```js const rawData = new URLSearchParams(Object.keys(postdata).map(key=>[key,postdata[key]])); console.log(rawData.toString());//a=1&b=2&c=3 ```
9,725,103
I have a nested inner class that extends AsyncTask to run a db query in the background. In the post execute method I am calling a parent's method to update the view something like this ``` private class QueryRunner extends AsyncTask<Void,Void,Cursor> { @Override protected Cursor doInBackground(Void... voids) { return getContentResolver().query(LeadContentProvider.buildUri(app.getEntityId()),new String[]{LeadContentProvider._ID},null,null,LeadContentProvider.LEAD_STATUS_DATETIME +" desc"); } @Override protected void onPostExecute(Cursor c) { onCursorLoaded(c); } } ``` The onCursorLoaded method looks like: ``` private void onCursorLoaded(Cursor c) { mPagerAdapter = new LeadDetailsFragmentPagerAdaper(getSupportFragmentManager()); mPager.setAdapter(mPagerAdapter); mPager.setCurrentItem(iIndex, false); } ``` Most of the time this works fine - but some users have crashes with this stack trace: ``` java.lang.IllegalStateException: Must be called from main thread of process at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1392) at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:431) at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:139) at android.support.v4.view.ViewPager.populate(ViewPager.java:804) at android.support.v4.view.ViewPager.setAdapter(ViewPager.java:344) at com.servicemagic.pros.activities.LeadDetails.onCursorLoaded(LeadDetails.java:205) at com.servicemagic.pros.activities.LeadDetails.access$200(LeadDetails.java:25) at com.servicemagic.pros.activities.LeadDetails$QueryRunner.onPostExecute(LeadDetails.java:196) at com.servicemagic.pros.activities.LeadDetails$QueryRunner.onPostExecute(LeadDetails.java:170) at android.os.AsyncTask.finish(AsyncTask.java:417) at android.os.AsyncTask.access$300(AsyncTask.java:127) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:150) at android.os.HandlerThread.run(HandlerThread.java:60) ``` So - why is the postExecute() method not called on the MainThread?
2012/03/15
[ "https://Stackoverflow.com/questions/9725103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/54321/" ]
Is "another\_value" supposed to represent a magic number or another vaiable? First things first, you should assign all primitives an initial value when they are defined. Don't use magic numbers, used #define ANOTHER\_VALUE 0, if this is the case. > > When I remove it from the C file and put it under the private variables in the header file, it compiles fine but then my output blows up. > > > Probably because you need to extern "C" they variable, if you are pulling in the protoype for use from c code: [How do I use extern to share variables between source files?](https://stackoverflow.com/questions/1433204/what-are-extern-variables-in-c) Here's a compiling example: externTest.hpp ``` /* * externTest.hpp * * Created on: Mar 15, 2012 */ #ifndef EXTERNTEST_HPP_ #define EXTERNTEST_HPP_ class eTest { private: unsigned long m_test; public: eTest(); void testValue(); }; #endif /* EXTERNTEST_HPP_ */ ``` externTest.cpp ``` //============================================================================ // Name : externTest.cpp // Author : // Version : //============================================================================ #include <stdio.h> #include <stdlib.h> #include <iostream> #include "externTest.hpp" extern "C" { #include "value.h" } using namespace std; eTest::eTest() { m_test=global_table; } void eTest::testValue() { printf("Global C Value: %lu \n", global_table); cout << "Test global value: " << m_test << endl; } ``` value.h ``` /* * value.h * * Created on: Mar 15, 2012 */ #ifndef VALUE_H_ #define VALUE_H_ extern unsigned long global_table; void assign_value(unsigned long lValue); void print_global_value(); #endif /* VALUE_H_ */ ``` value.c ``` /* * value.c * * Created on: Mar 15, 2012 */ #include "value.h" unsigned long global_table; void assign_value(unsigned long lValue) { global_table=lValue; } void print_global_value() { printf("Global C Value: %lu \n", global_table); } ``` If you want to use the physical address of table, just make m\_test a pointer to global\_table: ``` private: unsigned long *m_test; ``` Be sure to dereference your pointer for the value: ``` eTest::eTest() { m_test=&global_table; } void eTest::testValue() { printf("Global C Value: %lu \n", global_table); cout << "Test global value: " << *m_test << endl; } ```
Is `table` supposed to be shared between all instances of `test`, or do you want one instance per class instance (and zero instances when there are no instances). The semantics you have to begin with result in one instance shared between all instances of `test`. To get this with a member variable, it is necessary to declare it `static` in the class definition, and to define it in one of the source files.
12,373,064
Sorry I know this is a generic question, I'll try to provide as much detail as possible I am running Bitnami Rubystack (3.2.7) on Amazon EC2 Medium instance. and some aspects of Rails are extremely slow, here are some of them: * when logging in (I am using devise gem), if you provide an invalid password, it would take a long time to tell you that the password is invalid. * Sign Up process takes extremely long, responds after about 2 minutes (when all it has to do is run a couple of queries agains the db?) * File uploads (on carrierwave) are so slow they are practically not working. (files are going to S3 via Fog on CarrierWave). The code in the above instances is pretty straight forward and I don't see anything obviously wrong. In fact, most of the work gets performed by the gems (e.g. devise handles registrations and logins). any help would be greatly appreciated.
2012/09/11
[ "https://Stackoverflow.com/questions/12373064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would suggest you to compile a Ruby 1.9.3-p194 with falcon patch, it increases ruby and rails speed dramatically. [falcon patch in rvm](https://github.com/wayneeseguin/rvm/blob/master/patches/ruby/1.9.3/p194/falcon.diff) You download ruby src and apply this patch if you do not want to use RVM. It might also be a DNS issue if some parameter for reverse DNS lookup enabled in Apache configuration.
Just put gem [rails tweak](https://github.com/wavii/rails-dev-tweaks) in your gem file and after that run ``` bundle install ``` I think it will solve your problem. Thanks
36,516,614
Does anyone know a way to simulate a NOR-gate in JavaScript? <https://en.wikipedia.org/wiki/NOR_gate> From what I have seen so far the language has only AND and OR.
2016/04/09
[ "https://Stackoverflow.com/questions/36516614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6085786/" ]
Always you could negate the logic or making something like this: ``` if(!(true || true)) ``` this way you always going to obtain the or result negated, which really have a NOR-gate behavior.
Here's the bitwise version: ``` ~(a | b) ```
2,921,237
I'm looking for a package / module / function etc. that is approximately the Python equivalent of Arc90's readability.js <http://lab.arc90.com/experiments/readability> <http://lab.arc90.com/experiments/readability/js/readability.js> so that I can give it some input.html and the result is cleaned up version of that html page's "**main text**". I want this so that I can use it on the server-side (unlike the JS version that runs only on browser side). Any ideas? PS: I have tried Rhino + env.js and that combination works but the performance is unacceptable it takes minutes to clean up most of the html content :( (still couldn't find why there is such a big performance difference).
2010/05/27
[ "https://Stackoverflow.com/questions/2921237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/236007/" ]
Please try my fork <https://github.com/buriy/python-readability> which is fast and has all features of latest javascript version.
I have done some research on this in the past and ended up implementing [this approach [pdf]](http://www.psl.cs.columbia.edu/crunch/WWWJ.pdf) in Python. The final version I implemented also did some cleanup prior to applying the algorithm, like removing head/script/iframe elements, hidden elements, etc., but this was the core of it. Here is a function with a (very) naive implementation of the "link list" discriminator, which attempts to remove elements with a heavy link to text ratio (ie. navigation bars, menus, ads, etc.): ``` def link_list_discriminator(html, min_links=2, ratio=0.5): """Remove blocks with a high link to text ratio. These are typically navigation elements. Based on an algorithm described in: http://www.psl.cs.columbia.edu/crunch/WWWJ.pdf :param html: ElementTree object. :param min_links: Minimum number of links inside an element before considering a block for deletion. :param ratio: Ratio of link text to all text before an element is considered for deletion. """ def collapse(strings): return u''.join(filter(None, (text.strip() for text in strings))) # FIXME: This doesn't account for top-level text... for el in html.xpath('//*'): anchor_text = el.xpath('.//a//text()') anchor_count = len(anchor_text) anchor_text = collapse(anchor_text) text = collapse(el.xpath('.//text()')) anchors = float(len(anchor_text)) all = float(len(text)) if anchor_count > min_links and all and anchors / all > ratio: el.drop_tree() ``` On the test corpus I used it actually worked quite well, but achieving high reliability will require a lot of tweaking.
23,796,894
``` <form method="post" action=""> <input type=text name="nm" /> </form> ``` request.getParameter("nm"); I can get the parameter named nm, but I can't confirm it's confirm method ,post or get??
2014/05/22
[ "https://Stackoverflow.com/questions/23796894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3663191/" ]
I would follow nmenego's advice, but keep in mind that the values you get from text fields are inherently strings (not numbers). Javascript lets you play fast and loose with this, but this results in less than ideal results: Consider: <http://jsfiddle.net/eFkze/> ``` alert("10" > "9") ``` So... you'll want to collect the values and then the simplest thing is to try and multiply them by 1. The result of that operation will fail if the value is "some non numeric thing" but will work if it's "5" or "5.5".
Below code will first check if both the inputs are entered and if both the inputs are numbers and then proceed with the calculation. isNaN function is used to check for numbers. **HTML CODE** ``` <input type="text" id="inputfield1" /> <input type="text" id="inputfield2" /> <button onclick="compare()">Compare</button> ``` **JAVASCRIPT** ``` function compare() { var variable1, variable2; try { variable1 = parseInt(document.getElementById('inputfield1').value); variable2 = parseInt(document.getElementById('inputfield2').value); if (isNaN(variable1) || isNaN(variable2)) { alert("Either or both of the inputs is not a number"); } else if (variable1 > variable2) { alert("The first variable is greater than the second."); } else { alert("The second variable is greater than or equal to the first one."); } } catch (e) { alert ('Exception Caught '+e); } }; ```
31,000,636
I have a form which has 10 checkboxes. By default angular js triggers on individual checkbox. I want to grab all selected check box values on submit action only. Here is my code... ``` <form name="thisform" novalidate data-ng-submit="booking()"> <div ng-repeat="item in items" class="standard" flex="50"> <label> <input type="checkbox" ng-model="typeValues[item._id]" value="{{item._id}}"/> {{ item.Service_Categories}} </label> </div> <input type="submit" name="submit" value="submit"/> </form> ``` --- ``` $scope.check= function() { //console.log("a"); $http.get('XYZ.com').success(function(data, status,response) { $scope.items=data; }); $scope.booking=function(){ $scope.typeValues = []; console.log($scope.typeValues); } ``` I am getting empty array. Can somebody tell how to grab all selected checkbox values only on submit event.
2015/06/23
[ "https://Stackoverflow.com/questions/31000636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4846792/" ]
``` <div ng-repeat="item in items"> <input type="checkbox" ng-model="item.SELECTED" ng-true-value="Y" ng-false-value="N"/> </div> <input type="submit" name="submit" value="submit" ng-click="check(items)"/> $scope.check= function(data) { var arr = []; for(var i in data){ if(data[i].SELECTED=='Y'){ arr.push(data[i].id); } } console.log(arr); // Do more stuffs here } ```
Can I suggest reading the answer I posted yesterday to a similar StackOverflow question.. [AngularJS with checkboxes](https://stackoverflow.com/questions/30976425/how-to-filter-through-a-table-using-ng-repeat-checkboxes-with-angularjs/30977408#30977408) This displayed a few checkboxes, then bound them to an array, so we would always know which of the boxes were currently checked. ![enter image description here](https://i.stack.imgur.com/qHtnq.png) And yes, you could ignore the contents of this bound variable until the submit button was pressed, if you wanted to.
3,223,935
I'm using Eclipse along with plugin m2eclipse to build and manage my project. In POM, I have included entry for servlet-api: ``` <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> ``` Scope is provided, not to include the .jar file to .war package, (it is already provided by the tomcat servlet container). Compilation by **mvn install** is **correct**, file is **not** included into **WEB-INF\lib**, deployment to tomcat is working, program is working, it's ok. But, the case starts inside Eclipse. After starting my web application from eclipse, i'm getting error: > > \WEB-INF\lib\servlet-api-2.5.jar) - > jar not loaded. See Servlet Spec 2.3, > section 9.7.2. Offending class: > javax/servlet/Servlet.class > > > I don't know why, because, **Maven Dependencies**(including javac-servlet-2.5.jar) are included as **Java EE Module Dependencies**, and should **be** putted inside WEB-INF\lib folder, while starting from eclipse. On the other hand, in eclipse I've provided path to my apache tomcat directory, and inside project, there are automatic references to libraries from **Apache Tomcat v6.0** including **servlet-api.jar**. So basically, after removeing reference from the POM to servlet-api-2.5.jar, that library dissapears from **Maven Dependencies**, and I get no exception while starting my web app from eclipse. Everything is **fine... in eclipse**. Of course without entry inside POM, this time **mvn install failes** with the same exception, I have provided earlier. Is there any way to make it working without removing and than inserting reference, depending of what I want to do: compile with maven or run with Eclipse ? Regards
2010/07/11
[ "https://Stackoverflow.com/questions/3223935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/270315/" ]
This > > \WEB-INF\lib\servlet-api-2.5.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class > > > is simply a warning from the app server that it is ignoring one of your included JARs and will not load it. It can be safely ignored. Sounds like the issue is with the portion/plugin for Eclipse that loads your project in an embedded app server - sounds like it simply uses the list of dependencies as what to bundle as the library path, and has no concept of Maven scopes. Personally I would ignore something like this - your Maven build is working fine, running the app within Eclipse should work fine besides this ignorable warning - otherwise you'll have to go down the path of tweaking your project for what one tool expects (the web app plugin for Eclipse) versus another (Maven). (Also I've always found that running webapps as "Web projects" within Eclipse is a pain in the butt, and leads to all sorts of oddities - not worth the hassle - if you want to quickly load your Maven webapp project in a servlet container, simply use [`mvn jetty:run`](http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin) or [`mvn tomcat:run`](http://mojo.codehaus.org/tomcat-maven-plugin/deployment.html#Running%20a%20WAR%20project). Fighting with IDEs can be a waste of time).
Install the plugin which named "**Maven Integration for WTP**", it can completely sovled this problem. Repository URL: **<http://download.jboss.org/jbosstools/updates/m2eclipse-wtp/>**
59,129,171
For example, there is a sample flutter code. This code is not properly formatted. ``` import 'package:flutter/material.dart'; void main() => runApp(SampleApp()); class SampleApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: SafeArea( child: Container( child: const Text('123'),), // this line isn't properly formatted ), ), ); } } ``` I've heard that Android Studio is able to autoformat flutter code when a code saved in editor. In that case, certain conditions had to be respected, - all the commas should be present in code like it is in the above sample code. But I didn't find how to do that. So if it's true (i.e. if it's possible to do that) how to achive that?
2019/12/01
[ "https://Stackoverflow.com/questions/59129171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5829191/" ]
Go to **Settings -> Languages & Frameworks -> Flutter** and check **Format code on save**. --- You can also use Reformat code [shortcut](https://developer.android.com/studio/intro/keyboard-shortcuts) manually: Windows/Linux: `Ctrl` + `Alt` + `L` Mac: `Command` + `Option` + `L`
As @janstol said, there is a shortcut to auto reformat code. However, I had the same problem but I could not solve it because my command was not established, so I'll leave the route to get there in case someone needs it. Open **Setting > Preferences > Keymap** and search for the one that says "**Reformat code with 'dart format'**". There you can customize it as needed.
4,378,972
In Visual Studio there is a command to remove unused using statements ``` using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; ``` Is there a performance hit for having unused usings?
2010/12/07
[ "https://Stackoverflow.com/questions/4378972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322518/" ]
No. Namespaces are used to resolve class names at compile time. After compilation, your assembly only contains fully qualified class names like `System.Collections.Generic.List<int> myList = new System.Collections.Generic.List<int>()`, all the usings are gone.
I always thought they were removed away by the compiler.
4,340,292
If I have ``` char input[50] = "xFFFF"; int a; ``` How can I store the numerical value of input in a? the language is C.
2010/12/02
[ "https://Stackoverflow.com/questions/4340292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/386020/" ]
One way to do it might be: ``` if (sscanf(input, "x%x", &a) == 0) { /* matching failed */ } ``` If your input uses a real hex specifier (like "0xFFFF") you can just use %i: ``` if (sscanf(input, "%i", &a) == 0) { /* matching failed */ } ```
See [C++ convert hex string to signed integer](https://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer) and if you're in a pure C environment, make sure to scroll down.
33,122,986
I struggled for hours to find out how to make a javascript function to copy the current URL into a new alert window. For example, when a user click "Share this page", then a new alert window appears with the URL selected in an input text box: [![enter image description here](https://i.stack.imgur.com/vfhdR.png)](https://i.stack.imgur.com/vfhdR.png) How can I make it done with javascript? Thanks.
2015/10/14
[ "https://Stackoverflow.com/questions/33122986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5025969/" ]
As simple as this: ```js prompt('Please copy the following URL:', window.location); ```
For a better user experience you may consider allowing access to the clipboard with [clipboard.js](http://zenorocha.github.io/clipboard.js/).
9,676,740
Currently using Flexslider and would like to be able to hide the navigation arrows which presently appear on right and left side of the image but than have them appear when the user hovers over the image. I remember it being addressed on the old site - muffin one, but cannot find it on woothemes. Does anyone have an idea on how to change/modify/add info to do this? Thanks in advance.
2012/03/13
[ "https://Stackoverflow.com/questions/9676740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932795/" ]
You can modify the arrows in the css. If you want the arrows to always be visible you want to change the opacity. It's currently set to 0 which makes it non-visible until hover (the hover opacity is set to 1 which is completely visible). So you want to just make it visible like so: ``` .flex-direction-nav a {opacity: 1;} ``` If you then want to change the location of the arrow you will need to simply change the margin. It is currently set to -20px. If you want to make it appear outside the box you will need to make it something like this: ``` .flex-direction-nav a {margin: -40px 0 0;} ``` If you did both your css would look like this: ``` .flex-direction-nav a {opacity: 1; margin: -40px 0 0;} ``` This would make your arrows always be visible and appear outside the image (to the right and left of the image instead of on top of the image).
You can probably accomplish this via jQuery. In my case I am using FlexSlider for Drupal so I cannot promise that you will have the same CSS selectors, but I hope this code could provide a general idea :) ``` $(document).ready(function(){$("div.flexslider").hover(function() { $("a.prev").show(); $("a.next").show(); }, function() { $("a.prev").hide(); $("a.next").hide(); });}) ``` Good Luck! P.S. I forgot to mention that you should set your a tag selectors in your CSS to display:none; by default.
22,017,631
I use the Kendo UI grid in ajax mode and have a ClientFooterTemplate with a sum of the total for a column. This all works well, but if I create/update or remove a record the ClientFooterTemplate is not updated and the sum value stays the same. How can I update the ClientFooterTemplate so that the sum value is up to date after create/update or delete? This is what I tried so far: ``` .Events(events => { events.SaveChanges("SaveChanges"); events.Remove("Remove"); events.Save("SaveChanges"); }) <script> function SaveChanges(e) { Reload(e.sender); } function Remove(e) { Reload(e.sender); } function Reload(obj) { obj.dataSource.read(); } </script> ``` The obj.dataSource.read() is executed before the actual request to update.
2014/02/25
[ "https://Stackoverflow.com/questions/22017631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2600162/" ]
you need to update the `datasource` and fetch again if you using aggregates sum in you gird footer the following JavaScript will update your footer sum every time you create/update any row. ``` .DataSource(dataSource => dataSource .Ajax() .Aggregates(aggregates => { aggregates.Add(p => p.WorkOrderDetailsQuantity).Sum(); aggregates.Add(p => p.Total).Sum(); }) .Events(e=>e.Edit("onEdit").Save("onSave")) function onSave(e) { //update the aggregate columns var dataSource = this.dataSource; e.model.one("change", function () { dataSource.one("change", function () { dataSource.aggregates().Total.sum; }); dataSource.fetch(); }); } ```
If you don't want to reload your data, you can always do something like this (a little hacky...): First, use a different function for the Save event vs. the SaveChanges event, e.g.: ``` .Events(events => { events.Save("Save"); events.SaveChanges("SaveChanges"); events.Remove("Remove") }) ``` Second, define the JavaScript method, e.g.: ``` function Save(e) { if (e.value.Gewgaw) { // replace 'Gewgaw' with your column name var footer = $('tr.k-footer-template'), idx = 3, // replace 3 with the column index you want to aggregate aggregate = $(footer).children('td')[idx]; // I had to delay the stuff in this function to get it to load properly setTimeout(function () { var sum = 0; $('tr[role=row][data-uid]').each(function(i, e) { var $cell = $($(e).children()[idx]); /* do any necessary manipulations before this if your cell is formatted */ var cellAmount = parseFloat($cell.text()); sum += cellAmount; }); /* do any necessary formatting to sum before this if your cell is formatted */ $(aggregate).text(sum); }, 50); } } ``` If you do that stuff and remove/add the appropriate formatting, it should update the aggregate each time the respective cell is edited.
8,910,697
I have many classes with static final fields which are used as default values or config. What is best approach to create global config file? Should I move these fields to single static class, use properties file or what? Edit: I need to use this values both in java classes and xhtml pages. Values dosen't depend on envirnoment. I could compile project to set new values - no problem.
2012/01/18
[ "https://Stackoverflow.com/questions/8910697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/878418/" ]
The answer depends... * Put stuff in properties files if the values change depending on runtime environment (eg database connection settings, foreign server IPs), or that will likely change often/soon * Prefer using `enum` to `static final` constants where possible (avoid "stringly typed" code) * Find an existing library that might have what you want (eg use [`TimeUnit`](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/TimeUnit.html) to convert hours to seconds, rather than having `static final int SECONDS_IN_HOUR = 3600;`) * What's left (that hopefully isn't going to change any time soon), use `public static final` in the class that has "most ownership" over them * Avoid classes that have static methods that return a constant - it's just code bloat
Both the approches are fine: 1. Have a static class with required `final` fields. 2. Have a singelton but save it from multiple threads appropriately. 3. if possible use `enum` over static fields. This way you can group related fields together. If these are application level values, i'll prefer `static` class over singelton. and, you should decide if these are const values or configuration value that differ from time to time.
36,477,390
I'm working on a PDF Signer/Validator and don't know how I should handle pdf files with multiple signatures and dss dictionaries. Here is the scenario: A pdf file is signed twice, and after the second signature, a DSS dictionary is added with the CRLs, CERTs and OCSPs of both signatures: ``` [ Signature 1 ] [ Signature 2 ] DSS << VRI << /HashSignature1 10 0 R /HashSignature2 11 0 R >> ... >> ``` So far, so good. Both signatures are covered in the only DSS dictionary on the document. But someone else decided to sign this same document, and also add his CRLs and everything else. Then, I must create a new DSS dictionary, and my question is: Must the old signatures, already covered in another DSS dictionary, be in this one? I think so, since the DSS is inside an updated document catalog (and you removed the reference to the last dictionary), but there is little agreement in the company. ``` [ Signature 1 ] [ Signature 2 ] DSS << VRI << /HashSignature1 10 0 R /HashSignature2 11 0 R >> ... >> [ Signature 3 ] DSS << VRI << /HashSignature1 10 0 R /HashSignature2 11 0 R /HashSignature3 16 0 R >> ... >> ``` OR ``` [ Signature 1 ] [ Signature 2 ] DSS << VRI << /HashSignature1 10 0 R /HashSignature2 11 0 R >> ... >> [ Signature 3 ] DSS << VRI << /HashSignature3 16 0 R >> ... >> ``` Are both of them correct? Only one of them? With one?
2016/04/07
[ "https://Stackoverflow.com/questions/36477390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4979817/" ]
Andrea Valle, from Adobe, clarified this for me by e-mail: > > This has been discussed within ESI for some time, and finally the team decided to clarify this in EN 319 142-1. > > > See section 5.4.1 on page 11 of version 1.1.0: > > > The life-time of the protection can be further extended beyond the life-time of the last document time-stamp applied by adding further DSS information to validate the previous last document time-stamp along with a new document time-stamp. Every time a DSS Dictionary is updated during incremental update, it **should** contain the values from the previous DSS Dictionary. > > > > > > > NOTE: In general the DSS Dictionary will contain validation data from previous revisions plus validation data added for the current revision. If entries are removed from a DSS Dictionary during an incremental update the set of validation data might not be complete for validation of the signatures, but replacement of validation data - like e.g. more up-to-date certificate status information - might be performed for optimization reasons. > > > > > > > > > So it's actually **recommended** to add all entries from the older DSS dictionary, but not **mandatory**. You can update these entries if they don't break the signature, but that's optional. Reading a little bit further on the same document: > > The Document Security Store (DSS) shall be a dictionary that shall have the value DSS as key in the document catalog dictionary. This dictionary is used to provide a single place where all of the validation-related information for some or all signatures in the document should be placed. > > > The DSS is intended to provide a **single** place where **all** information **should** be placed. So, if you don't place all information there, you're not breaking anything, but you're not using the DSS as intended. Then, the answer is: a pdf signer should use the first approach, but a pdf validator should be prepared for the second. --- EDIT: Actually, any PAdES validator should check either the DSS entries existed earlier anyway. If you check only the lastest one, it's possible to re-validate an invalid signature, if the CA certificate used to sign the CRLs or OCSPs was compromissed latter, and this fake information was added in the latest DSS. Example: 1. Sig 1 was made with an revoked certificate 2. All DSS entries are added, and the signature is sure to be invalid 3. A DocumentTimeStamp is added, protecting this DSS. 4. **Sig 1 CA certificate is compromissed** 5. Sig 2 is made, with a valid certificate 6. Sig 2 DSS entries are added, LTV-enabling the signature 7. Sig 1 CRL/OCSP is replaced with a fake one made with the compromissed CA certificate In this situation, a validator that relies on the lattest DSS will validate Sig 1, when it shouldn't. That's why you add a DocumentTimeStamp to protect the information about that signature. --- TL;DR: Both options are right. The DSS should have information about all signatures, but it's not mandatory. And a validator should check the DSS that was made right after the signature, not only the latest one.
As there's only a single DSS entry in the Catalog dictionary you need to update the existing DSS dicionary (resp. the VRI dictionary and the other values).
985,460
I am running a IP PBX system with trixbox, what i'm trying to do is connect PSTN lines with IAX2 using X100P analogue card. The problem is i cannot call any outgoing routes. (already tried AsteriskNOW and elastix) The problem as i've learned is "low IRQ"(Interrupt Request), if that is the case how do i increase it? or am i missing something. I read all the documentations and still the problem exists, if anyone has any idea about IRQ then please help me. The error while i try to call out is what mentioned in the title. Any help would be appreciated.
2015/10/12
[ "https://superuser.com/questions/985460", "https://superuser.com", "https://superuser.com/users/493478/" ]
Try this script. You might need to edit the drive letters though ``` setlocal EnableDelayedExpansion @echo off Q: cd "Estimating\Estimating Files" FOR /D /R %%G IN ("*Drawings*") DO ( FOR /F "tokens=4,5 delims=\" %%H IN ("%%G") DO ( set temp=%%H set num=!temp:~4,2! set temp=%%I set alpha=!temp:~5! MKDIR "Q:\E27XXX\0XX\!num!\!alpha!\Drawings" CALL :mover "%%G" !num! !alpha! ) ) :mover FOR /R %1 %%X IN (*) DO ( COPY "%%X" "Q:\E27XXX\0XX\%2\%3 %4 %5\Drawings" ) ```
Here is the final code I used to copy the folders to the new directory. Thanks to @ElektroStudios for their help. ``` @Echo OFF Set "sourceDir=%CD%" Set "targetDir=S:\E30xxx" Set "findPattern=2 - Drawings" For /F "Tokens=6,7,8,9 Delims=\" %%a In ( 'Dir /B /S /A:D "%sourceDir%\*%findPattern%"' ) Do ( Call Set "Token1=%%~a" Call Set "Token2=%%~b" Call Set "Token3=%%~c" Call Set "Token4=%%~d" Call Set "sourcePath=%CD%\%%~a\%%~b\%%~c\%%~d" Call Set "targetPath=%targetDir%\%%Token1:~3,1%%xx\%%Token2:~4,2%%\%%Token3:~6%%" Echo+ Call Echo Source: "%%sourcePath%%" Call Echo Target: "%%targetPath%%" (Call RoboCopy.exe "%%sourcePath%%" "%%targetPath%%" /E /ZB /COPYALL)1>Nul ) Pause&Exit /B 0 ``` Just a case of getting to grips with RoboCoby and tokenisation of the delimited string.
2,324
It seems to me that the first AGIs ought to be able to perform the same sort and variety of tasks as people, with the most computationally strenuous tasks taking an amount of time compared to how long a person would take. If this is the case, and people have yet to develop basic AGI (meaning it's a difficult task), should we be concerned if AGI is developed? It would seem to me that any fears about a newly developed AGI, in this case, should be the same as fears about a newborn child.
2016/11/13
[ "https://ai.stackexchange.com/questions/2324", "https://ai.stackexchange.com", "https://ai.stackexchange.com/users/3604/" ]
There are basically two worries: If we create an AGI that is a slightly better AGI-programmer than its creators, it might be able to improve its own source code to become even more intelligent. Which would enable it to improve its source code even more etc. Such a selfimproving seed AI might very quickly become superintelligent. The other scenario is that intelligence is such a complicated algorithmic task, that when we finally crack it, there will be a significant hardware overhang. So the "intelligence algorithm" would be human level on 2030 hardware, but we figure it out in 2050. In that case we would immediately have superintelligent AI without ever creating human level AI. This scenario is especially likely because development often requires a lot of test runs to tweak parameters and try out different ideas.
To avoid a repetitive answer that has been already spoken about such as absurdly high iterative ability or it being able to create another AGI system and multiplying or anything sci-fi like - there is one line of thought I feel people do not speak enough about. Our human senses are extremely limited i.e. we can see objects only when light from within the visible light spectrum (~ 400nm-700nm) reflects into our eyes, we can hear only a limited range of frequencies the rest being inaudible etc. An AGI system apart from its obvious intelligence, would be able to gain a significant amount of information from even common observations. It can see infrared, ultraviolet and radio waves as what we interpret as colours; it would be able to hear sounds that we did not know were being emitted at all. Essentially an AGI with good input sensor capabilities would be able to take information from experiencing the world as it actually is, and not a limited illusion we experience.
102,930
It is common the use of [asterisk](https://en.wikipedia.org/wiki/Asterisk) (\*) to indicate required elements. I understand [the use of explicit text is better than relying on symbols](https://ux.stackexchange.com/questions/90685/using-asterisk-vs-required). So writing "required" or "optional" is more understandable than relying on some symbol. I'm creating lists of elements characteristics for **personal use**. These are not forms, just text lists. Most (90% or more) of the elements I am listing will be required. So **rather than indicate required elements I want to (only) indicate optional elements**, which are the minority. I can use my own symbol and give it the optional meaning as my team will be the only ones reading the elements. But I was wondering if there is any convention of a symbol for optional fields/elements. --- **My question is related to lists of text, not forms**. Although I think there might not really be much difference. As far as I understand it the required goes in the label anyway. Also, again, this will be for personal use. **So the question is if there is any symbol/way to represent optional elements**. Either used as a convention (in some niche) or if someone has any suggestion.
2016/12/26
[ "https://ux.stackexchange.com/questions/102930", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/32130/" ]
This is what I would do in order to specify when a field is required or optional [![enter image description here](https://i.stack.imgur.com/UZrf3.jpg)](https://i.stack.imgur.com/UZrf3.jpg) The last field is the active one, I added it in order to show that we still have the label when the field is active.
For simplicity, it feels natural to show which are required before an error message has to tell a user what's required. Anything else that's left as an option doesn't need an optional message by the nature of a required element. If no special required element existed, then everything can be perceived as an option unless expressed otherwise in a header sentence or paragraph.
57,842,810
I have an Ajax call which returns a JSON response and i'm loading the response using an array ``` var results = { "appointmentrequired": {"name": "Appointment Required?"}, }; success: function(data) { $.each(results, function(key, value) { // show results from `data` here }); } ``` But I'm not sure how to access the results inside the array loop. I've tried ``` console.log(data[key]); console.log(data.key); ``` But both return `undefined`
2019/09/08
[ "https://Stackoverflow.com/questions/57842810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4838253/" ]
If you `console.log()` both `key` and `value` you should be able to see what's being provided to the function arguments. As such, either `data[key].name` or `value.name` is what you need. ```js // mock AJAX response data var data = { "appointmentrequired": { "name": "Appointment Required?" }, }; // in AJAX response handler $.each(data, function(key, value) { console.log('key:', key) console.log('value:', value); console.log('Name from key:', data[key].name); console.log('Name from value:', value.name); }); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> ```
`$.each` run on arrays You want to explore `let keysArr = Object.keys(data)`
18,262,053
I'm struggling with how to do the query for this. I have three tables...ingredients, recipes, and stores. I'm trying to build a query that will tell me what recipes I can make from the ingredients available at a store. My tables are: ``` mysql> SELECT * FROM ingredients; +---------+ | id | +---------+ | apple | | beef | | cheese | | chicken | | eggs | | flour | | milk | | pasta | | sugar | | tomato | +---------+ 10 rows in set (0.00 sec) mysql> SELECT * FROM stores; +----------+------------+ | name | ingredient | +----------+------------+ | target | apple | | target | chicken | | target | flour | | target | milk | | target | sugar | | wal-mart | beef | | wal-mart | cheese | | wal-mart | flour | | wal-mart | milk | | wal-mart | pasta | | wal-mart | tomato | +----------+------------+ 11 rows in set (0.00 sec) mysql> SELECT * FROM recipes; +---------------+------------+ | name | ingredient | +---------------+------------+ | apple pie | apple | | apple pie | flour | | apple pie | milk | | apple pie | sugar | | cheeseburger | beef | | cheeseburger | cheese | | cheeseburger | flour | | cheeseburger | milk | | fried chicken | chicken | | fried chicken | flour | | spaghetti | beef | | spaghetti | pasta | | spaghetti | tomato | +---------------+------------+ 13 rows in set (0.00 sec) mysql> ``` Given the above I want to build a query where I give it the store name (say wal-mart for this example) and it produces a list of the recipes I can make from the ingredients available at wal-mart (cheeseburger & spaghetti). Here's the SQL to create these tables: ``` CREATE TABLE IF NOT EXISTS ingredients ( id varchar(32) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO ingredients (id) VALUES ('apple'), ('beef'), ('cheese'), ('chicken'), ('eggs'), ('flour'), ('milk'), ('pasta'), ('sugar'), ('tomato'); CREATE TABLE IF NOT EXISTS recipes ( `name` varchar(32) NOT NULL, ingredient varchar(32) NOT NULL, PRIMARY KEY (`name`,ingredient) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO recipes (`name`, ingredient) VALUES ('apple pie', 'apple'), ('apple pie', 'flour'), ('apple pie', 'milk'), ('apple pie', 'sugar'), ('cheeseburger', 'beef'), ('cheeseburger', 'cheese'), ('cheeseburger', 'flour'), ('cheeseburger', 'milk'), ('fried chicken', 'chicken'), ('fried chicken', 'flour'), ('spaghetti', 'beef'), ('spaghetti', 'pasta'), ('spaghetti', 'tomato'); CREATE TABLE IF NOT EXISTS stores ( `name` varchar(32) NOT NULL, ingredient varchar(32) NOT NULL, UNIQUE KEY NAME_INGREDIENT (`name`,ingredient) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO stores (`name`, ingredient) VALUES ('target', 'apple'), ('target', 'chicken'), ('target', 'flour'), ('target', 'milk'), ('target', 'sugar'), ('wal-mart', 'beef'), ('wal-mart', 'cheese'), ('wal-mart', 'flour'), ('wal-mart', 'milk'), ('wal-mart', 'pasta'), ('wal-mart', 'tomato'); ```
2013/08/15
[ "https://Stackoverflow.com/questions/18262053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1106281/" ]
try this: ``` SELECT r.name FROM recipes r GROUP BY r.name HAVING COUNT(*) = (SELECT COUNT(*) FROM recipes r2 INNER JOIN stores s ON r2.ingredient = s.ingredient AND s.name = 'wal-mart' WHERE r.name = r2.name) ``` [fiddle demo](http://sqlfiddle.com/#!2/3c763/9)
(Remodelled the data a bit to use only numerical keys) ``` CREATE TABLE IF NOT EXISTS ingredients ( ing_id INTEGER NOT NULL PRIMARY KEY , ing_name varchar(32) NOT NULL ) ; INSERT INTO ingredients (ing_id, ing_name) VALUES (1, 'apple' ), (2, 'beef' ), (3, 'cheese' ), (4, 'chicken' ), (5, 'eggs' ), (6, 'flour' ), (7, 'milk' ), (8, 'pasta' ), (9, 'sugar' ), (10, 'tomato' ); CREATE TABLE IF NOT EXISTS recipes ( rec_id INTEGER NOT NULL PRIMARY KEY , rec_name varchar(32) NOT NULL ); INSERT INTO recipes (rec_id, rec_name) VALUES (1, 'apple pie' ) , (2, 'cheeseburger' ) , (3, 'fried chicken' ) , (4, 'spaghetti' ) ; CREATE TABLE IF NOT EXISTS recipe_ingredient ( rec_id INTEGER NOT NULL REFERENCES recipes(rec_id) , ing_id INTEGER NOT NULL REFERENCES ingredients (ing_id) , PRIMARY KEY (rec_id, ing_id) ); INSERT INTO recipe_ingredient (rec_id, ing_id) VALUES (1, 1), (1, 6), (1, 7), (1, 9), (2, 2), (2, 3), (2, 6), (2, 7), (3, 4), (3, 6), (4, 2), (4, 8), (4, 10); 8), (4, 10); CREATE TABLE IF NOT EXISTS stores ( sto_id INTEGER NOT NULL PRIMARY KEY , sto_name varchar(32) NOT NULL ); INSERT INTO stores (sto_id, sto_name) VALUES (1, 'target' ), (2, 'wal-mart' ); CREATE TABLE IF NOT EXISTS store_ingredient ( sto_id INTEGER NOT NULL REFERENCES stores(sto_id) , ing_id INTEGER NOT NULL REFERENCES ingredients(ing_id) , PRIMARY KEY (sto_id, ing_id) ); INSERT INTO store_ingredient (sto_id, ing_id ) VALUES (1, 1), (1, 4), (1, 6), (1, 7), (1, 9), (2, 2), (2, 3), (2, 6), (2, 7), (2, 8), (2, 10) ; ``` Query to find all recipes for which **all the ingredients** can be supplied by wal-mart. ``` SELECT r.rec_name -- All the recipes FROM recipes r WHERE NOT EXISTS ( SELECT * -- ... that do not contain any ingredient FROM recipe_ingredient ri WHERE ri.rec_id = r.rec_id AND NOT EXISTS ( SELECT * -- ... that cannot be provided by wal-mart. FROM store_ingredient si JOIN stores s ON s.sto_id = si.sto_id WHERE si.ing_id = ri.ing_id AND s.sto_name = 'wal-mart' ) ); ```
71,414,890
I have some info in JSON form fetched from my API, now I want to console.log a specific object from it, I have tried a few ways, but I get either undefined or the whole JSON text printed out The code I have right now: ``` const api_url = 'http://127.0.0.1:8000/main/'; async function getapi(url) { const response = await fetch(url); data = await response.json(); return data; } getapi(api_url); var results = getapi(api_url); console.log(results); ``` I just started working with apis and async js I would love to get some help.
2022/03/09
[ "https://Stackoverflow.com/questions/71414890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18165364/" ]
You can use `itertools.dropwhile` ``` from itertools import dropwhile from collections import Counter data = [0.0,0.0,2.0,3.0,0.0,2.0] print(sum(1 for _ in dropwhile(lambda x: x == 0, data))) # 4 print(Counter(dropwhile(lambda x: x == 0, data))) # Counter({2.0: 2, 3.0: 1, 0.0: 1}) ```
You can simply wrap your counter code in a conditional, with something like this: ``` x=[0.0,0.0,2.0,3.0,0.0,2.0] start_counting = False item_count = 0 for i in x: if i != 0.0: start_counting = True if start_counting: item_count += 1 ``` `item_count` will now have the amount of items in the list without the starting 0.0s
15,743,550
I'm trying to implement a very simple SSDP functionality into my android app taken [from here](https://code.google.com/p/android-dlna/source/browse/trunk/src/org/ray/?r=2#ray/upnp/ssdp). My application sends some UDP packets containing a relevant M-SEARCH message to the broadcasting address without any issue. The problem is, I should be getting a proper response back from other devices that's running a UPNP server. For some reason, I'm only receiving the exact same packets back I sent from my android device. MainActivity.java ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE); WifiManager.MulticastLock multicastLock = wm.createMulticastLock("multicastLock"); multicastLock.setReferenceCounted(true); multicastLock.acquire(); setContentView(R.layout.activity_main); ((Button)this.findViewById(R.id.btnSendSSDPSearch)).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnSendSSDPSearch: new Thread(new Runnable() { @Override public void run() { SendMSearchMessage(); } }).start(); default: break; } } private void SendMSearchMessage() { SSDPSearchMsg searchContentDirectory = new SSDPSearchMsg(SSDPConstants.ST_ContentDirectory); SSDPSearchMsg searchAVTransport = new SSDPSearchMsg(SSDPConstants.ST_AVTransport); SSDPSearchMsg searchProduct = new SSDPSearchMsg(SSDPConstants.ST_Product); SSDPSocket sock; try { sock = new SSDPSocket(); for (int i = 0; i < 2; i++) { sock.send(searchContentDirectory.toString()); sock.send(searchAVTransport.toString()); sock.send(searchProduct.toString()); } while (true) { DatagramPacket dp = sock.receive(); //Here, I only receive the same packets I initially sent above String c = new String(dp.getData()); System.out.println(c); } } catch (IOException e) { // TODO Auto-generated catch block Log.e("M-SEARCH", e.getMessage()); } ``` SSDPSocket.java where the UDP packet transmission is actually done ``` public class SSDPSocket { SocketAddress mSSDPMulticastGroup; MulticastSocket mSSDPSocket; InetAddress broadcastAddress; public SSDPSocket() throws IOException { mSSDPSocket = new MulticastSocket(55325); //Bind some random port for receiving datagram broadcastAddress = InetAddress.getByName(SSDPConstants.ADDRESS); mSSDPSocket.joinGroup(broadcastAddress); } /* Used to send SSDP packet */ public void send(String data) throws IOException { DatagramPacket dp = new DatagramPacket(data.getBytes(), data.length(), broadcastAddress,SSDPConstants.PORT); mSSDPSocket.send(dp); } /* Used to receive SSDP packet */ public DatagramPacket receive() throws IOException { byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); mSSDPSocket.receive(dp); return dp; } public void close() { if (mSSDPSocket != null) { mSSDPSocket.close(); } } } ``` SSDPSearchMsg.java for constructing SSDP Broadcast string (Probably unrelated to the problem I'm experiencing but just in case) ``` public class SSDPSearchMsg { static final String HOST = "Host:" + SSDP.ADDRESS + ":" + SSDP.PORT; static final String MAN = "Man:ssdp:discover"; static final String NEWLINE = System.getProperty("line.separator"); int mMX = 3; /* seconds to delay response */ String mST; /* Search target */ public SSDPSearchMsg(String ST) { mST = ST; } public int getmMX() { return mMX; } public void setmMX(int mMX) { this.mMX = mMX; } public String getmST() { return mST; } public void setmST(String mST) { this.mST = mST; } @Override public String toString() { StringBuilder content = new StringBuilder(); content.append(SSDP.SL_MSEARCH).append(NEWLINE); content.append(HOST).append(NEWLINE); content.append(MAN).append(NEWLINE); content.append(mST).append(NEWLINE); content.append("MX:" + mMX).append(NEWLINE); content.append(NEWLINE); return content.toString(); } } ``` SSDPConstants.java ``` public class SSDPConstants { /* New line definition */ public static final String NEWLINE = "\r\n"; public static final String ADDRESS = "239.255.255.250"; public static final int PORT = 1900; /* Definitions of start line */ public static final String SL_NOTIFY = "NOTIFY * HTTP/1.1"; public static final String SL_MSEARCH = "M-SEARCH * HTTP/1.1"; public static final String SL_OK = "HTTP/1.1 200 OK"; /* Definitions of search targets */ public static final String ST_RootDevice = "St: rootdevice"; public static final String ST_ContentDirectory = "St: urn:schemas-upnp-org:service:ContentDirectory:1"; public static final String ST_AVTransport = "St: urn:schemas-upnp-org:service:AVTransport:1"; public static final String ST_Product = "St: urn:av-openhome-org:service:Product:1"; /* Definitions of notification sub type */ public static final String NTS_ALIVE = "NTS:ssdp:alive"; public static final String NTS_BYE = "NTS:ssdp:byebye"; public static final String NTS_UPDATE = "NTS:ssdp:update"; } ``` I also made sure that the manifest includes relevant permissions: ``` <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> ``` I'm testing the app on an actual device, not on emulator. Any assistance would be appreciated. Edit upon comment: Multicast itself should work without issue. I've downloaded an app called BubbleUPNP to test the SSDP functionality. Sure enough, wireshark properly captures all messages sent from the phone to the broadcasting address in SSDP Protocol: ``` M-SEARCH * HTTP/1.1 Man: "ssdp:discover" Mx: 3 Host: 239.255.255.250:1900 St: urn:schemas-upnp-org:service:AVTransport:1 ``` And the response ``` HTTP/1.1 200 OK ST:urn:schemas-upnp-org:service:ContentDirectory:1 USN:uuid:d5829e90-73ce-4213-9ad1-4e75dbdd0232::urn:schemas-upnp-org:service:ContentDirectory:1 Location:http://10.175.95.4:2869/upnphost/udhisapi.dll?content=uuid:d5829e90-73ce-4213-9ad1-4e75dbdd0232 OPT:"http://schemas.upnp.org/upnp/1/0/"; ns=01 01-NLS:05f3dd08b4b4b5aafa1fe983fa447f49 Cache-Control:max-age=900 Server:Microsoft-Windows-NT/5.1 UPnP/1.0 UPnP-Device-Host/1.0 ``` So yeah, this is without a doubt, an implementation issue. Nothing wrong with the device.
2013/04/01
[ "https://Stackoverflow.com/questions/15743550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1455529/" ]
Weird. I fixed the issue but I'm genuinely not sure what made it work. Here are some changes that I made: Instead of assigning a fixed port, I made it dynamically allocate an available port. ``` public class SSDPSocket { SocketAddress mSSDPMulticastGroup; MulticastSocket mSSDPSocket; InetAddress broadcastAddress; public SSDPSocket() throws IOException { mSSDPSocket = new MulticastSocket(); broadcastAddress = InetAddress.getByName(SSDPConstants.ADDRESS); mSSDPSocket.joinGroup(broadcastAddress); } ... } ``` I also changed the M-Search message structure, including its order. ``` public class SSDPSearchMsg { static final String HOST = "Host: " + SSDPConstants.ADDRESS + ":" + SSDPConstants.PORT; static final String MAN = "Man: \"ssdp:discover\""; static final String NEWLINE = "\r\n"; int mMX = 3; /* seconds to delay response */ String mST; /* Search target */ public SSDPSearchMsg(String ST) { mST = ST; } public int getmMX() { return mMX; } public void setmMX(int mMX) { this.mMX = mMX; } public String getmST() { return mST; } public void setmST(String mST) { this.mST = mST; } @Override public String toString() { StringBuilder content = new StringBuilder(); content.append(SSDPConstants.SL_MSEARCH).append(NEWLINE); content.append(MAN).append(NEWLINE); content.append("Mx: " + mMX).append(NEWLINE); content.append(HOST).append(NEWLINE); content.append(mST).append(NEWLINE); content.append(NEWLINE); return content.toString(); } } ``` And everything suddenly works. Why it works is beyond me. My previous implementation follows the SSDP protocol as far as I can tell.
On possible answer is that you may have an "old" device. Apparently multicast (from Java) is broken before Android 2.3.7 Reference: <https://stackoverflow.com/a/9836464/139985> Another possibility is that it is a device-specific problem; e.g. like this: <https://stackoverflow.com/a/3714848/139985>. (I'm not saying it is that specific problem ...) Another is that multicast is disabled in the kernel configs: <http://code.google.com/p/android/issues/detail?id=51195> It seems like there are a range of different causes for multicast not working on various Android devices ...
38,023,521
I have a function in c++ who returns a list of complex: ``` #include <complex> std::list< std::complex<double> > func(...); ``` what should i do in the '\*.i' file ? Thank you every body. ================= Following are details: the function i would like to use in python in x.h: ``` std::list<std::complex<double> > roots1(const double& d, const double& e); ``` I have tried some ways: (1) x.i: ``` %include <std_list.i> %include <std_complex.i> ``` than I try in IPython: ``` tmp = x.roots1(1.0, 2.0) len(tmp) ``` and I got: ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-9ebf7dab7cd9> in <module>() ----> 1 len(tmp) TypeError: object of type 'SwigPyObject' has no len() ``` and: ``` dir(tmp) ``` returns: ``` [ ... 'acquire', 'append', 'disown', 'next', 'own'] ``` (2) x.i: ``` %include <std_list.i> %include <std_complex.i> namespace std { %template(ComplexDouble) complex<double>; } ``` than, i got compile error: ``` error: command 'swig' failed with exit status 1 make: *** [py] Error 1 ``` (3) in x.i: ``` %include <std_list.i> %include <std_complex.i> namespace std { %template(ComplexDouble) list<complex<double> >; } ``` or: ``` %include <std_list.i> %include <std_complex.i> namespace std { %template(ComplexDouble) list<complex>; } ``` and I got: ``` x_wrap.cpp:5673:32: error: ‘complex’ was not declared in this scope template <> struct traits<complex > { ^ ``` ================================================ (Mr./Ms./Mrs) m7thon help me find the problem. In my python context: ``` Ubuntu: 45~14.04.1 Python: 3.4.3 SWIG: SWIG Version 2.0.11 Compiled with g++ [x86_64-unknown-linux-gnu] Configured options: +pcre ``` if define the x.i as: ``` %include <std_list.i> %include <std_complex.i> namespace std { %template(ComplexList) list<complex<double> >; } ``` there will be compiling error. But it works if x.i: ``` %include <std_list.i> %include <std_complex.i> %template(ComplexList) std::list< std::complex<double> >; ``` Thank you m7thon.
2016/06/24
[ "https://Stackoverflow.com/questions/38023521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6459155/" ]
This works: ``` %include <std_list.i> %include <std_complex.i> %template(ComplexList) std::list<std::complex<double> >; ... (your includes / function declarations) ``` I think your version (3) should actually also work. Strange that it doesn't. Maybe a SWIG bug.
To be more concise you can use the whole namespace: ``` %include <std_list.i> %include <std_complex.i> using namespace std; %template(ComplexList) list<complex<double> >; ``` But the initially suggested versions of including SWIG `%template` into the `std` namespace is not a good idea.
2,926,843
I wonder if Nihbernate closes db connection supplied as a parameter to `OpenSession` method. Example ``` using(var session = sessionFactory.OpenSession(connection)) { } ``` I want the connection to be disposed with the session. Best regards, Alexey Zakharov
2010/05/28
[ "https://Stackoverflow.com/questions/2926843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161287/" ]
I just used route globbing to achieve this: ``` map.connect "/*other", :controller => "pages", :action => "index" ``` Note that this route should be at the end of routes.rb so that all other routes are matched before it.
You can use the following ways to handle errors in a common place. Place this code in you ApplicationController ``` def rescue_404 @message = "Page not Found" render :template => "shared/error", :layout => "standard", :status => "404" end def rescue_action_in_public(exception) case exception when CustomNotFoundError, ::ActionController::UnknownAction then #render_with_layout "shared/error404", 404, "standard" render :template => "shared/error404", :layout => "standard", :status => "404" else @message = exception render :template => "shared/error", :layout => "standard", :status => "500" end end ``` Modify it to suit your needs, you can have redirects as well. HTH
38,236,723
I am using XCode 8 and testing with iOS 10.2 Beta. I have added the Photos, PhotosUI and MobileCoreServices frameworks to project. Very simple code: ``` #import <Photos/Photos.h> #import <PhotosUI/PhotosUI.h> #import <MobileCoreServices/MobileCoreServices.h> @interface ViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate, PHLivePhotoViewDelegate> @property (strong, nonatomic) IBOutlet UIImageView *imageview; @end ``` and implementation: ``` - (IBAction)grab:(UIButton *)sender{ UIImagePickerController *picker = [[UIImagePickerController alloc]init]; picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; picker.allowsEditing = NO; picker.delegate = self; // make sure we include Live Photos (otherwise we'll only get UIImages) NSArray *mediaTypes = @[(NSString *)kUTTypeImage, (NSString *)kUTTypeLivePhoto]; picker.mediaTypes = mediaTypes; // bring up the picker [self presentViewController:picker animated:YES completion:nil]; } ``` As soon as I tap the button, the app crashes with very useless error: `[access] <private>` That's it. Nothing else. Using break statements, the app seems to crash at "presentViewController". This is a brand new app and I don't have anything else in the UI other than the grab button. Also, testing on iOS 9.3, this works fine. Am I missing something which might be changed in iOS 10?
2016/07/07
[ "https://Stackoverflow.com/questions/38236723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1634905/" ]
in iOS 10 you need to add the key mentioned in below image if you are using camera or photo gallery in your app [![.plist image](https://i.stack.imgur.com/nw6ms.png)](https://i.stack.imgur.com/nw6ms.png)
In iOS 10, Apple has changed how you can access any user private data types. You need to add the **Privacy - Photo Library Usage Description** key to your app’s `Info.plist` and their usage information. For more information please find the below GIF. [![GIF](https://i.stack.imgur.com/IRHov.gif)](https://i.stack.imgur.com/IRHov.gif) Or if you want to add via `info.plist` then you need to add **NSPhotoLibraryUsageDescription** key. Just copy and paste below string in `info.plist`. ``` <key>NSPhotoLibraryUsageDescription</key> <string>Take the photo</string> ``` Please find the below GIF for more information. [![GIF](https://i.stack.imgur.com/owJMX.gif)](https://i.stack.imgur.com/owJMX.gif)
258,602
I tend to see these words a lot in Discrete Mathematics. I assumed these were just simple words until I bumped into a question. Is the following proposition **Satisfiable?** Is it **Valid**? $(P \rightarrow Q) \Leftrightarrow (Q \rightarrow R ) $ Then I searched in the net but in vain. So I'm asking here. What do you mean by Satisfiable and Valid? Please explain.
2012/12/14
[ "https://math.stackexchange.com/questions/258602", "https://math.stackexchange.com", "https://math.stackexchange.com/users/49700/" ]
A formula is valid if it is true for all values of its terms. Satisfiability refers to the existence of a combination of values to make the expression true. So in short, a proposition is satisfiable if there is at least one `true` result in its truth table, valid if all values it returns in the truth table are `true`.
* **Valid**: always true regardless of the values of its variables, e.g., `P OR NOT(P).`. Slightly more formally: *A valid formula is one which is always true, no matter what truth values its variables may have.* * **Satisfiable**: Can be solved, i.e., `true` and `false` values can be assigned to its variables, in a way that the final outcome is true. Slightly more formally: *A *satisfiable* formula is one which can sometimes be true, i.e., there is some assignment of truth values to its variables that makes it true.* An example of an *unsatisfiable* formula is `P AND NOT(P).`. --- Why are *satisfiability* and *validity* treated together? Because they are related: ``` To check that G is valid, we can check that NOT(G) is not satisfiable. ``` If you want to read more about satisfiability and validity in an accesible way, check the chapter 3 of [Mathematics for Computer Science by Lehman, Thomson and Meyer](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-spring-2015/readings/MIT6_042JS15_textbook.pdf).
78,712
It appears to be quite difficult to define agency in a metaphysical sense in a deterministic world. All handling I have seen suggests agents "choose" between paths, and thus require the system to be non-deterministic. Are there any philosophical approaches which support the reduction of a non-deterministic system into a deterministic one in a non-randomly selected way without invoking the concept of agency?
2021/01/24
[ "https://philosophy.stackexchange.com/questions/78712", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/8007/" ]
> > All handling I have seen suggests agents "choose" between paths, and thus require the system to be non-deterministic. > > > I don't believe that choice (or agency) requires non-determinism. Even if it is predetermined that I will choose A rather than B, the fact remains that at some point I do choose A rather than B. A pre-determined choice is still a choice. It is, however, a choice with the quality that one is pre-determined to make it. Some may argue that a pre-determined choice is NOT a choice at all. That seems to me to be a choice about how language ought to be used, and I don't find it compelling.
There is no concept of agency in a deterministic world. Agency is the capability to initiate actions. Determinism does not include any such capability. A non-deterministic system can be reduced to a deterministic system only by removing all things not possible in determinism. I have no idea how that could be done.
1,379,213
I just updated to 21.10. I was used to and loved using [Tilda](https://github.com/lanoxx/tilda) with F1 to drop it down and up. This does not seem to work on 21.10 easily. I couldn't deactivate the F1 help function, i.e. whenever I press F1, depending on the active window, the help window appears. Also other Fx keys don't seem to work for tilda (and anyways I really would like to get it to work with F1 again). Is there a hacky way to deactivate the built-in help on F1 or to make tilda work? Help is much appreciated! PS: I'm using a laptop.
2021/12/04
[ "https://askubuntu.com/questions/1379213", "https://askubuntu.com", "https://askubuntu.com/users/1549234/" ]
Ubuntu 20.04 and later has the python3.9 package in its default repositories. It can be installed alongside the default python3.8 package with `sudo apt update && sudo apt install python3.9` Installing the python3.9 package from the default Ubuntu repositories simplifies package management. If you are using Ubuntu 20.04 keep Python 3.8 as the default Python 3.x version and switch to Python 3.9 only when necessary using `update-alternatives`. After you are done using Python 3.9 you can switch the it back to the default Python 3 version. * List installed versions of Python: `update-alternatives --list python` * Switch between Python versions: `update-alternatives --config python` From the terminal command-line Press <enter> to keep the current choice[\*], or type selection number:
If you're asking about installing a version of python that's available system wide as a non-root user, I haven't found a good way to do this. However, there is no problem with having multiple versions of python available on your system at the same time. Download the appropriate .tgz file from the python website. Then (I'll use version 3.10.6 to illustrate): ``` # tar xfp Python-3.10.6.tgz # cd Python-3.10.6 # ./configure --prefix=/usr/local --exec_prefix=/usr/local --enable-optimizations # make # make altinstall ``` That's it. As long as /usr/local/bin is in your path, you can execute this version of python by typing: ``` $ python3.10 ``` For adding packages with pip, use ``` # pip3.10 install <a_package> ``` and it will add the package to the site-packages folder of the 3.10.6 install under /usr/local/lib.
2,182,744
I am using VS 2008(Professional edition) with SP1.I am new to ADO.NET DataServices.I am watching Mike Taulty videos. He used [DataWebKey] attribute to specifty the key field and he referred the namespace Microsoft.Data.Web. To follow that example I am trying to refer the same assembly,but it is not found in my system. How to fix it?
2010/02/02
[ "https://Stackoverflow.com/questions/2182744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264175/" ]
[`echo`](http://de.php.net/manual/en/function.echo.php) is not a function, but a language statement. It cannot be redefined. If you are looking to prettify your output markup, have look at [Tidy](http://de3.php.net/manual/en/class.tidy.php). --- What you *could* do, is use your IDE's search/replace method and replace all `echo` statements with `echo PHP_EOL,`. This would append the OS specific newline char(s) before any output. Note the comma after PHP\_EOL as it is important. You can output several values with echo like this: ``` echo 'one', $foo, PHP_EOL, 'two', $bar, PHP_EOL; ``` so there is no need to write `echo` on each line. **However**, I agree with anyone who suggested using a more dedicated approach to separate content and layout e.g. using template views or HereDoc. In additon, there is very little gain in having pretty markup. If you are using tools like Firebug to inspect the HTML, you will have properly formatted markup regardless of the mess the markup really is. Moreover, on sites with a lot of visitors, you'll often find the markup minified, which is the opposite of what you are trying to do, simply because all these newlines and tabs add to the weight of the page, which leads to slower page loads and increased traffic cost.
You have various possibilities to output HTML. You can use the [heredoc](http://php.net/manual/en/language.types.string.php) syntax: ``` $html = <<<EOF <h1>Rar<h1> <span>Rar</span> <p>Rar</p> EOF echo $hml; ``` Or (what is way better in my opinion), **separate HTML from PHP**. E.g. put all the PHP logic in the top of the file and the HTML after the PHP block: ``` <?php // all your PHP goes here $foo = 'bar' ?> <!-- HTML comes here --> <html> <body> <div>Hello <?php echo $foo; ?> </div> </body> </html> ``` Variables can be printed as shown above. But these variables **don't** contain HTML. When you have to output HTML based on a condition, you can use the [alternative syntax for control statements](http://php.net/manual/en/control-structures.alternative-syntax.php): ``` <?php if($some_condition): ?> <h1>Rar<h1> <span>Rar</span> <p>Rar</p> <?php endif ?> ``` This way it is also easier to debug your HTML as it is not only a PHP string.
26,338,107
Can you mix user input data with fixed data in a prepared statement security wise or does each query condition have to have a placeholder? For example: ``` $code = htmlspecialchars($_GET['code']); // USER INPUT DATA $status = 'A'; // FIXED $stmt = $connect->prepare("SELECT s_id FROM events WHERE s_code = ? AND s_status = ?") or die(mysqli_error()); $stmt->bind_param('ss', $code, $status); $stmt->execute(); $stmt->bind_result($reference); ``` Or is this also acceptable? ``` $code = htmlspecialchars($_GET['code']); // USER INPUT DATA $stmt = $connect->prepare("SELECT s_id FROM events WHERE s_code = ? AND s_status = 'A'") or die(mysqli_error()); $stmt->bind_param('s', $code); $stmt->execute(); $stmt->bind_result($reference); ```
2014/10/13
[ "https://Stackoverflow.com/questions/26338107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1826238/" ]
Here is my countdown timer: ***QuestionCountdownTimer*** ``` public class QuestionCountdownTimer extends CountDownTimer { private TextView remainingTimeDisplay; private Context context; public QuestionCountdownTimer(Context context,long millisInFuture, long countDownInterval,TextView remainingTimeDisplay) { super(millisInFuture, countDownInterval); this.context = context; this.remainingTimeDisplay = remainingTimeDisplay; } @Override public void onTick(long millisUntilFinished) { long millis = millisUntilFinished; String hms = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); remainingTimeDisplay.setText(hms); } @Override public void onFinish() { Toast.makeText(context,"COUNTDOWN FINISH :)",Toast.LENGTH_SHORT).show(); } } ``` **Note:** TextView remainingTimeDisplay remainingTimeDisplay.setText(hms); I use it to display the remaining time using a TextView Here I call the timer: ``` //Start Quiz timer QuestionCountdownTimer timer = new QuestionCountdownTimer(this,10000, 1000, remainingTimeDisplay); timer.start(); ``` -first parameter: this - I use it for context to show Toast message -second parameter: 10000 - total time (10 sec) -third parameter: 1000 - countdown interval (1 sec) -last parameter: dispaly remaining time in real time ***Tested and working***
You should use handler ``` private Handler tickResponseHandler = new Handler() { public void handleMessage(Message msg) { int time = msg.what; //make toast or do what you want } } ``` and pass it to MyCountDownTimer constructor ``` private Handler handler; public MyCountDownTimer(long startTime, long interval, Handler handler) { super(startTime, interval); this.handler = handler; } ``` And send message ``` @Override public void onTick(long millisUntilFinished) { text.setText("" + millisUntilFinished / 1); Message msg = new Message(); msg.what = millisUntilFinished/1; handler.sendMessage(msg); } ``` That's all you need to do :)
48,572,428
I am working on an Excel workbook that has one initial sheet. This first sheet is a form that asks the users how many items in their project they have. The macro then generates a sheet for each item in their project. Each generated sheet has buttons that perform specific functions, and these buttons have click events tied to them in the sheets code. I have coded out all the functionality I need in the sheet in a static sheet. I was wondering if there was a way to take this code and import it into all the dynamically created sheets once all the formatting and buttons are created by the form. Any help would be greatly appreciated!
2018/02/01
[ "https://Stackoverflow.com/questions/48572428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2796352/" ]
You could create a sheet named "Template" (potentially hidden) that would contain all the code and buttons and then use something like this: ``` Sheets("Template").Copy After:=Sheets(Sheets.count) ``` At this point, the Activesheet will be the newly copied sheet, so you can define a variable to refer to it and make all the changes you need. For example: ``` Dim ws as Worksheet set ws = Activesheet ws.Range("A1") = "test" ```
As @cyboashu said, just copy the sheet and it will copy all formulas and formatting over. At that point, any additional changes that are needed can still be made to the individual sheets. They are not linked copies. Here's a quick and dirty macro to copy worksheet(1) to the end of the workbook and rename. If you need to do any formatting, you can do it immediately after the paste using ActiveSheet. Assigning your new Activesheet to a variable to reference later is better practice but I'm not 100% sure how to do that without digging in further. Maybe someone can elaborate. ``` Sub copysheet() Dim Mainws As Worksheet Dim Mainwb As Workbook Set Mainwb = ThisWorkbook Set Mainws = ThisWorkbook.Worksheets(1) i = Mainwb.Worksheets.Count With Mainwb Mainws.Copy after:=Worksheets(i) Worksheets(i + 1).Name = "Copied Worksheet" End With With ActiveSheet Cells(1, 1).Value = "Copied Sheet" 'other formatting changes End With 'increment i variable if you plan to make more copies in a loop 'i = Mainwb.Worksheets.Count End Sub ```
60,240
In the following context is the word 'would' correct at all or do we have to use 'will'? > > Some countries grow hashish, and sometimes they **would** smuggle it to other countries. > > > Some countries grow hashish, and sometimes they **will** smuggle it to other countries. > > > What is the difference between these two vs the present simple form?
2012/03/06
[ "https://english.stackexchange.com/questions/60240", "https://english.stackexchange.com", "https://english.stackexchange.com/users/17953/" ]
*Would* makes it sound past tense. Also, "*they*" doesn't sound right, because countries don't smuggle, people do. I prefer either: > > Some countries grow hashish; sometimes it gets smuggled it to other > countries. > > > or: > > Some countries grew hashish; sometimes it would be smuggled it to > other countries. > > > or even: > > Some countries grow hashish, which is sometimes smuggled into other nations. > > >
*Would* is the past tense: 'People grew hashish, and sometimes they would smuggle it across the border' (habitually: if you mean specific instances 'sometimes they smuggled it'). It can be used even if hashish is still being grown ('Hashish has been grown in the region for centuries, and sometimes people would smuggle it across the border'), but you are definitely implying that smuggling no longer happens.
680,138
What is a good way for an ActiveX control to detect that its container (or container's container) is Internet Explorer? Currently, I am doing this by calling the control's IOleClientSite::GetContainer method and checking whether the container implements the IHtmlDocument2 interface, but now, I would like to check all of the control's ancestors to see if any of them implement IHtmlDocument. The problem is that the control is now contained in a CComCompositeControl and created using the CreateActiveXControls(resourceID) method, which creates the inner control as a child of a CAxHostWindow instance. In this case the CAxHostWindow instance reports itself as its own container, so I have not found a way to walk up the tree (if there is such a tree in this model).
2009/03/25
[ "https://Stackoverflow.com/questions/680138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13316/" ]
in the FragmentShader, you can write: ``` uniform sampler2D A; vec3 result = vec3(texture(A, TexCoord).r); ``` in the cpp file,you can write: ``` glTexImage2D( GL_TEXTURE_2D, 0, GL_RED, dicomImage->GetColumns(), dicomImage->GetRows(), 0, GL_RED, GL_UNSIGNED_BYTE, pixelArrayPtr); ```
You would use `GL_LUMINANCE` format in old versions of openGL, but now in modern 3.0+ OpenGL versions `GL_LUMINANCE` is deprecated, so new way of doing it is to use `GL_RED` format, but that would result in a red texture, so to get around this you should create a costum shader as above answers have shown, in that shader you grab red component of the texture, as it's the only one with data you have given and set green/blue channels to red channel's value, that will convert is to grayscale, because grayscale textures have all 3 RGB channels the same and Alpha/Transparency channel set to 1.
265,482
Imagine I want to make a laser of electrons like a laser of light. Is that possible, or does the Pauli exclusion principle prohibit that?
2016/06/30
[ "https://physics.stackexchange.com/questions/265482", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/103999/" ]
This is almost a duplicate then of *[Pauli exclusion principle in an electron beam](https://physics.stackexchange.com/questions/176481/pauli-exclusion-principle-in-electron-beam)*. Almost because it asks about cathode ray beams. The answer there is yes; the Pauli exclusion principle plays a role similar to the neutron star role. For an accelerator beam, where the electrons and positrons are considered free particles, as were the [LEP](https://en.wikipedia.org/wiki/Large_Electron%E2%80%93Positron_Collider) e+ e- beams, the effect has not been considered as far as I can see. As the other answer states, there is no time constraint in such beams.
Lasers operate via the stimulated emission of light. This is a phenomenon that applies to bosons, since the stimulated photon is in the same state as the photon that stimulates it. The same thing cannot happen in fermions; instead there is an analogous process called stimulated absorption which means that the intensity of a fermion beam would be decreased whilst travelling in the "lasing medium". Thus, no amplification. If on the other hand you are just asking whether degeneracy imposes a limit on the density of an electron beam where the electrons have a narrow range of momentum, then the answer is yes and is handled by the duplicate.
820,526
Does anyone know where I can find an implimentation that wraps a `std::map` and makes it thread safe? When I say thread safe I mean that it offers only serial access to the map, one thread at a time. Optimally, this map should use only the standard-library and / or boost constructs.
2009/05/04
[ "https://Stackoverflow.com/questions/820526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25882/" ]
Does not meet the criteria that you have specified, but you could have a look at the [TBB](http://www.threadingbuildingblocks.org/) containers. There is so called `concurrent_hash_map` which allows multiple threads to access concurrently the data in the map. There are some details, but everything is nicely documented and can give you an idea of the "concurrent container". Depending on your needs this might be totally inappropriate...
You might look at [Thread Safe Template Library](http://freshmeat.net/projects/tstl/)
439,688
I have a log file, each line in the log is prepend with a date, like so: `2012-03-06 11:34:48,657 blah blah blah...` How do I `grep` this file and get only the lines from 8am to 11pm only? My intention is I want to count the number of errors happening within 8am to 11pm.
2012/06/21
[ "https://superuser.com/questions/439688", "https://superuser.com", "https://superuser.com/users/34680/" ]
``` egrep '^[^ ]+ (0[89]|1[0-9]|2[012]):' ``` Detailed explanation can be found in various [regex](http://en.wikipedia.org/wiki/Regular_expression) (regular expression) tutorials; `egrep` uses "POSIX extended" syntax (`man 7 regex`). * The first `^` means "start of the line". * `[^ ]+` just matches the date field, regardless of the actual date. + `[...]` means "any character between the brackets", so `[89]` will match either `8` or `9`; `[0-9]` is any number, and `[^ ]` is anything *except* a space (because of the `^` inside brackets). + `+` means "one *or more* of the previous" (for example, `a+` would match `a`, `aaa`, and `aaaaaaaa`). + So `^[^ ]+` will start with the beginning of line, and match as many non-space characters as it can. * `(...|...|...)` means "either of the given patterns", so `(0[89]|1[0-9]|2[012])` means "either `0[89]` or `1[0-9]` or `2[012]`". It will match all numbers from 08 to 22. --- A somewhat better option is: ``` awk -F'[: ]' '$2 >= 8 && $2 <= 22 { print }' ``` The `-F` option splits every line into separate fields according to the `[: ]` regex (matching either `:` or a space), and the *awk* script checks the 2nd column (the hour).
There's actually a much easier way to do this. Download/Documentation: [autodrgrep.kl.sh](http://www.kinglazy.com/grep-date-range-in-log-files-awk-sed-linux-unix.htm) **Command:** ``` ./autodrgrep.kl.sh notchef /tmp/client.log '2016-05-08_08:00:00,2016-05-08_23:00:00' 'INFO' 'a2ensite' 5 10 -show ``` **Explanation:** * autodrgrep.kl.sh is the tool name. * notchef is an option that is passed to the tool to tell it what to do. In this particular case, it is telling the tool what type of log file /tmp/client.log is. * /tmp/client.log is of course the log file. * 2016-05-08\_19:12:00,2016-05-08\_21:13:00 is the range of date from within the log that you wish to scan * "INFO" is one of the strings that is in the lines of logs that you're interested in. * "a2ensite" is another string on the same line that you expect to find the "INFO" string on. Specifying these two strings (INFO and a2ensite) isolates and processes the lines you want a lot quicker, particularly if you're dealing with a huge log file. * 5 specifies Warning. By specifying 5, you're telling the program to alert as WARNING if there are at least 5 occurrences of the search strings you specified * 10 specifies Critical. By specifying 10, you're telling the program to alert as CRITICAL if there are at least 10 occurrences of the search strings you specified. * -show specifies what type of response you'll get. By specifying -shown, you're saying if anything is found that matches the specified patterns, output to screen. **Sample run:** ``` # ./autodrgrep.kl.sh notchef /tmp/client.log '2016-05-08_19:12:00,2016-05-08_21:13:00' 'INFO' 'a2ensite' 5 10 -show [2016-05-08 19:12:58-07:00] INFO: Processing template[/usr/sbin/a2ensite] action create (apache2::default line 90) [2016-05-08 19:12:58-07:00] INFO: Processing execute[a2ensite default] action run (apache2::default line 24) [2016-05-08 19:12:58-07:00] INFO: execute[a2ensite default] ran successfully [2016-05-08 19:13:09-07:00] INFO: Processing execute[a2ensite nagios3.conf] action run (logXrayServer::install line 24) [2016-05-08 19:13:12-07:00] INFO: execute[a2ensite default] sending restart action to service[apache2] (delayed) [2016-05-08 19:42:57-07:00] INFO: Processing template[/usr/sbin/a2ensite] action create (apache2::default line 90) [2016-05-08 19:42:57-07:00] INFO: Processing execute[a2ensite default] action run (apache2::default line 24) [2016-05-08 19:42:57-07:00] INFO: execute[a2ensite default] ran successfully [2016-05-08 19:43:08-07:00] INFO: Processing execute[a2ensite nagios3.conf] action run (logXrayServer::install line 24) [2016-05-08 19:43:11-07:00] INFO: execute[a2ensite default] sending restart action to service[apache2] (delayed) [2016-05-08 20:12:58-07:00] INFO: Processing template[/usr/sbin/a2ensite] action create (apache2::default line 90) [2016-05-08 20:12:58-07:00] INFO: Processing execute[a2ensite default] action run (apache2::default line 24) [2016-05-08 20:12:58-07:00] INFO: execute[a2ensite default] ran successfully [2016-05-08 20:13:10-07:00] INFO: Processing execute[a2ensite nagios3.conf] action run (logXrayServer::install line 24) [2016-05-08 20:13:12-07:00] INFO: execute[a2ensite default] sending restart action to service[apache2] (delayed) [2016-05-08 20:42:59-07:00] INFO: Processing template[/usr/sbin/a2ensite] action create (apache2::default line 90) [2016-05-08 20:42:59-07:00] INFO: Processing execute[a2ensite default] action run (apache2::default line 24) [2016-05-08 20:42:59-07:00] INFO: execute[a2ensite default] ran successfully [2016-05-08 20:43:09-07:00] INFO: Processing execute[a2ensite nagios3.conf] action run (logXrayServer::install line 24) [2016-05-08 20:43:12-07:00] INFO: execute[a2ensite default] sending restart action to service[apache2] (delayed) [2016-05-08 21:12:59-07:00] INFO: Processing template[/usr/sbin/a2ensite] action create (apache2::default line 90) [2016-05-08 21:12:59-07:00] INFO: Processing execute[a2ensite default] action run (apache2::default line 24) [2016-05-08 21:12:59-07:00] INFO: execute[a2ensite default] ran successfully 23 2---78720---23---ATWFILF---(2016-05-08)-(19:12)---(2016-05-08)-(21:13) SEAGM ``` **What if the user specified date range or time frame is not in the log?** Each run of the above command will always have a line (last line of the output) that either says "ATWFILF" or "ETWNFILF". * ATWFILF means that the actual date range or time frame you requested searched was found in the log. So this is very good. * ETWNFILF means the actual date range or time frame you requested searched was NOT found in the log. In this case, the closest time to the time you specified will be detected and used instead.
166,641
Introduction: ------------- The best options for the glass of your house will: 1. Let through as little heat as possible in both directions (insulation-value `Ug`). (2. Let through as much sunbeams as possible from the outside to the inside.) (3. Let through as much light as possible from the outside to the inside.) We only care about the first one for this challenge. In addition, there are different types of glass changing the `Ug`: regular single glass; regular double glass; HR double glass; HR+ double glass; HR++ double glass; HR+++ double glass. HR = High Rendement glass; regular double glass with have air between both layers, but HR will have a noble gas between both layers. Sources (not very useful for most though, because they are in Dutch, but added them anyway): [Insulate and save money](https://www.milieucentraal.nl/energie-besparen/energiezuinig-huis/isoleren-en-besparen/isolerende-raamfolie/) and [What is HR++ glass?](https://www.dubbelglas-weetjes.nl/hr-glas/) Challenge: ---------- **Input:** A string indicating glass and window foil (below the possible input-strings are explained) **Output:** (Calculate and) output the heat-transition `Ug` **Here a table with all glass options and the expected output `Ug`-values:** ``` Glass (optional foil) Ug-value Description | 5.8 Single-layered regular glass || 2.7 Double-layered regular glass | | 1.85 HR glass |+| 1.45 HR+ glass |++| 1.2 HR++ glass |+++| 0.7 HR+++ glass |r 3.4 Single-layered regular glass with reflective foil ||r 2.1 Double-layered regular glass with reflective foil |f 2.8 Single-layered regular glass with regular window-foil ||f 2.0 Double-layered regular glass with regular window-foil |g 4.35 | with insulating curtain ||g 2.025 || with insulating curtain | |g 1.3875 | | with insulating curtain |+|g 1.0875 |+| with insulating curtain |++|g 0.9 |++| with insulating curtain |+++|g 0.525 |+++| with insulating curtain |rg 2.55 |r with insulating curtain ||rg 1.575 ||r with insulating curtain |fg 2.1 |f with insulating curtain ||fg 1.5 ||f with insulating curtain / 8.7 Diagonal | // 4.05 Diagonal || / / 2.775 Diagonal | | /+/ 2.175 Diagonal |+| /++/ 1.8 Diagonal |++| /+++/ 1.05 Diagonal |+++| /r 5.1 Diagonal |r //r 3.15 Diagonal ||r /f 4.2 Diagonal |f //f 3.0 Diagonal ||f /g 6.525 Diagonal | with insulating curtain //g 3.0375 Diagonal || with insulating curtain / /g 2.08125 Diagonal | | with insulating curtain /+/g 1.63125 Diagonal |+| with insulating curtain /++/g 1.35 Diagonal |++| with insulating curtain /+++/g 0.7875 Diagonal |+++| with insulating curtain /rg 3.825 Diagonal |r with insulating curtain //rg 2.3625 Diagonal ||r with insulating curtain /fg 3.15 Diagonal |f with insulating curtain //fg 2.25 Diagonal ||f with insulating curtain ``` Some things to note about the values: the first ten are all the different default values (taken from the two linked sources). Adding a `g` (insulating curtain) lowers that value by 25%. Having a `/` (diagonal window) increases that value by 50%. Challenge rules: ---------------- * You can ignore any floating point precision errors * You can use the default decimal output-format of your languages, so if `3.0` is output as `3` instead; or if `0.9` is output as `0.900` or `.9` instead, it doesn't matter. * You'll only have to worry about the input-options given above. Inputting anything else may result in undefined behavior (weird outputs, errors, etc.) General rules: -------------- * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, please add an explanation of your answer.
2018/06/11
[ "https://codegolf.stackexchange.com/questions/166641", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/52210/" ]
JavaScript (ES6), ~~111~~ 109 bytes =================================== ```javascript s=>'_FQLKIe%f:}'.charCodeAt((g=c=>~-s.split(c).length)(/\W/)+3*g` `+6*g`r`+8*g`f`)*5%117/(g`g`?8:g`|`?6:4)*.3 ``` [Try it online!](https://tio.run/##XZJRT4MwFIXf9yvui2k7XAsDNsSwxRiXLC4hPvmgRiaj3XQZpiVG4/SvI5QWjX1p8nFyzrmXPq/f1iqXu9dqdCg3Rc2TWiUz9Li4WV0vixMefyGab9fysvl4UWEskjyZfY8UVa/7XYVzQvfFQVRbgtn9LSOOPxQZZM6kuWTmRM3FMzIMTzxvyrDIRDaPYpEds/kkDsiQ@nUKCXwOANARQXtiCGl0qkFHYhjTaQdAkxg8GoUdcXoSWKJRS8YWtCQG17pIY@vTwORIZHK8DvA@2DbhVuF2QBhFQH2T2yEtGYe2rjBV/GjaF7bM/WUatg3PfisL1ILQesnePrSB0jqF1oiLf4N0RGs0YHbHkVkGY/0grpEAsyZT48ucHnk90kz/CgtaogczErvn0LRhzOzZp56R8D59bCTcStzB1/lgkD49F3lFX4oPhVNCeSmv1vkWK0hmkJcHVe4Lui8Fls0r4lgRWpWL3XuxwQE5hQYmkN6phz8U5oDS67YoWlwsV4iQ@gc "JavaScript (Node.js) – Try It Online") ### How? We define the helper function **g()** as: ```javascript g = c => ~-s.split(c).length ``` `split()` takes either a string or a regular expression as input. Hence, so does **g()**. We define: ``` - N = g(/\W/) = number of non-alphanumeric characters - S = g(' ') = number of spaces - R = g('r') = number of "r" - F = g('f') = number of "f" - G = g('g') = number of "g" - P = g('|') = number of "|" ``` The formula **n = N + 3S + 6R + 8F** gives a unique identifier in **[1..10]** for all default values: ``` input | N | S | R | F | n ---------+---+---+---+---+---- "|" | 1 | 0 | 0 | 0 | 1 "||" | 2 | 0 | 0 | 0 | 2 NB: because 'g' characters are ignored in this formula "| |" | 3 | 1 | 0 | 0 | 6 and because a '/' is counted the same way as a '|', "|+|" | 3 | 0 | 0 | 0 | 3 the 2 other sets of inputs give the same results. "|++|" | 4 | 0 | 0 | 0 | 4 "|+++|" | 5 | 0 | 0 | 0 | 5 "|r" | 1 | 0 | 1 | 0 | 7 "||r" | 2 | 0 | 1 | 0 | 8 "|f" | 1 | 0 | 0 | 1 | 9 "||f" | 2 | 0 | 0 | 1 | 10 ``` We use this identifier to pick the corresponding entry from the following 1-indexed array, which contains the default values multiplied by **20**: ``` [116, 54, 29, 24, 14, 37, 68, 42, 56, 40] ``` This array is encoded as the string `"FQLKIe%f:}"`. For each character, we multiply the ASCII code by **5** and apply a **modulo 117**: ``` char | code | * 5 | mod 117 ------+------+-----+--------- 'F' | 70 | 350 | 116 'Q' | 81 | 405 | 54 'L' | 76 | 380 | 29 'K' | 75 | 375 | 24 'I' | 73 | 365 | 14 'e' | 101 | 505 | 37 '%' | 37 | 185 | 68 'f' | 102 | 510 | 42 ':' | 58 | 290 | 56 '}' | 125 | 625 | 40 ``` Finally, we divide this value by: * **80 / 3** if **G** is non-zero * **60 / 3** if **P** is non-zero * **40 / 3** otherwise
Excel & CSV, 194 bytes ====================== ``` ,"=HLOOKUP(SUBSTITUTE(SUBSTITUTE(A1,""g"",),""/"",""|""),2:3,2,)*IF(CODE(A1)=47,1.5,1)*IF(RIGHT(A1,1)=""g"",0.75,1)" |,||,| |,|+|,|++|,|+++|,|r,||r,|f,||f 5.8,2.7,1.85,1.45,1.2,0.7,3.4,2.1,2.8,2 ``` Input entered before the first `,`n and saved as `CSV`. When opened in Excel, Cell `B1` displays result. Sample usage: ``` /+++/g,"=HLOOKUP(SUBSTITUTE(SUBSTITUTE(A1,""g"",),""/"",""|""),2:3,2,)*IF(CODE(A1)=47,1.5,1)*IF(RIGHT(A1,1)=""g"",0.75,1)" |,||,| |,|+|,|++|,|+++|,|r,||r,|f,||f 5.8,2.7,1.85,1.45,1.2,0.7,3.4,2.1,2.8,2 ``` Opens as: ``` /+++/g 0.7875 | || | | |+| |++| |+++| |r ||r |f ||f 5.8 2.7 1.85 1.45 1.2 0.7 3.4 2.1 2.8 2 ```
308,158
In C++, it is possible to write an overriding for a base class's method even if the visibility declaration of the two don't match. What are the possible design considerations under the decision of not considering the visibility in the overriding rule? Consider this piece of code as an example: ``` class A{ public: virtual void f() { cout << "A::f" << endl; } }; class B : public A { private: void f() { cout << "B::f" << endl; } }; int main() { A* a = new B; a->f(); } ``` The above compiles in clang, and running it prints B::f, showing that it is possible to call a private function of B from outside the class, thus breaking encapsulation. I don't really see why this type of behavior should be allowed. It is clearly not for performance/efficiency reasons, since checking statically that two visibility declarations match is trivial. Does anybody have an idea or hypothesis about what could possibly be the design decision behind this?
2016/01/23
[ "https://softwareengineering.stackexchange.com/questions/308158", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/181877/" ]
> > The above compiles in clang, and running it prints B::f, showing that > it is possible to call a private function of B from outside the class, > thus breaking encapsulation. > > > The encapsulation isn't broken. It's B that's semi-broken. B publicly inherits from A. A's public interface *is* B's public interface. The real question is why B should be permitted to even create a private override of a public function. Simple fact is, there's just no real reason to ban it. If you're writing B and do so correctly, this should never happen in reality. Unless you explicitly intended it for some reason, in which case, congratulations.
It's absolutely intentional. Changing the visibility must (at most) change whether your code compiles or doesn't compile. It must never, ever change what the code does. If B::f() were public, then you would expect B::f() to be called. The fact that you made b::f() private cannot change this, according to the rule above; it is only allowed to change whether code compiles. Since the caller didn't even need to know about class B, the code must compile and call B::f(). There is no breaking of encapsulation here. In class A you declared that f is a virtual function which can be called by anyone through an instance of A. Subclasses cannot do anything to change that. If a developer thought that makeing B::f() private prevented the virtual function from being called, then that developer is just deluded.
8,750
It's being rather a tough choice on selecting projects. (Different case from what I had posted before.) Now in the scenario if there is Project A and B. Only one project can be executed and that has to be chosen. Both are given the same resources, costing/budgeting. Project A would generate revenue of 100$, and senior management would be happy. Project B will make 60$, increased productivity for staff and senior management will be happy as well. TMS = Top management Satisfaction UWE = User Workflow Efficiency Increased ``` | PROJECT | RESOURCES | COST | REVENUE | TMS | UWE | ---------------------------------------------------- | A | r100 | 30 | 100 | Yes | No | | B | r100 | 30 | 60 | Yes | Yes | ``` **Which project should be choosen and how to justify it?** Here is what I came up with and chose Project B, because: * The project that can be delivered in shorter period of time. * As staff is trained to and their workflow are more productive, they will increase the revenue generation in the long run not only for today. * 100$ seems like one time project and doesn't seem to have an impact on the company's business operations and backbone or users. * Probably Project B could leave re-usable prototypes, artifacts. * The project that uses development tools that doesn't have a high frequency of new versions coming in but stable plus possible to adapt to future changes in the business model and processes. There will be expertise answers out there and mine could have loop holes. Hence please throw some perspective or any guidance/article that could support better justification.
2013/02/21
[ "https://pm.stackexchange.com/questions/8750", "https://pm.stackexchange.com", "https://pm.stackexchange.com/users/5633/" ]
TL; DR ------ Project selection is the job of the project sponsor, product manager, or steering committee. It is *not* the job of the project manager. *Very Bad Things™* (mostly for you) will often result from this. Why You Shouldn't Do What You're Doing -------------------------------------- Part of the problem here is that it seems like a project manager is being asked to select and justify a project. This is generally out of scope for the role. Projects require an executive sponsor, who generally supports a given project for strategic reasons. Those reasons may be earnings, return on investment, efficiency or productivity improvements, or just because it will look good to someone else on Mahogany Row. The point is, *the reason doesn't matter* for the purposes of project initiation. The goals of the project may certainly impact scheduling or the selection of project controls, but the decision of which project to pursue belongs at a pay grade *above* the project manager. How a Project Manager Can Add Value to Portfolio Selection ---------------------------------------------------------- If you have opinions about the feasibility or value of a given project, or wish to exert some influence on the strategic decisions of your company, go right ahead and expend a little political capital by sharing what you know with the steering committee or project sponsor. However, I'd personally recommend against playing the Dilbertesque game of trying to quantify a business decision that is fundamentally one of subjective organizational value, and that is firmly outside the project management domain of **process control**. Division of Responsibilities ---------------------------- The executive sponsor has the responsibility to say "I want to champion this project because..." and then make the case for it. Your job, as a project manager, is to look at the proposed project and provide your professional opinion about the resources required to do it, and whether or not the goal can be met with the resources available to the project.
I haven't attended this course, but I'll cite it because it seems relevant [How to Prioritize Projects When Each One is Critical](http://www.pduotd.com/2013/03/01/how-to-prioritize-projects-when-each-one-is-critical-10/). I have no affiliation with the vendor - I just hoped it might help the OP (and provide some PDU's)
1,065
I just got finished a few weeks ago setting up my `torrc` to require connections to U.S. ExitNodes. I just used Vidalia to get into the "Tor Configuration File", and edited that. Worked great. Now I've downloaded the new Tor bundle (3.5) and, whoah, Vidalia is gone, and my ExitNodes are no longer constrained in the same way. This new version of Tor pulls random international ExitNodes. Until I figure out how to change ExitNodes in the new Tor, I'm going to stick with the old one, which still works properly. I gather the new Tor isn't looking at the original `torrc`. How, in the new Tor do I access the new configuration file?
2013/12/20
[ "https://tor.stackexchange.com/questions/1065", "https://tor.stackexchange.com", "https://tor.stackexchange.com/users/618/" ]
Tor Browser Bundle uses the `Data/Tor/torrc` file inside its own directory. From [Tor Project FAQ](https://www.torproject.org/docs/faq.html.en#torrc): > > If you installed Tor Browser Bundle, look for `Data/Tor/torrc` inside > your Tor Browser Bundle directory. > > > Core Tor puts the torrc file in `/usr/local/etc/tor/torrc` if you > compiled Tor from source, and `/etc/tor/torrc` or `/etc/torrc` if you > installed a pre-built package. > > > You should be able to set your exit node country to U.S. by adding the following to `torrc` file: `ExitNodes {us}`
Tor browser now uses `./Data/Tor/torrc-defaults`. In `./Data/Tor/torrc`, there's the warning: > > This file was generated by Tor; if you edit it, comments will not be preserved > > The old torrc file was renamed to torrc.orig.1 or similar, and Tor will ignore it > > > This is somewhat confusing, because in the [manual](https://www.torproject.org/docs/tor-manual.html.en), I see: > > --defaults-torrc FILE > > > > Specify a file in which to find default values for Tor options. The contents of this file are overridden by those in the regular configuration file, and by those on the command line. (Default: @CONFDIR@/torrc-defaults.) > > > But actually, that's the case in the Tor browser. It's just that "the regular configuration file" aka `./Data/Tor/torrc` is "generated by Tor", and doesn't preserve edits.
10,653,604
I have an object called "message" "message" holds an anonymous object (as a string): ``` {"action":"wakeup","hello":"testing123"} // this is what I get when I output "message" with alert() ``` How do I address/get the content of "hello" from that?
2012/05/18
[ "https://Stackoverflow.com/questions/10653604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284740/" ]
I think this is a JSON object so you should use the eval function to convert it to json and you can use it as a property of variable that will contain the result of convertion
Since your using JSON and jQuery I'll assume that you're getting the data from an AJAX call. You could use the `$.getJSON()` method which will give a nice fully formed Javascript object. If that's not correct you should be calling `eval()` on the message string to create a Javascript object.
27,454,350
I'm trying to compress pdf files using ghostscript like this: ``` gs -sDEVICE=pdfwrite -dPDFSETTINGS=/ebook -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -sOutputfile=output.pdf input.pdf ``` I've done this successfully in the past, but for some reason now it won't work. I get the following error: ``` GPL Ghostscript 9.15 (2014-09-22) Copyright (C) 2014 Artifex Software, Inc. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. **** Unable to open the initial device, quitting. Unrecoverable error: undefinedfilename in setpagedevice Operand stack: true --nostringval-- --nostringval-- --nostringval-- --nostringval-- --nostringval-- --nostringval-- --nostringval-- --nostringval-- ``` [Edit: I fixed the typo from -SOutputFile to -sOutputFile to avoid this red herring. (But that is what some of the comments/answers are referring to.)]
2014/12/13
[ "https://Stackoverflow.com/questions/27454350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/570251/" ]
This worked for me... ``` gs \ -sDEVICE=pdfwrite \ -dCompatibilityLevel=1.4 \ -dPDFSETTINGS=/printer \ -dNOPAUSE \ -dQUIET \ -dBATCH \ -sOutputFile=output.pdf \ input.pdf ``` **Edited by -kp-** To spell it out explicitly (and to re-iterate what KenS wrote in his comment): 1. `-SOutputFile=...` does NOT work 2. `-sOutputFile=...` is the correct syntax. (Ghostscript command line parameters are case sensitive!) Also, with recent versions of Ghostscript, you can now use `-o output.pdf` instead of the long version. `-o ...` also automatically and implicitely sets the `-dBATCH -dNOPAUSE` parameters. So the shortest way to write this command is: ``` gs \ -sDEVICE=pdfwrite \ -dCompatibilityLevel=1.4 \ -dPDFSETTINGS=/printer \ -q \ -o output.pdf \ input.pdf ```
It could be that you have simply mixed up your input and output filenames. I have done that before and got the same message. It's easy to do, since the output file command comes before the input file.
30,070,233
I have a text like this: ``` my text has $1 per Lap to someone. ``` Could anyone tell me how to pick the `per` part from it. I know how to pick the `$` amount. It's like this: ``` new Regex(@"\$\d+(?:\.\d+)?").Match(s.Comment1).Groups[0].ToString() ``` Any help would be highly appreciated.
2015/05/06
[ "https://Stackoverflow.com/questions/30070233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1077309/" ]
In case you have multiple substrings you need inside a larger string, you can use capturing groups. To obtain the `per` part, use the following regex and grab the `Groups[2].Value`: ``` var str = "my text has $1 per Lap to someone. "; var per_str = new Regex(@"(\$\d+(?:\.\d+)?)\s*(\p{L}+)").Match(str).Groups[2].Value; ``` Output: ![enter image description here](https://i.stack.imgur.com/UR7fz.png) The regex to capture `per` is `\p{L}+` where `\p{L}` captures all Unicode letters (e.g. `ф`, `ё`), not just Latin script. To get the number part, use the same regex, but grab `Groups[1].Value`: ``` var num_str = new Regex(@"(\$\d+(?:\.\d+)?)\s*(\p{L}+)").Match(str).Groups[1].Value; ``` Output: ![enter image description here](https://i.stack.imgur.com/rWxG8.png) *And another tip*: **compile your regex** first if you plan to use it multiple times during your app execution: ``` var rx = new Regex(@"(\$\d+(?:\.\d+)?)\s*(\p{L}+)", RegexOptions.Compiled); var per_str = rx.Match(str).Groups[2].Value; var num_str = rx.Match(str).Groups[1].Value; ``` In case you need just a number after `$`, just put the opening round bracket after it in the regex: `@"\$(\d+(?:\.\d+)?)\s*(\p{L}+)"`. And to get all groups in 1 go, you can use ``` var groups = rx.Matches(str).Cast<Match>().Select(p => new { num = p.Groups[1].Value, per = p.Groups[2].Value }).ToList(); ``` ![enter image description here](https://i.stack.imgur.com/jK4VG.png) **EDIT:** If you just want to match `per` after the number, you can use `@"(\$\d+(?:\.\d+)?)\s*(per)"` or (case-insensitive) `@"(\$\d+(?:\.\d+)?)\s*((?i:per\b))"`
``` (?<=\$\d+(?:\.\d+)?\s+)\S+ ``` This should do it for you.
8,014
According to [this answer,](https://stackoverflow.com/a/664779/5394409) the stack grows downward. It's in §4.4 of the cited document: > > As another example, the DEC PDP11 range has a hardware > stack which grows with decreasing store addresses. > > > Now, but the way this works is by the pre-decrement and post-increment addressing modes. We can just use `(r6)+` for pop or `-(r6)` for push. But isn't that just convention? From what I understand we could equally well reverse the direction and use `(r6)+` for push or `-(r6)` for pop. Yet every document I see says the stack grows downward on the PDP-11. So what am I missing?
2018/10/20
[ "https://retrocomputing.stackexchange.com/questions/8014", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/576/" ]
The PDP-11 was especially designed to allow code to be written in either of the three common addressing schemes: * Zero Address (Stack) * On Address (Acumulator) * Two Address There's a quite nice paper Gordon Bell (et. al) wrote [describing the PDP-11 architecture](https://gordonbell.azurewebsites.net/CGB%20Files/New%20Architecture%20PDP11%20SJCC%201970%20c.pdf) (\*1), which in great detail talks about the ability to handle a stack machine using either register - except R6 and R7 that is, as they are predefined as Hardware Stack and PC. It is the combination of features (\*2) for their new mini-computer (\*3), that may confuse a bit. > > [...]the stack grows downward. [...] But isn't that just convention? From what I understand we could equally well reverse the direction[...]. Yet every document I see says the stack grows downward on the PDP-11. So what am I missing? > > > It's the hardware stack. While each register (\*4) can be used to manage a stack structure, R6 is tied to certain instructions and hardware functions manipulating *this* stack. To keep it manageable two assumptions are common to all of them: * The (R6) stack is word sized * The (R6) stack grows downward For example `JSR` pushes the return address down on R6, while `RTS` pulls it upward. Similar all hardware interrupts/trap will use the same fashion. So, unless one can take the risk of having the top of stack destroyed by any of those, going along and using R6 is a downward fashion is a must. Of course, this does not hinder any programming (language) to let the hardware stack run for itself and use any other Register (R0..R5) for their own purpose - like one (or more) software stacks managing procedure passing and local data structures. Forth may be the best known example here. The mentioned paper goes into great detail that the PDP-11 is well suited to handle stack orientated programming so due its auto-indexing instruction set. Still, while the handling of a data stack can easy be implemented using any other register, the return stack is hard to be moved, as there are no simple instructions replacing `JSR`/`RTS`. Sure, one could use some /360-like mechanics, but missing a LINK type instruction each call would be something like ``` MOV [Rmystack]+,PC JMP subroutine ``` while returning would translate to ``` MOV R0,-[Rmystack] ADD R0,2 MOV PC,R0 ``` Doesn't look great with just the little memory they had back then, not to mention execution time. **Bottom line: The Hardware Stack (R6) is quite useful due it's implied use of R6 but ties it's working to being downward and word sized.** So, why do we then not use a different software stack for parameter passing, growing upward or being of different (byte) size? Well, as so often 'Hail C' is the answer. When C was developed, they decided to accept the limitations and go with the hardware stack. It removes the need to use a separate register and, at least for simple issues, it's as good as any other. As a result we got stuck with a downward growing word sized stack and the evil mix-up of program flow management and data management. --- \*1 - Made for a speech during the [*Minicomputers - the profile of tomorrow's components* track](https://dblp.org/db/conf/afips/afips70s.html) at the [AFIPS](https://en.wikipedia.org/wiki/American_Federation_of_Information_Processing_Societies) Spring [Joint Computer Conference](https://en.wikipedia.org/wiki/Joint_Computer_Conference) in May 1970 in Atlantic City and published in [Volume 36](https://rads.stackoverflow.com/amzn/click/B000F9W2WK) of their proceedings. \*2 - They tried to dance on as many weddings as possible. Process control as well as scientific computing and general purpose. Hardware supported CISC structure as well as simple and symmetric instruction set for high level (synthetic) programming. \*3 - The paper starts with a real nice definition of what a micro-, mini- and midi-computer is by defining them by number of registers, word length, memory size, memory speed and cost. A worthwhile metric to be copied here to not only show that these terms weren't (and aren't) as settled as one assumes today, as well, as it's about capabilities, not size. ``` Address Word CPU Cost Data Space Size State Types (Words) (Bits) (Register) (1970 USD) Micro 8k 8~12 2 5k Integer, bit Vector Mini 32k 12~16 2-4 5~10k Indexing Midi 65~128k 16~24 4-16 10~20k Floating Point ``` It also shows that even the most basic of today's microcontrollers (AVR, PIC, not to mention ARM) may well be placed in the Midi category of 1970, if not Mainframe :) \*4 - Using R7 can as well be a bit ... well, lets say complicated :))
Doesn't it really depend on how you draw your memory. ``` ________ ________ FFFF| | 0000| | | map 1 |down | map 2 | ^ | | v | |up 0000|________| FFFF|________| ``` If it is a decreasing address, then in map1, it grows downwards but in map2, it grows upwards. Map1 is typically drawn like a normal graph, where 0 is at the bottom and the higher address is on top. Hardware engineers and mathematicians would normally draw the memory graph like this. Map2 is typically drawn by software people who normally sort things in ascending order. It also depends on the person's background. Some people find it difficult to visualise if the graph is drawn *upside down* from what they are used to thinking. Look at the hardware manual - I have seen manuals where the map is drawn both ways. Some manufacturers draw it with 0 on top, others draw it with 0 at the bottom. Sometimes, both conventions are used by the same manufacturer (Intel): typically chapters written by different people. It really depends on which convention you are used to when you say the stack grows upwards or downwards.
22,513,289
I have a csv file which contains millions of rows. Now few of the rows contains more data then column data type can accommodate. For e.g. csv file has only two rows as shown below please not ^\_ is delimiter ``` A^_B^_C AA^_BB^_CC ``` Now assume each line can accomodate only one character so line 1 row 1 is correct but line 2 is not and I want to find out all these kinds of lines. So I thought if I get the longest lines from csv file I will be good and I tried to following but is not helping (from [longest line](https://stackoverflow.com/questions/1655372/longest-line-in-a-file)) ``` wc -L file ``` Please help me find the largest line/column in a csv file. Another problem is I have two delimiter so cant use cut command also.
2014/03/19
[ "https://Stackoverflow.com/questions/22513289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449355/" ]
``` awk -F'\\^_' -v OFS=':' ' { for (i=1;i<=NF;i++) { if (length($i) > max) { max = length($i) lineNr = NR line = $0 fldNr = i fld = $i } } } END { print lineNr, line print fldNr, fld } ' file ```
Here's an answer that requires defining the column lengths in a single line file using the same delimiter as the data ( assuming different columns can have different acceptable lengths ): ``` 1^_1^_1 ``` Using that file (which I called `clengths`) and using `split()` in an lazy way to get indexed elements: ``` awk -F'\\^_' ' NR==FNR {split($0,clen,FS); next} # store the lengths { split($0,a,FS); # put the current line in an array for( i in a ) { if( length(a[i]) > clen[i] ) print "["FNR","i"] = "a[i] } } ' clengths data ``` This outputs array styled indexes for the long data as `[row, col]` aka `[line #, field #]` starting at `[1,1]`: ``` [2,1] = AA [2,2] = BB [2,3] = CC ``` Everything in the output is "too big" and is indexed to make finding it again easier.
58,786,375
I'm a beginner for programming still a student. I tried to create a .txt file in C to write data, save it and after to read what I have written. And I did, it running smoothly in integer format, but when I tried to use characters (sentences), when I use spaces in my input eg:- Hi, My Name is Dilan.... It's only print Hi I tried to using different variables in both input and output codes but still getting same result. **This Is Data Writing Code** ----------------------------- ``` #include <stdio.h> #include <stdlib.h> int main() { char txt[400]; FILE *fptr; fptr = fopen("D:\\program.txt","w"); if(fptr == NULL) { printf("Error!"); exit(1); } printf(" Start Typing : "); scanf("%s",&txt); fprintf(fptr,"%s",&txt); fclose(fptr); return 0; } ``` **This Is Data Reading Code** ----------------------------- ``` #include <stdio.h> #include <stdlib.h> int main() { char txt[400]; FILE *fptr; if ((fptr = fopen("D:\\program.txt","r")) == NULL){ printf("Error! opening file"); exit(1); } fscanf(fptr,"%s", &txt); printf("You Have Entered :- %s", txt);`enter code here` fclose(fptr); return 0; } ``` ***I need when I type "Hi, My Name is Dilan ...." instead of just "Hi" I need full sentence like "Hi, My Name is Dilan ...."***
2019/11/10
[ "https://Stackoverflow.com/questions/58786375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12349956/" ]
Try to use `fgets(txt, 400, stdin)` instead of `scanf("%s", &txt)`
What are you tiping in console or something else input stream is saved in a buffer("string") in operation system, your C program acces this buffer, so when you call scanf it read from that buffer, your problem is because you use %s data specificator, which read a string while the character readed is different of blank space(space, newline or tab), up to blank spaces. After "Hi," is a space so the read will stop. You can use a different functions, one for string pourpouses, like fgets which read up to a newline character ('/n') or up to end of stream, or something else, you can search the best choice for your problem on internet. One other solution is to use scanf repetitive to read all string, but you have to put the spaces between words in your output file. Very important what you should have in mind all time, the functions which read from stdin stream use this buffer of OS, after one read(one execution of function) when you call again the function it will continue where it stoped in last execution, same for other streams (a file is a stream too). In your example after you typed "Hi, my name is Xtx." In OS's buffer will be store all string. The first call o scanf will get only "Hi," the second call will get "my" and same the following calls. The problem is when you type something else in stream, like a new sentence, it will be store in buffer at end of it. So maybe your calls are still read from old string while remained unread characters in buffer from last sentence. This problem is solved with fflush(), which clean this buffer.
33,798,600
I have a mobile application which needs to display images which will be sent to it via REST API. How do I tranfser images ove the API? I am developing a ASP.net Web API using C#. I tried converting image to base64 then send it though API to the mobile device, but this seems to take a lot of time as I have to send large number of images to my mobile device in one run. I need to send image file along with some other data through the API to mobile device and a Phonegap android will then save it in local db for further use. Any help would be appreciated.
2015/11/19
[ "https://Stackoverflow.com/questions/33798600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1650891/" ]
If you want to sent the images alongside other data in one request using base64 is the best way. You could think of using gzip to compress the image data to reduce the size. An other way would be to send the images in a reduced size to your android client alonside with a URL to a fully sized image. This enables you to show you results quickly to the user and then load the large images in a background task from the server and replace the small ones in the database.
If you want to send image or a file through REST Api then it should be implement through Multipart request. Please refer [here](http://www.jayway.com/2011/09/15/multipart-form-data-file-uploading-made-simple-with-rest-assured/) how it make your work easy. You can also use [Retrofit](http://square.github.io/retrofit/) for creating multipart request.
118,973
I'm currently preparing to leave my company and writing extended documentation on the system for an eventual successor. An important note: I was the sole developer on the whole project for the last three years and did everything from planning, testing, distribution, etc. by myself. So nobody else has any idea what and how things work. I am/was also the only developer in the company. I also don't have to be careful about hinting I'm leaving, as I already technically left and am working on a dynamic contract until everything is resolved or a certain amount of time passed. Currently the main thing my supervisor wants is a documentation on how to keep the installer up to date with projects from other parties, no problems. I have been using Git for my work there for the last three years. How can I properly encourage whoever is working on the project to continue to use Git to document their changes? I'm not asking how to force them (I know I can't), but I want to illustrate the eventual consequences of not doing so, and hopefully that will at least give them a proper and realistic view of the advantages and disadvantages so that they may choose to use Git. Of course the documentation would include a chapter on how to use Git in conjunction with an easy-to-use client and leave out anything too advanced (branches, merging) and focus just on doing commits and pushes for the sake of the successor and as a fail-safe. But I don't really know how to motivate a non-developer. My supervisor is additionally the CEO of the company, so arguments to avoid huge future investments should also be fine. **Update (1 year later):** after my break from work I ended up at the same company. So the rules where definitely a big plus for me starting again. Especially since no one dared to change anything without a developer in the company.
2018/09/10
[ "https://workplace.stackexchange.com/questions/118973", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/76538/" ]
In a situation like yours, a good starting point is to present the current use of Git as the rule. Add simple instructions like * Where do I get the current code? **Check out the Git repository XYZ**. * How do I make modifications to the code? Use development environment ABC, modify code and **commit changes to Git repository XYZ** Include Git into the written rules and guidelines and present it as a natural and ingrained tool in the development process. Adding a list of advantages of Git and worst case scenarios if it isn't used may help to create the illusion that you simply cannot work on this project without using Git. That has the following effects: * An inexperienced developer or general IT person without knowledge about software development will take those rules as written and adhere to them (provided that they find and read the rules). * A new employee will probably take over the existing development process at first and introduce changes gradually if they see any problems with the process. * An experienced developer knows about the importance of version control and will either keep working with Git or replace it with another solution.
On some days you made changes, which look good first (they compile) but terrible later on. When you notice such mistakes, you can roll out the better-working old code in an instant, or invest work hours into finding and undoing your changes -> while others have to work with software which doesn't work as intended. Both cost money, while a commit is done within a second and costs nothing. Another advantage of an repository is that you can check it out easily on different computers. This argument is probably small, since other people in your company probably won't have a git client, as non-developers (I am using it for LaTeX in a non-developing sense too.) That's why I am using repositories even for my private stuff, not to mention that you need one when your successor isn't a single person. I guess even a non-developing supervisor knows the importance of change logs and a repository is a powerful change log.
5,333,871
I am doing a build on a 32bit SLES10 machine. Using GCC 3.4.2 Here is a sample error ``` `.L8245' referenced in section `.rodata' of CMakeFiles/myproj.dir/c++/util/MyObj.o: defined in discarded section `.gnu.linkonce.t._ZN5boost9re_detail9reg_grep2INS0_21grep_search_predicateIPKcSaIcEEES4_cNS_12regex_traitsIcEES5_S5_EEjT_T0_SA_RKNS_14reg_expressionIT1_T2_T3_EEjT4_' of CMakeFiles/myproj.dir/c++/util/MyObj.o ```
2011/03/17
[ "https://Stackoverflow.com/questions/5333871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64758/" ]
This is typically due to 2 different .cpp's being compiled with different compiler switches - but also using the same templates. The generated template instantiations may differ in what they define/reference, and if the instantiation that is selected doesn't define/refer to the exact same symbols as the ones that got discarded you may get this error. Validate that all your .cpp's are compiled with the exact same compiler switches and defines. If this isn't possible, reorder the .obj files on the linker commandline, in particular try to move the .obj files mentioned in the error message to the end or beginning of the .obj file list. EDIT: Also, if you're linking against prebuilt c++ libraries, see if you can duplicate the compiler switches used for building these libraries.
This may be due to using a newer version of binutils. binutils version 2.15 treated this as a non-fatal error, but later versions of binutils changed and so the link started failing. See <https://bugzilla.redhat.com/show_bug.cgi?id=191618> for a similar report. In my case, I was able to get things to link once more by explicitly using binutils 2.16.1, instead of binutils 2.17.
14,897,826
How can u get my webworks app to pop open the blackberry 10 share panel? Ex: open a website in the browser, click the overflow button and then click share Thank you!
2013/02/15
[ "https://Stackoverflow.com/questions/14897826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/997410/" ]
You'll want to look at the invokeTargetPicker API. Essentially, you create a request ``` var request = { action: 'bb.action.SHARE', // for a file uri: 'file://' + path, // for text you'd use 'data' data: 'I am awesome', target_type: ["APPLICATION", "VIEWER", "CARD"] }; ``` Then you call the API ``` blackberry.invoke.card.invokeTargetPicker(request, "Your Title", // success callback function() { console.log('success'); }, // error callback function(e) { console.log('error: ' + e); } ); ``` API Documentation is available here: <https://developer.blackberry.com/html5/apis/blackberry.invoke.card.html#.invokeTargetPicker> I wrote a sample app, which you can test out on our GitHub repo: <https://github.com/ctetreault/BB10-WebWorks-Samples/tree/master/ShareTargets>
This should be an option that appears on any link, image or Text: "Share". Is the item not present in the Cross Cut menu shown?
40,289,427
I want to create a linked list with classes. I have two classes, one LinkedList and another LinkedNode. My problem is that my function InsertAtEnd always delete the current node. So when I want to print my linked list, I can't see anything. I know thanks to debugger that in the function InsertAtEnd, we don't enter in the while loop, this is the problem. But after several attemps I can't resolve my problem. This is my code: ``` void LinkedList::InsertAtend(int data) { LinkedNode* node = new LinkedNode(); node->setData(data); node->setNext(nullptr); LinkedNode* tmp = _header; if (tmp != NULL) { while (tmp->getNext() != nullptr) { tmp = tmp->getNext(); } tmp->setData(data); tmp->setNext(nullptr); } else { _header = node; } } ``` My class LinkedNode: ``` class LinkedNode { public: LinkedNode(); ~LinkedNode(); void setData(int data); void setNext(LinkedNode* next); int getData() const; LinkedNode* getNext() const; private: int _data; LinkedNode* _next; }; ``` My class LinkedList: #pragma once #include #include "LinkedNode.h" using namespace std; ``` class LinkedList { public: LinkedList(); ~LinkedList(); void PrintList(); void InsertAtend(int data); void PrintList() const; private: LinkedNode* _header; }; ``` Thanks for your help !
2016/10/27
[ "https://Stackoverflow.com/questions/40289427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7037642/" ]
`tmp` is the last Node, so if you don't want to delete it you shouldn't write value `data` in it. You should link it with the new Node, which you named `node`. Instead of ``` tmp->setData(data); tmp->setNext(nullptr); ``` You should write ``` tmp->setNext(node) ```
At the end of the loop, the `tmp` is the last node in the current list. As you want to add the new `node` after the last node, you need to ``` tmp->setNext(node); ``` to append it (and not set the data as the data are already set to the new `node`). Also note that you actually do not need to iterate through the entire list at all, if you keep another member variable to the current end of the list (`_tail`). Then you can access it directly and simply append and update.
23,570,273
When you click on the initial link to go to my website and go on the web page with the accordion the accordion appears and hides at 1500 as requested. However when i click on the headings to bring the text up nothing appears. The heading just highlights. There are no errors and the console log states "ready to do some jquery" as i asked it to do. part of my view ``` <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="<?php echo base_url('/js/my_accordian.js'); ?>"></script> <div id="accordion"> <h2>Information</h2> <p>more information</p> <h2>Information 2</h2> <p>more information 2</p> <h2>Information 3</h2> <p>more information 3</p> </div> ``` js ``` $(document).ready(function () { console.log("ready to do some jquery"); $('h2').addClass('exampleClass'); $('p').hide(1500); $("h2").click(function () { $('.activeHeading').next().slideUp(400); $('activeHeading').removeClass('activeHeading'); $(this).addClass('activeHeading'); $(this).next().slideToggle(400); }); }); ``` css ``` body { font-family:"Arial"; font-size:0.8em; color:black; line-height:22px; } h2 { /*border-top:1px solid #999999; */ padding:5px; } .pageTitle { font-family:"Garamond"; color:#777777; font-weight:lighter; font-size:3em; } .activeHeading { color:#00AAFF; } .exampleClass { background-color:red; } .anotherExampleClass { background-color:blue; } ```
2014/05/09
[ "https://Stackoverflow.com/questions/23570273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3616649/" ]
You need to use [**`.change()`**](http://api.jquery.com/change/). ``` $('.section .container-items input').change( function(){ $(this).parent().removeClass('red').siblings().addClass('red'); }); ``` [**Example Here**](http://jsfiddle.net/UDZaN/)
`[**Fiddle Demo**](http://jsfiddle.net/cse_tushar/dJgKE/)` ``` var chck = $('.section .container-items input');//cache selector chck.change(function () { //change event chck.filter(':not(:checked)').parent().addClass('red'); //add red to class red to parent if not checked chck.filter(':checked').parent().removeClass('red'); //checked elements remove red class }).change(); //trigger change event ```
29,696,717
`undefined method 'each' for nil:NilClass` OK so, I know that there is hundreds questions that are talking about that. I know what this error message means, and I know how to deal with that. My question is : Is there a way to force the nil class to return an empty array? My second question : Would it be safe ? Thanks Sebastien
2015/04/17
[ "https://Stackoverflow.com/questions/29696717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4328084/" ]
1) Of course, you could patch *nil* (there is always only one *nil* object in Ruby thread, so you could patch it, and not NilClass): ``` def nil.each puts 'Hey' end nil.each #outputs 'hey' ``` 2) But you should **never** do things like that, because it could break a lot of things inside a lot of libraries and even in Ruby itself.
If you are using something like `@products`..try ternary operator ``` @products = @products.present? ? @products : [] ``` Yes it's safe if you handle it properly using empty and check the relevant values that you need before you proceed ahead or save them
49,522,326
I want to send a json with Ajax to the Spring MVC controller but I can not get anything, I do not know what I'm failing Javascript: ``` var search = { "pName" : "bhanu", "lName" :"prasad" } var enviar=JSON.stringify(search); $.ajax({ type: "POST", contentType : 'application/json; charset=utf-8', url: 'http://localhost:8080/HelloSpringMVC/j', data: enviar, // Note it is important success :function(result) { // do what ever you want with data } }); ``` Spring MVC: ``` @RequestMapping(value ="/j", method = RequestMethod.POST) public void posted(@RequestBody Search search) { System.out.println("Post"); System.out.println(search.toString()); } ```
2018/03/27
[ "https://Stackoverflow.com/questions/49522326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9387062/" ]
I think you made things complicated,in fact,if you have a ***Search*** object defined,you can past the data directly to the Controller method,and **SpringMVC** will form an instance of the search object for you,try as below: ``` var search = { pName : "bhanu", lName :"prasad" }; $.ajax({ type: "POST", url: 'j',//do not put the full url,you need use an absolute url data: search,//put search js object directly here success :function(result) { // do what ever you want with data } ``` Now you can get the search object as below: ``` @RequestMapping(value ="/j", method = RequestMethod.POST) public void posted(Search search) { System.out.println("Post"); System.out.println(search.toString()); } ```
``` var fullName = $("#fullName").val(); var location = $("#location").val(); var capacity = $("#capacity").val(); var guarantee = $("#guarantee").val(); var status = $("#status").val(); var data = { name : fullName, capacity : capacity, guarantee : guarantee, location : location, status : status } var uri = $("#contextpath").val()+"/rooms/persist?inputParam="+encodeURIComponent(data); data = JSON.stringify(data); $.ajax({ url : uri, type : 'POST', dataType : 'json', success: function(data){ var successflag = data.response.successflag; var errors = data.response.errors; var results = data.response.result; if(successflag == "true"){ $("#fullName").val(""); $("#location").val(""); $("#capacity").val(""); $("#guarantee").val(""); $("#status").val(""); }else{ } }, error: function (xhr, ajaxOptions, thrownError) { } }); public static org.json.simple.JSONObject getInputParams(String inputParams) { JSONParser parser = new JSONParser(); org.json.simple.JSONObject inputJSON = new org.json.simple.JSONObject(); try { inputJSON = (org.json.simple.JSONObject) parser.parse(inputParams); } catch (ParseException e) { e.printStackTrace(); } return inputJSON; } @RequestMapping(value = "/persist", method = RequestMethod.POST) public @ResponseBody String add(Model model, HttpServletRequest request) { try { JSONObject inputJSON = CommonWebUtil.getInputParams(request.getParameter("inputParam").toString()); if (inputJSON != null){ if(inputJSON.get(CommonConstants.NAME) != null && !inputJSON.get(CommonConstants.NAME).toString().isEmpty()){ } if(inputJSON.get(CommonConstants.CAPACITY) != null && !inputJSON.get(CommonConstants.CAPACITY).toString().isEmpty()){ } if(inputJSON.get(CommonConstants.GUARANTEE) != null && !inputJSON.get(CommonConstants.GUARANTEE).toString().isEmpty()){ } if(inputJSON.get(CommonConstants.LOCATION) != null && !inputJSON.get(CommonConstants.LOCATION).toString().isEmpty()){ } if(inputJSON.get(CommonConstants.STATUS) != null && !inputJSON.get(CommonConstants.STATUS).toString().isEmpty()){ } } }catch (Exception e) { } } ```
3,394,580
In shell scripting how to find factorial of a number?
2010/08/03
[ "https://Stackoverflow.com/questions/3394580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/409345/" ]
10! in bash: ``` f=1; for k in {1..10}; do f=$[$k * $f] ; done; echo $f ``` or here in a step by step fashion: ``` $ t=$(echo {1..10}) $ echo $t 1 2 3 4 5 6 7 8 9 10 $ t=${t// /*} $ echo $t 1*2*3*4*5*6*7*8*9*10 $ echo $[$t] 3628800 ```
You have to use loop, see this link: <http://ubuntuforums.org/showthread.php?t=1349272>
2,588,502
This is my pom file: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sia.g7</groupId> <artifactId>sia</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>sia</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>commons-math</groupId> <artifactId>commons-math</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>jmathplot</groupId> <artifactId>jmathplot</artifactId> <version>1.0</version> <scope>system</scope> <systemPath>${project.basedir}/lib/jmathplot.jar</systemPath> </dependency> <dependency> <groupId>jgraphx</groupId> <artifactId>jgraphx</artifactId> <version>1.0</version> <scope>system</scope> <systemPath>${project.basedir}/lib/jgraphx.jar</systemPath> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <appendAssemblyId>false</appendAssemblyId> <archive> <manifest> <mainClass>com.sia.g7.AbstractSimulation</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build> </project> ``` And when I run the jar I get: ``` Exception in thread "main" java.lang.NoClassDefFoundError: com/mxgraph/swing/mxGraphComponent ``` which is part of the `jgraphx` dependency. What am I missing?
2010/04/06
[ "https://Stackoverflow.com/questions/2588502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/119895/" ]
You should remove the `<scope>system</scope>` clauses from those dependencies. When the scope is set to system that means the artifact is ALWAYS available, so jar-with-dependencies does not include it.
Unpack your jar and add it to src/main/resources.
473,932
In a dark room there are two people and a very faint candle. Then the candle emits one photon. Is it true that only one person can see the photon? Why? And are there any experiments? Edit 2019/4/23: Thanks a lot. I was originally asking about quantum mechanical things. Because I believe such an experiment will turn the two people into Schrodinger's Cat. That's weird because it is not likely for a macroscope object get correlated so easily. Now thanks to the answers I realized that the efficiency and noise is as bad as in cases of other quantum mechanical processes.
2019/04/20
[ "https://physics.stackexchange.com/questions/473932", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/226304/" ]
Seeing = detecting photons that happen to interact with your retina. You can't see photons when they are just travelling nearby. Take lasers for example. When someone is using laser pointer, the only reason you see the beam is that photons collide with dust and air particles and therefore their direction is changed. For example into your eye. Otherwise you wouldn't see anything. It isn't possible for two people to see the same photon.
Two people cannot see the same photon. Only one person can see a specific photon. To see a photon, it must be absorbed by a molecule in the retina [1]. The photon then no longer exists, so it is not available to be seen by another person. [1] [Mammalia retinas can respond to single photons](http://webhome.phy.duke.edu/~hsg/264L/images/photons-on-retina.html)
127,325
I have recently noticed wmpnetwk.exe using a more than usual amount of processor cycles. I'm on Windows 7 Home Premium on a Netbook. I'm guessing it's a feature of Windows Media player that recently got turned on, possibly because of a Windows update or accidental key combination. I don't usually use Media player that often. Does anyone know if it is a feature that has recently turned on, and if so, how do I turn it off ? Someimtes, like this morning, my netbook seems to be taking longer to boot up, or freezing around the login screen.
2010/04/04
[ "https://superuser.com/questions/127325", "https://superuser.com", "https://superuser.com/users/7891/" ]
Solution ======== You can use the `taskkill` command. **Note**: The command is not available in Windows XP Home/Starter Edition. Examples -------- ``` taskkill /IM app.exe taskkill /IM app*.exe ``` Further reading --------------- * [Taskkill](http://technet.microsoft.com/en-us/library/bb491009.aspx)
With PowerShell, you can use `Stop-Process` supplying either an id or name
19,906,078
``` public class TestReturn { int i = 0; public static void main(String[] args) { TestReturn t = new TestReturn(); System.out.println(t.test()); System.out.println(t.i); } private int test() { return i++; } } ``` output ``` 0 1 ``` My question is, 1. Since return value of test() is 0, i,e un-incremented, so when i print i why it is incremented. What i know is, `return` is the exit point of method but from this method i found that there is something happening after returning from method. So how exactly return works?
2013/11/11
[ "https://Stackoverflow.com/questions/19906078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332075/" ]
It's not the return that's the problem here, it's your usage of the post-increment operator. What happens with "return i++;" is that the value of i is returned, then the value is incremented. That's why you get 0 and 1 as the values.
If u wanna return `1`, give `return ++i;` `return i++;` will first return `i`, then increment it; `i++` can be imagined as another function like (the syntax not applicable to java tough)- ``` preIncrementFunction(int &i){ int j = *i; *i = *i+1; return j; } ``` so, the value getting printed is the un-incremented value of `i` but the value of `i` has changed.
27,126,658
Which between of the practises is better, style wise? using the keyword "this" or choosing a different parameter name for the parameter of the constructor? case1: ``` public class Student { //variables private String name; //constructor public Student(String name) { this.name = name; } } ``` or case 2: ``` public class Student { //variables private String name; //constructor public Student(String aName) { name = aName; } } ```
2014/11/25
[ "https://Stackoverflow.com/questions/27126658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1205944/" ]
There is no "standard" way of doing this. And you'll find people are split between different "schools of thinking" in regards to readability of code. My advice would be to go with whichever is most used in your organization, or which you consider to be more readable. I, for one, prefer to use different names for the parameters and also use "this." for the fields, because: * using the same name can cause minor head aches if you ever forget to use "this." * using "this." to make it obvious that that is a member field and not a local variable, even outside a color-coded IDE. Again, this is a personal decision you should make :)
I prefer the first one. It can always be used without thinking of new names such as aName. Moreover, this is how, for instance, eclipse generates setters.
67,811,950
I'm trying to make a code for finding siRNAs. For now I've made a code that's just finding all possible siRNAs combinations. I also need to find the best ones, which must contain from 30% to 50% of the GC or CG nucleotides. This program is searching for the 21 nucleotides length sequences with content of CG or GC from 30 to 50%. For now, my program just generates in one string all of the possible siRNAs with length of 21, but I need to separate the ones with needed amount of GC or CG. Example of how my program works with K = 2, which means a length of the iRNA sequences from mRNA: 1. inputting the DNA: ATGC 2. It's converting to the mRNA by replacing T with U, so we get: AUGC 3. Making a complementary chain by the Chargaff's rule, A to U, U to A, g to C, C to G, and we get: UACG 4. Now we have a big iRNA, and now we splitting it in all possible ways for get a siRNAs, so: All iRNA combinations ['UA', 'AC', 'CG'] And at the end I want to chose from them the ones that's content C+G nucleotides in range of 30-50%. Well, there we have only CG with 100, but lets change K to 4, and lets use a ATGCCGTA for the input. ATCGCGTA All iRNA combinations ['UAGC', 'AGCG', 'GCGC', 'CGCA', 'GCAU'] So, here, the right ones are - UAGC and GCAU ``` import re def converttostr(input_seq, seperator): # Join all the strings in list final_str = seperator.join(input_seq) return final_str DNA_seq = input("") RNA_seq = DNA_seq.replace("T", "U") N = RNA_seq iRNA = (N.translate(str.maketrans({"A": "U", "G": "C", "U": "A", "C": "G"}))) iRNA_str = iRNA K = 21 iRNA_comb = [iRNA[i: j] for i in range(len(iRNA_str)) for j in range(i + 1, len(iRNA_str) + 1) if len(iRNA_str[i:j]) == K] print("All iRNA combinations", iRNA_comb) seperator = ', ' LtS = converttostr(iRNA_comb, seperator) print("List converted to string: ", LtS) CG = re.split(" CG |[^a-zA-Z ]+",LtS) print("siRNA with CG founded",CG) ```
2021/06/02
[ "https://Stackoverflow.com/questions/67811950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13772234/" ]
I tried to figure out what this code does, but I couldn't)) Have you written in another language before? Just specify the input data and the output you want to receive. Returns **true** if fits the condition (30%-50%). Then you can add it to the list or whatever. ``` def foo(seq: str) -> bool: """searching for the 21 nucleotides length sequences with content of CG or GC from 30 to 50% """ return 30 < (seq.count("GC") * 2) / len(h) * 100 < 50 ```
``` DNA_seq = input("") RNA_seq = DNA_seq.replace("T", "U") N = RNA_seq iRNA = (N.translate(str.maketrans({"A": "U", "G": "C", "U": "A", "C": "G"}))) iRNA_str = iRNA K = 4 iRNA_comb = [iRNA[i: j] for i in range(len(iRNA_str)) for j in range(i + 1, len(iRNA_str) + 1) if len(iRNA_str[i:j]) == K] print("All iRNA combinations", iRNA_comb) siRNAs = iRNA_comb for x in siRNAs: print('siRNA: ', x, ' percentage: ',((x.count("C") + x.count("G"))) / len(x) * 100, '%') output = [x for x in siRNAs if 30 <= ((x.count("C") + x.count("G"))) / len(x) * 100 <=50] print('output: ', output) ```
19,611,603
So, I've been trying to create a users' activity page for a practice project, that shows all their activity and their friends' activity on a page. I've got this working, but can't order it by date due to the query being nested. The problem is that I have to first get the user's friends', which is in one table then I have to get notifications which mention this user. What is the best way make the query so that it can be ordered by date. Thanks for any help! tables are set up vaguely like so: A Users id || Firstname || Lastname || username B Friends User\_id || Friend id C wallpost: Wallpost\_id || from\_user\_id || to\_user\_id || wallpost || DateTime Code as follows: ``` try { $DBH = new PDO("mysql:host=$host;dbname=$db_name", $username, $password); $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch(PDOexception $e) { echo $e->getMessage(); } try { $myid = $_SESSION['identification']; $result = $DBH->prepare("SELECT Friends.*, users.id, users.Firstname,users.Lastname FROM Friends JOIN users ON Friends.Friends=users.id WHERE Friends.id=:myid"); $result->execute(array(':myid' => $myid)); $result->setFetchMode(PDO::FETCH_ASSOC); $r = $result->fetchAll(); echo "<br><br><br>"; echo "<ul>"; try{ $stmt = $DBH->prepare("CREATE TEMPORARY TABLE usering(`user_id` int(10) , `First_Name` varchar(250), `Last_Name` varchar(250), `user_name` varchar(135), `password` varchar(135), `NaCl` varchar(135))"); $stmt->execute(); $stmy = $DBH->prepare("INSERT INTO usering(`user_id`, `First_Name`, `Last_Name`, `user_name`, `password`, `NaCl`) SELECT * from users"); $stmy->execute(); }catch(PDOexception $e) { echo $e->getMessage(); } try { foreach($r as $row){ $FriendId = $row['Friends']; $result2 = $DBH->prepare("SELECT wallpost.*, usering.*, users.* FROM wallpost JOIN usering ON wallpost.from_user_id=usering.user_id JOIN users ON wallpost.to_user_id=users.id WHERE :FriendId in (from_user_id, to_user_id) ORDER BY wallpost_id DESC "); $result2->execute(array(':FriendId' => $FriendId)); $result2->setFetchMode(PDO::FETCH_ASSOC); $r2 = $result2->fetchAll(); foreach($r2 as $row2){ $from_user_id = $row2['from_user_id']; $fromUsername = $row2['user_name']; $from_user_name = $row2['First_Name'] . " " . $row2['Last_Name']; $to_user_name = $row2['Firstname'] . " " . $row2['Lastname']; $toUsername = $row2['username']; $to_user_id = $row2['to_user_id']; $wallpost = $row2['wallpost']; /*"<div class='miniprofile_right'><img class='microphoto' src='../" . $from_username . "/profile.jpg'><div class='status_text'><a href='../" . $from_username . "/" . $from_user_id . "profile.php'>" . $from_user_firstname . " " . $from_user_lastname . "</a> => ". $firstname . " " . $lastname . ":</br>" . $walldate2 . "<br>" . $wallpost . " - at " . $walltime . "</div></div><br><br>"*/ if($from_user_id == $to_user_id){ echo "<div class='miniprofile_right'><img class='microphoto' src='../members/" . $fromUsername . "/profile.jpg'><div class='status_text'><a href='../members/" . $fromUsername . "/" . $from_user_id . "profile.php'>" . $from_user_name . "</a> posted a status: <br>" . $wallpost . "</div></div></br></br>"; } else { echo "<div class='miniprofile_right'><img class='microphoto' src='../members/" . $fromUsername . "/profile.jpg'><div class='status_text'><a href='../members/" . $fromUsername . "/" . $from_user_id . "profile.php'>" . $from_user_name . "</a> posted on " . "<a href='../members/" . $toUsername . "/" . $to_user_id . "profile.php'>" . $to_user_name . "'s" . "</a> wall: <br> " . $wallpost . "</div></div></br></br>"; } } } }catch(PDOexception $e) { echo $e->getMessage(); } echo "</ul>"; } catch(PDOexception $e) { echo $e->getMessage(); } ```
2013/10/26
[ "https://Stackoverflow.com/questions/19611603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2310431/" ]
[![enter image description here](https://i.stack.imgur.com/GLkW3.gif)](https://i.stack.imgur.com/GLkW3.gif) This method does not require subclassing anything. You just add a `UILongPressGestureRecognizer` to the view and set the `minimumPressDuration` to zero. Then you check the state when the gesture events are called to see if the touch event is beginning or ending. Here is the entire project code for the example image above. ``` import UIKit class ViewController: UIViewController { @IBOutlet weak var myView: UIView! override func viewDidLoad() { super.viewDidLoad() let tap = UILongPressGestureRecognizer(target: self, action: #selector(tapHandler)) tap.minimumPressDuration = 0 myView.addGestureRecognizer(tap) } @objc func tapHandler(gesture: UITapGestureRecognizer) { // there are seven possible events which must be handled if gesture.state == .began { myView.backgroundColor = UIColor.darkGray return } if gesture.state == .changed { print("very likely, just that the finger wiggled around while the user was holding down the button. generally, just ignore this") return } if gesture.state == .possible || gesture.state == .recognized { print("in almost all cases, simply ignore these two, unless you are creating very unusual custom subclasses") return } // the three remaining states are // .cancelled, .failed, and .ended // in all three cases, must return to the normal button look: myView.backgroundColor = UIColor.lightGray } } ``` Thanks to [this answer](https://stackoverflow.com/a/34131464/3681880) for the idea.
Thanks to [Holly's answer](https://stackoverflow.com/a/19612446/1121497) I built a `ButtonView` convenience class. Edit: As this [answer](https://stackoverflow.com/a/31829331/1121497) says, `UILongPressGestureRecognizer` reacts quite faster so I updated my class. Usage: ``` let btn = ButtonView() btn.onNormal = { btn.backgroundColor = .clearColor() } btn.onPressed = { btn.backgroundColor = .blueColor() } btn.onReleased = yourAction // Function to be called ``` Class: ``` /** View that can be pressed like a button */ import UIKit class ButtonView : UIView { /* Called when the view goes to normal state (set desired appearance) */ var onNormal = {} /* Called when the view goes to pressed state (set desired appearance) */ var onPressed = {} /* Called when the view is released (perform desired action) */ var onReleased = {} override init(frame: CGRect) { super.init(frame: frame) let recognizer = UILongPressGestureRecognizer(target: self, action: Selector("touched:")) recognizer.delegate = self recognizer.minimumPressDuration = 0.0 addGestureRecognizer(recognizer) userInteractionEnabled = true onNormal() } func touched(sender: UILongPressGestureRecognizer) { if sender.state == .Began { onPressed(self) } else if sender.state == .Ended { onNormal(self) onReleased() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } ```
42,261,577
After I have disabled any button by clicking on it, the button looks like it's disabled but accepts more clicks. I have noted that there is no `<form>` in the page, but adding a `<form>` does not seem to matter. <https://jsfiddle.net/3y1dn29v/> Why? ```js function tally(card, suit) { cards += card; suits += suit; alert("btn" + card + suit); disableButton("btn" + card + suit) } function disableButton(button) { document.getElementById(button).setAttribute("class", "button disabled"); var x = document.getElementById(button).getAttribute("class"); alert(x); } var suits = ""; var cards = ""; ``` ```css .button { color: white; font-size: 16px; border-radius: 25px; } .disabled { opacity: 0.6; cursor: not-allowed; } ``` ```html <div id="Spades" class="tabcontent"> <h3>&spades;</h3> <div class="btn-group"> <button id="btnAS" class="button" onclick='tally("A","S")'>A</button> <button id="btnKS" class="button" onclick='tally("K","S")'>K</button> <button id="btnQS" class="button" onclick='tally("Q","S")'>Q</button> <button id="btnJS" class="button" onclick='tally("J","S")'>J</button> </div> </div> ```
2017/02/15
[ "https://Stackoverflow.com/questions/42261577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293245/" ]
You need to set the disabled attribute to true ``` function disableButton(button) { document.getElementById(button).setAttribute("class", "button disabled"); var x = document.getElementById(button).getAttribute("class"); alert(x); document.getElementById(button).disabled = true; } ```
add `pointer-events: none;` to your `.disabled` CSS
15,830,411
I have a table with 105 columns and around 300 rows in Sheet 1. I need in Sheet 2 a reduced version of the same table, filtered by some column values (not the first column). I've looked at Pivot Tables but it seems that I can not get the same tabular structure. I have tried with Advanced Filter and I get an error: > > "The extract range has a missing or illegal field name". > > > Could you help?
2013/04/05
[ "https://Stackoverflow.com/questions/15830411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693172/" ]
Microsoft's PowerQuery addin supports this. One of its many sources can be Excel Data-From Table.
You can use the [add-in for table-valued functions](http://finaquant.com/products/excel-add-in-for-table-valued-functions) I developed to make any operations (including filtering, partitioning, aggregation, distribution etc.) on data tables in Excel. Each table (ListObject in Excel) is an input or output parameter for a table-valued function. You can for example feed three tables as input parameters to a table function which generates some resultant tables.
73,377,829
How do I solve this? Warning message: package ‘dplyr’ was built under R version 4.2.1
2022/08/16
[ "https://Stackoverflow.com/questions/73377829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19749572/" ]
This warning appears when you load a package that was built under a version of R different to the one you are running. You have several options: * Update R to the latest version * build/compile dplyr with your current version of A * ignore the warning If the difference between your R version and the R version where the package was compiled is small (e.g. a patch version change 4.2.0 vs 4.2.1) it is usually fine to ignore the warning. If you don't want to ignore the warning, updating R and installing/updating the packages again is a solution. Building the packages yourself is also possible, you would need some specific tools such as Rtools on Windows and some compiler in any system. This is a bit harder so it would not be my first solution to try if you are starting with R.
I think you are trying to install the dplyr package in R4.2.1 and facing this issue. So you can try this, In RStudio, Click on Tools -> install packages.. -> Under packages section type dplyr -> install.
34,760,765
I tried to load a large audio dataset and implement audio.spectrogram. I got this error: ``` $ Torch: not enough memory: you tried to allocate 0GB. Buy new RAM! at /home/XXXX/torch/pkg/torch/lib/TH/THGeneral.c:222 stack traceback: [C]: at 0xb732c560 [C]: in function '__add' /home/XXXX/torch/install/share/lua/5.1/audio/init.lua:107: in function 'spectrogram' large.lua:24: in main chunk [C]: in function 'dofile' [string "_RESULT={dofile "large.lua"}"]:1: in main chunk [C]: in function 'xpcall' /home/XXXX/torch/install/share/lua/5.1/trepl/init.lua:650: in function 'repl' ...XX/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:199: in main chunk [C]: at 0x0804d6d0 ``` Does torch7 have the memory limit ?
2016/01/13
[ "https://Stackoverflow.com/questions/34760765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5118777/" ]
**No**, Torch does not have a memory limit but it requires that certain conditions are met when allocating memory. If you take a look at [`THGeneral.c`](https://github.com/torch/torch7/blob/3864f3782a74715e35d98176f9014a74524a868a/lib/TH/THGeneral.c#L226-L273) (where the error comes from), you'll see that this error is raised when the allocation using `THAllocInternal` has failed. From your output I guess you are on a Unix system and I also guess that you are trying to allocate a lot of memory (but less than 1GB). In the case where you want to align more than 5120 bytes, `THAllocInternal` will call [`posix_memalign`](http://man7.org/linux/man-pages/man3/posix_memalign.3.html) for 64 byte aligned memory otherwise it will call standard [`malloc`](http://en.cppreference.com/w/c/memory/malloc). That is to say that the error you see comes from either of those functions which are provided by your operating system. You will have to check there. You could also try to recompile Torch with the flag `DISABLE_POSIX_MEMALIGN` to rule that out.
You may have created a CNN model using PyTorch which runs on CUDA automatically if your system has a GPU. **Restart** the system, the memory will be cleared automatically.
1,952,505
i needed help refactoring the following class, Following is a class Operation with variety of Operations in switch : i want to avoid the switch statement.I read few articles on using polymorphism and state pattern .but when i refactor the classes i dont get access to many variables,properties Im confused on whether to use operation as abstract class or to implement an interface. Just wanted to know which type of refactoring will help in this case polymorphism or state pattern? And when to use them? ``` public class Operation { public enum OperationType { add, update, delete, retrieve } public enum OperationStatus { Success, NotStarted, Error, Fail, InProcess, Free } // raise this event when operation completes public delegate void OperationNotifier(Operation operation); public event OperationNotifier OperationEvent=null; private OperationStatus _status=OperationStatus.Free; public OperationStatus Status { get { return _status; } set { _status = value; } } private string _fileName = null; public string FileName { get { return _fileName; } set { _fileName = value; } } private string _opnid = null; public string OperationId { get { return _opnid; } set { _opnid = value; } } private OperationType _type; public OperationType Type { get { return _type; } set { _type = value; } } public void performOperation(OperationType type, string parameters) { switch (type) { case OperationType.add: _status = addOperation(parameters); break; case OperationType.update: _status = updateOperation(parameters); break; case OperationType.delete: _status = deleteOperation(parameters); break; case OperationType.retrieve: _status = retrieveOperation(parameters); break; default: break; } if (OperationEvent != null) OperationEvent(this); // return true; } public OperationStatus addOperation(string parameters) { DateTime start = DateTime.Now; //Do SOMETHING BIG TimeSpan timeTaken = DateTime.Now - start; System.Diagnostics.Debug.WriteLine("addOperation:-" + _opnid + "-" + _fileName + "--" + timeTaken.Milliseconds); return OperationStatus.Success; } ...other operations here.... ``` Calling code is similar to : ``` Operation oprnObj; Operation.OperationType operationType; oprnObj = new Operation(); oprnObj.FileName = String.Concat("myxmlfile",".xml"); oprnObj.OperationId = oprnid; oprnObj.OperationEvent += new Operation.OperationNotifier(oprnObj_OperationEvent); operation="add"; //get From Outside function getOperation() operationType = (Operation.OperationType)Enum.Parse(typeof(Operation.OperationType), operation.ToLower(), true); oprnObj.Type = operationType; oprnObj.performOperation(operationType, parameters); ``` References Threads: [Link](https://stackoverflow.com/questions/126409/ways-to-eliminate-switch-in-code) [Link](https://stackoverflow.com/questions/942481/refactoring-advice-for-big-switches-in-c) ..many more.
2009/12/23
[ "https://Stackoverflow.com/questions/1952505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158297/" ]
In C# you can use functions for the strategy, and using an extension method as the function gives you the ability to add operations as and when required: ``` public enum OperationStatus { Success, NotStarted, Error, Fail, InProcess, Free } public class Operation { // raise this event when operation completes public delegate void OperationNotifier(Operation operation, OperationStatus status); public event OperationNotifier OperationEvent = null; public string FileName { get; set; } public string OperationId { get; set; } public Func<string, OperationStatus> Function { get; set; } public void PerformOperation(string parameters) { OperationStatus status = Function(parameters); if (OperationEvent != null) OperationEvent(this, status); } } static class AddOp { public static OperationStatus AddOperation(this Operation op, string parameters) { DateTime start = DateTime.Now; //Do SOMETHING BIG TimeSpan timeTaken = DateTime.Now - start; System.Diagnostics.Debug.WriteLine("addOperation:-" + op.OperationId + "-" + op.FileName + "--" + timeTaken.Milliseconds); return OperationStatus.Success; } } class Program { static void Main(string[] args) { Operation oprnObj = new Operation(); oprnObj.FileName = String.Concat("myxmlfile", ".xml"); oprnObj.OperationId = "oprnid"; oprnObj.OperationEvent += new Operation.OperationNotifier(oprnObj_OperationEvent); string parameters = "fish"; oprnObj.Function = oprnObj.AddOperation; oprnObj.PerformOperation(parameters); } public static void oprnObj_OperationEvent(Operation op, OperationStatus status) { Console.WriteLine("{0} returned {1}", op.Function.Method.Name, status); } } ``` You could also pass the `OperationEvent` to the function if you want intermediate status updates.
I'd like you to check if this switch case is likely to be spawn at multiple places. If it is just isolated to one place, you may choose to live with this. (The alternatives are more complex). However if you do need to make the change, Visit the following link - <http://refactoring.com/catalog/index.html> Search for "Replace Type Code", there are 3 possible refactorings that you could use. IMHO the Strategy one is the one that you need.
8,587,330
This is the overview of my problem: I am adding (and confirm they are added) about 1400 relationships loaded from a soap service into CoreDat. After I close the app and open it again some of the relationships are lost; I only see around 800 of them (although it varies). Also, I am not getting any errors. And now, more details: I have an object called `User` that has information about services a user have saved; it looks something like this: ```c @interface OosUser : NSManagedObject + (OosUser *) userFromSlug: (NSString *) slug; @property (nonatomic, retain) NSString *name; @property (nonatomic, retain) NSString *slug; @property (nonatomic, retain) NSMutableSet /* Service */ *services; - (void) addServicesObject: (Service * )service; - (void) removeServicesObject: (Service *) service; @end @implementation User @dynamic name; @dynamic slug; @dynamic services; static NSString *fetchPredicate = @"slug = %@"; + (User *) userFromSlug:(NSString *)slug { User *result = [super objectWithPredicate: fetchPredicate, slug]; if (!result) { result = [super create]; result.slug = slug; } return result; } @end ``` In the part of the code where the data is used, the relationships are saved like this: ```c NSMutableSet *userServices = self.user.services; for (Service *service in servicesToAdd) { [self.services addObject: service]; bool contained = false; for (Service *userService in userServices) { if ((contained = [userService.slug isEqualToString:service.slug])) { break; } } if (!contained) { // [userServices addObject:service]; [self.user addServicesObject: service]; NSError *error = nil; if (![[service managedObjectContext] save:&error]) { NSLog(@"Saving failed"); NSLog(@"Error: %@", [error localizedDescription]); }else { NSLog(@"Registered service %d: %@", self.services.count, service.slug); } } } ``` The case is that I have checked with the debugger and I can see that all the over 1400 relationships are added, but when the app is reset and they are restored though self.user.services I only get around 800 objects. Why could this be happening? Anybody had this before? Thanks in advance. --- **UPDATE:** People keep suggesting that I am not using Core Data correctly but the problem is that the data is lost AFTER restarting the app. There is absolutely no problem with it while using it. I am using Core Data as correct as it could be given the limited documentation and examples you get from Apple.
2011/12/21
[ "https://Stackoverflow.com/questions/8587330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/458365/" ]
``` NSMutableSet *userServices = self.user.services; ... [userServices addObject:service]; ``` Can't do that. `self.user.services` does not return a mutable set. That's what that `addServicesObject` method is for. Change the second line to: ``` [self.user addServicesObject:service]; ``` From Apple documentation: > > It is important to understand the difference between the values returned by the dot accessor and by `mutableSetValueForKey:`. `mutableSetValueForKey:` returns a mutable proxy object. If you mutate its contents, it will emit the appropriate key-value observing (KVO) change notifications for the relationship. The dot accessor simply returns a set. If you manipulate the set as shown in this code fragment: > > > `[aDepartment.employees addObject:newEmployee]; // do not do this! > then KVO change notifications are not emitted and the inverse relationship is not updated correctly.` > > > Recall that the dot simply invokes the accessor method, so for the same reasons: > > > `[[aDepartment employees] addObject:newEmployee]; // do not do this, either!` > > >
I had the same issue the relationship to another entity lost every time I restart the app. I searched for hours. In the end I found the issue. I declared my relationship as **`Transient`**, this caused the issue. ![enter image description here](https://i.stack.imgur.com/qZXiC.png)
19,357,667
I have something like this: ``` public function options() { $out = ''; $docs = $this->getAll();; foreach($docs as $key => $doc) { $out .= ',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}'; } return $out; } ``` It gives me a list of options from the DB, but it also gives me a null value at the top. if I write it like this: ``` public function options() { //$out = ''; $docs = $this->getAll();; foreach($docs as $key => $doc) { $out = ''; $out .= '{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}'; } return $out; } ``` It doesn't give me the null value but it only returns one value. ``` $out .= ',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}'; ``` In this line if I don't add an `,` it gives me an error message, This because I have `$out = '';` at the top. Now can you guys give me an idea how can I get all the values from the DB without the empty value at the beginning. I also have another question , why we use `;;` (double semicolon) in this code: ``` $docs = $this->getAll();; ```
2013/10/14
[ "https://Stackoverflow.com/questions/19357667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2463411/" ]
test $out to see if it has any length, if so add the comma and the line, otherwise just set it to be the line: ``` $out=""; foreach($docs as $key=>$doc){ if(strlen($out)){ $out.=',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}'; }else{ $out='{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}'; } } ``` as to your other question, er, you wrote the code, so why did you put a double semi-colon?
I'd suggest using an [array](http://php.net/manual/en/language.types.array.php) instead to hold the individual values, and using [join](http://uk1.php.net/manual/en/function.join.php) to concatenate them together. ``` public function options() { $docs = $this->getAll(); // Create an empty array $items = array(); foreach($docs as $key => $doc) { // "Push" an item to the end of the array $items[] = '{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}'; } // Join the contents together $out = join(",", $items); return $out; } ``` Also, the double semi-colon is completely unnecessary.
16,383
***Background:*** I & the wife are looking to buy a house priced at $250k via an FHA loan. One of the requirements for the loan is that we have a 2 year continuous employment. I have a 1 year gap in income(i.e. I **was employed but not paid** because I wasn't working on any project) Anyways, after that 1 year gap, as of today i have been employed and earning for 1 year and 7 months. So I am short of the 2 year employment requirement by 5 months. We have good credit scores (715 - 750) ***Question:*** Due to this we have been declined a pre-approval by one bank and asked to come back in 5 months time. Another major bank has pre-approved us(based on all the info i gave them on the phone), but I fear that once we start closing, they will start reviewing all the info i gave and decline the loan at a late stage of closing. I don't want to wait 5 months and risk somebody else picking up the house in that time. Nor can i put down 25% as down payment on a conventional(non FHA) loan. What kind of creative financing strategy can be done here? ***UPDATE***:2 of the major banks that pre-approved me explained that my history is fine and since i have been employed in the same line of work before the gap, it is not an issue. Also since I was employed and earning for more than 2 years before the gap, that bolsters my case. I will just need to explain my case in writing. But my file is strong. But if any body has any better and creative financing strategies, please do share.
2012/08/09
[ "https://money.stackexchange.com/questions/16383", "https://money.stackexchange.com", "https://money.stackexchange.com/users/3282/" ]
Do you need to put down 25% on a conventional loan? Conventional loans can be done with 5%, 10%, or 20% down (if you're willing to pay PMI for the <20% down scenario). If you don't like FHA's terms, don't do an FHA loan..
These are your options: * Wait until you have two years of continuous employment. * Get a family member to gift you enough of a down payment to exceed 20%. You need $50,000 to reach the 20% level. Due to gift tax rules that will mean that the money will have to come from multiple people, or the donor will have to file a gift tax return with the IRS. * Get additional jobs to get enough money for a bigger down payment. * Try additional lenders: banks, mortgage brokers, credit unions. The best bets are institutions you have a history with. Unfortunately this will not be a quick process. You should note that until a potential lender goes through a detailed review of your finances you have only been pre-qualified. This is not as good as pre-approved. With pre-qualified they are basing the determination on what you told them, not what you can prove. Because you are aware of your short period of continuous employment you are best to be completely honest with a potential lender. That way you don't run into problems 30 days down the road when they realize the issue. The home seller will not be happy; and there was time and money wasted on down payments, credit checks, home inspections, and appraisals. In the US in most markets while there is a significant risk that a particular house will not be available in 5 months, there is a very slight risk that a neighborhood will not be available in 5 months.
25,833,956
Should not be needed create an instance of a class to access a public constant. I recently started working in Swift, so I must be missing something here. In this simple example: ``` public class MyConstants{ public let constX=1; } public class Consumer{ func foo(){ var x = MyConstants.constX;// Compiler error: MyConstants don't have constX } } ``` This foo code gives an compile error. To work, I need to create an instance of the MyConstants like this: ``` public class Consumer{ func foo(){ var dummy = MyConstants(); var x = dummy.constX; } } ``` Adding static to constX is not allowed.
2014/09/14
[ "https://Stackoverflow.com/questions/25833956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2700303/" ]
Use `struct` with `static` types.`struct`are more appropriate as in `enum` you can only bind one type of associative values but you can contain the "Type Property of any type" in both. ``` public struct MyConstants{ static let constX=1; } public class Consumer{ func foo(){ var x = MyConstants.constX; } } ```
If you want a constant, you can also "fake" the as-yet-unsupported class variable with a class computed property, which does currently work: ``` public class MyConstants{ public class var constX: Int { return 1 }; } public class Consumer{ func foo(){ var x = MyConstants.constX; // Now works fine. } } ```
42,132,789
``` [ { "Book ID": "1", "Book Name": "UNIX **<script type='text/javascript'>alert('test')</script>**", "Category": "Computers", "Price": "113" }, { "Book ID": "2", "Book Name": "Book two", "Category": "Programming", "Price": "562" } ] ``` This is the JSON I am sending via API I am sharing with multiple people. When I parse the JSON using JavaScript, `<script>` tag is not executed. What are the modification should I make in the JS injected into JSON so that `<script>` tag will be executed without doing any extra work at client side JS. Is it possible?
2017/02/09
[ "https://Stackoverflow.com/questions/42132789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2118565/" ]
The point of an `std::map` is to provide an efficient **key to value** mapping. What you need is an additional **value to key** mapping - that can be achieved in multiple ways: * Have with an extra `std::map` that goes from `Position` to `std::vector<ID>`. * Use some sort of *spatial partitioning* data structure *(e.g. quadtree, spatial hash, grid)* that makes it efficient to find entities depending on their position. * Use a **bidirectional multi-map** like [`boost::bimap`](http://www.boost.org/doc/libs/1_63_0/libs/bimap/doc/html/boost_bimap/the_tutorial/controlling_collection_types.html). This will allow you to have a bidirectional mapping over collection of values without having to use multiple data structures. > > "How do I choose?" > > > It depends on your priorities. If you want maximum performance, you should try all the approaches *(maybe using some sort of templatized wrapper)* and profile. If you want elegance/cleanliness, `boost::bimap` seems to be the most appropriate solution.
You need to provide a reverse mapping. There are a number of ways to do this, including `multimap`, but a simple approach if your mapping isn't modified after creation is to iterate over the map and build up the reverse mapping. In the reverse mapping, you map value -> list of keys. The code below uses `std::unordered_map` to map `std::pair<int, int>` (the value in the original map) to `std::vector<int>` (list of keys in the original map). The building of the reverse map is simple and concise: ``` std::unordered_map<Point, std::vector<int>, hash> r; for (const auto& item : m) { r[item.second].push_back(item.first); } ``` (See the full example for the definition of `hash`). There's no need to worry about whether the key exists; it will be created (and the vector of ids will be initialised as an empty vector) when you attempt to access that key using the `r[key]` notation. This solution targets simplicity; it's a workable solution if you need to do this and don't care about performance, memory usage or using third-party libraries like Boost. If you do care about any of those things, or you're modifying the map while doing lookups in both directions, you should probably explore other options. --- [Live example](http://coliru.stacked-crooked.com/a/6ff19e0ed0049e8b) ``` #include <iostream> #include <map> #include <unordered_map> #include <vector> // Define a point type. Use pair<int, int> for simplicity. using Point = std::pair<int, int>; // Define a hash function for our point type: struct hash { std::size_t operator()(const Point& p) const { std::size_t h1 = std::hash<int>{}(p.first); std::size_t h2 = std::hash<int>{}(p.second); return h1 ^ (h2 << 1); } }; int main() { // The original forward mapping: std::map<int, Point> m = { {1, {2, 3}}, {5, {6, 2}}, {12, {2, 3}}, {54, {4, 4}}, {92, {6, 2}} }; // Build reverse mapping: std::unordered_map<Point, std::vector<int>, hash> r; for (const auto& item : m) { r[item.second].push_back(item.first); } // DEMO: Show all indices for {6, 2}: Point val1 = {6, 2}; for (const auto& id : r[val1]) { std::cout << id << " "; } std::cout << "\n"; // DEMO: Show all indices for {2, 3}: Point val2 = {2, 3}; for (const auto& id : r[val2]) { std::cout << id << " "; } std::cout << "\n"; } ```