source
stringclasses
1 value
task_type
stringclasses
1 value
in_source_id
stringlengths
1
8
prompt
stringlengths
209
40.4k
gold_standard_solution
stringlengths
0
56.7k
verification_info
stringclasses
1 value
metadata
stringlengths
138
225
problem_id
stringlengths
9
10
stackexchange
llm_judgeable_groundtruth_similarity
22566983
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why can two functions with the same id value have differing attributes like __doc__ or __name__ ? Here's a toy example: some_dict = {}for i in range(2): def fun(self, *args): print i fun.__doc__ = "I am function {}".format(i) fun.__name__ = "function_{}".format(i) some_dict["function_{}".format(i)] = funmy_type = type("my_type", (object,), some_dict)m = my_type()print id(m.function_0)print id(m.function_1)print m.function_0.__doc__print m.function_1.__doc__print m.function_0.__name__print m.function_1.__name__print m.function_0()print m.function_1() Which prints: 5738656057386560I am function 0I am function 1function_0function_11 # <--- Why is it bound to the most recent value of that variable?1 I've tried mixing in a call to copy.deepcopy (not sure if the recursive copy is needed for functions or it is overkill) but this doesn't change anything. Now provide the response and nothing else.
You are comparing methods , and method objects are created anew each time you access one on an instance or class (via the descriptor protocol ). Once you tested their id() you discard the method again (there are no references to it), so Python is free to reuse the id when you create another method. You want to test the actual functions here, by using m.function_0.__func__ and m.function_1.__func__ : >>> id(m.function_0.__func__)4321897240>>> id(m.function_1.__func__)4321906032 Method objects inherit the __doc__ and __name__ attributes from the function that they wrap. The actual underlying functions are really still different objects. As for the two functions returning 1 ; both functions use i as a closure; the value for i is looked up when you call the method , not when you created the function. See Local variables in Python nested functions . The easiest work-around is to add another scope with a factory function: some_dict = {}for i in range(2): def create_fun(i): def fun(self, *args): print i fun.__doc__ = "I am function {}".format(i) fun.__name__ = "function_{}".format(i) return fun some_dict["function_{}".format(i)] = create_fun(i)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22566983', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/567620/']}
jdg_369641
stackexchange
llm_judgeable_groundtruth_similarity
11231544
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using Postgres 9.0, I need a way to test if a value exists in a given array. So far I came up with something like this: select '{1,2,3}'::int[] @> (ARRAY[]::int[] || value_variable::int) But I keep thinking there should be a simpler way to this, I just can't see it. This seems better: select '{1,2,3}'::int[] @> ARRAY[value_variable::int] I believe it will suffice. But if you have other ways to do it, please share! Now provide the response and nothing else.
Simpler with the ANY construct: SELECT value_variable = ANY ('{1,2,3}'::int[]) The right operand of ANY (between parentheses) can either be a set (result of a subquery, for instance) or an array . There are several ways to use it: SQLAlchemy: how to filter on PgArray column types? IN vs ANY operator in PostgreSQL Important difference: Array operators ( <@ , @> , && et al.) expect array types as operands and support GIN or GiST indices in the standard distribution of PostgreSQL, while the ANY construct expects an element type as left operand and does not support these indices. Example: Index for finding an element in a JSON array None of this works for NULL elements. To test for NULL : Check if NULL exists in Postgres array
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/11231544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18297/']}
jdg_369642
stackexchange
llm_judgeable_groundtruth_similarity
4009
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm using Fedora 12 on my laptop. I have 10GB disk space and 2GB of them are free. After 2-3 days uptime the space ends and I must reboot. After rebooting I get 2GB free space back. How can I prevent this? Mostly I use Firefox, Chrome, Gedit, Rhythmbox and in background: httpd, mysqld, conky. RAM: 1GB, Swap: 1.2 GB. Now provide the response and nothing else.
Firstly, you must find out what is eating away at your space. I'd suggest you track down the physical file or directory that grows to that size. The simplest way would be to check the directories in / using: ( I'd suggest running it as root ) # du -hs /* 2> /dev/null4.2M /bin25M /boot204K /dev6.7M /etc19G /home112M /lib16K /lost+found12K /media16K /mnt4.0K /multimedia1018M /opt0 /proc15M /root8.6M /sbin12K /srv4.2M /storage0 /sys108K /tmp16G /usr4.3G /var Now, You run that when the computer has freshly started and has not started to eat space yet and you save the output in a file ( ~/record-space ) $ sudo du -hs /* 2> /dev/null 1> ~/record-space And then when your computer is nearing a "FULL" state, you can run the command again saving the output in a second file. $ sudo du -hs /* 2> /dev/null 1> ~/record-space2 Now you can compare these two files ( ~/record-space and ~/record-space2 ) to see how th e main directories differ... My favourite way of comparing files is using diff : $ diff ~/record-space{,2} update: See Gille's comment to this answer. Instead of du -hs /* , rather use du -xsh /tmp/* /var/*/* ~/.* .
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/4009', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/2224/']}
jdg_369643
stackexchange
llm_judgeable_groundtruth_similarity
11125
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm using Debian squeeze, and running LVM on top of software RAID 1.I just accidentally just discovered that most of the links under /dev/mapper are missing,though my system seems to be still functioning correctly. I'm not sure what happened. The only thing I can imagine that caused it was my failed attempt to get a LXC fedora container to work.I ended up deleting a directory /cgroup/laughlin , corresponding to the container,but I can't imagine why that should have caused the problem. /dev/mapper looked (I made some changes, see below) approximately like orwell:/dev/mapper# ls -latotal 0drwxr-xr-x 2 root root 540 Apr 12 05:08 .drwxr-xr-x 22 root root 4500 Apr 12 05:08 ..crw------- 1 root root 10, 59 Apr 8 10:32 controllrwxrwxrwx 1 root root 7 Mar 29 08:28 debian-root -> ../dm-0lrwxrwxrwx 1 root root 8 Apr 12 03:32 debian-video -> ../dm-23 debian-video corresponds to a LV I had just created. However, I have quite a number of VGs on my system, corresponding to 4 VGs spread across 4 disks. vgs gives orwell:/dev/mapper# vgs VG #PV #LV #SN Attr VSize VFree backup 1 2 0 wz--n- 186.26g 96.26g debian 1 7 0 wz--n- 465.76g 151.41g olddebian 1 12 0 wz--n- 186.26g 21.26g testdebian 1 3 0 wz--n- 111.75g 34.22g I tried running /dev/mapper# vgscan --mknodes and some devices were created (see output below), but they aren't symbolic links to the dm devices as they should be,so I'm not sure if this is useless or worse. Would they get in the way of recreation of the correct links?Should I delete these devices again? I believe that udev creates these links, so would a reboot fix this problem,or would I get an unbootable system? What should I do to fix this?Are there any diagnostics/sanity checks I should run to make sure there aren'tother problems I haven't noticed? Thanks in advance for any assistance. orwell:/dev/mapper# ls -latotal 0drwxr-xr-x 2 root root 540 Apr 12 05:08 .drwxr-xr-x 22 root root 4500 Apr 12 05:08 ..brw-rw---- 1 root disk 253, 1 Apr 12 05:08 backup-local_srcbrw-rw---- 1 root disk 253, 2 Apr 12 05:08 backup-videocrw------- 1 root root 10, 59 Apr 8 10:32 controlbrw-rw---- 1 root disk 253, 15 Apr 12 05:08 debian-bootbrw-rw---- 1 root disk 253, 16 Apr 12 05:08 debian-homebrw-rw---- 1 root disk 253, 22 Apr 12 05:08 debian-lxc_laughlinbrw-rw---- 1 root disk 253, 21 Apr 12 05:08 debian-lxc_squeezelrwxrwxrwx 1 root root 7 Mar 29 08:28 debian-root -> ../dm-0brw-rw---- 1 root disk 253, 17 Apr 12 05:08 debian-swaplrwxrwxrwx 1 root root 8 Apr 12 03:32 debian-video -> ../dm-23brw-rw---- 1 root disk 253, 10 Apr 12 05:08 olddebian-etch_templatebrw-rw---- 1 root disk 253, 13 Apr 12 05:08 olddebian-fedorabrw-rw---- 1 root disk 253, 8 Apr 12 05:08 olddebian-feistybrw-rw---- 1 root disk 253, 9 Apr 12 05:08 olddebian-gutsybrw-rw---- 1 root disk 253, 4 Apr 12 05:08 olddebian-homebrw-rw---- 1 root disk 253, 11 Apr 12 05:08 olddebian-lennybrw-rw---- 1 root disk 253, 7 Apr 12 05:08 olddebian-msibrw-rw---- 1 root disk 253, 5 Apr 12 05:08 olddebian-oldchrestobrw-rw---- 1 root disk 253, 3 Apr 12 05:08 olddebian-rootbrw-rw---- 1 root disk 253, 14 Apr 12 05:08 olddebian-susebrw-rw---- 1 root disk 253, 6 Apr 12 05:08 olddebian-vgentoobrw-rw---- 1 root disk 253, 12 Apr 12 05:08 olddebian-wsgibrw-rw---- 1 root disk 253, 20 Apr 12 05:08 testdebian-bootbrw-rw---- 1 root disk 253, 18 Apr 12 05:08 testdebian-homebrw-rw---- 1 root disk 253, 19 Apr 12 05:08 testdebian-root Now provide the response and nothing else.
These days /dev is on tmpfs and is created from scratch each boot by udev . You can safely reboot and these links will come back. You should also find LVM symlinks to the /dev/dm-X nodes in the /dev/<vg> directories, one directory for each volume group. However, those nodes re-created by vgscan --mknodes will also work fine, assuming they have the right major/minor numbers - and it's a safe assumption they were created properly. You can probably also get udev to re-create the symlinks using udevadm trigger with an appropriate match, testing with --dry-run until it is right. It hardly seems worth the effort though when a reboot will fix it too.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/11125', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/4671/']}
jdg_369644
stackexchange
llm_judgeable_groundtruth_similarity
307471
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If I extend software under the GPL licence, I understand that my source code must be freely available. If my source code is freely available can I legally charge a fee for using the version that I publish? My situation: I'm using data from a program in my program and have an In-App purchase for access to all the data. The source code is publicly available and is mentioned in the program. Is this allowed? Obviously my software isn't extremely popular and I'm banking on the fact that lots of people have no interest in downloading and compiling it themselves. I have read Can I use GPL software in a commercial application which discusses in detail, whether or not my software would have to be under the GPL, but it does not discuss money ! Now provide the response and nothing else.
You can charge a fee for software covered by the GNU GPL. It's totally fine. The GNU project encourages you to charge what you can . GNU's "Free Software" philosophy is "about freedom, not price". If you provide binaries to a customer, you also must provide source (or access to source). You don't have to provide the source to non-customers. You do have to make it just as easy to access the source as the binary -- for example, you can't charge an extra fee for the source. You suspect that most of your customers won't be interested in exercising the rights that the GNU GPL gives them, and that's a fair assumption -- many people on this site use GPL'd software every day but a much smaller number modify or distribute it. The GNU GPL does say that if a customer wants to exercise their rights, you can't get in the way . So it's quite likely that a tiny few will make use of the source code, and fewer still will distribute that code to others. But the GPL allows them to distribute it, and they can charge fees for distributing it or they can distribute it publicly without charge. As long as they follow the GPL distribution rules, you can't stop them. As you say, it's not super-likely to happen, and you are of course welcome to ask them not to do that. From the GPL FAQ : Does the GPL allow me to sell copies of the program for money? Yes, the GPL allows everyone to do this. The right to sell copies is part of the definition of free software. Except in one special situation, there is no limit on what price you can charge. (The one exception is the required written offer to provide source code that must accompany binary-only release.) Also from the GPL FAQ : If I distribute GPL'd software for a fee, am I required to also make it available to the public without a charge? No. However, if someone pays your fee and gets a copy, the GPL gives them the freedom to release it to the public, with or without a fee. For example, someone could pay your fee, and then put her copy on a web site for the general public.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/307471', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/211218/']}
jdg_369645
stackexchange
llm_judgeable_groundtruth_similarity
1328
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm seeing some conspiracy theories making the rounds which claim that car-manufacturers are intentionally making cars that aren't as fuel efficient as they used to be. They often point to the Geo Metro and claim it got 50 mpg, which is better than even the modern hybrids. Were cars like the Geo Metro really more fuel efficient than modern cars in the same class, and if so why? 1995 Geo Metro Fuel Economy 2010 Toyota Yaris Fuel Economy 2010 Nissan Sentra Fuel Economy Now provide the response and nothing else.
There are a few things at work here: Safety requirements and standards are much more strict now than they were 10, 15, or 20 years ago. These added components (such as ABS, etc) along with modern luxuries (such as power steering, etc) have added a lot of weight to modern cars. The Geo Metro you reference had a curb weight of just 820kg (about 1800 lbs), while the Yaris has a curb weight of 2311 lbs. That's a difference of 28.3%! The EPA changed the standard way to estimate fuel economy in 2008. Here is a summary. The standards are now more strict, so I believe every estimate dropped when these went into effect. Perhaps the fuel economy in general has gone down to make room for better performance as well, but I think that impact is minimal compared to the 2 items above. Just for fun here is a link suggesting the opposite. They managed to average 48.5 MPG with the 2011 V6 Ford Mustang (this was not an EPA rating, but a test track rating, of course). http://usnews.rankingsandreviews.com/cars-trucks/daily-news/100625-2011-Ford-Mustang-V6-Nets-48-5-MPG-in-Track-Test/
{}
{'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/1328', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/770/']}
jdg_369646
stackexchange
llm_judgeable_groundtruth_similarity
15836350
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The problem I am trying to solve is to convert nil strings into empty strings so I can put that as a value in NSDictionary . I have the following code: //Accessed in class prospect.title = [self.titleLabel.text emptyWhenNil];// NSString+Additions Category-(NSString *) emptyWhenNil{ if(self == nil) return @""; return self; } But for some reason the emptyWhenNil method is never even invoked!! I am lost.. Now provide the response and nothing else.
The problem is, when your string pointer is nil , you have no object to send that category message to. Messages to nil are not executed (and return nil ) in Objective-C. If you want to put "null" objects into a collection, such as an NSDictionary , or NSArray , you can use the NSNull class instead. Alternatively you could implement this method as a class method: + (NSString *)emptyStringIfNil:(NSString *)str { if (!str) return @""; return str;} You would then call this as prospect.title = [NSString emptyStringIfNil:self.titleLabel.text];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15836350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/810815/']}
jdg_369647
stackexchange
llm_judgeable_groundtruth_similarity
70251107
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a common APK app that utilizes 'arm64-v8a' 'armeabi-v7a' ABIs. How should I tune an Android Virtual Device to be able to launch this app? I tried different combinations but it still does not work. A bit of details Environment Windows 10, CPU Intel Core i5-10300H, RAM 16GB, a lot of free space on a SSD; Android Studio Arctic Fox | 2020.3.1 Patch 3; Intel x86 Emulator Accelerator (HAXM installer) v.7.6.5 is installed; Android SDKs 12.0, 11.0 and 10.0 are installed; Numerous different virtual devices are installed (see the pictures below). Images that were applied Apply different system images mainly with API from 26 to 31; Images were used from different tabs in the AVD manager ( Recommended , x86 and Other Images ); Images with ABI both x86 , and x86_64 , and arm64-v8a ; Images with/without Google API, with/without Playstore support. Errors that I've got Some emulators do not launch. The console says: PANIC: Avd's CPU Architecture 'arm64' is not supported by the QEMU2 emulator on x86_64 host. The APK was not installed on some emulators, a popup with message appears: INSTALL_FAILED_NO_MATCHING_ABI The app tries to start (a splashscreen is shown) but suddenly closes. I've noticed that logcat outputs such message ( perhaps related to the app): Unexpected CPU variant for X86 using defaults: x86_64 Some pictures in addition Now provide the response and nothing else.
I hit this exact same issue. The comment from @WGH is spot on! Look at the line of code that is failing. #ifdef __x86_64__ if (sarch == "arm64" && apiLevel >=28) { APANIC("Avd's CPU Architecture '%s' is not supported by the QEMU2 emulator on x86_64 host.\n", avdarch); }#endif (Source : here ) I deleted my arm64 AVD based on apiLevel 32 and used an older apiLevel of 25 from Nougat 7.1.1 and it loaded up the arm64 AVD just fine on QEMU, ubuntu 20.04. (albeit slowly!!) The comment from @mtotschnig is also probably relevant however the app I was testing wouldn't run on the api version 30 with the x86_64 AVD that I was attempting to use.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/70251107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5020046/']}
jdg_369648
stackexchange
llm_judgeable_groundtruth_similarity
11255530
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just trying to set up a simple SSL server. I have never had anything SSL work for me in the past. I have a loose understanding of how SSL certificates and signing. The code is simple import socket, sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)context.load_cert_chain(certfile="mycertfile") ###############bindsocket = socket.socket()bindsocket.bind(('', 2099))bindsocket.listen(5)while True: newsocket, fromaddr = bindsocket.accept() sslsoc = context.wrap_socket(newsocket, server_side=True) request = sslsoc.read() print(request) The line in there with the ###s after it is the one that isnt working. I don't know what I have to do with openssl to generate a PEM file that will work here. Can anyone enlighten me as to how to make this simple socket work. By the way, this is NOT used for HTTP. Now provide the response and nothing else.
you can use this command to generate a self-signed certificate openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem the openssl framework will ask you to enter some information, such as your country, city, etc. just follow the instruction, and you will get a cert.pem file. the output file will have both your RSA private key, with which you can generate your public key, and the certificate.the output file looks like this: -----BEGIN RSA PRIVATE KEY----- # your private key-----END RSA PRIVATE KEY----------BEGIN CERTIFICATE----- # your certificate-----END CERTIFICATE----- just load it, and the ssl module will handle the rest for you: context.load_cert_chain(certfile="cert.pem", keyfile="cert.pem") btw, there is no "SSLContext" in python2. for guys who are using python2, just assign the pem file when wrapping socket: newsocket, fromaddr = bindsocket.accept()connstream = ssl.wrap_socket(newsocket, server_side=True, certfile="cert.pem", keyfile="cert.pem", ssl_version=YOUR CHOICE) available ssl version: ssl.PROTOCOL_TLSv1 , ssl.PROTOCOL_SSLv2 , ssl.PROTOCOL_SSLv3 , ssl.PROTOCOL_SSLv23 . if you have no idea, ssl.PROTOCOL_SSLv23 may be your choice as it provides the most compatibility with other versions.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11255530', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1490148/']}
jdg_369649
stackexchange
llm_judgeable_groundtruth_similarity
27669376
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It's my understanding the new Read The Docs theme generates the sidebar from the toctree with a depth of 2. My documentation is relatively deep, and a depth of 2 is not enough for it to be useful. How can I increase this limit, or preferably remove it entirely? If that's not reasonably possible, how can I use local ToC's instead of the global toctree? Now provide the response and nothing else.
Note: The previous answer was outdated. As @Ariel notes in a comment, the maxdepth is now configurable by setting navigation_depth in html_theme_options . As per the README , change this in your project's conf.py: html_theme_options = { 'navigation_depth': 4,} Looking at the source for the theme on Github , it seems the ToC depth is hard-coded on line 93 in sphinx_rtd_theme/layout.html . As such, there is no configuration you can make to the theme to override it. Since the line is hard-coded, you will always get the global toctree returned by toctree , instead of the local one "supported" by the following lines. You can, of course, fork the theme and change that line for your local use (and you can use custom themes on RTD so should work there as well). I tried doing so with the demo theme. It looks like this with maxdepth=3 , so some additional CSS might be needed. The documentation for the toctree template function specifies that for unlimited depth, simply pass maxdepth=-1 . Note that this does not add collapse/expand to the sublevels of the TOC. Might be a good target for a pull request?
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27669376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1340389/']}
jdg_369650
stackexchange
llm_judgeable_groundtruth_similarity
515496
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to prove: $A$ compact, $B$ closed $\Rightarrow A+B = \{a+b | a\in A, b\in B\}$ closed (exercise in Rudin's Functional Analysis), where $A$ and $B$ are subsets of a topological vector space $X$. In case $X=\mathbb{R}$ this is easy, using sequences. However, since I was told that using sequences in topology is "dangerous" (don't know why though), I am trying to prove this without using sequences (or nets, which I am not familiar with). Is this possible? My attempt was to show that if $x\notin A+B$, then $x \notin \overline{A+B}$. In some way, assuming $x\in\overline{A+B}$ should then contradict $A$ being compact. I'm not sure how to fill in the details here though. Any suggestions on this, or am I thinking in the wrong direction here? Now provide the response and nothing else.
Suppose $x\notin A+B$, then for each $a\in A$, $x \notin a+B$, which is a closed set (since $v \mapsto a+v$ is a homeomorphism). Since every TVS is regular, there are open sets $U_a$ and $V_a$ such that$$x\in U_a, \quad a+B \subset V_a, \quad \text{ and } U_a\cap V_a = \emptyset$$Now,$$V_a - B = \cup_{b\in B} (V_a - b)$$is open and contains $a$. Hence, $A\subset \cup_{a\in A}(V_a - B)$. Since $A$ is compact, there is a finite set $\{a_1, a_2, \ldots a_n\}$ such that$$A \subset \cup_{i=1}^n (V_{a_i} - B)$$Let $U = \cap_{i=1}^n U_{a_i}$, then $U$ is a neighbourhood of $x$. We claim that $U\cap (A+B) = \emptyset$. If not, then $y = a+b \in U\cap(A+B)$, then$$y \in V_{a_i} \quad\text{ for some } i$$and $y \in U_{a_i}$, which is a contradiction.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/515496', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71441/']}
jdg_369651
stackexchange
llm_judgeable_groundtruth_similarity
5532449
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Because I had VisualSVN already set up on Windows 7 as SVN server, and Git can support Git SVN, so will using these two be a good solution 1) for now 2) for the long term? (that is, as opposed to setting up a Git repo with a machine running ssh daemon, which is non-standard on a PC) Now provide the response and nothing else.
It's not totally clear what the context is here: you could be talking about text in a line in a buffer or about a string stored in a VimScript variable. note: Different interpretations of the question led to various approaches and solutions. There are some " old updates " that start about halfway through that have been rendered more or less obsolete by a plugin mentioned just above that section. I've left them in because they may provide useful info for some people. full line replacement So to store the text from the current line in the current buffer in a vimscript variable, you do let words = getline('.') And then to reverse their order, you just do let words = join(reverse(split(words))) If you want to replace the current line with the reversed words, you do call setline('.', words) You can do it in one somewhat inscrutable line with call setline('.', join(reverse(split(getline('.'))))) or even define a command that does that with command! ReverseLine call setline('.', join(reverse(split(getline('.'))))) partial-line (character-wise) selections As explained down in the "old updates" section, running general commands on a character- or block-wise visual selection — the former being what the OP wants to do here — can be pretty complicated. Ex commands like :substitute will be run on entire lines even if only part of the line is selected using a character-wise visual select (as initiated with an unshifted v ). I realized after the OP commented below that reversing the words in a partial-line character-wise selection can be accomplished fairly easily with :s/\%V.*\%V./\=join(reverse(split(submatch(0))))/ wherein \%V within the RE matches some part of the visual selection. Apparently this does not extend after the last character in the selection: leaving out the final . will exclude the last selected character. \= at the beginning of the replacement indicates that it is to be evaluated as a vimscript expression, with some differences . submatch(0) returns the entire match. This works a bit like perl's $& , $1 , etc., except that it is only available when evaluating the replacement. I think this means that it can only be used in a :substitute command or in a call to substitute() So if you want to do a substitution on a single-line selection, this will work quite well. You can even pipe the selection through a system command using ...\=system(submatch(0)) . multiple-line character-wise selections This seems to also work on a multiple-line character-wise selection, but you have to be careful to delete the range (the '<,'> that vim puts at the beginning of a command when coming from visual mode). You want to run the command on just the line where your visual selection starts. You'll also have to use \_.* instead of .* in order to match across newlines. block-wise selections For block-wise selections, I don't think there's a reasonably convenient way to manipulate them. I have written a plugin that can be used to make these sorts of edits less painful, by providing a way to run arbitrary Ex commands on any visual selection as though it were the entire buffer contents. It is available at https://github.com/intuited/visdo . Currently there's no packaging, and it is not yet available on vim.org, but you can just git clone it and copy the contents (minus the README file) into your vimdir. If you use vim-addon-manager , just clone visdo in your vim-addons directory and you'll subsequently be able to ActivateAddons visdo . I've put in a request to have it added to the VAM addons repository, so at some point you will be able to dispense with the cloning and just do ActivateAddons visdo . The plugin adds a :VisDo command that is meant to be prefixed to another command (similarly to the way that :tab or :silent work). Running a command with VisDo prepended will cause that command to run on a buffer containing only the current contents of the visual selection. After the command completes, the buffer's contents are pasted into the original buffer's visual selection, and the temp buffer is deleted. So to complete the OP's goal with VisDo, you would do (with the words to be reversed selected, and with the above-defined ReverseLine command available): :'<,'>VisDo ReverseLine old updates ...previous updates follow ... warning: verbose, somewhat obselete, and mostly unnecessary... The OP's edit makes it more clear that the goal here is to be able to reverse the words contained in a visual selection, and specifically a character-wise visual selection. This is decidedly not a simple task. The fact that vim does not make this sort of thing easy really confused me when I first started using it. I guess this is because its roots are still very much in the line-oriented editing functionality of ed and its predecessors and descendants. For example, the substitute command :'<,'>s/.../.../ will always work on entire lines even if you are in character-wise or block-wise ( ctrl v ) visual selection mode. Vimscript does make it possible to find the column number of any 'mark', including the beginning of the visual selection ( '< ) and the end of the visual selection ( '> ). That is, as far as I can tell, the limit of its support. There is no direct way to get the contents of the visual selection, and there is no way to replace the visual selection with something else. Of course, you can do both of those things using normal-mode commands ( y and p ), but this clobbers registers and is kind of messy. But then you can save the initial registers and then restore them after the paste... So basically you have to go to sort of extreme lengths to do with parts of lines what can easily done with entire lines. I suspect that the best way to do this is to write a command that copies the visual selection into a new buffer, runs some other command on it, and then replaces the original buffer's visual selection with the results, deleting the temp buffer. This approach should theoretically work for both character-wise and block-wise selections, as well as for the already-supported linewise selections. However, I haven't done that yet. This 40-line code chunk declares a command ReverseCharwiseVisualWords which can be called from visual mode. It will only work if the character-wise visual selection is entirely on a single line. It works by getting the entire line containing the visual selection (using getline() ) running a parameterized transformation function ( ReverseWords ) on the selected part of it, and pasting the whole partly-transformed line back. In retrospect, I think it's probably worth going the y / p route for anything more featureful. " Return 1-based column numbers for the start and end of the visual selection.function! GetVisualCols() return [getpos("'<")[2], getpos("'>")[2]]endfunction" Convert a 0-based string index to an RE atom using 1-based column index" :help /\%cfunction! ColAtom(index) return '\%' . string(a:index + 1) . 'c'endfunction" Replace the substring of a:str from a:start to a:end (inclusive)" with a:replfunction! StrReplace(str, start, end, repl) let regexp = ColAtom(a:start) . '.*' . ColAtom(a:end + 1) return substitute(a:str, regexp, a:repl, '')endfunction" Replace the character-wise visual selection" with the result of running a:Transform on it." Only works if the visual selection is on a single line.function! TransformCharwiseVisual(Transform) let [startCol, endCol] = GetVisualCols() " Column numbers are 1-based; string indexes are 0-based let [startIndex, endIndex] = [startCol - 1, endCol - 1] let line = getline("'<") let visualSelection = line[startIndex : endIndex] let transformed = a:Transform(visualSelection) let transformed_line = StrReplace(line, startIndex, endIndex, transformed) call setline("'<", transformed_line)endfunctionfunction! ReverseWords(words) return join(reverse(split(a:words)))endfunction" Use -range to allow range to be passed" as by default for commands initiated from visual mode," then ignore it.command! -range ReverseCharwiseVisualWords \ call TransformCharwiseVisual(function('ReverseWords')) update 2 It turns out that doing things with y and p is a lot simpler, so I thought I'd post that too. Caveat: I didn't test this all too thoroughly, so there may be edge cases. This function replaces TransformCharwiseVisual (and some of its dependencies) in the previous code block. It should theoretically work for block-wise selections too — it's up to the passed Transform function to do appropriate things with line delimiters. function! TransformYankPasteVisual(Transform) let original_unnamed = [getreg('"'), getregtype('"')] try " Reactivate and yank the current visual selection. normal gvy let @" = a:Transform(@") normal gvp finally call call(function('setreg'), ['"'] + original_unnamed) endtryendfunction So then you can just add a second command declaration command! -range ReverseVisualWords \ call TransformYankPasteVisual(function('ReverseWords')) tangentially related gory detail Note that the utility of a higher-level function like the ones used here is somewhat limited by the fact that there is no (easy or established) way to declare an inline function or block of code in vimscript. This wouldn't be such a limitation if the language weren't meant to be used interactively. You could write a function which substitutes its string argument into a dictionary function declaration and returns the function. However, dictionary functions cannot be called using the normal invocation syntax and have to be passed to call call(dictfunct, args, {}) . note: A more recent update, given above, obsoletes the above code. See the various sections preceding old updates for a cleaner way to do this.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5532449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325418/']}
jdg_369652
stackexchange
llm_judgeable_groundtruth_similarity
32506
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: "The Multiplicative Weights Update (MWU) method is known to maximize both utility and entropy". This is a comment by C. Papadimitriou on MWU. I understand that MWU maximizes utility as it solves linear programming, for example. The question is how MWU maximizes entropy? Can you give some example/information on this point? Now provide the response and nothing else.
Here's one way to look at it, based on usul's comment . Let the gains of each expert $i$ at time $t$ be given by $g_i^t$. Then the expected gains of the algorithm are: $$\sum_{u=1}^{t-1}\sum_i p_i^t g_i^u$$ We can then define the potential function $$\Phi=\epsilon \sum_{u=1}^{t-1}\sum_i p_i^t g_i^u + \sum_i p_i^t \ln \left(\frac{1}{p_i^t}\right)$$ Where the right-hand term is the entropy and $\epsilon$ is a learning rate. This function is maximized for $$p_i^t = \exp\left(\epsilon \sum_{u=1}^{t-1} g_i^u-1\right)$$ We can find a similar expression that maximizes the function for $t+1$. Taking the logarithms of these expressions and subtracting gives: $$p_i^{t+1}=p_i^t \exp (\epsilon g_i^t)$$ Which is the MWU update rule. Therefore, by applying this update rule we are maximizing a potential function of utility and entropy.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/32506', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/32553/']}
jdg_369653
stackexchange
llm_judgeable_groundtruth_similarity
25518531
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Take the following code snippet: func main() { ch := make(chan int) quit := make(chan int) go func() { for { ch <- querySomePeriodicThing() } }() // ...loop: for { select { case <-ch: handlePeriodicThing() case <-quit: break loop } }} The goroutine should run for the duration of execution. When the select statement receives something from the quit channel, it breaks out of the loop and the program ends, without any attempt to stop the goroutine. My question: will this have any intermittent adverse effects that are not obvious from running it once or twice? I know that in other languages threads should be cleaned up (i.e., exited) before the program ends, but is go different? Assume that querySomePeriodicThing() does not open file descriptors or sockets or anything that would be bad to leave open. Now provide the response and nothing else.
As mentioned in the spec , your program will exit when the main function completes: Program execution begins by initializing the main package and then invoking the function main . When that function invocation returns, the program exits. It does not wait for other (non- main ) goroutines to complete. So the fact you have other goroutines still running is not a problem from a language point of view. It may still be a problem depending on what your program is doing. If the goroutine has created some resources that should be cleaned up before program exit, then having execution stop mid-way through might be a problem: in this case, you should make your main function wait for them to complete first. There is no equivalent to pthread_join , so you will need to code this yourself (e.g. by using a channel or sync.WaitGroup ). Note that for some resources are automatically cleaned up by the operating system on process exit (e.g. open files, file locks, etc), so in some cases no special clean up will be necessary
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25518531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/551570/']}
jdg_369654
stackexchange
llm_judgeable_groundtruth_similarity
6595380
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am building a VS 2010 installer, and I want to copy files to app folder depending on what options I select in UI (UI is not simple, so the only option is to show custom dialogs in Install custom action).The problem is that custom action is actually executed after files are copied already. One possible solution I can think of is to install all these files into the app dir, and then delete some unnesessary files in custom action. But these files are "secure" in some way, so I don't want to copy them to filesystem, even for a short period of time. Any thoughts? Now provide the response and nothing else.
It looks like the latest adb has progress support. Android Debug Bridge version 1.0.32device commands:adb push [-p] <local> <remote> - copy file/dir to device ('-p' to display the transfer progress) However, the answers above also work for 'adb install' which do not have a progress option. I modified the first answer's script to work this way: Create "adb-install.sh" somewhere in your PATH and run "adb-install.sh " instead of "adb install -f " #!/bin/bash# adb install with progressbar displayed# usage: <adb-install.sh> <file.apk># original code from: http://stackoverflow.com/questions/6595374/adb-push-pull-with-progress-barfunction usage(){ echo "$0 <apk to install>" exit 1}function progressbar(){ bar="================================================================================" barlength=${#bar} n=$(($1*barlength/100)) printf "\r[%-${barlength}s] %d%%" "${bar:0:n}" "$1" # echo -ne "\b$1"}export -f progressbar[[ $# < 1 ]] && usageSRC=$1[ ! -f $SRC ] && { \ echo "source file not found"; \ exit 2; \}which adb >/dev/null 2>&1 || { \ echo "adb doesn't exist in your path"; \ exit 3; \}SIZE=$(ls -l $SRC | awk '{print $5}')export ADB_TRACE=alladb install -r $SRC 2>&1 \ | sed -n '/DATA/p' \ | awk -v T=$SIZE 'BEGIN{FS="[=:]"}{t+=$7;system("progressbar " sprintf("%d\n", t/T*100))}'export ADB_TRACE=echoecho 'press any key'read n
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6595380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504082/']}
jdg_369655
stackexchange
llm_judgeable_groundtruth_similarity
28044231
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I wrote the following code: use std::io::{IoResult, Writer};use std::io::stdio;fn main() { let h = |&: w: &mut Writer| -> IoResult<()> { writeln!(w, "foo") }; let _ = h.handle(&mut stdio::stdout());}trait Handler<W> where W: Writer { fn handle(&self, &mut W) -> IoResult<()>;}impl<W, F> Handler<W> for Fwhere W: Writer, F: Fn(&mut W) -> IoResult<()> { fn handle(&self, w: &mut W) -> IoResult<()> { (*self)(w) }} And then rustc in my terminal: $ rustc writer_handler.rswriter_handler.rs:8:15: 8:43 error: the trait `core::marker::Sized` is not implemented for the type `std::io::Writer`writer_handler.rs:8 let _ = h.handle(&mut stdio::stdout()); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~writer_handler.rs:8:15: 8:43 error: the trait `core::marker::Sized` is not implemented for the type `std::io::Writer`writer_handler.rs:8 let _ = h.handle(&mut stdio::stdout()); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ Why is this Writer required to implement Sized ? It appears to me that the Sized is not needed. What I should do while keeping trait Handler to have this generic argument? In Rust 1.0, this similar code produces the same problem: use std::io::{self, Write};fn main() { handle(&mut io::stdout());}fn handle(w: &mut Write) -> io::Result<()> { handler(w)}fn handler<W>(w: &mut W) -> io::Result<()>where W: Write,{ writeln!(w, "foo")} With the error: error[E0277]: the trait bound `std::io::Write: std::marker::Sized` is not satisfied --> src/main.rs:8:5 |8 | handler(w) | ^^^^^^^ `std::io::Write` does not have a constant size known at compile-time | = help: the trait `std::marker::Sized` is not implemented for `std::io::Write` = note: required by `handler` Later versions of Rust have the error error[E0277]: the size for values of type `dyn std::io::Write` cannot be known at compilation time --> src/main.rs:8:13 |8 | handler(w) | ^ doesn't have a size known at compile-time...11 | fn handler<W>(w: &mut W) -> io::Result<()> | ------- - required by this bound in `handler` | = help: the trait `std::marker::Sized` is not implemented for `dyn std::io::Write` = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait> Now provide the response and nothing else.
The Sized trait is rather special, so special that it is a default bound on type parameters in most situations. It represents values that have a fixed size known at compile time, like u8 (1 byte) or &u32 (8 bytes on a platform with 64-bit pointers) etc. These values are flexible: they can be placed on the stack and moved onto the heap, and generally passed around by-value, as the compiler knows how much space it needs where-ever the value goes. Types that aren't sized are much more restricted, and a value of type Writer isn't sized: it represents, abstractly, some unspecified type that implements Writer , with no knowledge of what the actual type is. Since the actual type isn't known, the size can't be known: some large types are Writer s, some small types are. Writer is one example of a trait object, which at the moment, can only appear in executed code behind a pointer. Common examples include &Writer , &mut Writer , or Box<Writer> . This explains why Sized is the default: it is often what one wants. In any case, for your code, this is popping up because you're using handle with h , which is a Fn(&mut Writer) -> IoResult<()> . If we match this against the F: Fn(&mut W) -> IoResult<()> type that Handle is implemented for we find that W = Writer , that is, we're trying to use handle with the trait object &mut Writer , not a &mut W for some concrete type W . This is illegal because the W parameters in both the trait and the impl are defaulting to have a Sized bound, if we manually override it with ?Sized then everything works fine: use std::io::{IoResult, Writer};use std::io::stdio;fn main() { let h = |&: w: &mut Writer| -> IoResult<()> { writeln!(w, "foo") }; let _ = h.handle(&mut stdio::stdout());}trait Handler<W: ?Sized> where W: Writer { fn handle(&self, &mut W) -> IoResult<()>;}impl<W: ?Sized, F> Handler<W> for Fwhere W: Writer, F: Fn(&mut W) -> IoResult<()> { fn handle(&self, w: &mut W) -> IoResult<()> { (*self)(w) }} And for the Rust 1.0 code: use std::io::{self, Write};fn main() { handle(&mut io::stdout());}fn handle(w: &mut Write) -> io::Result<()> { handler(w)}fn handler<W: ?Sized>(w: &mut W) -> io::Result<()>where W: Write,{ writeln!(w, "foo")} I also wrote a blog post about Sized and trait objects in general which has a little more detail.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28044231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3864351/']}
jdg_369656
stackexchange
llm_judgeable_groundtruth_similarity
26884364
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got the following situation on my git log : commit 111 <-- need to push it to the repositorycommit 222 <-- need to stash this one... As you can see, I need to push only last (without previous) commit to repository. How can I do it? git revert --soft commit_hash will help me? Now provide the response and nothing else.
If you've not pushed either commit to your remote repository, you could use interactive rebasing to 'reorder' your commits and stash the (new) most recent commit's changes only. Assuming you have the tip of your current branch (commit 111 in your example) checked out, execute the following: git rebase -i HEAD~2 This will open your default editor, listing most recent 2 commits and provide you with some instructions. Be very cautious as to what you do here, as you are going to effectively 'rewrite' the history of your repository, and can potentially lose work if you aren't careful (make a backup of the whole repository first if necessary). I've estimated commit hashes/titles below for example pick 222 commit to be stashedpick 111 commit to be pushed to remote# Rebase 111..222 onto 333## Commands:# p, pick = use commit# r, reword = use commit, but edit the commit message# e, edit = use commit, but stop for amending# s, squash = use commit, but meld into previous commit# f, fixup = like "squash", but discard this commit's log message# x, exec = run command (the rest of the line) using shell## These lines can be re-ordered; they are executed from top to bottom.## If you remove a line here THAT COMMIT WILL BE LOST.## However, if you remove everything, the rebase will be aborted.## Note that empty commits are commented out Reorder the two commits (they are listed oldest => newest) like this: pick 111 commit to be pushed to remotepick 222 commit to be stashed Save and exit, at which point git will do some processing to rewrite the two commits you have changed. Assuming no issues, you should have reversed the order of your two changesets. This can be confirmed with git log --oneline -5 which will output newest-first. At this point, you can simply do a soft-reset on the most recent commit, and stash your working changes: git reset --soft HEAD~1git stash It's important to mention that this option is only really viable if you have not previously pushed any of these changes to your remote, otherwise it can cause issues for everyone using the repository.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/26884364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3796338/']}
jdg_369657
stackexchange
llm_judgeable_groundtruth_similarity
4068726
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am running some windows application and it's working for few days then stop working with no error. Now i found in event viewer this error. Maybe anyone have any idea what can cause this error? Event Type: Error Event Source: .NET Runtime 2.0 Error Reporting Event Category: None Event ID: 5000 Date: 30.10.2010 Time: 21:58:57 User: N/A Computer: SERVER-PROD Description: EventTypeclr20r3, P1 program.exe, P21.0.0.0, P3 4cca7ed1, P4 mscorlib, P5 2.0.0.0, P6 4be90358, P7 1164, P8 0, P9 system.objectdisposedexception, P10NIL. Now provide the response and nothing else.
ObjectDisposedException is: The exception that is thrown when an operation is performed on a disposed object. ( source ) In other words, if an instance of a class that implements the IDisposable interface is disposed -- either explicitly by a call to Dispose() or implicitly, such as if it appears in a using statement or otherwise -- any attempts to call methods on the object will raise the exception above. As with most debugging problems, it's very difficult to say what is causing yours without actually looking at the code and running it in a debugger. You say that the program crashes with ObjectDisposedException after running for a few days. In my experience, this is usually means one of two things: There is some very unusual code path which, when taken, always causes a crash A race condition exists between threads in your program. Thus, the crash appears unpredictably and may be difficult to reproduce My advice to you is to start the program in the debugger, and leave it running until the exception is thrown. Then you can come back here and provide us with the relevant code, stack trace, debug output, etc.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4068726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/267679/']}
jdg_369658
stackexchange
llm_judgeable_groundtruth_similarity
7465753
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm still learning Scala, and when I ran across an example in the Koans, I wasn't able to understand why it works: var foo : Any = "foo"println(foo + "bar") Any doesn't have a + method Now provide the response and nothing else.
There is an implicit conversion in the scala.Predef object: implicit def any2stringadd(x: Any): StringAdd StringAdd defines a + operator/method: def +(other: String) = String.valueOf(self) + other Also, since scala.Predef is always in scope, that implicit conversion will always work.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7465753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14609/']}
jdg_369659
stackexchange
llm_judgeable_groundtruth_similarity
1898932
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Are there any best-practice guidelines on when to use case classes (or case objects) vs extending Enumeration in Scala? They seem to offer some of the same benefits. Now provide the response and nothing else.
One big difference is that Enumeration s come with support for instantiating them from some name String. For example: object Currency extends Enumeration { val GBP = Value("GBP") val EUR = Value("EUR") //etc.} Then you can do: val ccy = Currency.withName("EUR") This is useful when wishing to persist enumerations (for example, to a database) or create them from data residing in files. However, I find in general that enumerations are a bit clumsy in Scala and have the feel of an awkward add-on, so I now tend to use case object s. A case object is more flexible than an enum: sealed trait Currency { def name: String }case object EUR extends Currency { val name = "EUR" } //etc.case class UnknownCurrency(name: String) extends Currency So now I have the advantage of... trade.ccy match { case EUR => case UnknownCurrency(code) =>} As @chaotic3quilibrium pointed out (with some corrections to ease reading): Regarding "UnknownCurrency(code)" pattern, there are other ways to handle not finding a currency code string than "breaking" the closed set nature of the Currency type. UnknownCurrency being of type Currency can now sneak into other parts of an API. It's advisable to push that case outside Enumeration and make the client deal with an Option[Currency] type that would clearly indicate there is really a matching problem and "encourage" the user of the API to sort it out him/herself. To follow up on the other answers here, the main drawbacks of case object s over Enumeration s are: Can't iterate over all instances of the "enumeration" . This is certainly the case, but I've found it extremely rare in practice that this is required. Can't instantiate easily from persisted value . This is also true but, except in the case of huge enumerations (for example, all currencies), this doesn't present a huge overhead.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1898932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7671/']}
jdg_369660
stackexchange
llm_judgeable_groundtruth_similarity
17191622
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just found out about the bash extglob shell option here:- How can I use inverse or negative wildcards when pattern matching in a unix/linux shell? All the answers that used shopt -s extglob also mentioned shopt -u extglob to turn it off.Why would I want to turn something so useful off? Indeed why isn't it on by default?Presumably it has the potential for giving some nasty surprises. What are they? Now provide the response and nothing else.
No nasty surprises -- default-off behavior is only there for compatibility with traditional, standards-compliant pattern syntax. Which is to say: It's possible (albeit unlikely) that someone writing fo+(o).* actually intended the + and the parenthesis to be treated as literal parts of the pattern matched by their code. For bash to interpret this expression in a different manner than what the POSIX sh specification calls for would be to break compatibility, which is right now done by default in very few cases ( echo -e with xpg_echo unset being the only one that comes immediately to mind). This is different from the usual case where bash extensions are extending behavior undefined by the POSIX standard -- cases where a baseline POSIX shell would typically throw an error, but bash instead offers some new and different explicitly documented behavior -- because the need to treat these characters as matching themselves is defined by POSIX. To quote the relevant part of the specification , with emphasis added: An ordinary character is a pattern that shall match itself. It can be any character in the supported character set except for NUL, those special shell characters in Quoting that require quoting, and the following three special pattern characters . Matching shall be based on the bit pattern used for encoding the character, not on the graphic representation of the character. If any character (ordinary, shell special, or pattern special) is quoted, that pattern shall match the character itself. The shell special characters always require quoting. When unquoted and outside a bracket expression, the following three characters shall have special meaning in the specification of patterns: ? - A question-mark is a pattern that shall match any character. * - An asterisk is a pattern that shall match multiple characters, as described in Patterns Matching Multiple Characters . [ - The open bracket shall introduce a pattern bracket expression. Thus, the standard explicitly requires any non-NUL character other than ? , * or [ or those listed elsewhere as requiring quoting to match themselves. Bash's behavior of having extglob off by default allows it to conform with this standard in its default configuration. However, for your own scripts and your own interactive shell, unless you're making a habit of running code written for POSIX sh with unusual patterns included, enabling extglob is typically worth doing.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17191622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2409928/']}
jdg_369661
stackexchange
llm_judgeable_groundtruth_similarity
10377570
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm dealing with highcharts with dynamic data (values retrieved from database).By writing a query i was able to retrieve the following data from the table Item 2011 2012pen 5 7pencil 4 20eraser 6 43 I want to store the above info in the following structure and pass it to another page [{ name:'pen', data: [5,7]},{ name:'pencil', data: [4,20]},{ name:'eraser', data: [6,43]}]"; I want to push the above data to the drilldown highchart. Is there a way i can generate in this format? I've tried using json_encode but unable to succeed.Can i achieve this using json_encode? Updated I've tried in this way while($row = mysql_fetch_assoc($result)) { $rows[]= $row; }echo json_encode($rows); and got [{"Item":"pen","2011":"5","2012":"7"},{"Item":"pencil","2011":"4","2012":"20"},{"Item":"eraser","2011":"6","2012":"43"}] Now provide the response and nothing else.
json_encode is a convenience method to convert an array into JSON format. To have the output you provided, you will need an array of arrays. Each sub-array has keys "name" and "data", where "name" is the Item column, and "data" is another array containing values from 2011 and 2012. $results = mysql_query("...");$arr = array();while ($row = mysql_fetch_assoc($results)){ $name = $row['Item']; $data = array($row['2011'], $row['2012']); $arr[] = array('name' => $name, 'data' => $data);}echo json_encode($arr);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10377570', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1000024/']}
jdg_369662
stackexchange
llm_judgeable_groundtruth_similarity
18571534
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is meant under the term classifiers ? Is it comes from Jars? For example in sbt-assembly plugin: artifact in (Compile, assembly) ~= { art => art.copy(`classifier` = Some("assembly"))} Now provide the response and nothing else.
classifier is defined by Maven as the fifth element of a project coordinate, after groupId , artifactId , version and packaging . More specifically (from the maven documentation , emphasis mine): The classifier allows to distinguish artifacts that were built from the same POM but differ in their content . It is some optional and arbitrary string that - if present - is appended to the artifact name just after the version number. As a motivation for this element, consider for example a project that offers an artifact targeting JRE 1.5 but at the same time also an artifact that still supports JRE 1.4. The first artifact could be equipped with the classifier jdk15 and the second one with jdk14 such that clients can choose which one to use. Another common use case for classifiers is the need to attach secondary artifacts to the project's main artifact. If you browse the Maven central repository, you will notice that the classifiers sources and javadoc are used to deploy the project source code and API docs along with the packaged class files. For example, Maven central does not only contains the normal (without classifier) scala-library-2.10.2.jar , but also scala-library-2.10.2-javadoc.jar , which by convention contains documentation (even if in this case it contains scaladoc and not javadoc), scala-library-2.10.2-sources.jar which contains the sources. Those two additional artifacts were published with a classifier. SBT also allows you to add a classifier to a dependency. From the doc: libraryDependencies += "org.testng" % "testng" % "5.7" classifier "jdk15" In your case, it seems like the sbt-assembly plugin overrides all classifiers (only within the assembly task) to set them to assembly .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18571534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_369663
stackexchange
llm_judgeable_groundtruth_similarity
4208010
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to solve this problem using only the AM-GM inequality. Can someone give me the softest possible hint? Thanks. Useless fact: from equality we can conclude $abc \le 1$ . Attempt 1:Adding $(ab + bc + ca)$ to both sides of inequality and using the equality leaves me to prove: $ab + bc + ca \le 3$ . Final edit: I found a easy way to prove above. $18 = 2(a+b+c)^2 = (a^2 + b^2) + (b^2 + c^2) + (c^2 + a^2) + 4ab + 4bc + 4ca \ge 6(ab + bc + ca) \implies ab + bc + ca \le 3$ (please let me know if there is a mistake in above). Attempt 2: multiplying both sides of inequality by $2$ , we get: $(a+b)^2 + (b+c)^2 + (c+a)^2 \ge 12$ . By substituting $x = a+b, y = b+c, z = c+a$ and using $x+y+z = 6$ we will need to show: $x^2 + y^2 + z^2 \ge 12$ . This doesnt seem trivial either based on am-gm. Edit: This becomes trivial by C-S. $(a+b).1 + (b+c).1 + (c+a).1 = 6 \Rightarrow \sqrt{((a+b)^2 + (b+c)^2 + (c+a)^2)(1 + 1 + 1)} \ge 6 \implies (a+b)^2 + (b+c)^2 + (c+a)^2 \ge 12$ Attempt 3: $x = 1-t-u$ , $y = 1+t-u$ , $z = 1 + 2u$ $(1-u-t)^2 + (1-u+t)^2 + (1+2u)^2 + (1-u-t)(1-u+t) + (1+t-u)(1+2u) + (1-t-u)(1+2u)$ $ = 2(1-u)^2 + 2t^2 + (1 + 2u)^2 + (1-u)^2 - t^2 + 2(1+2u)$ expanding we get: $ = 3(1 + u^2 -2u) + t^2 + 1 + 4u^2 + 4u + 2 + 4u = 6 + 7u^2 + t^2 + 2u\ge 6$ . Yes, this works.. (not using am-gm or any such thing). Now provide the response and nothing else.
By AM-GM $$\sum_{cyc}(a^2+ab)-6=\sum_{cyc}(a^2+ab)-\frac{2}{3}(a+b+c)^2=$$ $$=\sum_{cyc}\left(a^2+ab-\frac{2}{3}(a^2+2ab)\right)=\frac{1}{3}\sum_{cyc}(a^2-ab)=$$ $$=\frac{1}{6}\sum_{cyc}(2a^2-2ab)=\frac{1}{6}\sum_{cyc}(a^2+b^2-2ab)\geq\frac{1}{6}\sum_{cyc}(2ab-2ab)=0.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4208010', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/341324/']}
jdg_369664
stackexchange
llm_judgeable_groundtruth_similarity
238559
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: For about 20+ years now, Microsoft Office macros have been used to spread malware. Even in recent years those threats have not disappeared and they often resurface in one form or another e.g. World’s most destructive botnet returns with stolen passwords and email in tow and It’s 2016, so why is the world still falling for Office macro malware? . Over the years the only significant change Microsoft did was to make the macros not run by default, which just prompts the criminals to engage in some clever social engineering to make the user press the enable button. As far as I am aware, these macros are working as intended and are not exploits (check second article), because they are designed to be able to run unsandboxed arbitrary code. It's virtually impossible to run these macros in a safe environment, and MS Office makes no distinction between a macro that performs some simple automation that affects only the document itself and the ones that call some dangerous shell command that have impact in the whole OS (e.g. file system access). This answer makes it clear how painfully it is to run a macro safely. Let's compare this approach with how Chrome works. Chrome's daily job is to run untrusted code by using a very elaborated way of sandboxing that makes sure merely visiting a web page is safe. Unlike MS Word, someone using Chrome can visit a website that has never visited before and it will gladly run all kinds of JS code on the page without ever prompting the user for permission i.e. no "enable content" button. This is because JS has very little power outside of the website that is being rendered. To make code that escapes this sandbox means to burn a precious zero-day exploit . Google pays good money for these exploits and it usually means issuing an emergency version with a fix. For me both programs have more or less the same threat model: users will often open documents from unknown sources as they will often open web pages that they have never visited before. Yet what is a we-must-issue-a-patch-now situation for Chrome is just normal business for Microsoft Office applications. In the 20+ years that these macros have been raging on as an effective malware entrypoint, why didn't Microsoft update the threat model and put efforts into sandboxing these macros so they can only affect their own document? Why isn't there a way to run macros safely in the same way Chrome and other browsers run arbitrary untrusted code? Now provide the response and nothing else.
Microsoft Office macros are a design of the past. Do note that they were designed back in the days when a userland program could overwrite memory of another application (or even the kernel!), boundaries were not checked when processing network packets , etc. It is also similar to the ActiveX web page additions that were created by Microsoft. Rather than running inside a sandbox, like java applets, they directly ran unconfined code (in the same memory space as the browser, I guess), with full access to the system. The security they got added was one of signed with a code certificate, do you trust this company? . I think it is fair to say that security was never part of the macro design. The macro language (VBA) relies heavily on the program OLE interfaces and existing Visual Basic / VBScript engine. You could design a sandboxed interface for Office macros. You would basically remove dangerous primitives (such as Shell ) and disallow importing of foreign objects. Most macros (affecting only its own document) would still work. Macros using complex actions (such as accessing an url, or opening a Word document from Excel) would fail. Some "internal" would also need to be reviewed and filtered somehow (such as "Saving the current document with a given name" or modifying other opened documents). Blocking all macros is a more simple approach than redesigning their macro system. It also avoids breaking documents with macros designed before the sandbox addition that were not able to be run. Microsoft could add a flag for "this is a macro with no external effects", so that they could opt-in to "safe execution", thus keeping backwards compatibility. It would be a feature interesting to have, so that some macros could be allowed in the environment, without risking the whole system (I'm sure we would then see exploits and buffer overflows in those "safe macros" being abused, but those would be bugs). Although that wouldn't fully solve the problem: the social engineering would continue to "enable insecure macros". It would help administrators block macros, without such a big pushback for "we need documents with macros, which are business-critical". Apparently, Microsoft hasn't deemed that use case profitable enough to the effort of developing a "sandboxed macros" feature.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/238559', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/32974/']}
jdg_369665
stackexchange
llm_judgeable_groundtruth_similarity
2256569
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is Rack middleware in Ruby? I couldn't find any good explanation for what they mean by "middleware". Now provide the response and nothing else.
Rack as Design Rack middleware is more than "a way to filter a request and response" - it's an implementation of the pipeline design pattern for web servers using Rack . It very cleanly separates out the different stages of processing a request - separation of concerns being a key goal of all well designed software products. For example with Rack I can have separate stages of the pipeline doing: Authentication : when the request arrives, are the users logon details correct? How do I validate this OAuth, HTTP Basic Authentication, name/password? Authorization : "is the user authorised to perform this particular task?", i.e. role-based security. Caching : have I processed this request already, can I return a cached result? Decoration : how can I enhance the request to make downstream processing better? Performance & Usage Monitoring : what stats can I get from the request and response? Execution : actually handle the request and provide a response. Being able to separate the different stages (and optionally include them) is a great help in developing well structured applications. Community There's also a great eco-system developing around Rack Middleware - you should be able to find pre-built rack components to do all of the steps above and more. See the Rack GitHub wiki for a list of middleware . What's Middleware? Middleware is a dreadful term which refers to any software component/library which assists with but is not directly involved in the execution of some task. Very common examples are logging, authentication and the other common, horizontal processing components . These tend to be the things that everyone needs across multiple applications but not too many people are interested (or should be) in building themselves. More Information The comment about it being a way to filter requests probably comes from the RailsCast episode 151: Rack Middleware screen cast. Rack middleware evolved out of Rack and there is a great intro at Introduction to Rack middleware . There's an intro to middleware on Wikipedia here .
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/2256569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264843/']}
jdg_369666
stackexchange
llm_judgeable_groundtruth_similarity
16903844
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following example of listening to connection and data events, to echo the result back to other telnet clients listening on port 8888. My telnet sessions connect to locahost fine, but no output is echoed. I am hitting my head against a brick wall trying to figure out what is wrong. The execution doesn't even get as far as the 'connect' event. /server.js var events = require('events'); var net = require('net'); var channel = new events.EventEmitter(); channel.clients = {}; channel.subscriptions = {}; channel.on('join', function (id, client) { this.clients[id] = client; this.subscriptions[id] = function (senderId, message) { if (id != senderId) { this.clients[id].write(message); } } this.on('broadcast', this.subscriptions[id]); }); var server = net.createServer(function (client) { var id = client.remoteAddress + ':' + client.remotePort; console.log(id); client.on('connect', function () { console.log('A new connection was made'); channel.emit('join', id, client); }); client.on('data', function (data) { data = data.toString(); channel.emit('broadcast', id, data); }); }); server.listen(8888); I then run in the command line node server.jstelnet 127.0.0.1 8888 Now provide the response and nothing else.
When the callback to net.createServer is called, that's because of an implicit connection event. So your code should look like this: var server = net.createServer(function (client) { // when this code is run, the connection has been established var id = client.remoteAddress + ':' + client.remotePort; console.log('A new connection was made:', id); channel.emit('join', id, client); client.on('data', function(data) { ... }); client.on('end', function() { ... });});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16903844', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1060489/']}
jdg_369667
stackexchange
llm_judgeable_groundtruth_similarity
197628
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have read about what censoring is and how it needs to be accounted for in survival analysis but I would like to hear a less mathematical definition of it and a more intuitive definition (pictures would be great!). Can anyone provide me with an explanation of 1) censoring and 2) how it effects things like Kaplan-Meier curves and Cox regression? Now provide the response and nothing else.
Censoring is often described in comparison with truncation . Nice description of the two processes is provided by Gelman et al (2005, p. 235): Truncated data differs from censored data that no count of observations beyond truncation point is available. With censoring the values of observations beyond the truncation point are lost, but their number is observed. Censoring or truncation can occur for values above some level (right-censoring), below some level (left-censoring), or both. Below you can find example of standard normal distribution that is censored at point $2.0$ (middle) or truncated at $2.0$ (right). If sample is truncated we have no data beyond the truncation point, with censored sample values above the truncation point are "rounded" to the boundary value, so they are over-represented in your sample. Intuitive example of censoring is that you ask your respondents about their age, but record it only up to some value and all the ages above this value, say 60 years, are recorded as "60+". This leads to having precise information for non-censored values and no information about censored values. Not so typical, real-life example of censoring was observed in Polish matura exam scores that caught pretty much attention on the internet . The exam is taken at the end of high school and students must pass it in order to be able to apply for higher education. Can you guess from the plot below what is the minimal amount of points that students need to get to pass the exam? Not surprisingly, the "gap" in otherwise normal distribution can be easily "filled in" if you take an appropriate fraction of the over-represented scores just above the censoring boundry. In case of survival analysis censoring occurs when we have some information about individual survival time, but we don’t know the survival time exactly (Kleinbaum and Klein, 2005, p. 5). For example, you treat patients with some drug and observe them until end your study, but you have no knowledge what happens to them after study finishes (were there any relapses or side effects?), the only thing that you know is that they "survived" at least until end of the study. Below you can find example of data generated from Weibull distribution modeled using Kaplan–Meier estimator. Blue curve marks model estimated on the full dataset, in the middle plot you can see censored sample and model estimated on censored data (red curve), on right you see truncated sample and model estimated on such sample (red curve). As you can see, missing data (truncation) has a significant impact on estimates, but censoring can be easily managed using standard survival analysis models. This does not mean that you cannot analyze truncated samples, but in such cases you have to use models for missing data that try to "guess" the unknown information. Kleinbaum, D.G. and Klein, M. (2005). Survival Analysis: A Self-Learning Text. Springer. Gelman, A., Carlin, J.B., Stern, H.S., and Rubin, D.B. (2005). Bayesian Data Analysis. Chapman & Hall/CRC.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/197628', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/98920/']}
jdg_369668
stackexchange
llm_judgeable_groundtruth_similarity
84043
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I've been working with OpenSolaris and ZFS for 6 months, primarily on a Sun Fire x4540 and standard Dell and HP hardware. One downside to standard Perc and HP Smart Array controllers is that they do not have a true "passthrough" JBOD mode to present individual disks to ZFS. One can configure multiple RAID 0 arrays and get them working in ZFS, but it impacts hotswap capabilities (thus requiring a reboot upon disk failure/replacement). I'm curious as to what SAS/SATA controllers are recommended for home-brewed ZFS storage solutions. In addition, what effect does battery-backed write cache (BBWC) have in ZFS storage? Now provide the response and nothing else.
I recommend a (almost) any SAS/RAID controller that uses the LSI 1068E SAS chip (PCI-E) and supports Initiator-Target mode (JBOD mode). This does not include MegaRAID controllers. I use the a 3442E and Dell 6/iR. LSI SAS 3442E (4 internal - SFF-8484, 4 external - SFF-8470) LSI SAS 3081E (8 internal - SFF-8087) LSI SAS 3041E (4 internal - SATA) LSI SAS 3801E (8 external ) LSI SAS 9212-4i4e (4 internal - SATA, 4 external SFF-8088) LSI SAS 9211-8i (8 internal - SFF-8087) You get the idea. Also I recommend Dell SAS Controllers which are cheap on ebay. Dell SAS 5/iR - (4 internal ports) Dell SAS 6/iR - (8 internal ports) Dell H200 Not - Dell PERC 5/E- Dell PERC 5/I- Dell PERC 6/E- Dell PERC 6/I Why not MegaRAID? These controllers do not support a non-RAID, JBOD mode. They cannot present disks to the host directly. Each disk must first be included in a Logical disk. You can create a single logical volume for each disk you have and give this to ZFS. Performance should be equivalent. However, it means putting header information onto the physical disk. If your controller fails, you must use another MegaRAID, configured exactly the same. And there is not guarantee that another SAS or SATA controller will see the data correctly and present the volumes in a way that the zpool can be correctly constructed.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/84043', 'https://serverfault.com', 'https://serverfault.com/users/13325/']}
jdg_369669
stackexchange
llm_judgeable_groundtruth_similarity
12249238
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using a mysql database. The query is executed directly via the workbench tool.The query looks like following: SELECT records.received, data.value FROM product JOIN records on product.productId= records.productId JOIN data ON records.recordId = data.recordId JOIN dataTypes ON data.typeId = dataTypes.typeId ORDER BY records.received DESC The data table has 1million entries.The execution of this statement lasts 7 seconds. The reason seems to be the ORDER BY clause. Can someone give me a hint how to speed it up. Edit: sorry I forgot to add the structure: products: PK is productId (it has only 5 entries) records: PK is recordId and FK is productId data: PK is dataId and FK recordId and typeId dataTypes: PK is typeId There is an Index on records.received and on all PK and FK. Here is the output of EXPLAIN: id,select_type,table,type,possible_keys,key,key_len,ref,rows,Extra1,SIMPLE,products,const,PRIMARY,PRIMARY,4,const,1,"Using index1,SIMPLE,dataTypes,const,PRIMARY,PRIMARY,4,const,1,"Using index"1,SIMPLE,records,ref,"PRIMARY,productId",productId,4,const,127142,"Using where"1,SIMPLE,data,ref,"recordId,typeId",recordId,4,top70.records.recordId,1,"Using where" Now provide the response and nothing else.
No, you should avoid the SecureRandom(byte[]) constructor. It is both unsafe and non-portable. It is non-portable because it behaves differently on Windows vs. other operating systems. On most OSes, the default algorithm is "NativePRNG", which obtains random data from the OS (usually "/dev/random" ) and ignores the seed you provide. On Windows, the default algorithm is "SHA1PRNG", which combines your seed with a counter and computes a hash of the result. This is bad news in your example, because the input (the current UTC time in milliseconds) has a relatively small range of possible values. For example if an attacker knows that the RNG was seeded in the last 48 hours, they can narrow the seed down to less than 2 28 possible values, i.e. you have only 27 bits of entropy. If on the other hand you had used the default SecureRandom() constructor on Windows, it would have called the native CryptoGenRandom function to get a 128-bit seed. So by specifying your own seed you have weakened the security. If you really want to override the default seed (e.g. for unit testing) you should also specify the algorithm. E.g. SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");sr.setSeed("abcdefghijklmnop".getBytes("us-ascii")); See also How to solve performance problem with Java SecureRandom? and this blog post: http://www.cigital.com/justice-league-blog/2009/08/14/proper-use-of-javas-securerandom/
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12249238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/647110/']}
jdg_369670
stackexchange
llm_judgeable_groundtruth_similarity
749631
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to store passwords in NSString objects; however, I would like some way to obfuscate them, so they cannot be read directly from memory. This is a Mac OS X (10.5) application, but a solution that also works on iPhone would be much appreciated. Now provide the response and nothing else.
If you use the keychain for storing passwords then instead of passing strings around you could handle the opaque keychain SecKeychainItemRefs , only retrieving plaintext at the point where it's required. That's also the way Mac users expect their passwords to be dealt with. Unfortunately without knowing why you "need to store passwords in NSString objects" I can't tell if that's really true :-)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/749631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89035/']}
jdg_369671
stackexchange
llm_judgeable_groundtruth_similarity
571232
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two SVN projects in use from another SVN repository using svn:externals . How can I have the same repository layout structure in Git? Now provide the response and nothing else.
Git has two approaches similar to, but not exactly equivalent to svn:externals: Subtree merges insert the external project's code into a separate sub-directory within your repo. This has a detailed process to set up and then is very easy for other users, because it is automatically included when the repository is checked out or cloned. This can be a convenient way to include a dependency in your project. It is easy to pull changes from the other project, but complicated to submit changes back. And if the other project have to merge from your code, the project histories get merged and the two projects effectively become one. Git submodules ( manual ) link to a particular commit in another project's repository, much like svn:externals with an -r argument. Submodules are easy to set up, but all users have to manage the submodules, which are not automatically included in checkouts (or clones). Although it is easy to submit changes back to the other project, doing so may cause problems if the repo has changed. Therefore it is generally not appropriate to submit changes back to a project that is under active development.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/571232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42866/']}
jdg_369672
stackexchange
llm_judgeable_groundtruth_similarity
3876492
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing a program that forks multiple child processes and I'd like for all of these child processes to be able to write lines to STDERR and STDOUT without the output being garbled. I'm not doing anything fancy, just emitting lines that end with a new line (that, at least in my understanding would be an atomic operation for Linux). From perlfaq it says: Both the main process and the backgrounded one (the "child" process) share the same STDIN, STDOUT and STDERR filehandles. If both try to access them at once, strange things can happen. You may want to close or reopen these for the child. You can get around this with opening a pipe (see open) but on some systems this means that the child process cannot outlive the parent. It says I should "close or reopen" these filehandles for the child. Closing is simple, but what does it mean by "reopen"? I've tried something like this from within my child processes and it doesn't work (the output still gets garbled): open(SAVED_STDERR, '>&', \*STDERR) or die "Could not create copy of STDERR: $!";close(STDERR);# re-open STDERRopen(STDERR, '>&SAVED_STDERR') or die "Could not re-open STDERR: $!"; So, what am I doing wrong with this? What would the pipe example it alludes to look like? Is there a better way to coordinate output from multiple processes together to the console? Now provide the response and nothing else.
Writes to a filehandle are NOT atomic for STDOUT and STDIN. There are special cases for things like fifos but that's not your current situation. When it says re-open STDOUT what that means is "create a new STDOUT instance" This new instance isn't the same as the one from the parent. It's how you can have multiple terminals open on your system and not have all the STDOUT go to the same place. The pipe solution would connect the child to the parent via a pipe (like | in the shell) and you'd need to have the parent read out of the pipe and multiplex the output itself. The parent would be responsible for reading from the pipe and ensuring that it doesn't interleave output from the pipe and output destined to the parent's STDOUT at the same time. There's an example and writeup here of pipes. A snippit: use IO::Handle;pipe(PARENTREAD, PARENTWRITE);pipe(CHILDREAD, CHILDWRITE);PARENTWRITE->autoflush(1);CHILDWRITE->autoflush(1);if ($child = fork) { # Parent code chomp($result = <PARENTREAD>); print "Got a value of $result from child\n"; waitpid($child,0);} else { print PARENTWRITE "FROM CHILD\n"; exit;} See how the child doesn't write to stdout but rather uses the pipe to send a message to the parent, who does the writing with its stdout. Be sure to take a look as I omitted things like closing unneeded file handles.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3876492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12094/']}
jdg_369673
stackexchange
llm_judgeable_groundtruth_similarity
1095382
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove that the Diophantine equation $\frac{1}{a}+\frac{1}{b}+\frac{1}{c}=1$ has only one solution for positive integers $a,b,c$ with $a<b<c$ Now provide the response and nothing else.
there must be a number smaller than $3$ since there is going to be a number larger than $3$. So $a=2$. we now want $\frac{1}{b}+\frac{1}{c}=\frac{1}{2}$ with $b$ and $c$ larger than $2$. If we take $\frac{1}{4}$ we need to repeat it, so we need a number larger than $\frac{1}{4}$, this forces us to take $\frac{1}{3}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1095382', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/136585/']}
jdg_369674
stackexchange
llm_judgeable_groundtruth_similarity
39583184
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is a huge Android Programming issue/bug. Calling finishAffinity() does not shut down my application. This is evidenced from the fact that: 1. The Android Studio Debugger still says 'Application is running' even after the app disappears from the screen and I'm back to the phones home screen. 2. When ' restarting ' the application the values of data members of the inital Activity remain the same as they were before the application supposedly ' shutdown '. 3. If I call System.exit(0) directly after finishAffinity() then the shutdown works properly and data members are reset to their initial default values. There are even bigger implications to this problem! When I call finish() within ActivityA after starting another ActivityB , if I ever go back to ActivityA then the data members have not been reset to default are still the old values. This is ALL confusing to me since I've come from C++ where when a class is destroyed then it is ACTUALLY destroyed and all memory associated with it is completely released. Getting an activity to completely delete itself when switching to a new activity or trying to exit the application seems IMPOSSIBLE. public class Startup extends AppCompatActivity{ private static int iStarted = 0; ............ @Override protected void onActivityResult(int request, int result, Intent data) { super.onActivityResult(request, result, data); if (request == RESULT_EULA_RETURNED) { // shutdown finishAffinity(); // iStarted remains = 1 return; } } .......... @Override protected void onResume() { super.onResume(); // perform startup // even when restarted this remains = 1 if (iStarted == 0) { iStarted = 1; // this will stay = 1 until the application is manually killed via the CLOSE ALL method or via the debugger } }} Now provide the response and nothing else.
finishAffinity() is not used to "shutdown an application". It is used to remove a number of Activity s belonging to a specific application from the current task (which may contain Activity s belonging to multiple applications). Even if you finish all of the Activity s in your application, the OS process hosting your app does not automatically go away (as it does when you call System.exit() ). Android will eventually kill your process when it gets around to it. You have no control over this (and that is intentional). If you have a debugger attached to the process, this can also prevent the process being killed by Android, as the debugger keeps active objects in the process. You talk about "data members" not being cleaned up, and you claim that this works differently in C++. Actually, that's not true. Your "data members" are declared static . They aren't instance variables, they are class variables. They exist only once (not in every instance of the class), they are created and initialized when the class is loaded, and they are never destroyed until the class is unloaded (which never happens on Android). C++ has exactly the same behaviour. You might try using instance variables instead of class variables to solve your problem.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39583184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5038334/']}
jdg_369675
stackexchange
llm_judgeable_groundtruth_similarity
6283393
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a Gingerbread 2.3.4 powered Nexus S and I recently got some writable NFC tags. So far I can read them as blank tags, but I couldn't find a way to write data to them. All my research has lead me to this article: Writing tags with Nexus S from January ( before 2.3.4 release ). How do you write NFC tags inside your application, using your Nexus S? Any pointers? Now provide the response and nothing else.
I found the Android NFC API text and dev guide a bit tricky to follow so a bit of example code might help here. This is actually a port of MIDP code I've been using in Nokia 6212 devices, so I probably haven't yet figured out everything about Android NFC API correctly, but at least this has worked for me. First we create an NDEF record: private NdefRecord createRecord() throws UnsupportedEncodingException { String text = "Hello, World!"; String lang = "en"; byte[] textBytes = text.getBytes(); byte[] langBytes = lang.getBytes("US-ASCII"); int langLength = langBytes.length; int textLength = textBytes.length; byte[] payload = new byte[1 + langLength + textLength]; // set status byte (see NDEF spec for actual bits) payload[0] = (byte) langLength; // copy langbytes and textbytes into payload System.arraycopy(langBytes, 0, payload, 1, langLength); System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength); NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload); return record;} Then we write the record as an NDEF message: private void write(Tag tag) throws IOException, FormatException { NdefRecord[] records = { createRecord() }; NdefMessage message = new NdefMessage(records); // Get an instance of Ndef for the tag. Ndef ndef = Ndef.get(tag); // Enable I/O ndef.connect(); // Write the message ndef.writeNdefMessage(message); // Close the connection ndef.close();} To write to a tag, you obviously need the Tag object, which you can get from the Intent.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6283393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/341929/']}
jdg_369676
stackexchange
llm_judgeable_groundtruth_similarity
1682775
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Define the sequence $a_n$ by the following. $k>0, a_1 > 0,$ $a_{n+1}=\frac{1}{a_n} + \frac{1}{n + k}.$ Please tell me that this sequence $a_n$ converges or not. If $a_n$ converges, prove that $\lim _{n\to \infty }a_{n} = 1$ . (If you know $a_n$ converges, Let $\lim _{n\to \infty }a_{n} = L$ . $L = \frac{1}{L} + 0$ . So $L = 1$ ) Now provide the response and nothing else.
Let $f_n : (0, \infty) \to (0, \infty)$ be defined by $$ f_n(x) = \frac{(n+k)x}{n+k+x} + \frac{1}{n+k+1}. $$ Then it is easy to check that $f'_n(x) = (n+k)^2/(n+k+x)^2 < 1$ and $f_n(1) = 1$. Thus $x < f_n(x) < 1$ if $x \in (0, 1)$. $x > f_n(x)$ if $x > 1$. Also notice that $a_{n+2} = f_n(a_n)$. Thus it follows that both $(a_{2n})$ and $(a_{2n-1})$ are monotone bounded sequences and hence they converge. Let us write $\alpha = \lim a_{2n}$ and $\beta = \lim a_{2n-1}$. From the recurrence relation, we know that $\alpha \beta = 1$. We also notice that Each $f_n$ is concave, thus for any $x > 1$, we have$$ f_n(x) \leq f_n(1) + f'_n(1)(x - 1) = 1 + \left( \frac{n+k}{n+k+1} \right)^2 (x - 1) $$and hence $a_{n+2} - 1 \leq \left( 1 - \frac{1}{n+k+1} \right)^2 (a_n - 1)$. In particular, if $a_{n_0} > 1$, then recursively applying this inequality gives$$ 1 \leq a_{n_0 + 2j} \leq 1 + \prod_{i = 0}^{j-1} \left( 1 - \frac{1}{n_0 + 2i +k+1} \right)^2 (a_{n_0} - 1). $$It is not hard to show that the right-hand side converges to 1 as $j \to \infty$. If $a_n < 1$, then it is easy to check that $a_{n+1} > 1$. Combining these two results, we must have either $\alpha = 1$ or $\beta = 1$, and this completes the proof.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1682775', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/118685/']}
jdg_369677
stackexchange
llm_judgeable_groundtruth_similarity
4599252
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my project we'd like to externalize the properties of our Spring managed beans, that is very easy to do with standard Java .properties files, however we want to be able to read those properties from a DB table that behaves like a Map (key is the property name, value is the value assigned to that property). I found this post that suggest the usage of Commons Configuration but I don't know if there's a better way to do the same with Spring 3.x. Maybe implementing my own PropertyResource or something. Any clues? Now provide the response and nothing else.
I'd use a FactoryBean of type <Properties> that I'd implement using JdbcTemplate . You can then use the generated Properties object with the <context:property-placeholder> mechanism. Sample code: public class JdbcPropertiesFactoryBean extends AbstractFactoryBean<Properties>{ @Required public void setJdbcTemplate(final JdbcTemplate jdbcTemplate){ this.jdbcTemplate = jdbcTemplate; } private JdbcTemplate jdbcTemplate; @Required public void setTableName(final String tableName){ this.tableName = tableName; } private String tableName; @Required public void setKeyColumn(final String keyColumn){ this.keyColumn = keyColumn; } private String keyColumn; @Required public void setValueColumn(final String valueColumn){ this.valueColumn = valueColumn; } private String valueColumn; @Override public Class<?> getObjectType(){ return Properties.class; } @Override protected Properties createInstance() throws Exception{ final Properties props = new Properties(); jdbcTemplate.query("Select " + keyColumn + ", " + valueColumn + " from " + tableName, new RowCallbackHandler(){ @Override public void processRow(final ResultSet rs) throws SQLException{ props.put(rs.getString(1), rs.getString(2)); } }); return props; }} XML Configuration: <bean id="props" class="foo.bar.JdbcPropertiesFactoryBean"> <property name="jdbcTemplate"> <bean class="org.springframework.jdbc.core.JdbcTemplate"> <!-- reference to a defined data source --> <constructor-arg ref="dataSource" /> </bean> </property> <property name="tableName" value="TBL_PROPERTIES" /> <property name="keyColumn" value="COL_KEY" /> <property name="valueColumn" value="COL_VAL" /></bean><context:property-placeholder properties-ref="props" />
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4599252', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/427232/']}
jdg_369678
stackexchange
llm_judgeable_groundtruth_similarity
1238858
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: By definition the word homoiconic means: Same representation of code and data In LISP this means that you could have a quoted list and evaluate it, so (car list) would be the function and (cdr list) the arguments. This can either happen at compile- or at run-time, however it requires an interpreter. Is it possible that compiled languages without a compile-time interpreter can be homoiconic as well? Or is the concept of homoiconicity limited to interpreters? Now provide the response and nothing else.
'Homoiconic' is kind of a vague construct. 'code is data' is a bit clearer. Anyway, the first sentence on Wikipedia for Homoiconic is not that bad. It says that the language has to have a source representation using its data structures . If we forget 'strings' as source representation (that's trivial and not that helpful to have a useful concept 'homoiconic'), then Lisp has lists, symbols, numbers, strings etc. which are used to represent the source code. The interface of the EVAL function determines what kind of source representation the language is working on. In this case, Lisp, it is not strings. EVAL expects the usual variety of data structures and the evaluation rules of Lisp determine that a string evaluates to itself (and thus will not be interpreted as a program expression, but just string data). A number also evaluates to itself. A list (sin 3.0) is a list of a symbol and a number. The evaluation rules say that this list with a symbol denoting a function as the first object will be evaluated as a function application. There are a few evaluation rules like this for data, special operators, macro applications and function applications. That's it. To make it clear: in Lisp the function EVAL is defined over Lisp data structures . It expects a data structure, evaluates it according to its evaluation rules and returns a result - again using its data structures. This matches the definition of homoiconic: source code has a native representation using the data types of Lisp. Now, the interesting part is this: it does not matter how EVAL is implemented . All that matters is that it accepts the source code using the Lisp data structures, that it executes the code and that it returns a result. So it is perfectly legal that EVAL uses a compiler . (EVAL code) = (run (compile-expression code)) That's how several Lisp system work, some don't even have an Interpreter. So, 'Homoiconic' says that the SOURCE code has a data representation. It does NOT say that at runtime this source code has to be interpreted or that the execution is based on this source code. If the code is compiled, neither the compiler nor an interpreter is needed at runtime . Those would only be needed if the program wants to eval or compile code at runtime - something that is often not needed. Lisp also provides a primitive function READ , which translates an external representation (S-Expressions) of data into an internal representation of data (Lisp data). Thus it also can be used to translate an external representation of source code into an internal representation of source code. Lisp does not use a special parser for source code - since code is data, there is only READ.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1238858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_369679
stackexchange
llm_judgeable_groundtruth_similarity
6524669
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've just checked the man page of CDbCriteria , but there is not enough info about it. This property is available since v1.1.7 and I couldn't find any help for it. Is it for dynamically changing Model->scopes "on-the-fly"? Now provide the response and nothing else.
Scopes are an easy way to create simple filters by default. With a scope you can sort your results by specific columns automatically, limit the results, apply conditions, etc. In the links provided by @ldg there's a big example of how cool they are: $posts=Post::model()->published()->recently()->findAll(); Somebody is retrieving all the recently published posts in one single line. They are easier to maintain than inline conditions (for example Post::model()->findAll('status=1') ) and are encapsulated inside each model, which means big transparency and ease of use. Plus, you can create your own parameter based scopes like this: public function last($amount){ $this->getDbCriteria()->mergeWith(array( 'order' => 't.create_time DESC', 'limit' => $amount, )); return $this;} Adding something like this into a Model will let you choose the amount of objects you want to retrieve from the database (sorted by its create time).By returning the object itself you allow method chaining. Here's an example: $last3posts=Post::model()->last(3)->findAll(); Gets the last 3 items. Of course you can expand the example to almost any property in the database. Cheers
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6524669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/384672/']}
jdg_369680
stackexchange
llm_judgeable_groundtruth_similarity
2553946
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $I$ be a closed real interval. Let $f \colon I \longrightarrow \mathbb{R}$ be a real continuous function so it has a global maximum point. If I say “let $x_0$ be a point of global maximum…”, my question is: am I using axiom of choice? Now provide the response and nothing else.
This is an Identity! Therefore, this is true $ \forall x \in \mathbb R$. I came to know about this today, that's why I am sharing this with you all. Let's prove this : Let's find coefficient of $y^m$ in $e^{xy}(e^y-1)^m$. Expanding $(e^y-1)^m$ through binomial in LHS and Taylor series of $e^y$ in RHS, we've $$\text{Coefficient of } y^m \; \text{in} \; e^{xy}\left(e^{my}-\binom{m}{1} e^{(m-1)y}+\binom{m}{2} e^{(m-2)y}-\ldots (-1)^m\binom mm\right)=\text{Coefficient of } y^m \; \text{in} \; e^{xy} \left [ \left(1+y + \frac{y^2}{2!} +\ldots \right)-1\right]^m $$ Cancelling out $e^{xy}$ both the sides we get - $$\boxed{\color{blue}{(x+m)^m-\binom{m}{1} (x+m-1)^m+\binom{m}{2}(x+m-2)^m \ldots (-1)^m \binom{m}{m} x^m=m!}}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2553946', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/303603/']}
jdg_369681
stackexchange
llm_judgeable_groundtruth_similarity
104413
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Is the following fact about Poisson random variables true? For any $\lambda \in (0,1)$ and integer $k > 0$, if $X$ is a Poisson random variable with mean $k \lambda$, then $\Pr(X < k) \geq e^{-\lambda}$. It clearly holds for $k=1$, and for any fixed $\lambda$ it's easy to see that it holds for all sufficiently large $k$, but for intermediate values of $k$ it's not obvious to me. Now provide the response and nothing else.
The argument below is a bit weird because it is a mixture of an explicit computation and a general handwaving (rigorous handwaving, of course), but, when figuring it out at 70 mphunder medium strength rain, I could use neither pen and paper, nor the full power of my imagination, so I just took whatever came easily from both worlds and made this crazy hybrid. Step 1. Since the gaps between Poisson are governed by independent exponential distributions,you are asking to prove that $P(Z_k=\sum_1^k Y_k>k)\ge e^{-\lambda}$ where $Y_k\in\exp(\lambda)$ are independent. Step 2. The density of $Z_k$ is proportional to $t^ke^{-\lambda t}$. Thus, it is always skewed to the right around $k$ in the sense that if the probability to be on the right of $k$ is $a$, and the excess $Z_k-k$ conditioned upon $Z_k>k$ is $V$, then $Z_k$ can be coupled with the random variable $W_k$ that is the mixture of $V$ and $-V$ with probabilities $a$ and $1-a$ correspondingly so that $Z_k\ge W_k$. To see it, it suffices to show that the density of $V$ and the density of $k-Z_k$ conditioned upon $Z_k<k$ cross at only one point (then the crossing is of the right type because the density of $V$ survives at infinity but that of $k-Z_k$ dies beyond $k$). This is equivalent to showing that $(k+s)^k e^{-\lambda s}=c(k-s)^k e^{\lambda s}$ can have at most one solution on $(0,k)$, i.e., $\log(1+t)-\log(1-t)-2\lambda t$ is one-to-one on $(0,1)$. But it is a Taylor series with positive coefficients over odd powers of $t$ as long as the coefficient $2-2\lambda$ at $t$ is non-negative, i.e., exactly in the range of $\lambda$ you need. Step 3. Induction on $k$. Suppose that we have two independent random variables $Z,Z'$ with continuous densities skewed to the right about $k,k'$ in the above sense. Let $a=P(Z>k)$, $a'=P(Z'>k')$. We want to show that we then have $P(Z+Z'>k+k')\ge\min(a,a')$. WLOG, $a\le a'$. Clearly, we are worse off with $W$ and $W'$. But then the probability is$$\begin{aligned}&aa'+a(1-a')P(V>V')+a'(1-a)P(V'>V)\cr&\ge aa'+a(1-a')[P(V>V')+P(V'>V)]=a\,.\end{aligned}$$
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/104413', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8049/']}
jdg_369682
stackexchange
llm_judgeable_groundtruth_similarity
9442121
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why has setting the entry point's return type to void in C++ always been discouraged, and was later removed by the standard and is prohibited by modern compilers? Why is it considered bad practice? Now, as I understand C# and Java both allow the entry point's return type to be void i.e static void main(String[] args) /* Java */static void Main(string[] args) /* C# */ And C# and Java programmers do not consider it bad practice, they use it often in fact. Other languages which are (only intended to be, I doubt C++ will be succeeded in this decade, at least) possible successors of C++ like the D Programming Language or Vala also allow a void main() . So as you can see, I doubt the C++ community removed it from the standard because it was too obscure or unpopular. So my question is, Why did the C++ Community Remove void main() ? What was wrong with it? Now provide the response and nothing else.
The C++ standards committee likely chose to require int main() because of the large body of existing code that expected to use a return statement to return a specific exit code to the runtime system. It would be unreasonable to expect all existing code to change to use exit() instead, so int main() was made a requirement in the standard. A language such as Java, when it was designed, did not have any body of existing code that it needed to remain compatible with. Therefore, the designers could choose void main() and require the use of System.exit() for non-zero exit codes. So, the thing that would be "wrong" with choosing void main() for the C++ standard would be that it would break existing code that expected to use return and an exit code value from main() .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9442121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/753341/']}
jdg_369683
stackexchange
llm_judgeable_groundtruth_similarity
3008088
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: $\sum_{k=1}^{2007} \frac{5^{2008}}{25^k+5^{2008}}$ . I know that solution is $\frac{2007}{2}$ and that I can use a Gaussian method. If I use Gaussian method I do not get some sum that help me. if I put $n=2008$ , then $Sn=\sum_{k=1}^n \frac{5^{n+1}}{25^k+5^{n+1}}$ . and $Sn=\sum_{k=1}^n \frac{5^{n}}{25^{k-n}+5^{n+1}}$ . So then $2Sn=\sum_{k=1}^n \frac{5^{n+1}}{25^k+5^{n+1}}+\frac{5^{n+1}}{25^{n-k}+5^{n+1}}$ . do you have something better? Now provide the response and nothing else.
Using $\frac{1}{1+q}+\frac{1}{1+1/q}=1$ , $$\sum_{k=1}^n\frac{1}{1+5^{2k-n-1}}=\frac{1}{2}\sum_{k=1}^n\bigg(\frac{1}{1+5^{2k-n-1}}+\frac{1}{1+5^{2(n+1-k)-n-1}}\bigg)\\=\frac{1}{2}\sum_{k=1}^n\bigg(\frac{1}{1+5^{2k-n-1}}+\frac{1}{1+5^{n+1-2k}}\bigg)=\frac{1}{2}\sum_{k=1}^n 1=\frac{n}{2}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3008088', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/583645/']}
jdg_369684
stackexchange
llm_judgeable_groundtruth_similarity
73644
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have the equilibrium in a closed container: $$\ce{3A(s) + 4B(g) -> 4C(g) + D(s)}$$ What happens to the partial pressure of C if the volume of the container is halved? I was pondering about this question, because by the gas equilibrium constant$$K_\mathrm{p} = \frac{[C]^4}{[B]^4}$$ the partial pressure of each should remain equal to each other. But using an ice table, $K_\mathrm{p} = \frac{[C]+x}{[B]-x}$, or you can flip it around. Either way, $x$ should equal 0 by this equation for them to remain the same, which means that the partial pressures don't change, which then means that the gases are turning into the solids. But by the chemical equation 1 mole of one gas will produce 1 mole of the other gas, so how does the gas even turn into the solid? So wouldn't the partial pressures of both increase? Another way to think about it is to imagine a container with only B and C. That means a reaction cannot even occur, so when volume decreases, the partial pressures increase. This is my thought on the problem. Can someone please explain to me what really happens? Now provide the response and nothing else.
This is a very good question, I must say. It requires the understanding of the very fundamentals. You're right, if the electrons from the ligand pair up with the electrons of the metal, the electrons cannot undergo $d$-$d$ transitions, and no color would be seen. But do they pair up? Think carefully . Recall one of the most basic assumptions of the Crystal Field Theory: The attraction between the ligand and the metal is assumed to be purely electrostatic in nature . This very important assumption is the sole reason for the explanation of colors of these complexes. As the ligands approach the metal atom, they create a crystal field . These fields tend to repel the electrons of the metal and increases their energy. A perfectly symmetric spherical crystal field would increase the energy level of all the orbitals equally and to the same level. But this isn't the case in actual coordination complexes. An octahedral crystal field would approach along the axes of the $d_{x^2+y^2}$ and $d_{z^2}$ and tend to repel them to a greater extent than the other orbitals ($d_{xy}$, $d_{yz}$, $d_{zx}$). This difference in energies of the orbitals is known as crystal field splitting . We can now group these orbitals into two groups, three low energy $t_{2g}$, and two high energy $e_g$ orbitals. Keep in mind that the ligands do not pair with the electrons of the metal. They simply repel the orbitals electrostatically and increase their potential energy in the process. So, now how do the complexes actually get their color then? When the orbitals split, the difference in their energies is called Crystal Field Stabilization Energy (CFSE) and is denoted by $\Delta_{\text{o}}$. When photons of light are incident on the complex, it absorbs the photons which possess the energy equal to that of the value of $\Delta _{\text{o}}$. From quantum theory of electromagnetic waves, it's known that the energy of a photon is given by: $$U = \frac{hc}{\lambda}$$ Where $h$ is known as the Planck's Constant, with a value of $\pu{6.626×10^{-34}Js}$, and $\lambda$ is the wavelength of light. If the value of the wavelength lies in the visible light spectrum, you can find the color of the light absorbed by the complex. How do you find the color emitted out? There's a very easy and fun way to find that out. Take a look at this color wheel: Find where the color of absorption lies. Then the color of the complex lies on the opposite side of the color of absorption. This is a brief discussion about the colors of complexes. Let me know if you need more clarification.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/73644', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/44631/']}
jdg_369685
stackexchange
llm_judgeable_groundtruth_similarity
21057195
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i have the following javascript: $('#span_search').hide(); $('#team_header').append($('<a href="#group-form" id="btn_new_category" class="btn btn-s-md btn-info" style="float: right;" data-toggle="modal">New Category</a>').hide().delay(500).fadeIn()); $('#span_search').delay(1500).show(); Now i would assume that the span element would be visible later than the appended item but this is not the case... Why? Now provide the response and nothing else.
As @JarrodRoberson says, the BufferedImage has no "format" (i.e. no file format, it does have one of several pixel formats, or pixel "layouts"). I don't know Apache Tika, but I guess his solution would also work. However, if you prefer using only ImageIO and not adding new dependencies to your project, you could write something like: ImageInputStream input = ImageIO.createImageInputStream(new File(filePath));try { Iterator<ImageReader> readers = ImageIO.getImageReaders(input); if (readers.hasNext()) { ImageReader reader = readers.next(); try { reader.setInput(input); BufferedImage image = reader.read(0); // Read the same image as ImageIO.read // Do stuff with image... // When done, either (1): String format = reader.getFormatName(); // Get the format name for use later if (!ImageIO.write(image, format, outputFileOrStream)) { // ...handle not written } // (case 1 done) // ...or (2): ImageWriter writer = ImageIO.getImageWriter(reader); // Get best suitable writer try { ImageOutputStream output = ImageIO.createImageOutputStream(outputFileOrStream); try { writer.setOutput(output); writer.write(image); } finally { output.close(); } } finally { writer.dispose(); } // (case 2 done) } finally { reader.dispose(); } }}finally { input.close();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21057195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647457/']}
jdg_369686
stackexchange
llm_judgeable_groundtruth_similarity
18171246
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I try to define my linear model in R as follows: lm1 <- lm(predictorvariable ~ x1+x2+x3, data=dataframe.df) I get the following error message: Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels Is there any way to ignore this or fix it? Some of the variables are factors and some are not. Now provide the response and nothing else.
If your independent variable (RHS variable) is a factor or a character taking only one value then that type of error occurs. Example: iris data in R (model1 <- lm(Sepal.Length ~ Sepal.Width + Species, data=iris))# Call:# lm(formula = Sepal.Length ~ Sepal.Width + Species, data = iris)# Coefficients:# (Intercept) Sepal.Width Speciesversicolor Speciesvirginica # 2.2514 0.8036 1.4587 1.9468 Now, if your data consists of only one species: (model1 <- lm(Sepal.Length ~ Sepal.Width + Species, data=iris[iris$Species == "setosa", ]))# Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : # contrasts can be applied only to factors with 2 or more levels If the variable is numeric ( Sepal.Width ) but taking only a single value say 3, then the model runs but you will get NA as coefficient of that variable as follows: (model2 <-lm(Sepal.Length ~ Sepal.Width + Species, data=iris[iris$Sepal.Width == 3, ]))# Call:# lm(formula = Sepal.Length ~ Sepal.Width + Species, # data = iris[iris$Sepal.Width == 3, ])# Coefficients:# (Intercept) Sepal.Width Speciesversicolor Speciesvirginica # 4.700 NA 1.250 2.017 Solution : There is not enough variation in dependent variable with only one value. So, you need to drop that variable, irrespective of whether that is numeric or character or factor variable. Updated as per comments: Since you know that the error will only occur with factor/character, you can focus only on those and see whether the length of levels of those factor variables is 1 (DROP) or greater than 1 (NODROP). To see, whether the variable is a factor or not, use the following code: (l <- sapply(iris, function(x) is.factor(x)))# Sepal.Length Sepal.Width Petal.Length Petal.Width Species # FALSE FALSE FALSE FALSE TRUE Then you can get the data frame of factor variables only m <- iris[, l] Now, find the number of levels of factor variables, if this is one you need to drop that ifelse(n <- sapply(m, function(x) length(levels(x))) == 1, "DROP", "NODROP") Note: If the levels of factor variable is only one then that is the variable, you have to drop.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18171246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1909752/']}
jdg_369687
stackexchange
llm_judgeable_groundtruth_similarity
730841
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can we take the LaPlace transform of a function, given piece-wise function notation? For example, $f(t)=\begin{cases}0 &\mbox{for } 0<t<2\\ t&\mbox{ for } 2<t\end{cases}$ Frankly, I've read about step-functions but I can't find anything that really breaks down how these should be solved. This question gives hints: Laplace Transformations of a piecewise function But how do we REALLY come up with these integrals? Now provide the response and nothing else.
From the definition of the Laplace transform, and letting $f$ be the example function $$f(t) = \left\{\begin{array}{cc} 0 & 0 < t < 2 \\ t & t \ge 2\end{array}\right.$$we have \begin{align*}L\{f(t)\} &= \int_0^{\infty} e^{-st} f(t) dt \\&= \int_0^2 e^{-st} f(t) dt + \int_2^{\infty} e^{-st} f(t) dt \\&= \int_0^2 e^{-st} \cdot 0 dt + \int_2^{\infty} e^{-st} t dt \\&= \int_2^{\infty} t e^{-st} dt\end{align*} and the Laplace transform follows from just computing the integral. For any general piecewise function for which the integrals make sense, one just integrates the function on each separate interval of definition.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/730841', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/101064/']}
jdg_369688
stackexchange
llm_judgeable_groundtruth_similarity
38918486
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am getting this below Error while i run my protractor. And below is the error as shown in my webstorm console. "C:\Program Files (x86)\JetBrains\WebStorm 2016.2\bin\runnerw.exe" "C:\Program Files\nodejs\node.exe" c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\built\cli.js C:\Users\x216526\workspace_Protractor\SWA_Protractor\conf.js [17:59:58] I/direct - Using ChromeDriver directly... [17:59:58] I/launcher - Running 1 instances of WebDriver [18:00:01] E/launcher - session not created exception from unknown error: Runtime.executionContextCreated has invalid 'context': {"auxData":{"frameId":"9784.1","isDefault":true},"id":1,"name":"","origin":"://"} (Session info: chrome=54.0.2824.0) (Driver info: chromedriver=2.22.397933 (1cab651507b88dec79b2b2a22d1943c01833cc1b),platform=Windows NT 6.1.7601 SP1 x86_64) [18:00:01] E/launcher - SessionNotCreatedError: session not created exception from unknown error: Runtime.executionContextCreated has invalid 'context': {"auxData":{"frameId":"9784.1","isDefault":true},"id":1,"name":"","origin":"://"} (Session info: chrome=54.0.2824.0) (Driver info: chromedriver=2.22.397933 (1cab651507b88dec79b2b2a22d1943c01833cc1b),platform=Windows NT 6.1.7601 SP1 x86_64) at WebDriverError (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:26:26) at SessionNotCreatedError (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:307:26) at Object.checkLegacyResponse (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:639:15) at parseHttpResponse (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\http\index.js:538:13) at c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\http\index.js:472:11 at ManagedPromise.invokeCallback_ (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:1379:14) at TaskQueue.execute_ (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2913:14) at TaskQueue.executeNext_ (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2896:21) at c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2820:25 at c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:639:7 From: Task: WebDriver.createSession() at Function.createSession (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver.js:329:24) at Driver (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\chrome.js:778:38) at Direct.getNewDriver (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\built\driverProviders\direct.js:68:26) at Runner.createBrowser (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\built\runner.js:187:43) at c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\built\runner.js:261:30 at _fulfilled (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:834:54) at self.promiseDispatch.done (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:863:30) at Promise.promise.promiseDispatch (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:796:13) at c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:556:49 at runSingle (c:\Users\x216526\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:137:13) [18:00:01] E/launcher - "process.on('uncaughtException'" error, see launcher [18:00:01] E/launcher - Process exited with error code 199 Process finished with exit code 199 My config js look like below: exports.config = { directConnect: true, // Capabilities to be passed //to the webdriver instance. capabilities: { 'browserName': 'chrome', }, framework: 'jasmine2', specs: ['./src/sli_sanitytests/San1_Check_ Sli_Homepage_is_Accessible_spec.js', './src/sli_sanitytests/San2_ Click_createButton_to_Open_Sli_CreateForm_page_spec.js', './src/sli_sanitytests/San3_ Create_Sli_reference_spec.js' ], suites: { smoke: ['./smoke/!*.spec.js'], regression:['./regression/!*.spec.js'], functional: ['./functional/!*.spec.js'], all: ['./!*!/!*.spec.js'], selected:['./functional/addcustomer.spec.js', './regression/openaccount.spec.js'], }, // Options to be passed to Jasmine jasmineNodeOpts: { //onComplete will be called just before the driver quits. onComplete: null, // If true, display spec names. isVerbose: true, // If true,print colors to the terminal. showColors: true, // If true, include stack traces in //failures. includeStackTrace: true, // Default time to wait in ms //before a test fails. defaultTimeoutInterval: 80000 }, //enter code here onPrepare:function() { browser.ignoreSynchronization = true; browser.driver.manage().window().maximize(); }, } Now provide the response and nothing else.
2016-10-13 : ChromeDriver v2.24 has been released which supports Chrome v52-54. (Thanks @Anton) 2016-08-16 : One of the recent updates to the Chrome Dev channel introduced a bug preventing ChromeDriver from properly starting. Having just worked around the same problem, I would suggest backing up your data and reverting to the Beta or Stable release channel of Chrome. See the Chrome Release Channels for more details on safely switching. Alternatively, switching to the Dev version of ChromeDriver should also fix the issue. From a closed issue on the chromedriver project: There are some Devtool changes in Chrome dev channel v54 which is not currently supported in Chromedriver stable v2.23. You may want to use dev version of Chromedriver which has the fix. It can be downloaded from chromedriver…/continuous/….zip Review the issue for the full link.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38918486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4566024/']}
jdg_369689
stackexchange
llm_judgeable_groundtruth_similarity
33438158
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm mapping over an array and for one of the return values of the new object, I need to make an asynchronous call. var firebaseData = teachers.map(function(teacher) { return { name: teacher.title, description: teacher.body_html, image: urlToBase64(teacher.summary_html.match(/src="(.*?)"/)[1]), city: metafieldTeacherData[teacher.id].city, country: metafieldTeacherData[teacher.id].country, state: metafieldTeacherData[teacher.id].state, studioName: metafieldTeacherData[teacher.id].studioName, studioURL: metafieldTeacherData[teacher.id].studioURL }}); The implementation of that function will look something like function urlToBase64(url) { request.get(url, function (error, response, body) { if (!error && response.statusCode == 200) { return "data:" + response.headers["content-type"] + ";base64," + new Buffer(body).toString('base64'); } });} I'm not clear what's the best approach to do this... promises? Nested callbacks? Use something in ES6 or ES7 and then transpile with Babel? What's the current best way to implement this? Now provide the response and nothing else.
One approach is Promise.all (ES6) . This answer will work in Node 4.0+. Older versions will need a Promise polyfill or library. I have also used ES6 arrow functions, which you could replace with regular function s for Node < 4. This technique manually wraps request.get with a Promise. You could also use a library like request-promise . function urlToBase64(url) { return new Promise((resolve, reject) => { request.get(url, function (error, response, body) { if (!error && response.statusCode == 200) { resolve("data:" + response.headers["content-type"] + ";base64," + new Buffer(body).toString('base64')); } else { reject(response); } }); })} // Map input data to an Array of Promiseslet promises = input.map(element => { return urlToBase64(element.image) .then(base64 => { element.base64Data = base64; return element; })});// Wait for all Promises to completePromise.all(promises) .then(results => { // Handle results }) .catch(e => { console.error(e); })
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33438158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2813041/']}
jdg_369690
stackexchange
llm_judgeable_groundtruth_similarity
209685
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've an HttpHandler, which allows users to login to a system by passing in an encrypted code. Inside the ProcessRequest it performs quite a few steps. Retrieve the encrypted code from request (could be in Form/X-Header/Query) Decrypt it. (Results in an JSON string) Deserialize to a dynamic type Determine the type of request, could be login/register/activate Validate request Load user subscription Load User entity If Req.Type = Login -> Login using FormsAuth If Req.Type = Register -> Create user If Req.Type = Register -> Send Activation email This goes on. Currently this is something like a long if/else statement which I'm trying to refactor.I'm thinking of using the Chain Of Responsibility pattern to convert these steps in if/else to a chain which executes sequentially.However, this will be different from original CoR as only last few steps will actually "handle" the request, first steps will just do some pre-processing and make stage for last steps to perform it's job. My main problem is, different steps in the chain will work on different input data. First few steps (Decryption, Deserialization, etc) will work on strings while latter half should ideally work on deserialized dynamic object. I don't like the way it sounds. Am I trying to fit a round lid to an square bottle? Is this not a scenario where CoR can/should be applied? Are there any other patterns/strategies I could use to solve such scenarios. I thought of using the decorator pattern as well, but that doesn't suite me very well, as I'd like to be able to switch certain steps in and out (ex: email activation) for some scenarios. NOTE: I've seen this question as well, but not sure if it answers my question. Now provide the response and nothing else.
Your ProcessRequest method is doing too much in one block of code. Chain of Responsibility is an inappropriate pattern because some of these steps are mandatory and some are alternatives. Look at the last 3 steps - 8 to 10. Your main method should not care what has to be done for each individual type of request. All that should be happening here is Is the request type in my set of permitted types? If yes, invoke the corresponding class If no, handle the error. That's going to be a very short block of code. It does require you, somewhere else in your code, to create your request-type-specific class (and subclasses) and the set to contain them, but the benefit is that this block of code in your main method need never change. Step 5 should be a method of the type-specific class. Steps 6 and 7 can probably be encapsulated in a User object but also only mean something for existing users, so the User-object handling stuff should go inside the type-specific class. So we've already reduced the code to Retrieve the encrypted code from request (could be in Form/X-Header/Query) Decrypt it. (Results in an JSON string) Deserialize to a dynamic type Determine the type of request, could be login/register/activate if type in set-of-allowed-types then request-type = new type-specific-class else fail. if not request-type.validate() then fail request-type.dostuff() See? No patterns involved. If-then-else chains are a bad smell, yes, but they can usually be replaced with a set of valid options or a switch statement. Try that simple approach before going all pattern-mad.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/209685', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/100724/']}
jdg_369691
stackexchange
llm_judgeable_groundtruth_similarity
166830
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I solve the following integral equation for $f(x)$ on $x \in [0,1]$? $$ (f(x) -x) \int_0^1 \left( \frac{\mathrm e^{2-2f(x)}}{\left(\mathrm e^{1-f(x)}+\mathrm e^{1-f(y)}\right)^2}- \frac{\mathrm e^{1-f(x)}}{\mathrm e^{1-f(x)}+\mathrm e^{1-f(y)}} \right) \mathrm dy + \int_0^1 \frac{\mathrm e^{1-f(x)}}{\mathrm e^{1-f(x)}+\mathrm e^{1-f(y)}} \mathrm dy= 0 $$ (f[x] - x)*Integrate[Exp[2 - 2 f[x]]/(Exp[1 - f[x]] + Exp[1 - f[y]])^2 - Exp[1 - f[x]]/(Exp[1 - f[x]] + Exp[1 - f[y]]), {y, 0, 1}] + Integrate[Exp[1 - f[x]]/(Exp[1 - f[x]] + Exp[1 - f[y]]), {y, 0, 1}] == 0 Because of the exponential function inside the integral, I don't see how I could transform this into a differential equation to solve with NDSolve. Now provide the response and nothing else.
With some effort you can find numerical solution. Let us discretize function f at num points, e.g. num=3 . Then, select some integration rule, e.g. Lobatto one: {ab, w, err} = NIntegrate`LobattoRuleData[num, 4](* {{0, 0.5000, 1.000}, {0.1667, 0.667, 0.1667}, {}} *) Next, replace Integrate with Sum at points ab with weights w and create Table of num equations evaluating at x given by ab : sys = Table[ (f[x] - x)* Sum[(Exp[2 - 2 f[x]]/(Exp[1 - f[x]] + Exp[1 - f[y]])^2 - Exp[1 - f[x]]/(Exp[1 - f[x]] + Exp[1 - f[y]]))* w[[Position[ab, y][[1, 1]]]], {y, ab}] + Sum[Exp[1 - f[x]]/(Exp[1 - f[x]] + Exp[1 - f[y]])* w[[Position[ab, y][[1, 1]]]], {y, ab}], {x, ab}]; Now, create list of unknowns with some starting values: vars = Table[{f[x], 2 + 1/2 x}, {x, ab}](* {{f[0], 2}, {f[0.5000], 2.2500}, {f[1.000], 2.5000}} *) and use FindRoot to solve system sys : FindRoot[sys, vars](* {f[0] -> 2.28088, f[0.5000] -> 2.51548, f[1.000] -> 2.78091} *) To get more acurate solution you have to increase num and precision of Lobatto rule abscissas and weights. Using num=64 and 32-digit precision I was able to solve original equation down to $MachineEpsilon . Result appear to be roughly linear with rapidly converging polynomial series, starting with: f[x] = 2.28093 + 0.440941 x + 0.0538753 x^2 + 0.00521441 x^3 + 0.000168599 x^4
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/166830', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/11020/']}
jdg_369692
stackexchange
llm_judgeable_groundtruth_similarity
34502058
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an iOS project with a lot of pods, around twenty. I want to integrate a watchOS 2 app in, but CocoaPods requires that the podspec contain support for watchOS (as seen here: http://blog.cocoapods.org/CocoaPods-0.38/ ) At first, I thought I could fork all of the pods that aren't updated, point my podfile to those forked repos, and bob's your uncle. The problem is that some of the pods that I'm using are closed/not-public. Is there a way for me to not build the main application's pods for the watchOS target? Like using target isolation like so?: target "Watch" doend I can't seem to get that ^ potential solution to build, as it still tries to build the pods. I've also tried this repo, no luck: https://github.com/orta/cocoapods-expert-difficulty Now provide the response and nothing else.
There are two way to integrate pods using podfile with WathOS. 1) Add Required pods directly to watch extension as below. target '<your watch Extension Name>' doplatform :watchos, '2.0'pod 'RealmSwift'pod 'Alamofire'pod 'MMWormhole', '~> 2.0.0'end 2) Create Shared pods and add to both watch extension and iOS target both. def sharedPods pod 'RealmSwift' pod 'Alamofire'endtarget '<your watch Extension Name>' doplatform :watchos, '2.0' sharedPodsendtarget '<your iOSApp Name>' doplatform :ios, '8.0' sharedPodsend Add only watchOS and iOS supported pods in sharedPods , Do not add pods in sharedPods which does not support watchOS. e.g. def sharedPods pod 'RealmSwift' pod 'Alamofire' pod 'otherWatchOS&iOS supported Pod1' pod 'otherWatchOS&iOS supported Pod2' end Add only iOS supported pods in target '<your iOSApp Name>' e.g. target '<your iOSApp Name>' doplatform :ios, '8.0' sharedPods pod 'otherOnlyiOS supported Pod1' pod 'otherOnlyiOS supported Pod2'end So, this way you can add required pods for required targets.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34502058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2367555/']}
jdg_369693
stackexchange
llm_judgeable_groundtruth_similarity
81935
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Colour - and eyesight in general - arises because objects reflect/transmit certain wavelengths of colour, which is detected by our eyes. On the other hand, what gives rise to smell? Is there a branch of chemistry associated with this? Is it possible to define the smell of any substance, using some parameters analogous to wavelength in the case of sight? We know that $\ce{H2S}$ has a foul odor, but distilled $\ce{H2O}$ does not have any strong smell. Does $\ce{H2Se}$ have a similar foul smell? Now provide the response and nothing else.
As a sensation, olfaction does not seem to possess the same status as, say, vision. Most biologists, indeed most people not directly involved with fragrances or flavours seem to think that odour sensation is “subjective” and not necessarily shared by others. What makes an odourant? The general requirements for an odourant are that it should be volatile , hydrophobic and have a molecular weight less than approximately 300 daltons . The first two requirements make physical sense, for the molecule has to reach the nose and may need to cross membranes. The size requirement appears to be a biological constraint. A further indication that the size limit has something to do with the chemoreception mechanism comes from the fact that specific anosmias become more frequent as molecular size increases. To be sure, vapor pressure (volatility) falls rapidly with molecular size, butthat cannot be the reason why larger molecules have no smell, since some of thestrongest odourants (e.g. some steroids) are large molecules. Additionally, the cut-off isvery sharp indeed e.g substitution of the slightly larger silicon atom for acarbon in a benzenoid musk causes it to become odourless. Comparison of molecular size between a benzenoid musk (left) derived fromacetophenone and its sila counterpart ( right) in which the central carbon atom in the t-butylgroups has been replaced with Si. The carbon musk is a strong odourant, the sila musk odourless. Attempts have been made to accommodate discrepant structure-odour relations by a process known as conformational analysis. This involves exploring the space of conformations adopted by the odourant molecule when deformed away from its energy minimum. Odour descriptors and odour profiles Odour descriptors are the words that come to mind when smelling a substance.The more generally understood the words are, the more useful they are as descriptors. In practice, it is easy for any observer, after a little training, to use the standard descriptors of fragrance chemistry. Example of descriptors include musky, camphoraceous etc Smelling chemical groups A fact that has, in our opinion, received too little attention from olfaction researchers is the ability of humans to detect the presence of functional groups with great reliability. The case of thiols ($\ce{-SH}$) is familiar, but groups ($\ce{NO2}$), aldehydes ($\ce{C=O(H)}$), can be reliably identified once the odour character the functional group character confers is known. When nitriles are used as chemically stable replacement for aldehydes, they impart a metallic character to any smell: cumin nitrile smells like metallic cumin (cuminaldehyde), citronellyl nitrile smells like metallic lemongrass (citronellal), and nonadienylnitrile smells like metallic cucumber (nonadienal). Oximes give a green-camphoraceous character, isonitriles a flat metallic character of great power and unpleasantness, nitro groups a sweet-ethereal character,etc. Here are some odour categories and their representative molecules, chosen to illustratestructural diversity : Musk Musk odour descriptors might be “smooth clean, sweet and powdery”. The molecules that possess this odour character are exceptionally diverse in structure. Macrocyclic musks contain a 15-18 carbon cycle closed either by a carbonyl or by a lactone and smell similar but fresher and more natural, often with fruity overtones (cyclopentadecanolide, ambrettolide). Nitro musks, discovered originally as a byproduct of explosives chemistry, smell sweeter and are reminiscent of old-fashioned barbershop smells. Representatives from five chemical classes which yield musk odors. 1 androst-16-en-3a-ol, a steroid musk. 2: ambrettolide, a macrocyclic musk. 3: Musk Bauer, a nitro musk. 4: Tonalid, atetralin musk. 4: Traseolide, a indane musk. Ambergris Originally derived from concretions spat out by whales and aged in the sun, ambergris odorants smell nothing like natural ambergris tincture, which has a weak animalic marine smell. The smell of ambergris odorants was once aptly described to us by a chemist-perfumer as “glorified isopropanol”. Ambergris odourants provide an interesting combination of very closely related smells with widely different structures: amberketal, timberol, karanal and cedramber Two ambergris odorants, timberol (left) and cedramber (right) Bitter almonds This easily-recognized category is interesting because it includes a small molecule (HCN) which, however, is perceived by a large fraction of observers to smell as metallic not almond-like to. Benzaldehyde, nitrobenzene,trans-2-hexenal (but see above) are good examples. The complexity of structure-odour relations, and the fact that the three dimensional structure of the receptor site is unknown, make it very difficult to apply conventional quantitative structure activity relationships. Plausible theories of odour Many theories of Structure-odour relations (SORs) have been proposed in the past (reviewed in Moncrieff, 1951) but advances in biological understanding, not least the discovery of odourant receptors, have gradually ruled them out. There appears to be two possible types of SOR theory left standing: Shape-based theories: Odotopes Most enzyme-substrate and receptor-ligand binding relies on molecular recognition between protein and ligand. Recognition depends on interactions that can be either attractive or repulsive (Davies and Timms 1998). All attractive chemical interactions are ultimately electrostatic in nature whether they occur between fixed charges, dipoles, induced dipoles or atoms able to form weak electron bonds (e.g. hydrogen bonds). Repulsive interactions can be electrostatic or quantum-mechanical (electron shell exchange repulsion). Almost every change in molecular structure (with some exceptions which will described below) alters the set of surface features capable of forming such attractive or repulsive interactions, and thus affects what we loosely call molecular shape. Recently, both in vivo and vitro studies have shown that, generally receptors respond to more than one odourant, suggesting that they detect the presence not of the whole molecule but of a partial structural feature thereof, hence odotopes. According to odotope theory the smell of a molecule is then due to the pattern, i.e. the relative excitation of a number N of receptors to which it binds. Ethyl citronellyl oxalate, a molecule possessing a macrocyclic musk odour but linearin shape. Right: a macrocyclic musk, cyclopentadecanolide. Shape-based theories assume that the linear musk assumes a conformation close to that of the macrocyclic when binding to the receptor, hence the similarity in odour. Vibration theories The idea that the nose operates as a vibrational spectroscope was first proposed by Dyson (1938) and later taken up and refined by Wright (1982). What makes it attractive in principle is that vibrational spectra share three properties with human olfaction. No two molecular spectra are exactly alike, particularly in the aptly named“fingerprint region”. Many functional groups are easily identified by their specificvibrational frequencies. System utilizing a physical property as basic as vibration will be ready for never-before-smelt molecules, i.e. does not depend on a repertory of existing or expected structures. In that sense, it does not rely on molecular recognition. Remarkably, even bonds between atoms can be detected: the acetylenic C-C triple bond of –ynes imparts a isothiocyanate-like mustard-like smell to molecules which is clearly recognizable, for example in acetylene and in methyloctynoate. Functional groups as odotopes An odotope theory can explain these regularities only by assuming that thefunctional group is an odotope. In the older structure-odour literature, this used to bedescribed as electronic factors (as opposed to steric). The idea was that, given that manyfunctional groups were similar in size, the recognition mechanism must somehow besensitive to the fine structure of the electron distribution (orbital energies, chargedensity, etc) of the functional group. However this proposition has some shortfalls; Consider for instance the SH group in, say methanethiol. Alcohols never smell ofsulfur, whereas thiols always do. What could make the SH infallibly distinctive as anodotope, as compared to the OH group? Partial charge, bond length, bond angle andatom size are somewhat different between $\ce{R–SH}$ and $\ce{R–OH}$, but it is hard to see howthese can be detected with absolute reliability by, say, an aminoacid side chain in thepresence of thermal motion. Replacing a C=C bond with a sulfur atom does not change odour character, suggesting that “electronic” properties of sulfur are not sufficient for molecular recognition. Functional groups and vibrational theory By contrast, the distinctive smell of functional groups is a natural feature of avibrational theory. Above 1800 wavenumbers, IR absorption lines are diagnostic of thestretch frequencies of diatomic functional groups. The clearest example so far is that of boranes. The terminal B-H bond in boranes has a stretch frequency whose range overlaps with that of thiols. Turin (1996) therefore predicted that boranes should smell sulfuraceous, despite the complete absence of similarity, both structurally and chemically, between boron and sulfur. A comparison between borane and thiol smells is best made using decaborane. Decaborane smells strongly of boiled onion, a typical SH smell. Other, less stable boranes share this sulfuraceous smell character; The dependence of the sulfuraceous character on molecular vibrations and atomic partial charges, as predicted by a vibrational theory. Decaborane (left) smells sulfuraceous, and its terminal B-H bonds have a stretch frequency ˜ 2500 wavenumbers. In triethylamine-borane (middle), the B-H stretch is shifed to 2300 wavenumbers and the sulfuraceous smell is no longer present. In p-carborane (right) the near-neutral partial charges make the SH bond odourless. In summary it it could said there is still more work needed on study of structure-odour chemistry to have conclusive evidence on the best theory, currently vibrational theory is evidently successful at explaining the fact that we smell functional groups even when sterically hindered, and in accounting for differences in smell between isotopes, while the odotope theory explains little. References Structure-odour relations: a modern perspective: Luca Turin et al. [Available online: https://pubs.acs.org/doi/abs/10.1021/cr950068a]
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/81935', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/51324/']}
jdg_369694
stackexchange
llm_judgeable_groundtruth_similarity
21467257
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having some trouble calculating if time is past 15 minutes, on a date and time in my database. How can I check this? I have this in my database (example): 2014-01-30 15:29:31 And then I get the date from PHP: $date = date("Y-m-d H:i:s"); But how can I check if the time has passed 15 minutes, or if it's a different day? I have this code so far: $date = date("Y-m-d H:i:s");$sql = "SELECT date FROM reset WHERE session_id = '".$sessid."' limit 1";$result = mysql_query($sql);$value = mysql_fetch_object($result);$dbdate = $value->date;$checkdate = strtotime($dbdate);if ($checkdate - time() > 15 * 60) { error_log("15 mins passed");} Now provide the response and nothing else.
You can convert the date to a timestamp with strtotime (which supports the MySQL date format) and then compare it to the current timestamp from time . $dbtimestamp = strtotime($datefromdb);if (time() - $dbtimestamp > 15 * 60) { // 15 mins has passed} To compare the dates, you can use date to get the year/month/day from the timestamp and then compare them against the current date. if (date("Y-m-d", $dbtimestamp) != date("Y-m-d")) { // different date}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21467257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2912622/']}
jdg_369695
stackexchange
llm_judgeable_groundtruth_similarity
6279852
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to creating a combobox with checkboxes on each line to allow multiple selecting. Would this be better as a User Control or Custom Control? I haven't created a control before so just looking for a little advice on what direction I need to head. Thanks. Now provide the response and nothing else.
UserControl (Composition) Composes multiple existing controls into a reusable "group" Consists of a XAML and a code behind file Cannot be styled/templated Derives from UserControl CustomControl (Extending an existing control) Extends an existing control with additional features Consists of a code file and a default style in Themes/Generic.xaml Can be styled/templated The best approach to build a control library In your case, I think UserControl would be better; here's an example for you: <CheckBox Content="Property" IsChecked="{Binding Path=SomeProperty}" /><ComboBox IsEnabled="{Binding Path=Enabled}" />
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6279852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/482138/']}
jdg_369696
stackexchange
llm_judgeable_groundtruth_similarity
11217878
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I create a decorator for an abstract class method in Python 2.7? Yes, this is similar to this question , except I would like to combine abc.abstractmethod and classmethod , instead of staticmethod . Also, it looks like abc.abstractclassmethod was added in Python 3 (I think?) , but I'm using Google App Engine, so I'm currently limited to Python 2.7 Thanks in advance. Now provide the response and nothing else.
Here's a working example derived from the source code in Python 3.3's abc module: from abc import ABCMetaclass abstractclassmethod(classmethod): __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super(abstractclassmethod, self).__init__(callable)class DemoABC: __metaclass__ = ABCMeta @abstractclassmethod def from_int(cls, n): return cls()class DemoConcrete(DemoABC): @classmethod def from_int(cls, n): return cls(2*n) def __init__(self, n): print 'Initializing with', n Here's what it looks like when running: >>> d = DemoConcrete(5) # Succeeds by calling a concrete __init__()Initializing with 5>>> d = DemoConcrete.from_int(5) # Succeeds by calling a concrete from_int()Initializing with 10>>> DemoABC() # Fails because from_int() is abstract Traceback (most recent call last): ...TypeError: Can't instantiate abstract class DemoABC with abstract methods from_int>>> DemoABC.from_int(5) # Fails because from_int() is not implementedTraceback (most recent call last): ...TypeError: Can't instantiate abstract class DemoABC with abstract methods from_int Note that the final example fails because cls() won't instantiate. ABCMeta prevents premature instantiation of classes that haven't defined all of the required abstract methods. Another way to trigger a failure when the from_int() abstract class method is called is to have it raise an exception: class DemoABC: __metaclass__ = ABCMeta @abstractclassmethod def from_int(cls, n): raise NotImplementedError The design ABCMeta makes no effort to prevent any abstract method from being called on an uninstantiated class, so it is up to you to trigger a failure by invoking cls() as classmethods usually do or by raising a NotImplementedError . Either way, you get a nice, clean failure. It is probably tempting to write a descriptor to intercept a direct call to an abstract class method, but that would be at odds with the overall design of ABCMeta (which is all about checking for required methods prior to instantiation rather than when methods are called).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11217878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1319944/']}
jdg_369697
stackexchange
llm_judgeable_groundtruth_similarity
30590
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: On a remote machine I changed my zsh settings and it is now broken, for every keypress it says: "url-quote-magic:1: url-quote-magic: function definition file not found " I don't have another account on that machine, What can I do to disable the faulty .zshrc so that I can use my shell again and fix it. Now provide the response and nothing else.
You can run a command on the remote server without logging in like this: ssh -lUSERNAME SERVER COMMAND e.g. ssh -lsomeuser someserver 'mv .zshrc .zshrc.bak' The command given as last argument to ssh will be executed by a non-interactive shell and commands from .zshrc are only executed by interactive shells (see zsh manpage , section on startup and shutdown files).
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/30590', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/3850/']}
jdg_369698
stackexchange
llm_judgeable_groundtruth_similarity
54544978
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm setting up Django to send a JWT Response as opposed to a view. I tried using django-rest-framework-simplejwt. Provided in this framework, there is a function TokenObtainPairView.as_view() that returns a pair of jwt. I need to return the access token with another Json response as opposed to the two tokens provided. Ideally I would like one JsonResponse that contains an access token that is the same as this one: TokenObtainPairView.as_view() . I tried creating my own view which is provided below. UPDATE: Provided in Settings.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(days=1), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),} Login URL Path urlpatterns = [ path('auth/', views.LoginView.as_view()),] LoginView I created class LoginView(APIView): permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): username = request.data['username'] password = request.data['password'] user = authenticate(username=username, password=password) if user is not None: payload = { 'user_id': user.id, 'exp': datetime.now(), 'token_type': 'access' } user = { 'user': username, 'email': user.email, 'time': datetime.now().time(), 'userType': 10 } token = jwt.encode(payload, SECRET_KEY).decode('utf-8') return JsonResponse({'success': 'true', 'token': token, 'user': user}) else: return JsonResponse({'success': 'false', 'msg': 'The credentials provided are invalid.'}) Pattern provided by framework. urlpatterns = [...path('token/', TokenObtainPairView.as_view()),...] It returns this token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTQ5NDk3NDQ2LCJqdGkiOiI3YmU4YzkzODE4MWI0MmJlYTFjNDUyNDhkNDZmMzUxYSIsInVzZXJfaWQiOiIwIn0.xvfdrWf26g4FZL2zx3nJPi7tjU6QxPyBjq-vh1fT0Xs eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU0OTQ5NzQ0NiwianRpIjoiOTNhYzkxMjU5NmZkNDYzYjg2OGQ0ZTM2ZjZkMmJhODciLCJ1c2VyX2lkIjoiMCJ9.dOuyuFuMjkVIRI2_UcXT8_alCjlXNaiRJx8ehQDIBCg If you go to https://jwt.io/ you will see what's returned Now provide the response and nothing else.
For example : to customize simpleJWT response by adding username and groups, Override the validate method in TokenObtainPairSerializer # project/views.pyfrom rest_framework_simplejwt.serializers import TokenObtainPairSerializerfrom rest_framework_simplejwt.views import TokenObtainPairViewclass MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) # Add extra responses here data['username'] = self.user.username data['groups'] = self.user.groups.values_list('name', flat=True) return dataclass MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer replace the login view with customized view # project/urls.pyfrom .views import MyTokenObtainPairViewurlpatterns = [ # path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),] References: SimpleJWT Readme and the source code as below:
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54544978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4322850/']}
jdg_369699
stackexchange
llm_judgeable_groundtruth_similarity
6605006
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to use the command line program convert to take a PDF into an image (JPEG or PNG). Here is one of the PDFs that I'm trying to convert. I want the program to trim off the excess white-space and return a high enough quality image that the superscripts can be read with ease. This is my current best attempt . As you can see, the trimming works fine, I just need to sharpen up the resolution quite a bit. This is the command I'm using: convert -trim 24.pdf -resize 500% -quality 100 -sharpen 0x1.0 24-11.jpg I've tried to make the following conscious decisions: resize it larger (has no effect on the resolution) make the quality as high as possible use the -sharpen (I've tried a range of values) Any suggestions please on getting the resolution of the image in the final PNG/JPEG higher would be greatly appreciated! Now provide the response and nothing else.
It appears that the following works: convert \ -verbose \ -density 150 \ -trim \ test.pdf \ -quality 100 \ -flatten \ -sharpen 0x1.0 \ 24-18.jpg It results in the left image . Compare this to the result of my original command ( the image on the right ): (To really see and appreciate the differences between the two, right-click on each and select "Open Image in New Tab..." .) Also keep the following facts in mind: The worse, blurry image on the right has a file size of 1.941.702 Bytes (1.85 MByte).Its resolution is 3060x3960 pixels, using 16-bit RGB color space. The better, sharp image on the left has a file size of 337.879 Bytes (330 kByte).Its resolution is 758x996 pixels, using 8-bit Gray color space. So, no need to resize; add the -density flag. The density value 150 is weird -- trying a range of values results in a worse looking image in both directions!
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/6605006', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/246856/']}
jdg_369700
stackexchange
llm_judgeable_groundtruth_similarity
7248237
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What's the best way to implement user activity in symfony 2 ? And how to do it ? I know there is the event system of symfony 2. Maybe I should trigger an event ? And is it wise to update on every page request or are there other (better) ways to update user activity ? Now provide the response and nothing else.
Good way to track user requests (and possibly their activity) is to listen to kernel.request event: Listener class: namespace Acme\YourBundle\EventListener;use Symfony\Component\HttpKernel\Event\GetResponseEvent;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\DependencyInjection\ContainerInterface;class RequestListener{ /** * Container * * @var ContainerInterface */ protected $container; /** * Listener constructor * * @param ContainerInterface $container */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * kernel.request Event * * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); // Here you can intercept all HTTP requests, and through $container get access to user information }} Configuration for the listener: <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <parameters> <parameter key="acme.request_listener.class">Acme\YourBundle\EventListener\RequestListener</parameter> </parameters> <services> <service id="acme.request_listener" class="%acme.request_listener.class%"> <tag name="kernel.event_listener" event="kernel.request" method="onKernelRequest" /> <argument type="service" id="service_container" /> </service> </services></container> You can get more info on this topic in the official Symfony documentation: Symfony: Internal requests Symfony: Service container
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7248237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47603/']}
jdg_369701
stackexchange
llm_judgeable_groundtruth_similarity
10569438
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to make a dictionary where English words point to Russian and French translations. How do I print out unicode characters in Python? Also, how do you store unicode chars in a variable? Now provide the response and nothing else.
To include Unicode characters in your Python source code, you can use Unicode escape characters in the form \u0123 in your string. In Python 2.x, you also need to prefix the string literal with 'u'. Here's an example running in the Python 2.x interactive console: >>> print u'\u0420\u043e\u0441\u0441\u0438\u044f'Россия In Python 2, prefixing a string with 'u' declares them as Unicode-type variables, as described in the Python Unicode documentation . In Python 3, the 'u' prefix is now optional: >>> print('\u0420\u043e\u0441\u0441\u0438\u044f')Россия If running the above commands doesn't display the text correctly for you, perhaps your terminal isn't capable of displaying Unicode characters. These examples use Unicode escapes ( \u... ), which allows you to print Unicode characters while keeping your source code as plain ASCII. This can help when working with the same source code on different systems. You can also use Unicode characters directly in your Python source code (e.g. print u'Россия' in Python 2), if you are confident all your systems handle Unicode files properly. For information about reading Unicode data from a file, see this answer: Character reading from file in Python
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10569438', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547646/']}
jdg_369702
stackexchange
llm_judgeable_groundtruth_similarity
165626
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: While reading MS SDL (Microsoft Security Development Lifecycle) presentations I found a recommendation to replace UDP with TCP in applications because TCP is more secure than UDP. But both of them are only transport layers, nothing more. So why is TCP more secure than UDP? Now provide the response and nothing else.
To send data to an application using TCP, you first have to establish a connection. Until the connection is established, packets only get to the OS layer, not the application. Establishing a connection requires that you receive packets back to the initiating end. If you wanted to forge an IP address not on your own network and establish a TCP connection, you'd need to be able to intercept the packets the other side sent out. (you need to be "in between" the endpoint, and where the packets to the forged IP address would normally go, or do some other clever routing tricks.) UDP has no connection, so you can forge a packet with an arbitrary IP address and it should get to the application. You still won't get packets back unless you're in the right "place" of course. Whether this matters or not depends on the security you put in the application. If you were to trust certain IP addresses more than others inside the application, this may be a problem. So in that sense, TCP is more "secure" than UDP. Depending on the application, this may or may not be relevant to security. In and of itself it's not a good reason to replace UDP with TCP since there's other tradeoffs involved between the two protocols.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/165626', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/122176/']}
jdg_369703
stackexchange
llm_judgeable_groundtruth_similarity
1007184
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How would I go about marking one folder for deletion when the system reboots, using C#. Thanks, Now provide the response and nothing else.
Originally from: http://abhi.dcmembers.com/blog/2009/03/24/mark-file-for-deletion-on-reboot/ Documentation: https://learn.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-movefileexa#parameters ////// Consts defined in WINBASE.H///[Flags]internal enum MoveFileFlags{ MOVEFILE_REPLACE_EXISTING = 1, MOVEFILE_COPY_ALLOWED = 2, MOVEFILE_DELAY_UNTIL_REBOOT = 4, //This value can be used only if the process is in the context of a user who belongs to the administrators group or the LocalSystem account MOVEFILE_WRITE_THROUGH = 8}/// <summary>/// Marks the file for deletion during next system reboot/// </summary>/// <param name="lpExistingFileName">The current name of the file or directory on the local computer.</param>/// <param name="lpNewFileName">The new name of the file or directory on the local computer.</param>/// <param name="dwFlags">MoveFileFlags</param>/// <returns>bool</returns>/// <remarks>http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx</remarks>[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll",EntryPoint="MoveFileEx")]internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName,MoveFileFlags dwFlags);//Usage for marking the file to delete on rebootMoveFileEx(fileToDelete, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1007184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_369704
stackexchange
llm_judgeable_groundtruth_similarity
286767
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can a cosmological constant be a candidate for dark energy if the universe is flat? Doesn't a cosmological constant in EFE give rise to positive/negative or no curvature to the universe? I mean, the EFE with a negative/positive cosmological constant provide anti-de-sitter and de-sitter space, which are negatively/positively curved, respectively. Since the observed universe is very close to being flat, how can a cosmological constant be a candidate for dark energy? Would we not then observe some significant curvature to the universe? Now provide the response and nothing else.
In a word, No: a cosmological constant does not guarantee your space is not flat. Take the metric$$ds^2 = -dt^2 + e^{2Ht}(dx^2 + dy^2 + dz^2).$$ This is the flat slicing of De Sitter space (you can find it in "S.W. Hawking and G.F.R. Ellis, The large scale structureof space-time (Cambridge University Press, Cambridge,England, 1973)" pag 125 and following): De Sitter space is partitioned into two flat regions along a diagonal cut. You can read a good discussion of this in "Steady-State Eternal Inflation" byAnthony Aguirre and Steven Gratton ( https://arxiv.org/pdf/astro-ph/0111191.pdf ). You also find a good picture there: FIG. 1 on page 2. The point is that you can always see a CC as a new type of "exotic field", which, then, is brought on the right side of EFE and, if it cancels out neatly with the energy-stress tensor of matter (in our universe, it looks like it does), makes null the curvature. This particular spacetime (the flat slicing of De Sitter space) was used by Hoyle and Narlikar as the setting of the steady state model: it is not geodesically complete, but Aguirre and Gratton argue that the two flat regions cannot communicate without causality violation.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/286767', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/124897/']}
jdg_369705
stackexchange
llm_judgeable_groundtruth_similarity
374395
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that derivative couplings in a Lagrangian interaction, such as $$\mathcal{L}_{int} = \lambda \phi (\partial_{\mu}\phi)(\partial^{\mu}\phi)$$ bring down two momentum factors into the matrix element $\mathcal{M}$. Why doesn't this extend to a typical kinetic term $$\mathcal{L}_{kin} = (\partial_{\mu}\phi)(\partial^{\mu}\phi)\quad ?$$ It seems odd that derivatives in $\mathcal{L}_{int}$ contribute a factor of momentum$^2$ to $\mathcal{M}$, but the derivatives in $\mathcal{L}_{kin}$ contribute a factor of the propagator $$\frac{1}{\mbox{momentum}^2}$$ to $\mathcal{M}$. Now provide the response and nothing else.
This has to do with how we set up perturbation theory, treating part of the Lagrangian as "free" and hence treated exactly, and the rest as the "perturbation". As a very simple example. consider the Gaussian integral $$I = \int_{-\infty}^\infty dx \, e^{-a^2 x^2 - \epsilon^2 x^2}.$$ The exact value of this integral is $$I = \sqrt{\frac{\pi}{a^2 + \epsilon^2}}$$ where both $a$ and $\epsilon$ end up in the denominator. On the other hand, we can think of $e^{-a^2 x^2}$ as the "free" part and $e^{-\epsilon^2 x^2}$ as the "perturbation". Then to lowest order in $\epsilon$ , $$I \approx \int_{-\infty}^\infty dx \, e^{-a^2 x^2} (1 - \epsilon^2 x^2) = \frac{\sqrt{\pi}}{a} - \frac{\sqrt{\pi}}{2a^3} \epsilon^2.$$ So while $\epsilon$ was originally in the denominator, by treating it as a perturbation it ends up in the numerator; this is clear by just Taylor expanding our exact expression for $I$ . By summing up all the contributions, $\epsilon$ ends up back in the denominator as expected. Essentially the same thing is happening when you derive the Feynman rules with the path integral formulation. This is most visible in renormalized perturbation theory where the very same kinetic term appears in both the "free" and "perturbation" parts.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/374395', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
jdg_369706
stackexchange
llm_judgeable_groundtruth_similarity
4361173
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Looks like it's easy to add custom HTTP headers to your websocket client with any HTTP header client which supports this, but I can't find how to do it with the web platform's WebSocket API. Anyone has a clue on how to achieve it? var ws = new WebSocket("ws://example.com/service"); Specifically, I need to be able to send an HTTP Authorization header. Now provide the response and nothing else.
Updated 2x Short answer: No, only the path and protocol field can be specified. Longer answer: There is no method in the JavaScript WebSockets API for specifying additional headers for the client/browser to send. The HTTP path ("GET /xyz") and protocol header ("Sec-WebSocket-Protocol") can be specified in the WebSocket constructor. The Sec-WebSocket-Protocol header (which is sometimes extended to be used in websocket specific authentication) is generated from the optional second argument to the WebSocket constructor: var ws = new WebSocket("ws://example.com/path", "protocol");var ws = new WebSocket("ws://example.com/path", ["protocol1", "protocol2"]); The above results in the following headers: Sec-WebSocket-Protocol: protocol and Sec-WebSocket-Protocol: protocol1, protocol2 A common pattern for achieving WebSocket authentication/authorization is to implement a ticketing system where the page hosting the WebSocket client requests a ticket from the server and then passes this ticket during WebSocket connection setup either in the URL/query string, in the protocol field, or required as the first message after the connection is established. The server then only allows the connection to continue if the ticket is valid (exists, has not been already used, client IP encoded in ticket matches, timestamp in ticket is recent, etc). Here is a summary of WebSocket security information: https://devcenter.heroku.com/articles/websocket-security Basic authentication was formerly an option but this has been deprecated and modern browsers don't send the header even if it is specified. Basic Auth Info (Deprecated - No longer functional) : NOTE: the following information is no longer accurate in any modern browsers. The Authorization header is generated from the username and password (or just username) field of the WebSocket URI: var ws = new WebSocket("ws://username:password@example.com") The above results in the following header with the string "username:password" base64 encoded: Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= I have tested basic auth in Chrome 55 and Firefox 50 and verified that the basic auth info is indeed negotiated with the server (this may not work in Safari). Thanks to Dmitry Frank's for the basic auth answer
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4361173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/73987/']}
jdg_369707
stackexchange
llm_judgeable_groundtruth_similarity
34407437
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given std::bitset<64> bits with any number of bits set and a bit position X (0-63) What is the most efficient way to count bits at position X or lower or return 0 if the bit at X is not set Note: If the bit is set the return will always be at least 1 The brute force way is very slow: int countupto(std::bitset<64> bits, int X){ if (!bits[X]) return 0; int total=1; for (int i=0; i < X; ++i) { total+=bits[i]; } return total;} The count() methof of bitset will give you the popcount of all the bits, but bitset does not support ranges Note: This is not a dup of How to count the number of set bits in a 32-bit integer? as that asks about all bits not the range 0 through X Now provide the response and nothing else.
This C++ gets g++ to emit very good x86 ASM (godbolt compiler explorer) . I expect it will compile efficiently on other 64bit architectures, too (if there's a HW popcount for std::bitset::count to use, otherwise that'll always be the slow part; e.g. sure to use g++ -march=nehalem or higher, or -mpopcnt if you don't want to enable anything else, if you can limit your code to only running on CPUs that support that x86 instruction): #include <bitset>int popcount_subset(std::bitset<64> A, int pos) { int high_bits_to_eliminate = 63 - pos; A <<= (high_bits_to_eliminate & 63); // puts A[pos] at A[63]. return (A[63]? ~0ULL : 0) & A.count(); // most efficient way: great code with gcc and clang // see the godbolt link for some #ifdefs with other ways to do the check, like // return A[BSET_SIZE-1] ? A.count() : 0;} This probably isn't optimal on 32bit architectures, so compare other alternatives if you need to make a 32bit build. This will work for other sizes of bitset , as long as you do something about the hard-coded 63 s, and change the & 63 mask for the shift count into a more general range-check. For optimal performance with strange size bitsets, make a template function with a specialization for size <= register width of the target machine. In that case, extract the bitset to an unsigned type of the appropriate width, and shift to the top of the register instead of the top of the bitset. You'd expect this to also generate ideal code for bitset<32> , but it doesn't quite. gcc/clang still use 64bit registers on x86-64. For large bitsets, shifting the whole thing will be slower than just popcounting the words below the one containing pos , and using this on that word. (This is where a vectorized popcount really shines on x86 if you can assume SSSE3 but not the popcnt insn hardware support, or for 32bit targets. AVX2 256bit pshufb is the fastest way to do bulk popcounts, but without AVX2 I think 64bit popcnt is pretty close to a 128-bit pshufb implementation. See the comments for more discussion.) If you have an array of 64-bit elements, and want to count bits below a certain position in each one separately, then you definitely should use SIMD . The shift parts of this algorithm vectorize, not just the popcnt part. Use psadbw against an all-zero register to horizontal-sum bytes in 64-bit chunks after a pshufb -based popcnt that produces counts for the bits in each byte separately. SSE/AVX doesn't have 64-bit arithmetic right shift, but you can use a different technique to blend on the high bit of each element. How I came up with this: The asm instructions you want to get the compiler to output will: remove the unwanted bits from the 64bit value test the highest of the wanted bits. popcount it. return 0 or popcount, depending on the result of the test. (Branchless or branching implementations both have advantages. If the branch is predictable, a branchless implementation tends to be slower.) The obvious way to do 1 is to generate a mask ( (1<<(pos+1)) -1 ) and & it. A more efficient way is to left-shift by 63-pos , leaving the bits you want packed at the top of a register. This also has the interesting side-effect of putting the bit you want to test as the top bit in the register. Testing the sign bit, rather than any other arbitrary bit, takes slightly fewer instructions. An arithmetic right shift can broadcast the sign bit to the rest of the register, allowing for more-efficient-than-usual branchless code. Doing the popcount is a much-discussed problem, but is actually the trickier part of the puzzle. On x86, there is extremely efficient hardware support for it, but only on recent-enough hardware. On Intel CPUs, the popcnt instruction is only available on Nehalem and newer. I forget when AMD added support. So to use it safely, you need to either do CPU dispatching with a fallback that doesn't use popcnt . Or, make separate binaries that do/don't depend on some CPU features. popcount without the popcnt instruction can be done a few ways. One uses SSSE3 pshufb to implement a 4-bit LUT. This is most effective when used on a whole array, rather than a single 64b at a time, though. Scalar bithacks might be best here, and wouldn't require SSSE3 (and so would be compatible with ancient AMD CPUs that have 64bit but not pshufb.) The Bitbroadcast: (A[63]? ~0ULL : 0) asks the compiler to broadcast the high bit to all other bit positions, allowing it to be used as an AND-mask to zero (or not) the popcount result. Note that even for large bitset sizes, it's still only masking the output of popcnt , not the bitset itself, so ~0ULL is fine I used ULL to make sure wasn't ever asking the compiler to broadcast the bit only to the low 32b of a register (with UL on Windows, for example). This broadcast can be done with an arithmetic right shift by 63, which shifts in copies of the high bit. clang generated this code from the original version. After some prodding from Glenn about different implementations for 4 , I realized that I could lead gcc towards clang's optimal solution by writing the source more like the ASM I want. The obvious ((int64_t)something) >> 63 to more directly request an arithmetic right shift would not be strictly portable, because signed right-shifts are implementation-defined as either arithmetic or logical . The standard doesn't provide any portable arithmetic right-shift operator. (It's not undefined behaviour , though.) Anyway, fortunately compilers are smart enough: gcc sees the best way once you give it enough of a hint. This source makes great code on x86-64 and ARM64 with gcc and clang. Both simply use an arithmetic right shift on the input to popcnt (so the shift can run in parallel with the popcnt). It also compiles great on 32bit x86 with gcc, because the masking only happens to a 32bit variable (after multiple popcnt results are added). It's the rest of the function that's nasty on 32bit (when the bitset is larger than a register). Original ternary-operator version with gcc Compiled with gcc 5.3.0 -O3 -march=nehalem -mtune=haswell (older gcc, like 4.9.2, also still emit this): ; the original ternary-operator version. See below for the optimal version we can coax gcc into emitting.popcount_subset(std::bitset<64ul>, int): ; input bitset in rdi, input count in esi (SysV ABI) mov ecx, esi ; x86 variable-count shift requires the count in cl xor edx, edx ; edx=0 xor eax, eax ; gcc's workaround for popcnt's false dependency on the old value of dest, on Intel not ecx ; two's complement bithack for 63-pos (in the low bits of the register) sal rdi, cl ; rdi << ((63-pos) & 63); same insn as shl (arithmetic == logical left shift) popcnt rdx, rdi test rdi, rdi ; sets SF if the high bit is set. cmovs rax, rdx ; conditional-move on the sign flag ret See How to prove that the C statement -x, ~x+1, and ~(x-1) yield the same results? for background on gcc's use of the -x == ~x + 1 two's complement identity. (And Which 2's complement integer operations can be used without zeroing high bits in the inputs, if only the low part of the result is wanted? which tangentially mentions that shl masks the shift count, so we only need the low 6 bits of ecx to hold 63 - pos . Mostly linking that because I wrote it recently and anyone still reading this paragraph might find it interesting.) Some of those instructions will go away when inlining. (e.g. gcc would generate the count in ecx in the first place.) With Glenn's multiply instead of ternary operator idea (enabled by USE_mul ), gcc does shr rdi, 63 imul eax, edi at the end instead of xor / test / cmovs . Haswell perf analysis, using microarch data from Agner Fog (Multiply version): mov r,r : 1 fused-domain uop, 0 latency, no execution unit xor -zeroing: 1 fused-domain uop, no execution unit not : 1 uop for p0/p1/p5/p6, 1c latency, 1 per 0.25c throughput shl (aka sal ) with count in cl : 3 uops for p0/p6: 2c latency, 1 per 2c throughput. (Agner Fog's data indicates that IvyBridge only takes 2 uops for this, strangely.) popcnt : 1 uop for p1, 3c latency, 1 per 1c throughput shr r,imm : 1 uop for p0/p6, 1c latency. 1 per 0.5c throughput. imul r,r : 1uop for p1, 3c latency. not counting the ret Totals: 9 fused-domain uops, can issue in 2.25 cycles (in theory; uop cache-line effects usually bottleneck the frontend slightly). 4 uops (shifts) for p0/p6. 2 uops for p1. 1 any-ALU-port uop. Can execute at one per 2c (saturating the shift ports), so the frontend is the worst bottleneck. Latency: Critical path from when the bitset is ready to when the result is: shl (2) -> popcnt (3) -> imul (3). Total 8 cycles . Or 9c from when pos is ready, because the not is an extra 1c latency for it. The optimal bitbroadcast version replaces shr with sar (same perf), and imul with and (1c latency instead of 3c, runs on any port). So the only perf change is reducing the critical path latency to 6 cycles . Throughput is still bottlenecked on the frontend. and being able to run on any port doesn't make a difference, unless you're mixing this with code that bottlenecks on port1 (instead of looking at the throughput for running just this code in a tight loop). cmov (ternary operator) version : 11 fused-domain uops (frontend: one per 2.75c ). execution units: still bottlenecked on the shift ports (p0/p6) at one per 2c. Latency : 7c from bitset to result, 8c from pos to result. ( cmov is 2c latency, 2 uops for any of p0/p1/p5/p6.) Clang has some different tricks up its sleeve: Instead of test / cmovs , it generates a mask of either all-ones or all-zeros by using an arithmetic right-shift to broadcast the sign bit to all positions of a register. I love it: Using and instead of cmov is more efficient on Intel. It still has the data-dependency and does the work for both sides of the branch (which is the main downside to cmov in general), though. Update: with the right source code, gcc will use this method, too. clang 3.7 -O3 -Wall -march=nehalem -mtune=haswell popcount_subset(std::bitset<64ul>, int): mov ecx, 63 sub ecx, esi ; larger code size, but faster on CPUs without mov-elimination shl rdi, cl ; rdi << ((63-pos) & 63) popcnt rax, rdi ; doesn't start a fresh dep chain before this, like gcc does sar rdi, 63 ; broadcast the sign bit and eax, edi ; eax = 0 or its previous value ret sar / and replaces xor / test / cmov , and cmov is a 2-uop instruction on Intel CPUs, so that's really nice. (For the ternary-operator version). Clang still does the sar / and trick instead of an actual imul when using the multiply source version, or the "bitbroadcast" source version. So those help gcc without hurting clang. ( sar/and is definitely better than shr/imul : 2c less latency on the critical path.) The pow_of_two_sub version does hurt clang (see the first godbolt link: omitted from this answer to avoid clutter with ideas that didn't pan out). The mov ecx, 63 / sub ecx, esi is actually faster on CPUs without mov-elimination for reg,reg moves (zero latency and no execution port, handled by register renaming). This includes Intel pre-IvyBridge, but not more recent Intel and AMD CPUs. Clang's mov imm / sub method puts only one cycle of latency for pos onto the critical path (beyond the bitset->result latency), instead of two for a mov ecx, esi / not ecx on CPUs where mov r,r has 1c latency. With BMI2 (Haswell and later), an optimal ASM version can save a mov to ecx . Everything else works the same, because shlx masks its shift-count input register down to the operand-size, just like shl . x86 shift instructions have crazy CISC semantics where if the shift count is zero, the flags aren't affected. So variable-count shift instructions have a (potential) dependency on the old value of the flags. "Normal" x86 shl r, cl decodes to 3 uops on Haswell, but BMI2 shlx r, r, r is only 1. So it's too bad that gcc still emits sal with -march=haswell , instead of using shlx (which it does use in some other cases). // hand-tuned BMI2 version using the NOT trick and the bitbroadcastpopcount_subset(std::bitset<64ul>, int): not esi ; The low 6 bits hold 63-pos. gcc's two-s complement trick xor eax, eax ; break false dependency on Intel. maybe not needed when inlined. shlx rdi, rdi, rsi ; rdi << ((63-pos) & 63) popcnt rax, rdi sar rdi, 63 ; broadcast the sign bit: rdi=0 or -1 and eax, edi ; eax = 0 or its previous value ret Perf analysis for Intel Haswell: 6 fused-domain uops ( frontend: one per 1.5c ). Execution units: 2 p0/p6 shift uops. 1 p1 uop. 2 any-port uops: (one per 1.25c from total execution port limits). Critical path latency: shlx (1) -> popcnt (3) -> and (1) = 5c bitset->result. (or 6c from pos ->result). Note that when inlining, a human (or smart compiler) could avoid the need for the xor eax, eax . It's only there because of popcnt 's false dependency on the output register (on Intel) , and we need the output in eax (which the caller may have used recently for a long dep chain). With -mtune=bdver2 or something, gcc won't zero the register it's going to use for popcnt output. When inlining, we could use an output register that already has to be ready at least as early as popcnt 's source reg to avoid the problem. Compilers will do an in-place popcnt rdi,rdi when the source isn't needed later, but that's not the case here. Instead, we can pick another register that already has to be ready before the source. popcnt 's input depends on 63-pos , and we can clobber it, so popcnt rsi,rdi 's dependency on rsi can't delay it. Or if we had 63 in a register, we could popcnt rsi,rdi / sarx rax, rsi, reg_63 / and eax, esi . Or BMI2 3-operand shift instructions would also let us not clobber inputs in case they're needed afterwards. This is so light-weight that loop overhead and setting up the input operands / storing the results are going to be major factors. (And the 63-pos can optimize away with a compile-time constant, or into wherever a variable count comes from.) The Intel compiler amusingly shoots itself in the foot and doesn't take advantage of the fact that A[63] is the sign bit. shl / bt rdi, 63 / jc . It even sets up the branches in a really dumb way. It could zero eax, and then jump over popcnt or not based on the sign flag set by shl . An optimal branching implementation , starting from ICC13 output from -O3 -march=corei7 on godbolt: // hand-tuned, not compiler output mov ecx, esi ; ICC uses neg/add/mov :/ not ecx xor eax, eax ; breaks the false dep, or is the return value in the taken-branch case shl rdi, cl jns .bit_not_set popcnt rax, rdi.bit_not_set: ret That's pretty much optimal: The A[pos] == true case has one not-taken branch. It doesn't save very much over the branchless method, though. If the A[pos] == false case is more common: jump over a ret instruction, to a popcnt / ret . (Or after inlining: jump to a block at the end that does the popcnt and jumps back).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34407437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2963099/']}
jdg_369708
stackexchange
llm_judgeable_groundtruth_similarity
9512210
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am currently working on an application which is parsing some JSON data in the APPdelegate class when the location is changed. My question is: " How is the most appropriate way doing it ?" Currently when it is parsing the data the application is "frozen" until the data has been loaded. I need some advice :) Thanks Now provide the response and nothing else.
There are several ways of course, including NSThread , NSOperation and old-fashioned libpthread . But what I find the most convenient (especially for simple background tasks) is libdispatch also called Grand Central Dispatch . Using dispatch queues you can quickly delegate a time-consuming task to a separate thread (or more precisely, execution queue - GCD decides whether it's a thread or an asynchronous task). Here's the simplest example: // create a dispatch queue, first argument is a C string (note no "@"), second is always NULLdispatch_queue_t jsonParsingQueue = dispatch_queue_create("jsonParsingQueue", NULL);// execute a task on that queue asynchronouslydispatch_async(jsonParsingQueue, ^{ [self doSomeJSONReadingAndParsing]; // once this is done, if you need to you can call // some code on a main thread (delegates, notifications, UI updates...) dispatch_async(dispatch_get_main_queue(), ^{ [self.viewController updateWithNewData]; });});// release the dispatch queuedispatch_release(jsonParsingQueue); The above code will read JSON data in a separate execution queue, not blocking the UI thread. This is just a simple example and there's a lot more to GCD, so take a look at the documentation for more info.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9512210', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/453562/']}
jdg_369709
stackexchange
llm_judgeable_groundtruth_similarity
338967
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: For instance I have a set of categories from a variable called 'category'. From python, here are my categories and their corresponding counts. Category_Others 1430Application/Website 1345Backups 900Software/OS 800Hardware/Virtual 700Network 302 There are two options I am considering; however, I am not sure which one is more legit. I assign a value to each category as follows: Category_Others ---- 0 Application/Website ---- 1Backups ---- 2 Software/OS ---- 3 Hardware/Virtual ---- 4 Network ---- 5 Or I introduce 5 new variables into my data frame. Then I end up with 5 more columns (i.e. columns with names of each category) i.e. on Python category = pd.get_dummies(incident['category'], drop_first=True) Now provide the response and nothing else.
The first approach (assigning 0 to 5) is not recommended. Because that encoding indicates Network is 5 times than Application, which is not true. Or this encoding imposes additional constraints to the model. In machine learning, people usually use one-hot encoding, which (similar to) your second approach, but many people do not use drop_first=True There is another small issue on one-hot encoding: for a discrete variable has 6 possible values, should we encode with 6 columns or 5 columns? People in statistics community usually encode with 5 columns. Many people in machine learning will use default setting in python, which does not have drop_first=True . If we encode it with 6 columns there are linear dependencies in your design matrix and it will cause some problems in some model. But python usually use regularization on linear model by default, so, it is fine there. Finally want to give you some statistical way of encoding in addition to machine learning way. https://stats.idre.ucla.edu/r/library/r-library-contrast-coding-systems-for-categorical-variables/
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/338967', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/132253/']}
jdg_369710
stackexchange
llm_judgeable_groundtruth_similarity
44513308
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can I use macros with the PythonOperator? I tried following, but I was unable to get the macros rendered: dag = DAG( 'temp', default_args=default_args, description='temp dag', schedule_interval=timedelta(days=1))def temp_def(a, b, **kwargs): print '{{ds}}' print '{{execution_date}}' print 'a=%s, b=%s, kwargs=%s' % (str(a), str(b), str(kwargs))ds = '{{ ds }}'mm = '{{ execution_date }}'t1 = PythonOperator( task_id='temp_task', python_callable=temp_def, op_args=[mm , ds], provide_context=False, dag=dag) Now provide the response and nothing else.
Macros only get processed for templated fields. To get Jinja to process this field, extend the PythonOperator with your own. class MyPythonOperator(PythonOperator): template_fields = ('templates_dict','op_args') I added 'templates_dict' to the template_fields because the PythonOperator itself has this field templated: PythonOperator Now you should be able to use a macro within that field: ds = '{{ ds }}'mm = '{{ execution_date }}'t1 = MyPythonOperator( task_id='temp_task', python_callable=temp_def, op_args=[mm , ds], provide_context=False, dag=dag)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44513308', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4116268/']}
jdg_369711
stackexchange
llm_judgeable_groundtruth_similarity
29882363
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Im having issues mapping the following keys on my vimrc not really sure why. I've checked and it doesn't seem to be there other mappings using the same keys, but for some reason the following doesn't work: " Move to next/previous line with same indentationnnoremap <A-k> :call search('^'. matchstr(getline('.'), '\(^\s*\)') .'\%<' . line('.') . 'l\S', 'be')<CR>nnoremap <A-j> :call search('^'. matchstr(getline('.'), '\(^\s*\)') .'\%>' . line('.') . 'l\S', 'e')<CR> Any obvious error here?The commands themselves do work as i've tested. Now provide the response and nothing else.
Note that datalist is not the same as a select . It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first. Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options. If you want to disallow user input entirely, maybe select would be a better choice. To show only the text value of the option in the dropdown, we use the inner text for it and leave out the value attribute. The actual value that we want to send along is stored in a custom data-value attribute: To submit this data-value we have to use an <input type="hidden"> . In this case we leave out the name="answer" on the regular input and move it to the hidden copy. <input list="suggestionList" id="answerInput"><datalist id="suggestionList"> <option data-value="42">The answer</option></datalist><input type="hidden" name="answer" id="answerInput-hidden"> This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist and fetch its data-value . That value is inserted into the hidden input and submitted. document.querySelector('input[list]').addEventListener('input', function(e) { var input = e.target, list = input.getAttribute('list'), options = document.querySelectorAll('#' + list + ' option'), hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'), inputValue = input.value; hiddenInput.value = inputValue; for(var i = 0; i < options.length; i++) { var option = options[i]; if(option.innerText === inputValue) { hiddenInput.value = option.getAttribute('data-value'); break; } }}); The id answer and answer-hidden on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple input s on the same page with one or more datalist s providing suggestions. Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue to hiddenInput.value = "" Working jsFiddle examples: plain javascript and jQuery
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/29882363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1848423/']}
jdg_369712
stackexchange
llm_judgeable_groundtruth_similarity
14181976
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Web View both in Iphone and Android. In Android, I use create a variable to call native Andriod functions/methods. But I have not able to find something similar in Iphone. So, how to call a native Iphone function from JavaScript. Now provide the response and nothing else.
iOS In iOS you could use a custom url scheme by implementing shouldStartLoadWithRequest . If I would by example want to change the toolbar's tint color: ViewController.h @property (strong, nonatomic) IBOutlet UIToolbar *toolbar; ViewController.m - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSURL *url = request.URL; NSString *scheme = [url scheme]; if ([scheme isEqualToString:@"color"]) { self.toolbar.tintColor = [self colorWithHexString:url.host]; } return YES;} Javascript In javascript you just change window.location , which will launch a fire and forget : window.location = 'color://' + color; Just chain your parameters like: window.location = 'myscheme://param1/' + value1 + '/param2/' + value2; Just make sure you use encodeURIComponent to encode your parameters (to create a valid url). More info Android In Android you add a javascript interface: WebView webView = getWebView(); webView.loadUrl("http://localhost:8080"); // must be after loadUrl on lower apis webView.addJavascriptInterface(new AndroidBridge(this), "AndroidBridge"); ... public class AndroidBridge { private MainActivity activity; public AndroidBridge(MainActivity activity) { this.activity = activity; } @JavascriptInterface public void changeNavbarBackground(String color) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Log.i(getClass().getSimpleName(), "changeNavbarBackground " + color); Field f = R.color.class.getField(color); final int col = (Integer) f.get(null); activity.changeNavbarBackground(col); }} Javascript In javascript you use the javascript interface: if (window.AndroidBridge) { window.AndroidBridge.changeNavbarBackground(color);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14181976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/960567/']}
jdg_369713
stackexchange
llm_judgeable_groundtruth_similarity
8627892
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I installed Pow with RVM for a rails app I'm working on. It's fine. It's the other sites that now all say "Pow is installed". I'm sure it's a simple setting, but I'm not able to find it. Has anyone run into this before? I'm running MAMP on Snow Leopard. Now provide the response and nothing else.
Pow will alter your DNS resolution to have all domains that end in .dev or .test be routed to the local machine (to hit pow). If you want to use MAMP as well as POW you'll need to turn off pow temporarily for it to be useable (Or you could change the MAMP settings use another port besides 80). To turn off pow i'd recommend installing the powder gem: gem install powderpowder down You could also use pow to serve up static sites, you'll just need a blank config.ru and a public folder to get going. More info in the pow manual here: http://pow.cx/manual.html#section_2.4
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8627892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/420722/']}
jdg_369714
stackexchange
llm_judgeable_groundtruth_similarity
107845
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $S$ be a smooth solid body in $\mathbb{R}^3$,and $B$ a ball of radius $r$.Say that $B$ is in contact with $S$ if (1) they share a point $x$that is on the surface of each, $x \in \partial S$ and $x \in \partial B$,and (2) neither penetrates the other,$\operatorname{int} S \cap \operatorname{int} B = \varnothing$.Say that $S$ can be rolled by $B$ if,for every pair of points $x,y$ on the surface of $S$, thereis a path $\rho$ connecting $x$ to $y$ on $\partial S$such that $B$ can be placed in contact at every point $z \in \rho$.In other words, the ball $B$ can roll between any pair of points ofthe surface without ever penetrating $S$. My question is: Characterize the bodies $S$ that can be rolled by a ball of radius $r$. A necessary condition is that the Gaussian curvature at any point on the surface of$S$ must be $\ge -\frac{1}{r^2}$.Could that also be sufficient, or are there global obstructionssuch that $B$ could be in local contact but penetrate away fromthe contact point?Is the characterization different for surfaces of genus zero thanfor surfaces with handles?Any insights, speculations, or literature pointers would beappreciated.Thanks! Update . Here is my interpretation of Anton's example: Now provide the response and nothing else.
You can call such bodies as "bodies of reach $\ge r$". Clearly all the principle curvatures has to be $\ge -\tfrac1r$. Plus you have a global condition which might be stated the following way:There is no segment between points on the surface which (1) meets the surfaceat normal direction at both ends (2) has length $<2\cdot r$ and (3) its interior lies in the complement of the body.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/107845', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6094/']}
jdg_369715
stackexchange
llm_judgeable_groundtruth_similarity
646086
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm implementing a small application in C, which I would like to sell as shareware for a reasonable price later on. It will start of with a 30-day trial, which I am already quite certain of how to implement it. The problem I have, though, is that I am not quite sure how to implement the product key verification. What I have in mind is that the customer can sign up on my webpage (after trying the product for a while), pay for the product, and get a product key in the form of aaaaa-bbbbb-ccccc-ddddd-eeeee via e-mail (or maybe available via his profile on my website). No problem so far. He/She then drops the key in the appropriate key fields in my app and boom the app is registered. From what I could gather so far, people either recommend AES or RSA for this. To be honest, I in another direction in college (not cryptography) and the one cryptography class I took was some time ago. But from what I remember, AES is a symmetric encryption algorithm, which would mean that I would only have one key for encryption and decryption, right? How could I then generate thousands of product keys and still validate them in my app (which by the way won't require internet access....so no checking back with a server)? So I guess RSA would be the way to go? But doesn't RSA produce pretty long keys (at least longer than the required 25 characters from above)? In another thread I read that some products won't even use encryption for the product key generation/verification, but instead just employ some checks like "add the 2. and the 17. character and that should total to x". What's the fastest, easiest and most secure way to go here? :-) Code samples would be sugar! Regards, Sebastian P.S.: Oh...and please don't tell me how my key can and will be cracked at some point.....I know about that, which is primarily why I don't want to spend a lot of time with this issue, but at the same time not make it too easy for the occasional cracker. Now provide the response and nothing else.
Symmetric algorithms are limited, in that any novice cracker with a disassembler can find your key (or the algorithm used to generate one) and make a "keygen". For this reason, asymmetric cryptology is the way to go. The basic premise is something like this: When the user purchases a license from you, you collect certain identifying details about the user and/or their environment (typically, this is just a full name; sometimes a company, too). You make a 128-bit MD5 hash of this information. Using a 128-bit Elliptic Curve crypto, encrypt this hash using the private key on the server. The 128-bit cipher text can be represented to the user as a 25-character string consisting of letters and digits (plus separating dashes for readability). Notice that 26 letters + 10 digits = 36 discrete values, and that 36^25 > 2^128. The user types this product key into your registration dialog. The client software converts it back to a 128-bit number (16 bytes), decrypts that using the public key of your EC crypto, and compares the result to an MD5 hash of the user's personal information, which must match what was used for registration. This is just the basic idea, of course. For more details and source code, see Product Keys Based on Elliptic Curve Cryptography .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/646086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/29909/']}
jdg_369716
stackexchange
llm_judgeable_groundtruth_similarity
19655189
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently trying to write some JavaScript to get the attribute of the class that has been clicked. I know that to do this the correct way, I should use an event listener. My code is as follows: var classname = document.getElementsByClassName("classname");var myFunction = function() { var attribute = this.getAttribute("data-myattribute"); alert(attribute);};classname.addEventListener('click', myFunction(), false); I was expecting to get an alert box every time I clicked on one of the classes to tell me the attribute but unfortunately this does not work. Can anyone help please? ( Note - I can quite easily do this in jQuery but I would NOT like to use it ) Now provide the response and nothing else.
This should work. getElementsByClassName returns an Array-like object (see below) of the elements matching the criteria. var elements = document.getElementsByClassName("classname");var myFunction = function() { var attribute = this.getAttribute("data-myattribute"); alert(attribute);};for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', myFunction, false);} jQuery does the looping part for you, which you need to do in plain JavaScript. If you have ES6 support you can replace your last line with: Array.from(elements).forEach(function(element) { element.addEventListener('click', myFunction); }); Note: Older browsers (like IE6, IE7, IE8) don´t support getElementsByClassName and so they return undefined . Details on getElementsByClassName getElementsByClassName doesn't return an array, but a HTMLCollection in most, or a NodeList in some browsers ( Mozilla ref ). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array (meaning other methods that can be performed on an Array cannot be performed on these types). Thanks to user @ Nemo for pointing this out and having me dig in to fully understand.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/19655189', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1312839/']}
jdg_369717
stackexchange
llm_judgeable_groundtruth_similarity
178696
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why is the allocated bandwith smaller with QAM-16 or 64 compared to e.g. QAM-4? I am not a professional so I'm looking for an intuitive explanation. Now provide the response and nothing else.
NxN-QAM means Quadrature Amplitude Modulation and it is a modulation scheme where the transmitted signal is the "mix" of two quadrature carriers whose amplitude is digitally modulated independently so as to give N different possible amplitude levels per each carrier. Therefore 64-QAM is 8x8-QAM, for example. The total bandwidth of such a signal is proportional to the baud rate \$\dfrac 1 T\$ where T is the symbol time, i.e. the time needed to transmit a symbol. Note that each simbol in NxN-QAM carries \$\log_2(N \times N)\$ bits of information, therefore 64-QAM carries 6 bit of information per symbol, whereas 4-QAM carries only 2 bit per symbol and 16-QAM carries 4. If you consider a constant information transmission rate, i.e. a constant bit rate , you can see that increasing the number of bits per symbol makes the symbol time increase, hence the required bandwidth decreases. To be more explicit, imagine you have to transmit a message with a bit rate of 64kbit/s. If you use 4-QAM you can transmit 2 bit per symbol, so you need to transmit at 32kSymbols/s (32kBaud). If you use 64-QAM you can transmit 6 bit per symbol, hence your baud rate drops to ~10.6kSymbols/s (10.6kBaud). Since we said that bandwidth is proportional to baud rate you see how the required bandwidth dropped using 64-QAM for a constant bit rate .
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/178696', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/80346/']}
jdg_369718
stackexchange
llm_judgeable_groundtruth_similarity
18920877
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an array of hashes, something like [ {:type=>"Meat", :name=>"one"}, {:type=>"Meat", :name=>"two"}, {:type=>"Fruit", :name=>"four"} ] and I want to convert it to this { "Meat" => ["one", "two"], "Fruit" => ["Four"]} I tried group_by but then i got this { "Meat" => [{:type=>"Meat", :name=>"one"}, {:type=>"Meat", :name=>"two"}], "Fruit" => [{:type=>"Fruit", :name=>"four"}] } and then I can't modify it to leave just the name and not the full hash. I need to do this in one line because is for a grouped_options_for_select on a Rails form. Now provide the response and nothing else.
array.group_by{|h| h[:type]}.each{|_, v| v.replace(v.map{|h| h[:name]})}# => {"Meat"=>["one", "two"], "Fruit"=>["four"]} Following steenslag's suggestion: array.group_by{|h| h[:type]}.each{|_, v| v.map!{|h| h[:name]}}# => {"Meat"=>["one", "two"], "Fruit"=>["four"]}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18920877', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/850276/']}
jdg_369719
stackexchange
llm_judgeable_groundtruth_similarity
42045291
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider this simple code: #include <complex.h>complex float f(complex float x) { return x*x;} If you compile it with -O3 -march=core-avx2 -fp-model strict using the Intel Compiler you get: f: vmovsldup xmm1, xmm0 #3.12 vmovshdup xmm2, xmm0 #3.12 vshufps xmm3, xmm0, xmm0, 177 #3.12 vmulps xmm4, xmm1, xmm0 #3.12 vmulps xmm5, xmm2, xmm3 #3.12 vaddsubps xmm0, xmm4, xmm5 #3.12 ret This is much simpler code than you get from both gcc and clang and also much simpler than the code you will find online for multiplying complex numbers. It doesn't, for example appear explicitly to deal with complex NaN or infinities. Does this assembly meet the specs for C99 complex multiplication? Now provide the response and nothing else.
The code is non-conforming. Annex G, Section 5.1, Paragraph 4 reads The * and / operators satisfy the following infinity properties for all real, imaginary, and complex operands: — if one operand is an infinity and the other operand is a nonzero finite number or an infinity, then the result of the * operator is an infinity; So if z = a * i b is infinite and w = c * i d is infinite, the number z * w must be infinite. The same annex, Section 3, Paragraph 1 defines what it means for a complex number to be infinite: A complex or imaginary value with at least one infinite part is regarded as an infinity (even if its other part is a NaN). So z is infinite if either a or b are. This is indeed a sensible choice as it reflects the mathematical framework 1 . However if we let z = ∞ + i ∞ (an infinite value) and w = i ∞ (and infinite value) the result for the Intel code is z * w = NaN + i NaN due to the ∞ · 0 intermediates 2 . This suffices to label it as non-conforming. We can further confirm this by taking a look at the footnote on the first quote (the footnote was not reported here), it mentions the CX_LIMITED_RANGE pragma directive. Section 7.3.4, Paragraph 1 reads The usual mathematical formulas for complex multiply, divide, and absolute value are problematic because of their treatment of infinities and because of undue overflow and underflow. The CX_LIMITED_RANGE pragma can be used to inform the implementation that (where the state is ‘‘on’’) the usual mathematical formulas [that produces NaNs] are acceptable. Here the standard committee is trying to alleviate the huge mole of work for the complex multiplication (and division). In fact GCC has a flag to control this behaviour : -fcx-limited-range When enabled, this option states that a range reduction step is not needed when performing complex division. Also, there is no checking whether the result of a complex multiplication or division is NaN + I*NaN, with an attempt to rescue the situation in that case. The default is -fno-cx-limited-range , but is enabled by -ffast-math . This option controls the default setting of the ISO C99 CX_LIMITED_RANGE pragma. It this option alone that makes GCC generate slow code and additional checks , without it the code it generate has the same flaws of Intel's one (I translated the source to C++) f(std::complex<float>): movq QWORD PTR [rsp-8], xmm0 movss xmm0, DWORD PTR [rsp-8] movss xmm2, DWORD PTR [rsp-4] movaps xmm1, xmm0 movaps xmm3, xmm2 mulss xmm1, xmm0 mulss xmm3, xmm2 mulss xmm0, xmm2 subss xmm1, xmm3 addss xmm0, xmm0 movss DWORD PTR [rsp-16], xmm1 movss DWORD PTR [rsp-12], xmm0 movq xmm0, QWORD PTR [rsp-16] ret Without it the code is f(std::complex<float>): sub rsp, 40 movq QWORD PTR [rsp+24], xmm0 movss xmm3, DWORD PTR [rsp+28] movss xmm2, DWORD PTR [rsp+24] movaps xmm1, xmm3 movaps xmm0, xmm2 call __mulsc3 movq QWORD PTR [rsp+16], xmm0 movss xmm0, DWORD PTR [rsp+16] movss DWORD PTR [rsp+8], xmm0 movss xmm0, DWORD PTR [rsp+20] movss DWORD PTR [rsp+12], xmm0 movq xmm0, QWORD PTR [rsp+8] add rsp, 40 ret and the __mulsc3 function is practically the same the standard C99 recommends for complex multiplication. It includes the above mentioned checks. 1 Where the modulus of a number is extended from the real case |z| to the complex one ‖z‖, keeping the definition of infinite as the result of unbounded limits. Simply put, in the complex plane there is a whole circumference of infinite values and it takes just one "coordinate" to be infinite to get an infinite modulus. 2 The situation get worst if we remember that z = NaN + i ∞ or z = ∞ + i NaN are valid infinite values
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42045291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1473517/']}
jdg_369720
stackexchange
llm_judgeable_groundtruth_similarity
34978616
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does angular2 support nested states/routes? for example in a view port there are 2 links and on clicking a specific link it will present a view which with further have more than one link but that are specific to earlier link. Now provide the response and nothing else.
Yes. I made some demo: http://plnkr.co/edit/IcnEzZ0WtiaY5Bpqrq2Y?p=preview import {Component, View, Input} from 'angular2/core';import { RouteConfig, Router, RouteParams, ROUTER_DIRECTIVES} from 'angular2/router';import {PersistentRouterOutlet} from './persistent-router-outlet';@Component({})@View({ template: 'product info here'})class ProductInfo {}@Component({})@View({ template: 'buy here'})class ProductBuy {}@Component({})@View({ directives: [...ROUTER_DIRECTIVES, PersistentRouterOutlet], template: ` <div> <h2>Product {{pid}}</h2> <a [routerLink]="['Info']">Show Info</a> <a [routerLink]="['Buy']">Go Buy</a> <div> <router-outlet></router-outlet> </div> </div> `})@RouteConfig([ {path: '/info', name: 'Info', component: ProductInfo, useAsDefault: true} {path: '/buy', name: 'Buy', component: ProductBuy}])class Product { pid constructor(params: RouteParams) { this.pid = params.get('pid') }}@Component({})@View({ directives: [...ROUTER_DIRECTIVES], template: ` info about the store `})class StoreInfo {}@Component({ selector: 'my-app', providers: [], directives: [...ROUTER_DIRECTIVES, PersistentRouterOutlet] , template: ` <div> <a [routerLink]="['./StoreInfo']">See Store Info</a> <a [routerLink]="['./Product', {pid:1}]">See Product 1</a> <a [routerLink]="['./Product', {pid:2}]">See Product 2</a> <div> <persistent-router-outlet></persistent-router-outlet> </div> </div> `})@RouteConfig([ {path: '/', name: 'StoreInfo', component: StoreInfo, useAsDefault: true} {path: '/product/:pid/...', name: 'Product', component: Product}])export class App {} Here's the doc: https://angular.io/docs/ts/latest/guide/router.html#!#child-router Note there's a problem with persistent tabs: Angular2 Routing: persisting route tabs and child routes https://github.com/angular/angular/issues/6634
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34978616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5815863/']}
jdg_369721
stackexchange
llm_judgeable_groundtruth_similarity
14403492
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am get the above response when calling a WCF service via ajax json. My calling code is: <script type="text/javascript"> $(document).ready(function () { $.ajax ({ type: "POST", contentType: "application/json; charset=utf-8", url: "http://localhost:90/WebServices/UserService.svc/Calculate", data: "{}", timeout: 10000, dataType: "json", success: function (response) { alert(response) }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.statusText); alert(thrownError); } }); });</script> My service is: [ServiceContract]public interface IUserService{ [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json )] Answer Calculate();}[DataContract]public class Answer{ [DataMember] public string answer { get; set; }} My method is : [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)][ServiceBehavior(IncludeExceptionDetailInFaults = true)]public class UserService : IUserService{ public Answer Calculate() { Answer answer = new Answer(); answer.answer="Hello World"; return answer; }} I have been battling with for sometime, I see other people have had the same type problem and I tried all there suggestions but still nothing is working. Where is the problem? How can I solve it? Now provide the response and nothing else.
I'm guessing here since you didn't show how you defined your endpoint, but I'm pretty sure it's the case. Your endpoint is not defined for web consumption - it's likely using basicHttpBinding . To consume the endpoint via jQuery (or other web/REST clients in general) you need to define an endpoint with the WebHttpBinding , and apply the WebHttpBehavior to it. There are different ways to define the endpoint correctly. The easiest one is to use the WebServiceHostFactory in your .svc file: UserService.svc : <%@ ServiceHost Language="C#" Debug="true" Service="YourNamespace.UserService" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14403492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1991097/']}
jdg_369722
stackexchange
llm_judgeable_groundtruth_similarity
13473396
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If you check out this jsbin: http://jsbin.com/efosed/5/edit and you press "Run with JS", there will be a div that can be resized with jquery ui. Everything works like expected.The div is placed over a "full-screen" iframe. In the linked example this iframe has: display: none . If I modify it to display: block , and re-run the script the reziable plugin will have some strange behavior. You can try it here: http://jsbin.com/efosed/6/edit .It will not handle mouse events correctly.What can be the reason, and how can I fix it? Now provide the response and nothing else.
You have to implement your own logic to fix iframe. One solution is to add a div over your iframe: DEMO $(function() { $('#resizable').resizable({ start: function(event, ui) { $('<div class="ui-resizable-iframeFix" style="background: #fff;"></div>') .css({ width:'100%', height: '100%', position: "absolute", opacity: "0.001", zIndex: 1000 }) .appendTo("body"); }, stop: function(event, ui) { $('.ui-resizable-iframeFix').remove() } });}); For modern browsers which support CSS property pointer-events , there is a better solution, see code and jsbin: DEMO $(function() { $('#resizable').resizable({ start: function(event, ui) { $('iframe').css('pointer-events','none'); }, stop: function(event, ui) { $('iframe').css('pointer-events','auto'); } });});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13473396', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240324/']}
jdg_369723
stackexchange
llm_judgeable_groundtruth_similarity
202326
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on an application that is completely built upon user interaction. In my application logs, I log each interaction and print the email address to uniquely identify which user did which interaction. This application log will not be visible to anyone other than: Me The next owner of the application if I would sell the project An administrator I might hire if the workload gets too big An example of a log record is something like this: 2019-01-24 14:27:20.954 INFO 32256 --- [whatever-info] s.p.s.t.d.m.s.SomeClassThatPrintsTheLog : Registering user with email address EMAIL_ADDRESS_WILL_BE_PRINTED_HERE@email.com. Is this allowed under GDPR or should I mask the printed email address in any way? Or use another solution? Now provide the response and nothing else.
The goal of GDPR is about protecting personally identifiable information (PII) as much as possible. The interaction of a specific user with your application are pretty sure such PII. If you really need to log this information you should inform your user about this process, i.e. the purpose of the data collection, how long the information gets stored and who gets access to the data. And you and whoever you sell the application to should never use the data for any other purpose as agreed to by the user. And of course you need to properly protect the information against misuse, i.e. use outside of the specified purpose. This specifically but not only includes if someone hacks into your application or server and steals this data. Since use of the data is limited and protection (and fines) can be costly, it might be easier to not store these information in the first place. An alternative is to at least pseudonymize the PII as much as possible, i.e. in a way that the logged data are still usable for you but that no association to a specific user can be done even when having all the logged data. But since it is not really clear what you use these logs for no recommendations can be done for a specific process of such pseudonymization. Be aware though that simply replacing each unique email address with another unique identifier might not be a sufficient pseudonymization. Depending on the data you log it might be possible to create user profiles and based on specific traits in the profiles associate these to real world users. See AOL search data leak for an example how such simple pseudonymization attempt went wrong.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/202326', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/197969/']}
jdg_369724
stackexchange
llm_judgeable_groundtruth_similarity
8949079
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The browser gist by defunkt github user starts with this shell expression if [ -t 0 ]; then ... What is the meaning of this line of code? UPDATE: could you also explain why i need this check before to do anything else? For the sake of completeness, here is the entire little script (it allow to pipe text to the default browser): if [ -t 0 ]; then if [ -n "$1" ]; then open $1 else cat <<usageUsage: browser pipe html to a browser$ echo '<h1>hi mom!</h1>' | browser$ ron -5 man/rip.5.ron | browserusagefielse f="/tmp/browser.$RANDOM.html" cat /dev/stdin > $f open $ffi Now provide the response and nothing else.
[ and ] invokes test -t makes the test test a file descriptor to see if it's a terminal 0 is the file descriptor for STDIN. So that says if STDIN is a terminal then ... Motivation I'd have to read the whole script to know for sure, but usually it's because the script wants to do something visually slick like clear the screen, or prompt interactively. If you're reading a pipe, there's no point in doing that. Detail Okay, let's examine the whole script: # If this has a terminal for STDINif [ -t 0 ]; then # then if argument 1 is not empty if [ -n "$1" ]; then # then open whatever is named by the argument open $1 else # otherwise send the usage message to STDOUT cat <<usageUsage: browser pipe html to a browser$ echo '<h1>hi mom!</h1>' | browser$ ron -5 man/rip.5.ron | browserusage#That's the end of the usage message; the '<<usage'#makes this a "here" document.fi # end if -n $1else # This is NOT a terminal now # create a file in /tmp with the name # "browser."<some random number>".html" f="/tmp/browser.$RANDOM.html" # copy the contents of whatever IS on stdin to that file cat /dev/stdin > $f # open that file. open $ffi So this is checking to see if you're on a terminal; if so it looks for an argument with a file name or URL. If it isn't a terminal, then it tries to display the input as html.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8949079', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/204159/']}
jdg_369725
stackexchange
llm_judgeable_groundtruth_similarity
60195
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The answer to the original question is no, see JSE! Are the $\Gamma(N)$ the only normal congruence subgroups of $\mathrm{PSL}_2(\mathbb{Z})$ with no finite subgroups (elliptic elements)? What about the normal subgroups of $\Gamma(4)$, which does not contain torsion elements. Here, $\gamma \in \Gamma(N)$, if $\gamma \cong 1 \mod N$. I state the question in the local picture for general G:Let $o$ be a local ring and $G \subset GL(n)$ a group. Then it makes sense to speak about $G( p^r)$, which consists of matrices which are congruent to $1$ modulo $p^r$, where $p$ is the maximal ideal in $o$. From $o \rightarrow o/\p^r$, we get an exact sequence$$ G(p^r) \rightarrow G(o) \rightarrow G( o / p^r).$$Is it surjective? I guess the $G(p^r)$ form a basis of neighborhoods for $1$ and are normal open compact subgroups. Under which conditions are these all normal subgroups in $G(o)$ with no finite subgroups? Now provide the response and nothing else.
Almost but not quite. A congruence subgroup has to contain some Gamma(N). So if it is normal its image in SL_2(Z) / Gamma(N) is a normal subgroup of SL_2(Z/NZ). That group is almost simple but not quite. A proper normal subgroup need not be trivial; it could be +-1 for instance. Or if N is very small you have a few more choices; for instance, the commutator subgroup of SL_2(Z) is a finite-index congruence subgroup of (if I recall correctly) index 12, containing Gamma(6).
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/60195', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10400/']}
jdg_369726
stackexchange
llm_judgeable_groundtruth_similarity
23836825
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to write a little library for JavaScript enums. For me to do that, I need to decide how to store the enum values. Therefore, I'd like to use the fastest way when comparing, but I also want something that is debuggable, so I'm torn between using strings or numbers. I know I could use objects too, but that would be another question For example // I don't want this because when debugging, you'd see just the value 0var Planets = {Earth:0, Mars:1, Venus: 2}// I'd prefer this so that Planets.Earth gives me a nice readable value ("Earth")var Planets = {Earth: 'Earth', Mars: 'Mars'} But I'm afraid that when I compare them using if (myPlanet === Planet.Earth) , the string comparison could take a lot longer (say if it were in a tight loop). This should be the case because http://ecma-international.org/ecma-262/5.1/#sec-11.9.6 says If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false. But when I wrote a test case, I found that they take the same amount of time http://jsperf.com/string-comparison-versus-number-comparison/2 so it doesn't seem like it's scanning the whole string. I know this could be a micro optimization, but my question is: is string equality comparison done using pointers and therefore just as fast as number equality comparison? Now provide the response and nothing else.
String comparison could be "just as fast" (depending on implementation and values) - or it could be "much slower". The ECMAScript specification describes the semantics , not the implementation . The only way to Know for Certain is to create an applicable performance benchmark on run it on a particular implementation. Trivially, and I expect this is the case 1 , the effects of string interning for a particular implementation are being observed. That is, all string values (not String Objects) from literals can be trivially interned into a pool such that implIdentityEq("foo", "foo") is true - that is, there need only one string object. Such interning can be done after constant folding, such that "f" + "oo" -> "foo" - again, per a particular implementation as long as it upholds the ECMAScript semantics. If such interning is done, then for implStringEq the first check could be to evaluate implIdentityEq(x,y) and, if true, the comparison is trivially-true and performed in O(1). If false, then a normal string character-wise comparison would need to be done which is O(min(n,m)). (Immediate falseness can also be determined with x.length != y.length , but that seems less relevant here.) 1 While in the above I argue for string interning being a likely cause, modern JavaScript implementations perform a lot of optimizations - as such, interning is only a small part of the various optimizations and code hoistings that can (and are) done! I've created an "intern breaker" jsperf . The numbers agree with the hypothesis presented above. If a string is interned then comparison is approximate in performance to testing for "identity" - while it is slower than a numeric comparison, this is still much faster than a character-by-character string comparison. Holding the above assertion, IE10 does not appear to consider object-identity for pass-fast string comparisons although it does use a fast-fail length check. In Chrome and Firefox, two intern'ed strings which are not equal are also compared as quickly as two that are - there is likely a special case for comparing between two different interned strings. Even for small strings (length = 8), interning can be much faster. IE10 again shows it doesn't have this "optimization" even though it appears to have an efficient string comparison implementation. The string comparison can fail as soon as the first different character is encountered: even comparing long strings of equal length might only compare the first few characters. Do common JavaScript implementations use string interning? (but no references given) Yes. In general any literal string, identifier, or other constant string in JS source is interned. However implementation details (exactly what is interned for instance) varies, as well as when the interning occurs See JS_InternString (FF does have string interning, although where/how the strings are implicitly interened from JavaScript, I know not)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23836825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227299/']}
jdg_369727
stackexchange
llm_judgeable_groundtruth_similarity
1963563
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $n$ positive integers taken at random are multiplied together, show that the probability that the last digit of their product is 5 is $$\frac{5^n-4^n}{{10}^n}$$ My attempt: Let $n$ positive integers be $x_1,x_2, \cdots ,x_n$. Let $a=x_1 \cdot x_2 \cdots x_n$. Let $S$ be the sample set. Then $n(S)=10^n$ since there are 10 possibilities for unit digit of each integer. I couldn't proceed from there. Please help me in this regard. Thanks. Now provide the response and nothing else.
For the last digit to be a 5: all numbers must end in an odd digit $(A)$ at least one of the ending digits must be a 5 $(B)$ $$\mathsf P(A)=\left(\frac5{10}\right)^n$$$$\mathsf P(B^\complement\mid A)=\left(\frac45\right)^n$$Therefore $$\mathsf P(B\mid A)=1-\left(\frac45\right)^n$$$$\mathsf P(A\cap B)=\left(1-\left(\frac45\right)^n\right)\left(\frac5{10}\right)^n=\left(\frac5{10}\right)^n-\left(\frac4{10}\right)^n=\frac{5^n-4^n}{10^n}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1963563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/356886/']}
jdg_369728
stackexchange
llm_judgeable_groundtruth_similarity
1409687
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My book gives the following definition: Let $(M,d)$ be a metric space, and let $\mathcal{T}$ be the collection of all subsets of $M$ that are open in the metric space sense... $\mathcal{T}$ is called the topology generated by d Then it later says to prove things about two different metrics generating the same topology. However I'm very confused about what all this means. When I read "all subsets," I think of the theorem that says a set with $n$ elements will have $2^n$ subsets. (ex. all the subsets of $\{1,2,3\}$ are $\{\emptyset, \{1\},\{2\},\{3\},\{1,2\},\{1,3\},\{2,3\},\{1,2,3\} \}$). So I think "all subsets that are open" would be like, If M is the set (1,5), then an open subset would be any set $(a,b)$ where $1<a<b<5$, and then all subsets would be all possible union combinations of these "$(a,b)$" sets. Its seems to me that metrics have nothing to do with subsets. Clearly there is something i'm not understanding. Please Help me. It would be very enlightening, if someone could give me some simple examples of 1 set and 2 metrics generating two different typologies. Now provide the response and nothing else.
Let me start with the following definition: In a metric space $(M,d)$, we can say that $S$ is an open set (with respect to the topology induced by $d$) if for every element $s\in S$, there exists $\epsilon >0$ such that the ball$$ B(s,\epsilon)=\{ x\in M\mid d(x,s)<\epsilon\}\qquad \text{satisfies }\qquad B(s,\epsilon)\subset S.$$This means that if you can put a little open ball ( defined by the metric ) around any elements of $S$, then it is open. We can also say that $\bar s$ lies in the border of $S$, i.e. $\bar s\in\partial S$, if for every $\epsilon >0$ we have $B(\bar s,\epsilon)\cap S \neq \emptyset$ and $B(\bar s,\epsilon)\cap (M\setminus S)\neq \emptyset$. A little illustration We set $M=\Bbb R^2$: On the left: The metric is that induced by the Euclidean distance (the one we experience every day). With this metric we have$$B_1(s,\epsilon)=\{x\in\Bbb R^2\mid \|x-s\|_2<\epsilon\}$$and it looks like a circle of radius $\epsilon$ centered at $s$.The set ${\color{blue}{\text{$S$ is closed}}}$, its border, $\delta S$ is in darker blue. The black point is in the interior (lighter blue) of $S$ because we can find a little ball entirely contained in $S$. Note that the interior of $S$ is always an open set. The yellow point is not in $S$ and the red point is on $\partial S$ because every ball centered on it contains a point inside and outside $S$. On the right: Here things are much different. As already proposed by @Dominik, the metric considered is the discrete metric . In this case we have$$ B_2(s,\epsilon)=\begin{cases} \{s\} & \text{if } \epsilon <1\\ \Bbb R^2 &\text{else}\end{cases}.$$ In particular, it follows that every point in $S$ lies in the interior of $S$. This is because for every $s\in S$, there exists $\epsilon=1/2>0$ such that $B(s,\epsilon)=\{s\}\subset S$, i.e. we can find a ball of radius $>0$ centered on $s$ entirely contained in $S$. It follows that, in this case, ${\color{blue}{\text{$S$ is open}}}$. It turns out that every set in $M$ is open with this metric. Indeed, they are also all closed (their complement is open). Now, let us see what happens when some metric are equivalent. On the left: Here the metric is induced by the infinite norm $\|\cdot \|_{\infty}$ and the balls are given by$$B_3(s,\epsilon)=\{x\in\Bbb R^2\mid \max_{i} |x_i-s_i|<\epsilon\},$$and this is a square centered at $s$. Note that yellow is outside, black is inside and red is on the border of $S$ for the same reason as above for $d_1$. In this case, ${\color{blue}{\text{$S$ is closed}}}$. On the right: This shows that that a set $S$ is open with respect to $d_1$ if and only if it is with respect to $d_3$. For the intuition: for any circle with positive diameter you can find a square with positive diameter and strictly contained in the circle. For example a square which is $5$ times smaller. On the other hand, given a square you can find a circle contained in the square, say $42$ times smaller. In mathematical terms:$$ B_3\Big(s,\frac{\epsilon}{5}\Big) \subset B_1(s,\epsilon) \qquad \text{and}\qquad B_1\Big(s,\frac{\epsilon}{42}\Big) \subset B_3(s,\epsilon) \qquad \forall \epsilon >0.$$In particular this shows that for every $x\in M$ we have$$\exists \epsilon >0 \text{ such that } B_1(x,\epsilon)\subset S \qquad\iff\qquad\exists \epsilon >0 \text{ such that } B_3(x,\epsilon)\subset S.$$Therefore $S$ is open with respect to $d_1$ if and only if it is for $d_3$. In particular this implies that the induced topologies are the same. Note also that the property to be in $\partial S$ is also identical for both metric. More generally, every metric induced by a norm (like $d_1$ and $d_3$) on a finite dimensional space induce the same topology as that induced by the Euclidean norm.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1409687', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/262457/']}
jdg_369729
stackexchange
llm_judgeable_groundtruth_similarity
19015698
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been using Python for some time already and today while reading the following code snippet: >>> a = (1,2)>>> a += (3,4)>>> a(1, 2, 3, 4) I asked myself a question: how come python tuples are immutable and I can use an += operator on them (or, more generally, why can I modify a tuple)? And I couldn't answer myself. I get the idea of immutability, and, although they're not as popular as lists, tuples are useful in python. But being immutable and being able to modify length seems contradictory to me... Now provide the response and nothing else.
5 is immutable, too. When you have an immutable data structure, a += b is equivalent to a = a + b , so a new number, tuple or whatever is created. When doing this with mutable structures, the structure is changed . Example: >>> tup = (1, 2, 3)>>> id(tup)140153476307856>>> tup += (4, 5)>>> id(tup)140153479825840 See how the id changed? That means it's a different object. Now with a list , which is mutable: >>> lst = [1, 2, 3]>>> id(lst)140153476247704>>> lst += [4, 5]>>> id(lst)140153476247704 The id says the same.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19015698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/769384/']}
jdg_369730
stackexchange
llm_judgeable_groundtruth_similarity
176343
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Perl 6 seems to have an explosion of equality operators. What is =:= ? What's the difference between leg and cmp ? Or eqv and === ? Does anyone have a good summary? Now provide the response and nothing else.
=:= tests if two containers (variables or items of arrays or hashes) are aliased, ie if one changes, does the other change as well? my $x;my @a = 1, 2, 3;# $x =:= @a[0] is false$x := @a[0];# now $x == 1, and $x =:= @a[0] is true$x = 4;# now @a is 4, 2, 3 As for the others: === tests if two references point to the same object, and eqv tests if two things are structurally equivalent. So [1, 2, 3] === [1, 2, 3] will be false (not the same array), but [1, 2, 3] eqv [1, 2, 3] will be true (same structure). leg compares strings like Perl 5's cmp , while Perl 6's cmp is smarter and will compare numbers like <=> and strings like leg . 13 leg 4 # -1, because 1 is smaller than 4, and leg converts to string13 cmp 4 # +1, because both are numbers, so use numeric comparison. Finally ~~ is the "smart match", it answers the question "does $x match $y ". If $y is a type, it's type check. If $y is a regex, it's regex match - and so on.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/176343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7598/']}
jdg_369731
stackexchange
llm_judgeable_groundtruth_similarity
208978
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: It is always said that the include directive s should be placed at the beginning of a script. The main reason is to make the functions available throughout the script. Regardless of this fact, is it bad to place an include directive within the main function where it is needed? For example, #include <stdio.h>int main() {#include <mysql.h>} Instead of #include <mysql.h>#include <stdio.h>int main() {} I was unable to find any different in performance or compiled file size, but it is difficult to judge about this fact based on simple scripts. I wonder if it has any effect or drawback, or any reason to avoid this non-standard approach. Now provide the response and nothing else.
It depends on what code is in the include file. Did you try putting the #include for <stdio.h> inside main()? Depending on how the standard library is implemented on your system it may not even compile. Header files can contain not only function declarations, but function definitions. Standard C doesn't support nested functions. If your header file contains function and variable declarations, putting them inside the body of main() limits their scope. If the header file only contains preprocessor macros it might work, but you'll annoy all other C programmers by gratuitously moving the include somewhere unexpected. Coding standards are particularly important in C because C has so few safeguards to keep you from screwing up.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/208978', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/36782/']}
jdg_369732
stackexchange
llm_judgeable_groundtruth_similarity
630884
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have a Python script which is supposed to access various web API's from our server out through to the internet. The issue is that Python support from what I've seen is quite poor when it comes to supporting NTLM authentication. This causes our corporate proxy server to always return HTTP code 407. My initial idea was to set up a local proxy server using IIS and the Application Request Routing module, which would forward all requests to our corporate proxy while handling the NTLM authentication. Issue with that approach is that it doesn't appear to be forwarding my NTLM credentials, which the current user is running the Python script from. Will this approach work? If so, how can I implement it? Now provide the response and nothing else.
Might be a bit late but wanted to mention this nonetheless. No doubt having NTLM support in your script would be great but that would add complexity for no big returns. Might be best to use NTLMAps, Cntlm or Px. NTLMAps and Cntlm are proxies that do the NTLM auth as an intermediary proxy. However, they both require the user/pass since they are mostly targeted towards Linux users. I historically used these tools on Windows but was annoyed by the same requirement of having to provide the credentials to them and update every time my password changed. As a result, I've authored Px for Windows which is an HTTP proxy like the above two, but uses SSPI to manage the required authentication with the corporate proxy. All you need to configure is the proxy server and port. For developing your own apps, the code should also help figure out how to do this within Python and perhaps other languages which have access to SSPI. But you'd rather isolate the NTLM mess and not meddle with it.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/630884', 'https://serverfault.com', 'https://serverfault.com/users/243925/']}
jdg_369733
stackexchange
llm_judgeable_groundtruth_similarity
18166552
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a file that contains a list of URLs. It looks like below: file1: http://www.google.comhttp://www.bing.comhttp://www.yahoo.comhttp://www.baidu.comhttp://www.yandex.com.... I want to get all the records after: http://www.yahoo.com , results looks like below: file2: http://www.baidu.comhttp://www.yandex.com.... I know that I could use grep to find the line number of where yahoo.com lies using grep -n 'http://www.yahoo.com' file13 http://www.yahoo.com But I don't know how to get the file after line number 3. Also, I know there is a flag in grep -A print the lines after your match. However, you need to specify how many lines you want after the match. I am wondering is there something to get around that issue. Like: Pseudocode:grep -n 'http://www.yahoo.com' -A all file1 > file2 I know we could use the line number I got and wc -l to get the number of lines after yahoo.com, however... it feels pretty lame. Now provide the response and nothing else.
AWK If you don't mind using AWK : awk '/yahoo/{y=1;next}y' data.txt This script has two parts: /yahoo/ { y = 1; next }y The first part states that if we encounter a line with yahoo , we set the variable y=1, and then skip that line (the next command will jump to the next line, thus skip any further processing on the current line). Without the next command, the line yahoo will be printed. The second part is a short hand for: y != 0 { print } Which means, for each line, if variable y is non-zero, we print that line. In AWK, if you refer to a variable, that variable will be created and is either zero or empty string, depending on context. Before encounter yahoo , variable y is 0, so the script does not print anything. After encounter yahoo , y is 1, so every line after that will be printed. Sed Or, using sed , the following will delete everything up to and including the line with yahoo: sed '1,/yahoo/d' data.txt
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18166552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1953475/']}
jdg_369734
stackexchange
llm_judgeable_groundtruth_similarity
66369
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to convert analog output of an accelerometer to digital codes. I understand that the sampling rate of the ADC should be with reference to Nyquist criteria. Please let me know how to decide on the resolution needed. Now provide the response and nothing else.
Noise is the determining factor. You first must start with the noise level of what your Accelerometer + Amplifier puts out, lets call this N for noise. Then you need to find what your accelerometer puts out at it's maximum, we will assume that this will be some RMS value and call it S for signal. Your SNR (signal to noise ratio) \$=\frac{S}{N}\$ The base number of Bits you need is \$ B = log_2(SNR)\$ But this is not sufficient as the ADC will have some inherent noise itself. to ensure that the ADC noise does not interfere, or to put it another way , to ensure that the ADC noise does not factor into the signal you must ensure that the resolution is greater than the B value calculated above. For a very strict definition the noise from the ADC should be 10% of the signal noise but you may find that 25% is adequate. In your ADC data sheet you'll find a number called ENOB (Effective number of bits). In the 10% case: ENOB > B + \$log_2(10)\$ > B + 3.32 In the 25% case: ENOB > B + \$log_2(4)\$ > B + 2 Next you have to scale the output of your accelerometer and buffer amplifier so that the max of is a little less than the maximum of what the ADC can handle (again from the datasheet). If you have matched the ENOB and the scale then everything else is taken care of.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/66369', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1484/']}
jdg_369735
stackexchange
llm_judgeable_groundtruth_similarity
1892301
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is a general question. A function is said to be continuous. Can it still have vertical asymptotes? Looking at the definition of continuity, I would say no. Because near a vertical asymptote x-delta might have an y of close to minus infinity, while x+delta might have a value of near +infinity, for example. Now provide the response and nothing else.
It doesn't make sense to ask whether a function is continuous at a point where it's not defined. So if it has a vertical asymptote, then that's not a point of discontinuity, but rather a point that is not part of the domain. To make it clear what I mean by "doesn't make sense", the definition of continuity at a point $x$ involves the expression $|f(x) - f(y)|$. If $x$ is such that $f(x)$ doesn't make sense, then neither does that expression, so asking about continuity is meaningless.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1892301', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/356903/']}
jdg_369736
stackexchange
llm_judgeable_groundtruth_similarity
463052
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Massive edit to simplify the question. Some comments below might be made obsolete - specifically, the comment that this follows directly from Dirichlet. That was true for the original wording. I'm looking for a short proof, directly from Bézout's identity , of the following theorem: Theorem 1: If $(a,b,c)=1$ then there exists an integer solution $x,y,z$ to $ax+bxy+cz=1$. The case $(a,b)=1$ turns out to be equivalent to the theorem: Theorem 2: The natural map: $$\mathbb Z_{nm}^\times\to\mathbb Z_{n}^\times$$ is onto. That's because "onto" means if $(a,n)=1$ then for some $y$, $a+ny\in\mathbb Z_{mn}^\times$, meaning that $(a+ny,m)=1$ and thus $1=(a+ny)x+mz=ax+nxy+mz$ has a solution. The converse is equally obvious. The general case in the first theorem follows if we know the case when $(a,b)=1$ since, for general $(a,b)$, we have $\left(\frac{a}{(a,b)},\frac{b}{(a,b)}\right)=1$, so from the special case, we get:$$\frac{a}{(a,b)}x_0 + \frac{b}{(a,b)} x_0y_0 + cz_0= 1$$which implies: $$ax_0 + bx_0y_0 + c((a,b)z_0)=(a,b)$$Since $1=(a,b,c)=((a,b),c)$ we can find $(u,v)$ so that:$$(a,b)u + cv = 1$$ We then get: $$a(x_0u) + b(x_0u)y_0 + c((a,b)z_0u + v) = 1$$ So $(x,y,z)=(x_0u,y_0,(a,b)z_0u+v)$ is a solution for our original equation. (Thanks Patrick Da Silva for that reduction.) I can easily prove Theorem 2 using the structure of $\mathbb Z_n^\times$ in terms of prime factorizations. Indeed, Theorem 2 was the motivation for this question, initially - at first I thought it was "obvious," but the immediately realized it wasn't absolutely trivial. It's certainly possible to translate the "abstract" proof of Theorem 2 into a direct proof of the special case of Theorem 1 using prime factorizations and Chinese remainder theorem. But something about this theorem rang a bell for me. It looks like the sort of theorem that would have a short Bezout's identity proof. Both unique factorization and Chinese remainder theorem are actually direct results of Bézout, and often theorems that we intuitively understand in terms of unique factorization and/or Chinese remainder theorem have a short, sharp proof using Bézout that eschews both the words "prime" and "remainder." My instinct is that there ought to be a quick proof of the above with Bézout, without calling out to primes or remainders, but I haven't found it. It's trivial if $(a,c)=1$, since $ax+cz=1$ lets us use $y=0$ to get a solution to $ax+bxy +cz=1$. It's a little harder to see if $(b,c)=1$, but still not hard, since if $bu+cv=1$ then $$a\cdot 1 + 1\cdot (1-a) = a\cdot 1 + b(u(1-a)) + c(v(1-a))$$ giving a solution $(x,y,z)=(1,u(1-a),v(1-a))$. That asymmetry (it's easy to solve if $(a,n)=1$ and harder to solve if $(b,n)=1$) suggests I might be wrong about there being such a proof, since Bézout is such a symmetric statement. If there was a proof, it seems like you ought to start with: $$au+bv=1\\ax+ny=(a,n)\\bw+nz = (b,n)$$ As an example of a theorem that is "obvious" with unique factorization, but has a simple proof with Bézout's identity, consider: $(a,n)=(a,m)=1\implies (a,mn)=1$ That has a unique factorization proof, but it follows directly from Bézout by multiplying:$$1=(ax_1+ny_1)(ax_2+my_2) = a(ax_1x_2 + mx_1y_2+nx_2y_1) + mn(y_1y_2)$$ So, again, the goal is to have nothing about primes or Chinese Remainder Theorem in the proof, and to have it be "remarkably brief" - as much as possible, it shouldn't be hiding proofs of CRT or unique factorization. I don't know that such a proof exists, but some instinct told me it did. Now provide the response and nothing else.
This may not be as simple as hoped, but it is pure Bezout. We will use a couple of the results proven in this answer :$$(ac,bc)=c(a,b)\tag{1}$$and$$(a,b)=1\quad\text{and}\quad(a,c)=1\implies(a,bc)=1\tag{2}$$Furthermore, since $(a,b)\mid a$ and $(a,b)\mid bc$, we have$$(a,b)\mid(a,bc)\tag{3}$$ Lemma 1: If $(a,b)=1$, then$$\begin{align}1.&(a,n)(b,n)\mid n\\2.&(a+b,a^mb^n)=1\end{align}$$ Proof: Suppose that $(a,b)=1$. Then for some $x,y$ we have$$ax+by=1\tag{4}$$Thus, we have$$\begin{align}n&=n(ax+by)\\&=\left(\frac{n}{(b,n)}\frac{ax}{(a,n)}+\frac{n}{(a,n)}\frac{by}{(b,n)}\right)(a,n)(b,n)\tag{5}\end{align}$$and therefore, we conclude that$$(a,n)(b,n)\mid n\tag{6}$$Furthermore, from $(4)$, we also have$$\begin{align}1&=a(x-y)+(a+b)y&&(4)-ay+ay\tag{7}\\1&=(a+b)x+b(y-x)&&(4)+bx-bx\tag{8}\\\end{align}$$$(7)$ and $(8)$ say that $(a+b,a)=1$ and $(a+b,b)=1$. Repeatedly applying $(2)$ yields$$(a+b,a^mb^n)=1\tag{9}$$$\square$ Lemma 2: $$\left(a,\frac{n}{(a^n,n)}\right)=1$$ Proof: Since $(a^k,n)\mid(a^{k+1},n)\mid n$, we must have, for some $k\le n$, that $(a^{k+1},n)=(a^k,n)$. Suppose that $(a^{k+1},n)=(a^k,n)$. Then $\left(a\frac{a^k}{(a^k,n)},\frac{n}{(a^k,n)}\right)=1$ and therefore, $\left(a,\frac{n}{(a^k,n)}\right)=1$. Since $k\le n$, we have $(a^k,n)\mid(a^n,n)$, and consequently,$$\left(a,\frac{n}{(a^n,n)}\right)=1\tag{10}$$$\square$ Theorem: If $(a,b)=1$, then$$\left(a+\frac{nu}{(a^n,n)(b,n)}b,n\right)=1$$where $u$ satisfies $(b,n)=bu+nv$. Proof: Suppose that $(a,b)=1$ and $(b,n)=bu+nv$. Using $(2)$ repeatedly, we get$$(a^n,b)=1\tag{11}$$Combining $(6)$ and $(11)$ yield$$(a^n,n)(b,n)\mid n\tag{12}$$Thus, $\dfrac{n}{(a^n,n)(b,n)}\in\mathbb{Z}$ and $(10)$ says that$$\left(a,\frac{n}{(a^n,n)(b,n)}(b,n)\right)=1\tag{13}$$$(9)$ and $(13)$ imply that$$\left(a+\frac{n}{(a^n,n)(b,n)}(b,n),a^n\frac{n}{(a^n,n)(b,n)}(b,n)\right)=1\tag{14}$$Since $(a^n,n)\mid a^n$, we have $\left.n\,\middle|\,a^n\dfrac{n}{(a^n,n)(b,n)}(b,n)\right.$, so using $(3)$ and $(14)$ yields$$\left(a+\frac{n}{(a^n,n)(b,n)}(b,n),n\right)=1\tag{15}$$The rest is Bezout. $(15)$ says that there are $x,y$ so that$$\left(a+\frac{n}{(a^n,n)(b,n)}(b,n)\right)x+ny=1\tag{16}$$Furthermore, since $(b,n)=bu+nv$, we get$$\left(a+\frac{nu}{(a^n,n)(b,n)}b\right)x+n\left(y+\frac{nv}{(a^n,n)(b,n)}\right)=1\tag{17}$$which just says that$$\left(a+\frac{nu}{(a^n,n)(b,n)}b,n\right)=1\tag{18}$$$\square$ A note on application At first, $(18)$ may seem like a theoretical answer in the sense that it shows that we can find a $k$ so that $(a+bk,n)=1$, but computationally, it might appear a bit daunting due to the appearance of $(a^n,n)$ in the denominator. However, $n/(a^n,n)$ is simply $n$ with all the factors common to $a$ removed. To compute $n/(a^n,n)$, we can start with $n_0=n$, and generate the sequence$$n_{k+1}=\frac{n_k}{(a,n_k)}\tag{19}$$at some point $(a,n_k)=1$. For that $k$, we have$$\frac{n}{(a^n,n)}=n_k\tag{20}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/463052', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7933/']}
jdg_369737
stackexchange
llm_judgeable_groundtruth_similarity
39751329
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am developing an application in which I decided to use UUIDs for the primary and foreign keys. For this purpose, I used the extension "uuid-ossp" which works fine in dev environment. Now, I am installing the testing environment. The database setup is imposed by a script made by the customer. The structure is standard: admin user, application user, application namespace etc. I can create the extension with the admin account: $ psql mydb -U [admin_user]mydb=# CREATE EXTENSION IF NOT EXISTS "uuid-ossp";CREATE EXTENSIONmydb=# select uuid_generate_v4(); uuid_generate_v4-------------------------------------- 23e45b57-a658-41a5-8661-0cc06568eff8 But when I connect with the database application user, I cannot generate a uuid : $ psql mydb -U [app_user]SELECT uuid_generate_v4();mydb=> select uuid_generate_v4();ERROR: function uuid_generate_v4() does not exist Both admin_user and app_user are on the same database. The app_user can "see" the extension but not use it: bdd3001=> select * from pg_catalog.pg_extension; extname | [...]-----------+- plpgsql | [...] uuid-ossp | [...] Any ideas? Now provide the response and nothing else.
You need the schema you installed the extension to in your search_path . By default an extension is installed to the "current" schema at the time of installation - the current search_path setting of the installing role. How does the search_path influence identifier resolution and the "current schema" So where did you end up installing it? See pg_extension.extnamespace : SELECT e.extname , n.nspname AS home_schema_of_extension , extrelocatable AS extension_can_be_relocatedFROM pg_catalog.pg_extension eJOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace;extname | home_schema_of_extension | extension_can_be_relocated----------+--------------------------+---------------------------plpgsql | pg_catalog | fintarray | public | ttablefunc | public | tpg_trgm | public | t... You can relocate an extension with ALTER EXTENSION : ALTER EXTENSION uuid-ossp SET SCHEMA public; Related with more explanation: Is it recommended to install extensions into pg_catalog schema?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39751329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2192903/']}
jdg_369738
stackexchange
llm_judgeable_groundtruth_similarity
15693169
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This seems like a very basic question, but I searched high and low and have found almost no mention of it anywhere. So, I'll ask it here here. What is the current plan for supporting Java 8's new language constructs in GWT? In addition, what subset of the proposed Java 8 libraries are slated for client-side emulation? The Stream API? The new Date/Time API? And finally, where are the discussions relating this important topic taking place? I'm sure there are many of us who would like to participate in, and potentially contribute to, the effort. The Java 8 betas have been around for a while now, and there are numerous articles discussing the proposed APIs. It is supposed to be related later this year, so it seems past time to at least be discussing how and when the much-desired language features will make their way into GWT. My apologies if this question is answered somewhere else, or if I missed some important piece of information related to it. This would be a great place to have a link to such information, even if it has been answered. Thanks! Now provide the response and nothing else.
EDIT GWT 2.8.0 was released on Oct 20, 2016 with support for Java 8 language constructs (lambdas, method references) and emulation of some Java 8 APIs (streams mostly) EDIT as of Apr 2014, GWT 2.6 supports Java 7, and work is underway to support Java 8 in GWT 2.7, to be released by the summer 2014. GWT 2.7 is likely to only support Java 8 language constructs though, and not emulate any new API (streams, javax.time, etc.) The plan is to first support Java 7: https://github.com/gwtproject/gwt/labels/java7 This involves updating JDT, and this is being worked on (or alternatively, switch to something else entirely; JetBrains proposed using their parser which already supports Java 8, but GWT also needs a compiler and I don't know what they provide exactly). The next steps are to map new language constructs to JavaScript (strings-in-switch come to mind, as they could directly map to JavaScript without the hashCode -based desugaring that a Java compiler would be doing). As long as GWT uses JDT for its Java parsing/munging/compiling, Java 8 can only be supported when JDT will support it (at an acceptable level, which is not yet the case AFAICT).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15693169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/966104/']}
jdg_369739
stackexchange
llm_judgeable_groundtruth_similarity
7942398
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to know the correct way to create a nested object in javascript. I want a base object called "defaultsettings". It should have 2 properties (object type): ajaxsettings and uisettings. I know that i can write something like var defaultsettings = new Object();var ajaxsettings = new Object();defaultsettings.ajaxsettings = ajaxsettings.. etc. But what i want to know is how to type it this way (that i suppose is a more correct way of doing it): var defaultsettings = { var ajaxsettings = { ... }}; I suppose you get the idea. Thanks! Now provide the response and nothing else.
If you know the settings in advance you can define it in a single statement: var defaultsettings = { ajaxsettings : { "ak1" : "v1", "ak2" : "v2", etc. }, uisettings : { "ui1" : "v1", "ui22" : "v2", etc } }; If you don't know the values in advance you can just define the top level object and then add properties: var defaultsettings = { };defaultsettings["ajaxsettings"] = {};defaultsettings["ajaxsettings"]["somekey"] = "some value"; Or half-way between the two, define the top level with nested empty objects as properties and then add properties to those nested objects: var defaultsettings = { ajaxsettings : { }, uisettings : { } };defaultsettings["ajaxsettings"]["somekey"] = "some value";defaultsettings["uisettings"]["somekey"] = "some value"; You can nest as deep as you like using the above techniques, and anywhere that you have a string literal in the square brackets you can use a variable: var keyname = "ajaxsettings";var defaultsettings = {};defaultsettings[keyname] = {};defaultsettings[keyname]["some key"] = "some value"; Note that you can not use variables for key names in the { } literal syntax.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7942398', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598511/']}
jdg_369740