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
24214468
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 user control in WPF that has a binding to a Dependency Property. When I try to compile the app, I get a "Property Name" was already registered by "ControlName" error, and the designer shows a "Cannot create an instance of "User Control" error. Here is what my simple control looks like: ExampleUserControl.xaml: <UserControl x:Class="ExampleApp1.ExampleUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:ExampleApp1" mc:Ignorable="d" > <TextBox Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:ExampleUserControl}}, Path=SomeStringValue}" /></UserControl> ExampleUserControl.xaml.cs: public partial class ExampleUserControl : UserControl{ public DependencyProperty SomeStringValueProperty = DependencyProperty.Register("SomeStringValue", typeof(string), typeof(ExampleUserControl)); public string SomeStringValue { get { return GetValue(SomeStringValueProperty) as string; } set { SetValue(SomeStringValueProperty, value); } } public ExampleUserControl() { InitializeComponent(); }} The Main Window it's hosted in: <Window x:Class="ExampleApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:ExampleApp1" Title="MainWindow" Height="350" Width="525"> <StackPanel> <local:ExampleUserControl SomeStringValue="Test 1" /> <local:ExampleUserControl SomeStringValue="Test 2" /> </StackPanel></Window> Here is what the designer looks like: Here is what the XAML designer looks like: Now provide the response and nothing else.
What's happening is the Dependency Property is getting Registered multiple times under the same name and owner. Dependency Properties are intended to have a single owner, and should be statically instanced. If you don't statically instance them, an attempt will be made to register them for each instance of the control. Make your DependencyProperty declaration static.Change it from: public DependencyProperty SomeStringValueProperty = DependencyProperty.Register("SomeStringValue", typeof(string), typeof(ExampleUserControl)); To: public static DependencyProperty SomeStringValueProperty = DependencyProperty.Register("SomeStringValue", typeof(string), typeof(ExampleUserControl));
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24214468', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1322678/']}
jdg_377441
stackexchange
llm_judgeable_groundtruth_similarity
5292350
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First I will list my environment and status: Environment: System: Mac OS 10.6 Python: 2.6 Apache: 2.2 mod_wsgi: 3.3 mysql: 5.x php: 3.5 trac:0.12 Status:I can run trac as alone-server without problem. Now I integrate trac to apache, problem come out. mod_wsgi can run normal wsgi page correctly, but cannot load mysql connection. I test it in piece of code, put " import MySQLdb " in wsgi page, it still cannot. I also can access trac through apache, but it shows me Cannot load Python bindings for MySQL I refer to the apache log: [Sun Mar 13 13:36:44 2011] [error] [client ::1] mod_wsgi (pid=37060): Target WSGI script /Users/alex/Library/apache2/htdocs/sql.wsgi' cannot be loaded as Python module.[Sun Mar 13 13:36:44 2011] [error] [client ::1] mod_wsgi (pid=37060): Exception occurred processing WSGI script '/Users/alex/Library/apache2/htdocs/sql.wsgi'.[Sun Mar 13 13:36:44 2011] [error] [client ::1] Traceback (most recent call last):[Sun Mar 13 13:36:44 2011] [error] [client ::1] File "/Users/alex/Library/apache2/htdocs/sql.wsgi", line 2, in <module>[Sun Mar 13 13:36:44 2011] [error] [client ::1] import MySQLdb[Sun Mar 13 13:36:44 2011] [error] [client ::1] File "build/bdist.macosx-10.6-universal/egg/MySQLdb/__init__.py", line 19, in <module>[Sun Mar 13 13:36:44 2011] [error] [client ::1] File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 7, in <module>[Sun Mar 13 13:36:44 2011] [error] [client ::1] File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 6, in __bootstrap__[Sun Mar 13 13:36:44 2011] [error] [client ::1] ImportError: dlopen(/Users/alex/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.16.dylib[Sun Mar 13 13:36:44 2011] [error] [client ::1] Referenced from: /Users/alex/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so[Sun Mar 13 13:36:44 2011] [error] [client ::1] Reason: image not found[Sun Mar 13 13:36:57 2011] [error] [client ::1] mod_wsgi (pid=37061): Target WSGI script This looks like mod_wsgi cannot find libmysqlclient.16.dylib. I encounter similar problem when I install mysqldb for python, so I add export DYLD_LIBRARY_PATH=/Users/alex/Library/mysql-5.x/lib SO python -c "import MySQLdb" can work, but mod_wsgi cannot work.So I put os.environ['DYLD_LIBRARY_PATH'] = '/Users/alex/Library/mysql-5.x/lib' into trac.ini.It doesn't work for trac in apache still. So anyone has this problem before? Thanks Now provide the response and nothing else.
The message is actually pretty clear: something creates a ThreadLocal with value of type org.apache.axis.MessageContext - this is a great hint. It most likely means that Apache Axis framework forgot/failed to cleanup after itself. The same problem occurred for instance in Logback. You shouldn't bother much, but reporting a bug to Axis team might be a good idea. Tomcat reports this error because the ThreadLocal s are created per HTTP worker threads. Your application is undeployed but HTTP threads remain - and these ThreadLocal s as well. This may lead to memory leaks ( org.apache.axis.MessageContext can't be unloaded) and some issues when these threads are reused in the future. For details see: http://wiki.apache.org/tomcat/MemoryLeakProtection
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5292350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/508755/']}
jdg_377442
stackexchange
llm_judgeable_groundtruth_similarity
45913
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 frequently use the program nohup so that my processes are immune to hangups. So if I want to make the program program immune to hangups, I use the command nohup program & where & puts the process in the background. When starting, nohup gives me the message: nohup: appending output to `nohup.out' Is there any way to send the output to a file other than nohup.out ? Often I want to run many processes in the same directory using nohup , but if I do this, all the output gets lumped together in a single nohup.out file. The manual page (for example, here ) does not seem to have an option for specifying the log file. Can you please confirm this? Also, do you have any thoughts of how I can work around this problem? Now provide the response and nothing else.
GNU coreutils nohup man page indicates that you can use normal redirection: If standard input is a terminal, redirect it from /dev/null . If standard output is a terminal, append output to nohup.out if possible, $HOME/nohup.out otherwise. If standard error is a terminal, redirect it to standard output. To save output to FILE, use nohup COMMAND > FILE . Edit: I didn't read your link at first; you may have a different version of nohup , although this section suggests that you can still use normal redirection: nohup.out The output file of the nohup execution if standard output is a terminal and if the current directory is writable. You can redirect standard output and standard error to different files: nohup myprogram > myprogram.out 2> myprogram.err & or to the same file: nohup myprogram > myprogram.out 2>&1 & (don't forget the & at the end to put into the background)
{}
{'log_upvote_score': 9, 'links': ['https://unix.stackexchange.com/questions/45913', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/9605/']}
jdg_377443
stackexchange
llm_judgeable_groundtruth_similarity
683994
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 is not totally rigth that I can run a Bash function with 000 permissions, but almost. My code is: #!/bin/bashfunction hello {echo Hello! } The hello-file has permissions: -r-------- 1 UnixBasics hello_file Firtsly, I type with the current permissions: $ . ./hello_file;hello The tweak is to change the 400 permissions to 000 right before running the bash script script: $ chmod 000 hello_file$ . ./hello_file;hello [1]-bash: ./hello_file: Permission denied Hello! It gives one error, but it does not stop running the function. I cannot understand. I now unset the hello-function: "unset hello". I receive the errors: -bash: ./hello_file: Permission denied-bash: hello: command not found Why did I not get them at the first time? Has it something to do with cache, buffer or something like it? Why can I run the Bash script with 000 permissions [1]? Now provide the response and nothing else.
You are not running the script, you are sourcing (including) it. In order to source a script, you only need the read permission. By the way, functions simply exist, they don't have permission. Once the file was sourced and the function defined, you can run it as much as you want. Update: Why did I not get them at the first time? Has it something to do with cache, buffer or something like it? Yes, like Pax answered, hello was probably previously defined there from a previous sourcing of the file. You may be confused with what sourcing ("." builtin command) does. Sourcing reads the file and runs all its commands in the current shell, then goes back to the prompt. So, if you run the file once, its functions are defined in the current shell instance, and they stay there until you finish that shell session (or unset them). Why can I run the Bash script with 000 permissions [1]? You can't. Note that it presents an error. Quoting your output: $ . ./hello_file;hello [1]-bash: ./hello_file: Permission denied Hello! You executed two commands in a single command-line. The sourcing failed with "Permission denied". The "Hello!" output is from a previous sourcing of the file. You just proved it yourself when you unset it and tried the same command-line again. You can't call that caching... it is how the shell works. You source another file, all its definitions are included in the current shell session and stay there. If you actually run the script (not sourcing) you shouldn't get any residues in the current session. $ chmod +x hello_file$ ./hello_file # note: executed, not sourced$ hello-bash: hello: command not found
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/683994', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/54964/']}
jdg_377444
stackexchange
llm_judgeable_groundtruth_similarity
649428
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: It 's been a long time since I touched this kind of math , so please help me to solve the relation step by steps : $V_k = (1+i)*V_{k-1}+P$ I know the answer is $V_k = (P/i)*((1+i)^k-1) $ Thanks in advance. Now provide the response and nothing else.
If you want a methodical way to find the answer that you don't know yet, you could use generating functions. Defining $F(x) = \sum_{k=0}^\infty V_k x^k$, and assuming the initial condition is $V_0=0$, the recursion gives\begin{align*}F(x) &= V_0 x^0 + \sum_{k=1}^\infty \big( (1+i)V_{k-1} + P \big) x^k \\&= 0 + (1+i)x \sum_{k=1}^\infty V_{k-1} x^{k-1} + Px \sum_{k=1}^\infty x^{k-1} \\&= (1+i)x \sum_{k=0}^\infty V_k x^k + Px \sum_{k=0}^\infty x^k \\&= (1+i)x F(x) + \frac{Px}{1-x}.\end{align*}Solving for $F(x)$ gives $\big(1 - (1+i)x \big) F(x) = Px/(1-x)$, and so\begin{align*}F(x) &= \frac{Px}{(1 - (1+i)x )(1-x)} \\&= \frac Pi \bigg( \frac1{(1-(1+i) x)}-\frac1{1-x} \bigg) \\&= \frac Pi \bigg( \sum_{k=0}^\infty ((1+i) x)^k - \sum_{k=0}^\infty x^k \bigg).\end{align*}Comparing coefficients of $x^k$ then yields $V_k = \frac Pi \big( (1+i)^k - 1 \big)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/649428', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/88804/']}
jdg_377445
stackexchange
llm_judgeable_groundtruth_similarity
7936066
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 attempting to learn more about mobile/tablet development and, as a .NET developer, I am naturally drawn to Mono. But I am confused--I thought that Mono was free and open source; however, all signs seem to point to Mono being a "pay-to-play" deal (https://store.xamarin.com/). Can someone please help me understand which is the correct answer? Thanks! Matt Now provide the response and nothing else.
Update (2016/03/31) Mono has been re-licensed to MIT ; The Xamarin.iOS, Xamarin.Mac and Xamarin.Android SDK are going open source ; History answer First let's clear up the Mono case :-) Mono is free as in free speech , not free beer . You can get it for free (i.e. without paying) as it is available under open source licenses that allow this. But you could still pay for it too (e.g. people did pay for some versions of Mono in Novell's days). Also some people cannot use Mono under the free open source licenses (e.g. as a game engine where the source is not available...). In such cases a commercial license, from the copyright holders, is needed. Mono for Android is a commercial product based on Mono and sold by Xamarin (who has the rights to license Mono). It re-use a lot of what Mono has achieved and also brings a lot more features to allow .NET developers to use their skills on the Android platforms. Finally evaluation versions of Mono for Android are free and fully functional when used with the Android emulator (not with devices). So you can still try, learn and enjoy Mono and Mono for Android without paying a dime to Xamarin :-) note: the same applies for MonoTouch which allows you to build .NET-based iPhone/iPad (iOS) applications from an Mac OSX computer. Disclaimer: I work for Xamarin
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7936066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/856790/']}
jdg_377446
stackexchange
llm_judgeable_groundtruth_similarity
987935
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: We have an in house Kubernetes cluster running on bare-metal, can I set up an NFS server on one of the nodes (either worker or master) in the cluster? If yes do I need to change anything in the cluster? Now provide the response and nothing else.
You can setup a pod that will act as NFS server. There is a ready image on Docker Hub cpuguy83/nfs-server . To use it you need to created a service to expose the NFS server to pods inside the cluster: kind: ServiceapiVersion: v1metadata: name: nfs-servicespec: selector: role: nfs ports: # Open the ports required by the NFS server # Port 2049 for TCP - name: tcp-2049 port: 2049 protocol: TCP # Port 111 for UDP - name: udp-111 port: 111 And a pod which will run the image: kind: PodapiVersion: v1metadata: name: nfs-server-pod labels: role: nfsspec: containers: - name: nfs-server-container image: cpuguy83/nfs-server securityContext: privileged: true args: # Pass the paths to share to the Docker image - /exports An example of a pod using the NFS volume: kind: PodapiVersion: v1metadata: name: pod-using-nfsspec: # Add the server as an NFS volume for the pod volumes: - name: nfs-volume nfs: # URL for the NFS server server: 10.108.211.244 # Change this! path: / # In this container, we'll mount the NFS volume # and write the date to a file inside it. containers: - name: app image: alpine # Mount the NFS volume in the container volumeMounts: - name: nfs-volume mountPath: /var/nfs # Write to a file inside our NFS command: ["/bin/sh"] args: ["-c", "while true; do date >> /var/nfs/dates.txt; sleep 5; done"]
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/987935', 'https://serverfault.com', 'https://serverfault.com/users/509898/']}
jdg_377447
stackexchange
llm_judgeable_groundtruth_similarity
44209858
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 this XML File <?xml version="1.0" encoding="utf-8" standalone="yes"?><Mobiles> <Mobile ID="98a2d0b9c2661725a7486423ebd94abdef53ed89051ff5ac7a9c63a4b2a99d7a" RegDate="26/05/2017"> <FullName>Galaxy S-4</FullName> <Vendor>Samsung</Vendor> <Date>2010</Date> <Price>30000SYP</Price> <Weight>5g</Weight> <Features>All</Features> <Notifecations></Notifecations> <Picture>/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQ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gdEUdlH5k8nsB21LUuTY0rBRRRUjCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//2Q==</Picture> </Mobile> <Mobile ID='00283f5aa9c0c68c342c02977051757a7faae0ee70b086e628da7cc5baef2100' RegDate="26/05/2017"> <FullName>6600</FullName> <Vendor>Nokia</Vendor> <Date>2006</Date> <Price>200SYP</Price> <Weight>10g</Weight> <Features>blutooth</Features> <Notifecations></Notifecations> <Picture>/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABbAEUDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1d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wZrdzdWlk914fvCchRuEQPJVvTHY9MY719I0YHpQJo+U9K0S3uQJrSe8aBvuoNPkmz+KjFdvpXhvUxtNroepTt03C0itQP+BSkH8ga92ooFynmtn4B1K6nWbUJbWyUf3P8ASZ/wZgFX8FNd5pum22lWK2topWMckscsxPUk9yfWrtFBQtFFFAH/2Q==</Picture> </Mobile></Mobiles> When I try to remove Mobile element depending on IDtextbox.text rather than static value in XPath expression it doesn't execute I'm using Windows application in Visual Studio 2010, C# language I need two examples:1- Depending on an element inside the parent element.2- depending on an attribute of the parent element, make sure that attribute is not an integer value, it's code.Notice: I have searched for many websites and view multiple solutions nobody mention about using control value in XPath expressions. Now provide the response and nothing else.
You can suppress Kotlin using wildcards in generics as described in the Kotlin reference where it describes the @JvmSuppressWildcards annotation (or the reverse of that @JvmWildcard annotation). From the docs: On the other hand, if we don't need wildcards where they are generated, we can use @JvmSuppressWildcards : fun unboxBase(box: Box<@JvmSuppressWildcards Base>): Base = box.value// is translated to // Base unboxBase(Box<Base> box) { ... } NOTE: @JvmSuppressWildcards can be used not only on individual type arguments, but on entire declarations, such as functions or classes, causing all wildcards inside them to be suppressed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44209858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6455496/']}
jdg_377448
stackexchange
llm_judgeable_groundtruth_similarity
57138
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 my local machine, I run: ssh -X me@remotemachine.com (For completeness, I have also tested all of the following using -Y with identical results). As expected, this accesses remotemachine.com fine, and all appears well. If I then attempt to run xcalc however, I get: connect /tmp/.X11-unix/X0: No such file or directory Error: Can't open display: localhost:10.0 But, $ ls -la /tmp/.X11-unix/total 36drwxrwxrwt 2 root root 4096 2012-11-23 09:29 .drwxrwxrwt 8 root root 32768 2012-11-29 08:22 ..srwxrwxrwx 1 root root 0 2012-11-23 09:29 X0 So not only does /tmp/.X11-unix/X0 exist, it has universal r/w/x permissions! I've previously used x-forwarding without issue, though not in some time... uname -a on the server for reference: Linux machinename 2.6.32-25-generic #45-Ubuntu SMP Sat Oct 16 19:52:42 UTC 2010 x86_64 GNU/Linux Been searching around on the web for a couple hours now without success. Other mentions of the same problem, but no solutions. Now provide the response and nothing else.
If you have a X server running and the DISPLAY environment variable is set to :0 , that tells applications to connect to the X server using a unix domain socket which is generally to be found on Linux in /tmp/.X11-unix/X0 (though see below about the abstract namespace on recent Linux). When you ssh to machine remotemachine , sshd on remotemachine sets DISPLAY to localhost:10 (for instance), which this time means that X connections are do be done over TCP to port 6010 of machine localhost. sshd on remotemachine listens for connections on there and forwards any incoming connection to the ssh client. The ssh client then tries to connect to /tmp/.X11-unix/X0 (on the local end, not the remote) to contact your X server. Now, maybe you don't have a X server running (are you on Mac?) or maybe the unix domain socket is not to be found in /tmp/.X11-unix which would mean ssh hasn't been configured properly at compile time. To figure out what the proper path is for the unix socket, you could try a strace -e connect xlogo (or the equivalent on your system) on your local machine to see what a normal X application does. netstat -x | grep X may also give a clue. For the record, on a Linux Debian wheezy machine here, Xorg listens on both /tmp/.X11-unix/X0 in the filesystem and /tmp/.X11-unix/X0 on the abstract namespace (generally written @/tmp/.X11-unix/X0 ). From strace , X11 applications seem to now use that abstract namespace by default, which explains why those still work if /tmp/.X11-unix is removed, while ssh doesn't use that abstract namespace.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/57138', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/11231/']}
jdg_377449
stackexchange
llm_judgeable_groundtruth_similarity
11617786
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 app that plays audio in the background. I'm trying to use beginBackgroundTaskWithExpirationHandler to skip to the next track when the current track is finished. Here is the code that is called when the playback state changes. It never logs the "beginBG called" even though other code in the same method implements successfully in the background. UIApplication *app = [UIApplication sharedApplication];bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ [self ffwButtonPressed:ffwButton]; NSLog(@"beginBG called"); [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid;}]; ffwButtonPressed invokes a few different methods to change the track. When that is complete... UIApplication *app = [UIApplication sharedApplication]; if (bgTask != UIBackgroundTaskInvalid) { [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; NSLog(@"end bgTask"); Edit: Declaration UIBackgroundTaskIdentifier bgTask; Edit: In ViewDidLoad bgTask = 0; Now provide the response and nothing else.
You are actually misunderstanding the function -(UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void (^)(void))handler The block argument called "handler" is what will happen when the background task expire (10min). To get your code running you need to put your code out of the expiration handler: UIApplication *app = [UIApplication sharedApplication];bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ bgTask = UIBackgroundTaskInvalid;};[self ffwButtonPressed:ffwButton];NSLog(@"beginBG called");[app endBackgroundTask:bgTask]; Here is a link to the documentation
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11617786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1228914/']}
jdg_377450
stackexchange
llm_judgeable_groundtruth_similarity
23006728
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 does the Developer command prompt for Visual studio 2012 search the location of ildasm.exe. Running command window Developer command prompt for Visual studio 2012 will point to location C:\Program Files (x86)\Microsoft visual studio 11.0 but at this location ildasm.exe couldn't be found. In fact input to command window, ildasm.exe will open the ildasm tool. Can any one clarify how does Developer command prompt for Visual studio 2012 locate the physical ildasm.exe. Now provide the response and nothing else.
When you start Developer command prompt for Visual studio 2012 the command (it is a bat script) modifies environment PATH (and other things that does not matter in this case). You can see the difference when you type set in Developer command prompt for Visual studio 2012 and in classic cmd . When you open Developer command prompt for Visual studio 2012 it is true that you land in C:\Program Files (x86)\Microsoft visual studio 11.0 but thanks to the modified PATH variable windows will look in every directory mentioned by this variable. It will find ildasm.exe in i.e. c:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\ .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23006728', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1142075/']}
jdg_377451
stackexchange
llm_judgeable_groundtruth_similarity
18123965
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 is if True slower than if 1 in Python? Shouldn't if True be faster than if 1 ? I was trying to learn the timeit module. Starting with the basics, I tried these: >>> def test1():... if True:... return 1... else:... return 0>>> print timeit("test1()", setup = "from __main__ import test1")0.193144083023>>> def test2():... if 1:... return 1... else:... return 0>>> print timeit("test2()", setup = "from __main__ import test2")0.162086009979>>> def test3():... if True:... return True... else:... return False>>> print timeit("test3()", setup = "from __main__ import test3")0.214574098587>>> def test4():... if 1:... return True... else:... return False>>> print timeit("test4()", setup = "from __main__ import test4")0.160849094391 I am confused by these things: According to the response from Mr. Sylvain Defresne in this question , everything is implicitly converted to a bool first and then checked. So why is if True slower than if 1 ? Why is test3 slower than test1 even though only the return values are different? Like Question 2, but why is test4 a little faster than test2 ? NOTE: I ran timeit three times and took the average of the results, then posted the times here along with the code. This question does not relate to how to do micro benchmarking(which I did in this example but I also understand that it is too basic) but why checking a 'True' variable is slower than a constant. Now provide the response and nothing else.
True and False are not keywords in Python 2 . They must resolve at runtime. This has been changed in Python 3 Same test on Python 3: >>> timeit.timeit('test1()',setup="from __main__ import test1", number=10000000)2.806439919999889>>> timeit.timeit('test2()',setup="from __main__ import test2", number=10000000)2.801301520000038>>> timeit.timeit('test3()',setup="from __main__ import test3", number=10000000)2.7952816800000164>>> timeit.timeit('test4()',setup="from __main__ import test4", number=10000000)2.7862537199999906 Time error is in 1%, which is acceptable.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18123965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/850018/']}
jdg_377452
stackexchange
llm_judgeable_groundtruth_similarity
5225197
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 NSArray of objects , which has a particular property called name (type NSString). I have a second NSArray of NSStrings which are names . I'd like to get an NSArray of all the objects whose .name property matches one of the names in the second NSArray. How do I go about this, fast and efficiently as this will be required quite often. Now provide the response and nothing else.
Why not just to use predicates to do that for you?: // For number kind of values:NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF = %@", value];NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];// For string kind of values:NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", value];NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];// For any object kind of value (yes, you can search objects also):NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", value];NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5225197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191463/']}
jdg_377453
stackexchange
llm_judgeable_groundtruth_similarity
50840726
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 out Node.js for scripting. I have a script, where I check the existence of ./node_modules/some-package . If it doesn't exist, some-package is installed. This seems kind of hacky however. Is there a better way to check if a particular package is installed from within the script? sample code const fs = require('fs');let installed;try { fs.accessSync('./node_modules/.bin/some-package'); installed = true;} catch (err) { installed = false;} Now provide the response and nothing else.
One problem with the question's approach could be, that the path of the node_modules folder may be changed ( npm local install package to custom location ). One way to utilize npm for getting information about installed packages is via npm ls . The following call will return the installed version of some-package : npm ls some-package In case the package exists, it will print the version information, otherwise (empty) . Make use of the --json cli-flag in case you want to parse the response. If you're interested whether the package exists or not, you may just use the exit code: it's 0 if the package exists and non-zero otherwise.* Bonus: Refer to Execute a command line binary with Node.js on how to execute shell commands from nodejs. Source: Find the version of an installed npm package , https://docs.npmjs.com/cli/ls *At least for me with node 5.6.0
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50840726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5587552/']}
jdg_377454
stackexchange
llm_judgeable_groundtruth_similarity
150448
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 wonder whether it is really secure to store the Two Factor Authentication seed code (e.g. the secret key for TOTP) within a password manager together with the user and password for the service. If someone gets access to the decrypted password database (e.g. while the password manager is unlocked or by brute forcing the master password), the attacker also has access to the TOTP token which makes Two Factor Authentication pretty useless. In my eyes, storing the Two Factor Authentication code in the password manager is everything beyond secure. Now provide the response and nothing else.
I don't think it's as bad an idea as you assume. Think about what threats you're trying to guard against by using TOTP, and think about what attack scenarios are made easier (or not) if storing the TOTP seed in your password safe. With the seed in your password database, TOTP will still guard against: Password breaches of the website where you hold your account Keyloggers on untrusted computers (on which I assume you will not actually run your password manager, but rather read a password off a trusted device and type it in manually) Network captures on open WiFi networks, etc. Phishing/social engineering of you , the user Things which are NOT guarded against include: Social engineering of customer service/tech support of the website owner A stolen password database and master password The first case cannot be helped regardless of where your TOTP seed is stored. The second case deserves some additional consideration. Specifically, how can your database and master password be breached? Either: The attacker obtains a copy of your database from cloud storage, or a discarded backup, and cracks your master password. A strong master password (80+ bits of entropy) and secure implementation of a KDF on the part of the password manager developers should completely prevent this attack. The attacker puts malware on your machine which is specifically designed to target your password manager. But consider: if you have such targeted malware on your machine, why not write malware to hijack a browser session? Or force-install a browser extension to steal all the desired information? Or install a custom certificate to allow a MITM attack? A browser extension could even display pages making it look like you were simply logging into the site again, whereas in reality you were providing the credentials needed to disable 2FA entirely! Now, some caveats: there is ready-made malware (or at least proof-of-concept code) out there which can already target specific password managers. I'm not aware of any ready-made malware that interactively takes over an account to disable 2FA. But the point is, the only scenario where the TOTP seed causes problems for you, is a scenario that would also cause problems even if your TOTP seed was stored elsewhere. With that in mind, I've not seen any convincing arguments against keeping the TOTP code in my password manager, especially for password managers that can use the TOTP seed to generate the codes for you in place of Authenticator, Authy, etc. Recent events have brought to my attention a scenario I did not consider above: if you store an account in your password manager, which you only ever access on specific systems, you can expose yourself to increased risk by storing the 2FA code for that specific account in your normal, synced-everywhere, day-to-day password vault. Specifically, I'm referring to the continued fallout from the late 2022 LastPass breach. It came to light recently that a senior DevOps engineer at LastPass had their personal password manager data stolen from their home computer. From there, the attackers extracted login credentials for a corporate vault that only 3 other employees had access to: https://arstechnica.com/information-technology/2023/02/lastpass-hackers-infected-employees-home-computer-and-stole-corporate-vault/ Now, the article does not specify whether the corporate vault was protected with any sort of 2FA, or if seed values for TOTP-based 2FA for this vault were stored in the engineer's personal password manager. It also doesn't specify whether the engineer ever used this corporate vault from their home computer (but that seems unlikely). The level of sophistication and persistence these attackers showed, and the high value of this engineer's account, imply that this person may have been compromised eventually even if they did have 2FA codes stored only on their phone. HOWEVER, the event raises the following plausible scenario in my mind: You have a sensitive account which you access only at work (or similar). You do not (or maybe cannot) access this account at home. You sync your password manager between home and work. You store your work-only account password and 2FA key together in your personal password manager. An attacker completely pwns your home computer, while you access your personal vault at home. In this very specific scenario, your work-only account is indeed at increased risk of exposure. Presumably, corporate assets are protected better than your home computer and are less likely to have vulnerable media player software and the like installed so their attack surface is reduced. If you have accounts you only ever access from specific devices, storing both the password and 2FA seed together in a vault accessed from multiple other devices does probably degrade the security of that specific account. HOWEVER: as before, storing the 2FA code in an encrypted vault on the same device you use to login doesn't really add risk. Looking at how this engineer's personal vault was compromised, 2FA did not help at all. It didn't matter if they had stored their 2FA seed in their vault, or on their phone. The attacker was running malware locally on the computer the engineer was logged into, and was able to bypass MFA simply by waiting for the engineer to enter the MFA code themself. I assume that most people generally do not have high-value accounts only accessible from specific devices, where they login using their vault shared with other devices. If you are one of the high-value targets holding keys to a high-value asset, it is probably wise not to store password and 2FA seeds together on some other less secure device. If this very specific scenario does not describe you and the account you are protecting (I assume this is the case for most people), then refer to the previous analysis.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/150448', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/138286/']}
jdg_377455
stackexchange
llm_judgeable_groundtruth_similarity
16148598
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 populate a GeoJson layer with data and then dynamically filter what features to show. I have gotten the filter function to work but I do not know how to change the filter and then refresh the layer. Is there any way I can update the filter after I have added the data? Now provide the response and nothing else.
I did this by adding each feature type to a different LayerGroup based on a property of the feature. e.g. GeoJSON var data =[ { type: "Feature", properties: { type: "type1" }, geometry: { type: "Point", coordinates: [-1.252,52.107] } }, { type: "Feature", properties: { type: "type2" }, geometry: { type: "Point", coordinates: [-2.252,54.107] } }]; Create the GeoJSON Layer //array to store layers for each feature typevar mapLayerGroups = [];//draw GEOJSON - don't add the GEOJSON layer to the map hereL.geoJson(data, {onEachFeature: onEachFeature})//.addTo(map);/* *for all features create a layerGroup for each feature type and add the feature to the layerGroup*/function onEachFeature(feature, featureLayer) { //does layerGroup already exist? if not create it and add to map var lg = mapLayerGroups[feature.properties.type]; if (lg === undefined) { lg = new L.layerGroup(); //add the layer to the map lg.addTo(map); //store layer mapLayerGroups[feature.properties.type] = lg; } //add the feature to the layer lg.addLayer(featureLayer); } Then you can call the Leaflet map.addLayer/removeLayer functions e.g. //Show layerGroup with feature of "type1"showLayer("type1");/** show/hide layerGroup */function showLayer(id) { var lg = mapLayerGroups[id]; map.addLayer(lg); }function hideLayer(id) { var lg = mapLayerGroups[id]; map.removeLayer(lg); }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16148598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/104059/']}
jdg_377456
stackexchange
llm_judgeable_groundtruth_similarity
3495663
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 new to mathematical proofs, and I am not quite sure how to tackle problems of that nature. Here is the problem: Prove that if $b≥-1$ , $b≠0$ , then $\frac{4b^2+b+1}{4|b|} ≥ \sqrt{b+1}$ I tried to rearrange the inequality on the right like so, $\frac{4b^2+b+1-4|b|\sqrt{b+1}}{4|b|} ≥ 0$ but this didn't really help me much. I am aware that I need to use the factthat $b≥-1$ to proceed further, however, I don't know when it should come into play. I am also not exactly sure if I always need to start working with the latter part ( $\frac{4b^2+b+1}{4|b|} ≥ \sqrt{b+1}$ ) when dealing with proofs of this kind? Thanks a lot in advance! Now provide the response and nothing else.
In general, there is no method that will solve any inequality. Inequalities need to be tackled case by case, although we can simplify particular forms given prior experience and knowledge. General mathematical intuition and perserverance will go a long way toward unfamiliar forms. A specific strategy is to change your variables so the condition is something nice. This usually makes the problem much easier to read and digest. Here it doesn't change too much but it's a good general strategy to keep in mind, so I will demonstrate it anyways. Let $b = c-1$ . This means if $b \ge -1$ , then $c \ge 0$ . Now we can rewrite the inequality as: $$\frac{4(c-1)^2+c}{4|c-1|} \ge \sqrt{c}$$ Next, notice that there is a $|c-1|$ in the denominator and a $(c-1)^2$ in the numerator. This is very good because it will be very easy to reduce. $$\frac{4(c-1)^2}{4|c-1|} + \frac{c}{4|c-1|} \ge \sqrt{c} \\|c-1| + \frac{c}{4|c-1|} \ge \sqrt{c}$$ Now multiply out the denominator: $$4(c-1)^2 + c \ge 4|c-1|\sqrt{c} \\4(c-1)^2 - 4|c-1|\sqrt{c} + c \ge 0$$ Setting $0$ on one side is very useful here because we know that $a^2 \ge 0$ for all real $a$ . We can try to see if the left side is a perfect square: $$\left(2|c-1| - \sqrt{c} \right)^2 \ge 0$$ It is in fact a perfect square! This means that as long as the expression in parentheses is real, we have a solution. The only way in which this works is if $\sqrt{c}$ is positive, or in other words, $c \ge 0$ . We remove the $c = 1$ singularity and we are done! EDIT: @pidgeon's comment is excellent, because it takes an inequality that is true for an entire domain and applies it directly. You can take that inequality and immediately apply it to a problem if you can find the clever substitutions. This will be much faster than my more brute force approach, but it is the method I use when I don't have a better one. Another really great inequality to always keep on hand is the AM-GM-HM inequality, which simply states that for any set of positive numbers, the arithmetic mean is at least the geometric mean, which is at least the harmonic mean.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3495663', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/730571/']}
jdg_377457
stackexchange
llm_judgeable_groundtruth_similarity
41055292
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 function: template <typename T, typename std::enable_if <std::is_same<T, int>::value == true>::type* = nullptr>void test(T i){ //process data} It works. However, I need to enable this function not only for int , but for float and const char * as well... how to do this without writing the same method 3x times? Now provide the response and nothing else.
Like this: template <typename T, typename std::enable_if <std::is_same<T, int >::value || std::is_same<T, float >::value || std::is_same<T, const char *>::value>::type* = nullptr>void test(T i){ //process data}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41055292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1130231/']}
jdg_377458
stackexchange
llm_judgeable_groundtruth_similarity
19019
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: NET Version : "I have created a man just as the LORD did!" (Genesis 4:1) Most other translations have her giving credit to the Lord, whereas this one has her pretending to be a Godess. While this translation at first surprised me, it seems consistent in it's own way to Eve's original desire to be a God, whereas the other versions seem to have her hoping in God. The variation seems diametrically opposed to the traditional thought "The Lord has helped me" Is there a biblical or translational reason to think this might be accurate? Now provide the response and nothing else.
When considering the NET translation one should always consider the footnotes. 4 tn Here is another sound play (paronomasia) on a name. The sound of the verb קָנִיתִי (qaniti, “I have created”) reflects the sound of the name Cain in Hebrew (קַיִן, qayin) and gives meaning to it. The saying uses the Qal perfect of קָנָה (qanah). There are two homonymic verbs with this spelling, one meaning “obtain, acquire” and the other meaning “create” (see Gen 14:19, 22; Deut 32:6; Ps 139:13; Prov 8:22). The latter fits this context very well. Eve has created a man. Notice that the footnote states there are two verbs with this same spelling one that means "obtain, acquire" and another that means "create" the NET choice of "create" is based upon the value judgement of the translators that it fits best however two points should be noted against that assumption. (1) The more common meaning of the verb is obtain, as “acquired” (NJB), “gotten” (AV, NASB), or “gained” (NJPS) this accounts for around 220 uses of the the word out of 226. (2) In The infrequent occasions this verb is used in the sense of create (as “brought forth” (NIV, REB) or “produced” (NAB, NRSV)) God is invariably its subject (Cf. Gen 14:19, 22; Deut 32:6; Ps 139:13; Prov 8:22; also perhaps Exod 15:16; Ps 78:54.), but here we have the woman, Eve, as the subject. Then there is also the LXX rendering to be considered as well. Genesis 4:1 Αδαμ δὲ ἔγνω Ευαν τὴν γυναῖκα αὐτοῦ καὶ συλλαβοῦσα ἔτεκεν τὸν Καιν καὶ εἶπεν ἐκτησάμην ἄνθρωπον διὰ τοῦ θεοῦ The lexicons seems to unite in their agreement that κτάομαι means to obtain, acquire or get, for example: [GING] κτάομαι procure for oneself, acquire, get Mt 10:9; Lk 18:12; 21:19; Ac 1:18; 8:20; 22:28; 1 Th 4:4.* [pg 114] [Fri] κτάομαι fut. κτήσομαι; 1aor. ἐκτησάμην; (1) as procuring something for oneself get, obtain, acquire (AC 1.18); (2) idiomatically; (a) σκεῦος κτᾶσθαι literally possess a container, i.e. control one's sexual life, derivative, derivation, derived from regarding σκεῦος (container) either as one's body or one's wife (1TH 4.4); (b) κτᾶσθαι τὴν ψυχήν literally acquire one's soul, i.e. save oneself, protect one's life (LU 21.19) ἐκτησάμην VIAD--1S κτάομαι It seems to me that the NET needs to do more to make its case than simply assert "The latter fits this context very well." The other significant footnote is: 5 tn Heb “with the Lord.” The particle אֶת־ (’et) is not the accusative/object sign, but the preposition “with” as the ancient versions attest. Some take the preposition in the sense of “with the help of” (see BDB 85 s.v. אֵת; cf. NEB, NIV, NRSV), while others prefer “along with” in the sense of “like, equally with, in common with” (see Lev 26:39; Isa 45:9; Jer 23:28). Either works well in this context; the latter is reflected in the present translation. Some understand אֶת־ as the accusative/object sign and translate, “I have acquired a man – the Lord.” They suggest that the woman thought (mistakenly) that she had given birth to the incarnate Lord, the Messiah who would bruise the Serpent’s head. This fanciful suggestion is based on a questionable allegorical interpretation of Gen 3:15 (see the note there on the word “heel”). Ignoring the last part of the footnote that is irrelevant to the discussion at hand the translator acknowledges that either the meaning of "with the help of" or "just as the Lord did" is possible. It seems to this writer however that the NET chooses its preferred option based upon its translation of created rather than acquired. If one chooses to go with acquired as there is strong evidence to do then "with the help of" seems like the most probably translation. In conclusion I quote the NAC commentary: Rather, her exclamation acknowledges that this achievement came only by the assistance of the Lord. T his first birth recorded in the Bible is consonant with all of remaining Scripture, which invariably attributes conception and life to the unique work of God and as evidence of his blessing (e.g., Pss 127:3–5; 139:13). From the outset of God’s plan for the human family, procreation is the divine-human means whereby the man and woman might achieve the dominion that God has envisioned for them (1:28). This motif of children (“seed”) dominates Genesis and was critical to later Israel’s understanding of its own destiny as it interpreted the life of the patriarchs (e.g., 12:7). Mathews, K. A. (1996). Genesis 1-11:26 (Vol. 1A, p. 265). Nashville: Broadman & Holman Publishers.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/19019', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/9866/']}
jdg_377459
stackexchange
llm_judgeable_groundtruth_similarity
5859097
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say I have interface IFoo { /// <summary> /// Comments about Bar method goes here. /// </summary> void Bar(); } I'm using reflection to display the methods at runtime MethodInfo[] mis = typeof(IFoo).GetMethods(); but I was wondering if I can get the comments included in <summary> </summary> for the methods. I realize that comments are just ignored my the compiler but is there anything that could be done to retrieve comments? Right now I have a seperate file that has the methods and the comments but I hate the redundancy and was wondering if there is any way to do this. Thanks, Now provide the response and nothing else.
The C# compiler csc.exe has a /doc option that outputs an external XML file having your triple-slash comments. This XML file is used by documentation generators (e.g. Sandcastle does this kind of thing). That same option to export XML comments is available from Visual Studio. To set this compiler option in the Visual Studio development environment: Open the project's Properties page. For details, see How to: Set Project Properties (C#, J#). Click the Build property page. Modify the XML Documentation File property. You can load up this XML file using an XML parser from the .NET framework, access the Types in it, and grab the related comments from around them. You're right the C# compiler doesn't compile comments into the meta data. However Microsoft created triple-slash comments for export ability, so you can get a handle to them. Instructions for processing the XML file are here on MSDN . As an example, I enable the XML output file option and documented the following method: /// <summary>/// This method parses the given name for/// capitalization./// </summary>public void ParseStringCase(string name){ // behaviour of method...} It produces the following XML in a file in the bin/ folder.... <?xml version="1.0"?><doc> <assembly> <name>WindowsFormsApplication3</name> </assembly> <members> <member name="M:WindowsFormsApplication3.Form1.ParseStringCase(System.String)"> <summary> This method parses the given name for capitalization. </summary> </member> </members></doc>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5859097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_377460
stackexchange
llm_judgeable_groundtruth_similarity
1638499
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: A question was raised in our class about the non-existence of product in a category. The two examples that came up in the discussion was the category of smooth manifolds with boundary and the category of fields. But I cannot formally prove why categorical product does not exist in these categories. I can see that category of finite fields cannot have infinite products due to cardinality reasons, but I would like to know why category of fields cannot even have finite products. Is there any other simple example of a category without (finite) products? Any help regarding this appreciated. Now provide the response and nothing else.
For fields the most basic problem is fields of different characteristic. If $K$ and $L$ are fields, then the product $K\times L$ (if it existed) would have to be a field that can map into both $K$ and $L$, which means in particular it has the same characteristic as both $K$ and $L$, which is impossible if $K$ and $L$ have different characteristic. Even if you restrict to fields of a fixed characteristic, however, you still don't have products. For instance, in the category of fields of some fixed characteristic, let $K$ be any field with a non-identity endomorphism $e:K\to K$. Then I claim there is no product $K\times K$. For suppose there were; call it $P$, and let $p:P\to K$ and $q:P\to K$ be the two projections. Considering $L=K$ and the identity maps $f=g=1:L\to K$, by the universal property of the product there must exist $h:L\to P$ such that $ph=f$ and $qh=g$. Since $f$ and $g$ are the identity and every map of fields is injective, this means that $h$ must be an isomorphism and $p=q$ is its inverse. But now consider $g'=e:L\to K$; there is then an $h':L\to K$ such that $ph'=f$ and $qh'=g'$. Since $p=q$, this means $f=g'$, which is a contradiction since we assumed $e\neq 1$. The case of smooth manifolds with boundary is fairly subtle (indeed, the category of smooth manifolds has some limits you might not expect it to have). Let me sketch a proof that there is no product $[0,1)\times[0,1)$ in the category of smooth manifolds with boundary. Suppose you had such a product $P$. By considering maps from the $1$-point manifold to $P$, you can identify the underlying set of $P$ with the cartesian product $[0,1)\times[0,1)$. By considering smooth maps from $\mathbb{R}$, you can show that $P$ is connected. By considering smooth maps from $\mathbb{R}^2$, you can show that $P$ is $2$-dimensional and that $\{0\}\times [0,1)\cup[0,1)\times\{0\}$ must be its boundary (here we use that a point is in the interior of a $2$-manifold iff there is an injective smooth map from $\mathbb{R}^2$ to the manifold whose image contains the point but no such map from $\mathbb{R}^n$ for any $n>2$). Again using smooth maps from $\mathbb{R}$, you can show that this boundary must be connected, and that (via the classification of $1$-manifolds) in fact it must be diffeomorphic to $\mathbb{R}$. Such a diffeomorphism $\mathbb{R}\to P$ onto the boundary then gives a smooth injection $i:\mathbb{R}\to\mathbb{R}^2$ whose image is $\{0\}\times [0,1)\cup[0,1)\times\{0\}$, and $i$ has the property that every smooth map $j:\mathbb{R}\to\mathbb{R}^2$ whose image is contained in $\{0\}\times [0,1)\cup[0,1)\times\{0\}$ factors smoothly through $i$. You can show that no such $i$ exists by examining what it does near the corner: assuming without loss of generality that $i(0)=(0,0)$, then all the derivatives of $i$ must vanish at $0$. But then $j(x)=i(\sqrt[3]{x})$ is smooth and does not factor through $i$, which is a contradiction. For other examples of categories without products, it is very easy to get examples if you look at small categories you think of as an individual algebraic structure, rather than categories like "the category of all structures of a certain kind". For instance, you can form a category with any set of objects and no non-identity morphisms, and this doesn't have products of distinct objects. Or you can take a monoid and consider it as a category with one object, and it will rarely have a product of two copies of the object.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1638499', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54151/']}
jdg_377461
stackexchange
llm_judgeable_groundtruth_similarity
41286898
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 method that takes std::string_view and uses function, which takes null terminated string as parameter. For example: void stringFunc(std::experimental::string_view str) { some_c_library_func(/* Expects null terminated string */);} The question is, what is the proper way to handle this situation? Is str.to_string().c_str() the only option? And I really want to use std::string_view in this method, because I pass different types of strings in it. Now provide the response and nothing else.
You cannot alter a string through std::string_view . Therefore you cannot add a terminating '\0' character. Hence you need to copy the string somewhere else to add a '\0' -terminator. You could avoid heap allocations by putting the string on the stack, if it's short enough. If you know, that the std::string_view is part of a null-terminated string, then you may check, if the character past the end is a '\0' character and avoid the copy in that case. Other than that, I don't see much more room for optimizations.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41286898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6275792/']}
jdg_377462
stackexchange
llm_judgeable_groundtruth_similarity
142090
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Greetings, I was wondering how one might link a Linux MIT Kerberos with a Windows 2003 Active Directory to achieve the following: A user, USER@WINDOWDIRECTORY.INTERNAL, attempts to log in at an Apache website, which runs on the same server as the Linux MIT Kerberos. The Apache module first asks the local Linux MIT Kerberos if he knows a user by that name or realm. The MIT Kerberos finds out it isn't responsible for that realm, and forwards the request to the Windows 2003 Active Directory. The Windows 2003 Active Directory replies positively and gives this information to the Linux MIT Kerberos, which in turn tells this to the Apache module, which grants the user access to its files. Here is an image of the situation: The documentation I have read concerning this issue often differ from this problem: Some discuss linking up a MIT Kerberos with an Active Directory to gain access to resources on the Active Directory server; While another uses the link to authenticate Windows users to the MIT Kerberos through the Windows 2003 Active Directory. (My problem is the other way around.) So what my question boils down to, is this: Is it possible to have a Linux MIT Kerberos server pass through requests for a Active Directory realm, and then have it receive the reply and give it to the requesting service? (Although it's not a problem if the requesting service and the Windows 2003 Active Directory communicate directly.) Suggestions and constructive criticism are greatly appreciated. :) LATER EDIT I'm having some issues with this. I've successfully configured mod_auth_kerb to do negotiation with the MIT Kerberos (in my case, EINDWERK.LAN), and if I fetch a ticket for the local MIT Kerberos with kinit on Ubuntu, I can surf to the Apache webserver without being prompeted for a login. However, if I fetch a ticket from the Active Directory server (in my case, WINDOWS.LAN) and surf to the Apache webserver, I am greeted with a login prompt. Looking at the packets through Wireshark, it appears the Apache webserver is incorrectly attempting to use a TGT of EINDWERK.LAN for WINDOWS.LAN. I have uploaded the Wireshark output for: A kinit for the Active Directory user "tester" (tester@WINDOWS.LAN), which succeeds (ignore KRB5KDC_ERR_PREAUTH_REQUIRED, there is no preauth here) One trip to the Apache webserver,where you can see that it goes wrong. [LINK] EDIT: Yup, it always tries to authenticate with a TGT for EINDWERK.LAN. I'm going to try and create a trust between the AD and the MIT Kerberos and see if that fixes it. EDIT2: Ok, by creating a trust ( Here's a tutorial ), everything seems to be checking out correctly, but I had to force rc4-hmac encryption for the tickets from the Active Directory, and the Apache HTTP service is encrypted in des3-cbc-sha1. Does anyone know how to delete a principal and encrypt its keys with a certain encryption? Now provide the response and nothing else.
Microsoft has courteously created an entire KB article called " How To Use SQL Server to Analyze Web Logs " which should answer your title question. Yes it makes sense to store the logs in sql server if for no other reason than mitigating file corruption issues and also making backups of those files easier using SQL scheduler. The pros of using a SQL Server database are virtually self evident. Flat text files offer no data mining ability. Relational databases that can be queried via SQL are made for information storage and retrieval. That information can easily be culled for trends, statistics, correlations and etc. It's all a matter of developing the queries and reports. What other solution? Possible using Splunk to gather information from the flat files, but that's not the same. That's not statistics in quite the same way.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/142090', 'https://serverfault.com', 'https://serverfault.com/users/41270/']}
jdg_377463
stackexchange
llm_judgeable_groundtruth_similarity
10933838
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 know how to do it for a TXT file, but now I am having some trouble doing it for a CSV file. How can I read a CSV file from the bottom in Python? Now provide the response and nothing else.
Pretty much the same way as for a text file: read the whole thing into a list and then go backwards: import csvwith open('test.csv', 'r') as textfile: for row in reversed(list(csv.reader(textfile))): print ', '.join(row) If you want to get fancy, you could write a lot of code that reads blocks starting at the end of the file and working backwards, emitting a line at a time, and then feed that to csv.reader , but that will only work with a file that can be seeked, i.e. disk files but not standard input. Some of us have files that do not fit into memory, could anyone come with a solution that does not require storing the entire file in memory? That's a bit trickier. Luckily, all csv.reader expects is an iterator-like object that returns a string (line) per call to next() . So we grab the technique Darius Bacon presented in " Most efficient way to search the last x lines of a file in python " to read the lines of a file backwards, without having to pull in the whole file: import osdef reversed_lines(file): "Generate the lines of file in reverse order." part = '' for block in reversed_blocks(file): for c in reversed(block): if c == '\n' and part: yield part[::-1] part = '' part += c if part: yield part[::-1]def reversed_blocks(file, blocksize=4096): "Generate blocks of file's contents in reverse order." file.seek(0, os.SEEK_END) here = file.tell() while 0 < here: delta = min(blocksize, here) here -= delta file.seek(here, os.SEEK_SET) yield file.read(delta) and feed reversed_lines into the code to reverse the lines before they get to csv.reader , removing the need for reversed and list : import csvwith open('test.csv', 'r') as textfile: for row in csv.reader(reversed_lines(textfile)): print ', '.join(row) There is a more Pythonic solution possible, which doesn't require a character-by-character reversal of the block in memory (hint: just get a list of indices where there are line ends in the block, reverse it, and use it to slice the block), and uses chain out of itertools to glue the line clusters from successive blocks together, but that's left as an exercise for the reader. It's worth noting that the reversed_lines() idiom above only works if the columns in the CSV file don't contain newlines. Aargh! There's always something. Luckily, it's not too bad to fix this: def reversed_lines(file): "Generate the lines of file in reverse order." part = '' quoting = False for block in reversed_blocks(file): for c in reversed(block): if c == '"': quoting = not quoting elif c == '\n' and part and not quoting: yield part[::-1] part = '' part += c if part: yield part[::-1] Of course, you'll need to change the quote character if your CSV dialect doesn't use " .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10933838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1234383/']}
jdg_377464
stackexchange
llm_judgeable_groundtruth_similarity
33527566
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 was learning C++ and come across the following question. I'm just a beginner and I got confused. Isn't sizeof() function supposed to return the size of the datatype? Why could a data object has different size from its sizeof()? I don't understand the explanation of the answer. Suppose in a hypothetical machine, the size of char is 32 bits. What would sizeof(char) return? a) 4 b) 1 c) Implementation dependent d) Machine dependent Answer:b Explanation: The standard does NOT require a char to be 8-bits, but does require that sizeof(char) return 1. Now provide the response and nothing else.
The sizeof operator yields the size of a type in bytes , where a byte is defined to be the size of a char . So sizeof(char) is always 1 by definition, regardless of how many bits char has on a given platform. This applies to both C and C++. From the C11 standard, 6.5.3.4 The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand.... Then, When sizeof is applied to an operand that has type char , unsigned char , or signed char , (or a qualified version thereof) the result is 1. From the C++11 standard, 5.3.3 The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id .... ... sizeof(char) , sizeof(signed char) and sizeof(unsigned char) are 1. (emphasis mine)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33527566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5175084/']}
jdg_377465
stackexchange
llm_judgeable_groundtruth_similarity
4261133
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 running a PHP script and continue to receive errors like: Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10 Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11 Warning: Undefined array key "my_index" in C:\wamp\www\mypath\index.php on line 11 Line 10 and 11 looks like this: echo "My variable value is: " . $my_variable_name;echo "My index value is: " . $my_array["my_index"]; What is the meaning of these error messages? Why do they appear all of a sudden? I used to use this script for years and I've never had any problem. How do I fix them? This is a General Reference question for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific. Related Meta discussion: What can be done about repetitive questions? Do “reference questions” make sense? Now provide the response and nothing else.
Notice / Warning: Undefined variable From the vast wisdom of the PHP Manual : Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of empty() since it does not generate a warning or error message if the variable is not initialized. From PHP documentation : No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var== false . This means that you could use only empty() to determine if the variable is set, and in addition it checks the variable against the following, 0 , 0.0 , "" , "0" , null , false or [] . Example: $o = [];@$var = ["",0,null,1,2,3,$foo,$o['myIndex']];array_walk($var, function($v) { echo (!isset($v) || $v == false) ? 'true ' : 'false'; echo ' ' . (empty($v) ? 'true' : 'false'); echo "\n";}); Test the above snippet in the 3v4l.org online PHP editor Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue a very low level error, E_NOTICE , one that is not even reported by default, but the Manual advises to allow during development. Ways to deal with the issue: Recommended: Declare your variables, for example when you try to append a string to an undefined variable. Or use isset() / !empty() to check if they are declared before referencing them, as in: //Initializing variable$value = ""; //Initialization value; Examples //"" When you want to append stuff later //0 When you want to add numbers later//isset()$value = isset($_POST['value']) ? $_POST['value'] : '';//empty()$value = !empty($_POST['value']) ? $_POST['value'] : ''; This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator : // Null coalesce operator - No need to explicitly initialize the variable. $value = $_POST['value'] ?? ''; Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file): set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT) Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is: error_reporting( error_reporting() & ~E_NOTICE ) Suppress the error with the @ operator . Note: It's strongly recommended to implement just point 1. Notice: Undefined index / Undefined offset / Warning: Undefined array key This notice/warning appears when you (or PHP) try to access an undefined index of an array. Ways to deal with the issue: Check if the index exists before you access it. For this you can use isset() or array_key_exists() : //isset()$value = isset($array['my_index']) ? $array['my_index'] : '';//array_key_exists()$value = array_key_exists('my_index', $array) ? $array['my_index'] : ''; The language construct list() may generate this when it attempts to access an array index that does not exist: list($a, $b) = array(0 => 'a');//orlist($one, $two) = explode(',', 'test string'); Two variables are used to access two array elements, however there is only one array element, index 0 , so this will generate: Notice: Undefined offset: 1 # $_POST / $_GET / $_SESSION variable The notices above appear often when working with $_POST , $_GET or $_SESSION . For $_POST and $_GET you just have to check if the index exists or not before you use them. For $_SESSION you have to make sure you have the session started with session_start() and that the index also exists. Also note that all 3 variables are superglobals and are uppercase. Related: Notice: Undefined variable Notice: Undefined Index
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/4261133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187606/']}
jdg_377466
stackexchange
llm_judgeable_groundtruth_similarity
18017869
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 complex json file that I have to handle with javascript to make it hierarchical, in order to later build a tree.Every entry of the json has :id : a unique id, parentId : the id of the parent node (which is 0 if the node is a root of the tree)level : the level of depth in the tree The json data is already "ordered". I mean that an entry will have above itself a parent node or brother node, and under itself a child node or a brother node. Input : { "People": [ { "id": "12", "parentId": "0", "text": "Man", "level": "1", "children": null }, { "id": "6", "parentId": "12", "text": "Boy", "level": "2", "children": null }, { "id": "7", "parentId": "12", "text": "Other", "level": "2", "children": null }, { "id": "9", "parentId": "0", "text": "Woman", "level": "1", "children": null }, { "id": "11", "parentId": "9", "text": "Girl", "level": "2", "children": null } ], "Animals": [ { "id": "5", "parentId": "0", "text": "Dog", "level": "1", "children": null }, { "id": "8", "parentId": "5", "text": "Puppy", "level": "2", "children": null }, { "id": "10", "parentId": "13", "text": "Cat", "level": "1", "children": null }, { "id": "14", "parentId": "13", "text": "Kitten", "level": "2", "children": null }, ]} Expected output : { "People": [ { "id": "12", "parentId": "0", "text": "Man", "level": "1", "children": [ { "id": "6", "parentId": "12", "text": "Boy", "level": "2", "children": null }, { "id": "7", "parentId": "12", "text": "Other", "level": "2", "children": null } ] }, { "id": "9", "parentId": "0", "text": "Woman", "level": "1", "children": { "id": "11", "parentId": "9", "text": "Girl", "level": "2", "children": null } } ], "Animals": [ { "id": "5", "parentId": "0", "text": "Dog", "level": "1", "children": { "id": "8", "parentId": "5", "text": "Puppy", "level": "2", "children": null } }, { "id": "10", "parentId": "13", "text": "Cat", "level": "1", "children": { "id": "14", "parentId": "13", "text": "Kitten", "level": "2", "children": null } } ]} Now provide the response and nothing else.
There is an efficient solution if you use a map-lookup. If the parents always come before their children you can merge the two for-loops. It supports multiple roots. It gives an error on dangling branches, but can be modified to ignore them. It doesn't require a 3rd-party library. It's, as far as I can tell, the fastest solution. function list_to_tree(list) { var map = {}, node, roots = [], i; for (i = 0; i < list.length; i += 1) { map[list[i].id] = i; // initialize the map list[i].children = []; // initialize the children } for (i = 0; i < list.length; i += 1) { node = list[i]; if (node.parentId !== "0") { // if you have dangling branches check that map[node.parentId] exists list[map[node.parentId]].children.push(node); } else { roots.push(node); } } return roots;}var entries = [{ "id": "12", "parentId": "0", "text": "Man", "level": "1", "children": null }, { "id": "6", "parentId": "12", "text": "Boy", "level": "2", "children": null }, { "id": "7", "parentId": "12", "text": "Other", "level": "2", "children": null }, { "id": "9", "parentId": "0", "text": "Woman", "level": "1", "children": null }, { "id": "11", "parentId": "9", "text": "Girl", "level": "2", "children": null }];console.log(list_to_tree(entries)); If you're into complexity theory this solution is Θ(n log(n)). The recursive-filter solution is Θ(n^2) which can be a problem for large data sets.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18017869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2299336/']}
jdg_377467
stackexchange
llm_judgeable_groundtruth_similarity
511208
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'm far from an electrician. Just a guy trying to get some new life out of an existing piece of machinery. See the image below, this 5HP motor comes from a heavy duty commercial treadmill. Based on the fact that it has no start capacitor, 6 leads, and that heavy flywheel on the right this is a 3-phase single-volt motor. The labels originally were W,V,U but some of them were scratched off and unreadable. But there's two additional wires both black and missing labels, and the green for total of 6 wires. I've labeled the black wires A,B,C,D,E and measured them using ohms setting on a multimeter: * A<->B: nothing* A<->C: nothing* A<->D: 0.6* A<->E: nothing* B<->C: 2.2* B<->D: nothing* B<->E: 2.5* C<->D: nothing* C<->E: 2.5* D<->E: nothing My questions are: how do I restore the original labels of W,V,U from the information above? if 3 wires were W,V,U and the other two had no labels remaining, what purpose are the other two wires? assuming i identify all the wires are correctly labeled, any quick way to test the functionality of this motor before wiring it to a control board? Now provide the response and nothing else.
It certainly appears to be a three-phase induction motor. The resistances between leads B, C and E seems high for stator resistance, but the fact that they are equal would indicate they are U, V and W. Which is which doesn't matter much. If the motor runs backwards when powered, swap two of them. The resistance between A and D would be nearly zero if it is an over temperature switch. Both this and the B, C, E resistances could be just an indication that the meter doesn't read low resistances accurately. I doubt that the motor will harm the controller board. I would be inclined to test the motor and controller board together rather than try to test the motor my itself. The current on the nameplate posted by @StainlessSteelRat indicates that the "SPL" marked after 5 Hp stands for "sales person lie." That is a "peak Hp" rating that means it can produce the torque of a 5 Hp motor for a very short time prior to failing. It is really something like a 1.5 Hp motor. The measured resistances are more reasonable for 1.5 Hp.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/511208', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/257990/']}
jdg_377468
stackexchange
llm_judgeable_groundtruth_similarity
584041
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 am learning SPI protocol in serial communications now. I got stuck with the clock phase and polarity controls concept. Why there are 4 modes available other than a single universal transfer mode. What is the ground reason to run SPI protocol in 4 modes. Also, why these transfer modes are not available in I2C? Now provide the response and nothing else.
TL; DR : SPI is a generic physical interface that can do four different bit transmission protocols to be compatible with various chip interface specifications, while I2C is a specification that defines the bit transmission protocol and physical interface. They are different interfaces built from different starting point. Having selectable clock polarity and phase makes no sense on I2C as then you could not connect different kind of chips to the same bus. SPI devices need separate chip select pin to know they are being talked to so they can ignore clock pulses or just not load data in which allows using chips with different setting on same bus. The clock phase and polarity is selectable because different chips use different edge to load in data. Initially the SPI peripheral was introduced to MCUs to simplify communication to various existing chips which already had various different serial interfaces - SPI literally means it is just a Serial Peripheral Interface to offload the data transfer from software bit-banging to a byte-oriented hardware peripheral. So the SPI peripheral in the MCU was just made with all possible options one could ever need to communicate with existing chips easily. There is no formal specification or protocol of a SPI bus, it was just a helpful tool. Sometimes you have multiple chips on bus and require different settings for each chip. And this is fine as the settings of SPI can be changed. I2C is different as it was developed from ground up to have a specification first and then chips can be designed to meet this specification, so you don't have any variability or compability issues on the bus, as everyone must use the defined protocol. And since I2C is open drain bus, and data changes are allowed only when clock is low means that if data changes when clock is high should not normally happen then these can be used to signal start and stop conditions which don't exist on SPI.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/584041', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/154096/']}
jdg_377469
stackexchange
llm_judgeable_groundtruth_similarity
5572876
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 noticed that in functional languages such as Haskell and OCaml you can do 2 actions with lists. First you can do x:xs where x is an element ans xs is a list and the resulting action is we get a new list where x is appended to the beginning of xs in constant time. Second is x++y where both x and y are lists and the resulting action is we get a new list where y gets appended to the end of x in linear time with respect to the number of elements in x. Now I'm no expert in how languages are designed and compilers are built, but this seems to me a lot like a simple implementation of a linked list with one pointer to the first item. If I were to implement this data structure in a language like C++ I would find it to be generally trivial to add a pointer to the last element. In this case if these languages were implemented this way (assuming they do use linked lists as described) adding a "pointer" to the last item would make it much more efficient to add items to the end of a list and would allow pattern matching with the last element. My question is are these data structures really implemented as linked lists, and if so why do they not add a reference to the last element? Now provide the response and nothing else.
Yes, they really are linked lists. But they are immutable. The advantage of immutability is that you don't have to worry about who else has a pointer to the same list. You might choose to write x++y , but somewhere else in the program might be relying on x remaining unchanged. People who work on compilers for such languages (of whom I am one) don't worry about this cost because there are plenty of other data structures that provide efficient access: A functional queue represented as two lists provides constant-time access to both ends and amortized constant time for put and get operations. A more sophisticated data structure like a finger tree can provide several kinds of list access at very low cost. If you just want constant-time append, John Hughes developed an excellent, simple representation of lists as functions, which provides exactly that. (In the Haskell library they are called DList .) If you're interested in these sorts of questions you can get good info from Chris Okasaki's book Purely Functional Data Structures and from some of Ralf Hinze's less intimidating papers.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5572876', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/381261/']}
jdg_377470
stackexchange
llm_judgeable_groundtruth_similarity
15205773
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 have a form in my Meteor html template and on submit insert that data to my MongoDB list. My questions are: Is this possible without using extra packages? Could I just add an HTML form as a template? Does the on submit event work for latest Meteor? I've read that we can use the click event for the submit button: Could you tell me how I would go for finding in my DOM the values of my input elements? (without using jQuery?) Now provide the response and nothing else.
JQuery is included in meteor & very simplifying, why would you want to avoid it? Its quite long to traverse the dom manually with js You could use javascript to submit your forms ajax style: So you could just use normal form html in your template like usual: // HTML<form id="myform"> <input type="text" name="firstname"/> <input type="text" name="lastname"/> <input type="text" name="email"/> <input type="submit" id="submit"/></form>// Client JSfunction submitme() { form = {}; $.each($('#myform').serializeArray(), function() { form[this.name] = this.value; }); // Do validation on // form = { // firstname: 'first name', // lastname: 'last name', // email: 'email@email.com' // } MyCollection.insert(form, function(err) { if(!err) { alert("Submitted!"); $('#myform')[0].reset(); } else { alert("Something is wrong"); console.log(err); } });} You could bind the select button to insert the data when clicked: Event map binding: Template.templatename.events({ 'submit' : function(event) { event.preventDefault(); //prevent page refresh submitme(); }}); If you HATE jQuery & cant use it at all // HTML<form id="myform"> <input id="firstname" type="text" name="firstname"/> <input id="lastname" type="text" name="lastname"/> <input id="email" type="text" name="email"/> <input type="submit" id="submit"/></form>// Client JSfunction submitme() { form = { firstname: firstname.value, lastname: lastname.value, email: email.value }; // Do validation on // form = { // firstname: 'first name', // lastname: 'last name', // email: 'email@email.com' // } MyCollection.insert(form, function(err) { if (!err) { alert("Submitted!"); // Empty field values email.value = ""; firstname.value = ""; lastname.value = ""; } else { alert("Something is wrong"); console.log(err); } });}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15205773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/458060/']}
jdg_377471
stackexchange
llm_judgeable_groundtruth_similarity
3207198
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 had a conversation on this site about some question , and a claim had been made by one of the users on this site that the truth value of this statement(" $\frac{1}{0}$ =5 is false statement " ) is undetermined. And I had many objections on why I think that " $\frac{1}{0}$ =5" is false statement. Like: 1-Assuming a=0 ,can i ask why you can't assign truth value for the consequent? If we assume that the implication is true we get a contradiction ( $\frac{1}{a}$ is undefined and defined), so the negation must be true, so the whole implication is false.Therefore the primes is true and the conclusion is false. 2-But the statement x=5 means: x is defined and has the value 5. Since $\frac{1}{0}$ is undefined, then saying $\frac{1}{0}$ =5 is like saying: $\frac{1}{0}$ is undefined and defined at the same time, so it's false statement. 3-Regardless of what is the precise meaning of undefined. Still the statement can be translated into a form of two mutually exclusive statements( defined and undefined ) that are true at the same time, which is a contradiction. If I can say: It is not the case that $\frac{1}{0}$ =5 ( what ever the interpretation of that statement is ) is true statement, then it has to be false. There is no other alternative if we are talking in the context of propositional logic.Another example : If I say blue = cat, although this statement has no meaning, but since i can't say it is true ( "blue" is not an identity of "cat" ), then it is a false statement. If i'm wrong ( which is very possible ), I want to know what is wrong with saying: blue=cat is false statement. But I'm not sure, I hope that someone could clarify what is going on. And if it is the case that this statement is unprovable, then it would be helpful if someone could give such a proof. Now provide the response and nothing else.
This is a case where we need to distinguish between whether we're doing formal logic or ordinary informal/semi-formal mathematical reasoning. In formal logic , we define what it means to for a formula to have a truth value in a particular interpretation of the non-logical symbols in them. If we want to use the notation $\frac{\text{something}}{\text{something else}}$ in the formulas we deal with, the interpretation needs to provide some value for every pair of operands, including when the denominator is zero. However, in formal logic it is also commonly the case that we don't specify our interpretations completely. Instead we write down axioms that we assume that our interpretation will follow -- and we're quite serenely comfortable with the fact that there may be many different interpretations that all satisfy our axioms. This is the case for division by zero, where the axioms we write down typically only demands something of the outcome of the division when the denominator happens to be nonzero. One interpretation could choose to make $\frac10=5$ ; another could make $\frac10=42$ -- as long as both of them satisfy all of the axioms whatever we derive from the axioms will be true of both of them. The fact that the axioms don't constrain the value of $\frac10$ means that it is a pretty useless to write down, but in formal logic "useless" doesn't necessarily mean "forbidden". In each particular interpretation, $\frac10=5$ is either true or false. Until we have selected an interpretation it doesn't make sense to ask about its truth value. Even then, however, we can still speak about "provable" and "disprovable" from the axioms. It might very well be that $\frac10=5$ is neither provable nor disprovable from our axioms. In ordinary mathematical reasoning we're not doing formal logic, but natural language. We're not even trying to imitate formal logic (it is the other way around; formal logic is an attempt to imitate ordinary mathematical reasoning in a way that is convenient to reason about ). Your philosophical position that "every sentence that is not true must be false" is not really tenable for arbitrary natural language sentences. It breaks down for the liar paradox : This sentence is false. which is certainly not true because it denies itself, but it cannot be false either because then it would be true! So at least for the liar paradox we need to come to terms with the fact that it is possible to say something that is apparently neither true nor false. And once we have resigned to work with such a category of sentences, we might as well declare that "one divided by zero makes five" is a sentence of the same kind. Doing so matches the way people usually speak about mathematics (an unmitigatedly good thing) and sweeps all the potential problems you point at off the table, without creatiung any new problems that we don't already need to deal with anyway.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3207198', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/654260/']}
jdg_377472
stackexchange
llm_judgeable_groundtruth_similarity
6616739
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On my 64-bit machine, this C# code works: new byte[2L * 1024 * 1024 * 1024 - 57] but this one throws an OutOfMemoryException : new byte[2L * 1024 * 1024 * 1024 - 56] Why? I understand that the maximum size of a managed object is 2 GB and that the array object I'm creating contains more than the bytes I want. Namely, there is 4 bytes (or 8?) for the syncblock number, 8 bytes for MethodTable reference and 4 bytes for the size of the array. That's 24 bytes including padding, so why can't I allocate an array with 2G - 24 bytes? Is the maximum size really exactly 2 GB? If that's the case, what is the rest of 2 GB used for? Note: I don't actually need to allocate an array with 2 million of bytes. And even if I did, 56 bytes is negligible overhead. And I could easily work around the limit using custom BigArray<T> . Now provide the response and nothing else.
You need 56 bytes of overhead. It is actually 2,147,483,649-1 minus 56 for the maximum size. That's why your minus 57 works and minus 56 does not. As Jon Skeet says here: However, in practical terms, I don't believe any implementation supports such huge arrays. The CLR has a per-object limit a bit short of 2GB, so even a byte array can't actually have 2147483648 elements. A bit of experimentation shows that on my box, the largest array you can create is new byte[2147483591]. (That's on the 64 bit .NET CLR; the version of Mono I've got installed chokes on that.) See also this InformIT article on the same subject. It provides the following code to demonstrate the maximum sizes and overhead: class Program{ static void Main(string[] args) { AllocateMaxSize<byte>(); AllocateMaxSize<short>(); AllocateMaxSize<int>(); AllocateMaxSize<long>(); AllocateMaxSize<object>(); } const long twogigLimit = ((long)2 * 1024 * 1024 * 1024) - 1; static void AllocateMaxSize<T>() { int twogig = (int)twogigLimit; int num; Type tt = typeof(T); if (tt.IsValueType) { num = twogig / Marshal.SizeOf(typeof(T)); } else { num = twogig / IntPtr.Size; } T[] buff; bool success = false; do { try { buff = new T[num]; success = true; } catch (OutOfMemoryException) { --num; } } while (!success); Console.WriteLine("Maximum size of {0}[] is {1:N0} items.", typeof(T).ToString(), num); }} Finally, the article has this to say: If you do the math, you’ll see that the overhead for allocating an array is 56 bytes. There are some bytes left over at the end due to object sizes. For example, 268,435,448 64-bit numbers occupy 2,147,483,584 bytes. Adding the 56 byte array overhead gives you 2,147,483,640, leaving you 7 bytes short of 2 gigabytes. Edit: But wait, there's more! Looking around and talking with Jon Skeet, he pointed me to an article he wrote on Of memory and strings . In that article he provides a table of sizes: Type x86 size x64 sizeobject 12 24object[] 16 + length * 4 32 + length * 8int[] 12 + length * 4 28 + length * 4byte[] 12 + length 24 + lengthstring 14 + length * 2 26 + length * 2 Mr. Skeet goes on to say: You might be forgiven for looking at the numbers above and thinking that the "overhead" of an object is 12 bytes in x86 and 24 in x64... but that's not quite right. and this: There's a "base" overhead of 8 bytes per object in x86 and 16 per object in x64... given that we can store an Int32 of "real" data in x86 and still have an object size of 12, and likewise we can store two Int32s of real data in x64 and still have an object of x64. There's a "minimum" size of 12 bytes and 24 bytes respectively. In other words, you can't have a type which is just the overhead. Note how the "Empty" class takes up the same size as creating instances of Object... there's effectively some spare room, because the CLR doesn't like operating on an object with no data. (Note that a struct with no fields takes up space too, even for local variables.) The x86 objects are padded to 4 byte boundaries; on x64 it's 8 bytes (just as before) and finally Jon Skeet responded to a question I asked of him in another question where he states (in response to the InformIT article I showed him): It looks like the article you're referring to is inferring the overhead just from the limit, which is silly IMO. So to answer your question, actual overhead is 24 bytes with 32 bytes of spare room, from what I gather.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6616739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/41071/']}
jdg_377473
stackexchange
llm_judgeable_groundtruth_similarity
75973
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 have a file xx that has the following contents: @base_url = "http://dmstaffing-stage.herokuapp.com/" I want to use sed to eliminate this line (replace with nothing). I have used this sed technique with several other line successfully, e.g. sed -i 's/require "selenium-webdriver"//' xx But my attempt for the @base_url line isn't working. I suspect either the " or the // in the http:// are messing it up but I can't seem to fix! I have tried: $ sed 's/@base_url = "http://dmstaffing-stage.herokuapp.com/"//' xxsed: -e expression #1, char 23: unknown option to `s'$ sed 's/@base_url = \"http://dmstaffing-stage.herokuapp.com/\"//' xxsed: -e expression #1, char 24: unknown option to `s'$ sed 's/@base_url = "http:\/\/dmstaffing-stage.herokuapp.com/"//' xxsed: -e expression #1, char 58: unknown option to `s' but none worked. Now provide the response and nothing else.
As mentioned, use other separator or escape the slashes. Your last try misses escape of last slash. And as pointed out by @StephaneChazelas , escape dot 's as well. And, including @terdon if sed is not needed; grep -Fxv , where -F is fixed string, not regex, would be an option. -x makes sure it matches whole lines. -v inverts. A simple (very simple) benchmark with time -v seems to favor sed though. (GNU variants.) sed 's/@base_url = "http:\/\/dmstaffing-stage\.herokuapp\.com\/"//' xx To delete it completely (not leave blank line) use: sed '/@base_url = "http:\/\/dmstaffing-stage\.herokuapp\.com\/"/d' xx | +--- Delete
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/75973', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/10043/']}
jdg_377474
stackexchange
llm_judgeable_groundtruth_similarity
28073
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have an un-directed, un-weighted graph G.Starting from a given node A, i want to find whether there is a path from A to a node of a certain type .There can be many nodes of that type. The problem is to find the shortest path from A to any such node, if it exists.This can be achieved by doing a breadth first search which would give the shortest distance between A and the desired node if it exists. Given that the graph can be pretty dense, what could be a better algorithm to achieve this? Both memory and time taken for the search are to be kept in mind while designing this. If such queries could be optimized by doing some pre-processing while the graph is built, such additional hit on performance could be acceptable (not memory though). Now provide the response and nothing else.
By definition,$$ f(n) \in O(g(n))$$means there exists some positive constant $c$, such that for any large enough $n$,$$ |f(n)| \le c |g(n)|$$or equivalently, $\lim_{n\to\infty} \frac{f(n)}{g(n)} \le c < \infty$ Taking $\log$ of both sides, for any large enough $n$ it holds that$$ \log (f(n)) \le log (c) + \log(g(n)) $$ so, $$\frac{\log f(n)}{\log g(n)} \le \frac{\log c}{\log g(n)}+ c$$ Now can this go to infinity? only if $\log(g(n)) \to 0$ So let's try, and take $f(n)=2^{-n}$ and $g(n)=1/n$. Obviously $f(n) \in O(g(n))$.Yet, taking the logs we have $\log f(n) = -n$, $\log g(n) =-\log n$, and it is clear that no constant $c'$ will satisfy $|\log f(n)| \le c' |\log g(n)|$ for large enough $n$. Yet, I always find it weird to discuss $O$ of negative functions. EDIT: Here's example w/o negative function. Get back to the requirement of $\log(g(n)) \to 0$. Take $g(n) = 1+1/n$. Thus $\log (g(n)) \to 0$. (actually, the above example of $2^{-n}$ vs $1/n$ satisfies $g(n)\to 0$ rather than $log(g(n))\to 0$. Oops). If we take $f(n) = 2 + 1/n$ then $\log f(n) \to 1$ (binary log, obviously). so while $f(n) \le 3g(n)$ for every $n\ge 1$, it is not true that $\log f(n) \le c' \log g(n)$ for all large enough $n$, as the right-hand side approaches zero, while the left-hand side approaches 1.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/28073', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/10008/']}
jdg_377475
stackexchange
llm_judgeable_groundtruth_similarity
12344332
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 in over my head, trying to parse JSON for my first time and dealing with a multi dimensional array. { "secret": "[Hidden]", "minutes": 20, "link": "http:\/\/www.1.com", "bookmark_collection": { "free_link": { "name": "#free_link#", "bookmarks": [ { "name": "1", "link": "http:\/\/www.1.com" }, { "name": "2", "link": "http:\/\/2.dk" }, { "name": "3", "link": "http:\/\/www.3.in" } ] }, "boarding_pass": { "name": "Boarding Pass", "bookmarks": [ { "name": "1", "link": "http:\/\/www.1.com\/" }, { "name": "2", "link": "http:\/\/www.2.com\/" }, { "name": "3", "link": "http:\/\/www.3.hk" } ] }, "sublinks": { "name": "sublinks", "link": [ "http:\/\/www.1.com", "http:\/\/www.2.com", "http:\/\/www.3.com" ] } }} This is divided into 3 parts, the static data on my first dimension (secret, minutes, link) Which i need to get as seperate strings. Then I need a dictionary per "bookmark collection" which does not have fixed names, so I need the name of them and the links/names of each bookmark. Then there is the seperate sublinks which is always the same, where I need all the links in a seperate dictionary. I'm reading about parsing JSON but most of the stuff I find is a simple array put into 1 dictionary. Does anyone have any good techniques to do this ? Now provide the response and nothing else.
After you parse the JSON, you will end up with a Python dict. So, suppose the above JSON is in a string named input_data: import json# This converts from JSON to a python dictparsed_input = json.loads(input_data)# Now, all of your static variables are referenceable as keys:secret = parsed_input['secret']minutes = parsed_input['minutes']link = parsed_input['link']# Plus, you can get your bookmark collection as:bookmark_collection = parsed_input['bookmark_collection']# Print a list of names of the bookmark collections...print bookmark_collection.keys() # Note this contains sublinks, so remove it if needed# Get the name of the Boarding Pass bookmark:print bookmark_collection['boarding_pass']['name']# Print out a list of all bookmark links as:# Boarding Pass# * 1: http://www.1.com/# * 2: http://www.2.com/# ...for bookmark_definition in bookmark_collection.values(): # Skip sublinks... if bookmark_definition['name'] == 'sublinks': continue print bookmark_definition['name'] for bookmark in bookmark_definition['bookmarks']: print " * %(name)s: %(link)s" % bookmark# Get the sublink definition:sublinks = parsed_input['bookmark_collection']['sublinks']# .. and print themprint sublinks['name']for link in sublinks['link']: print ' *', link
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12344332', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/837767/']}
jdg_377476
stackexchange
llm_judgeable_groundtruth_similarity
71604
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: Is there a meaningful way to define the covariant derivative of the connection coefficients, $\Gamma^a_{bc}$? As in, does it make sense to define the object $\nabla_d\Gamma^a_{bc}$? Since the connection coefficients symbol doesn't transform as a tensor, it would seem like there should be some obstruction to defining this in the usual way, treating $a$ as a contravariant index and $b$ and $c$ a covariant indices. Part of my motivation for thinking about this was for writing the Riemann tensor in terms of this symbol $\nabla_d\Gamma^a_{bc}$. If you work in a local Lorentz frame at a point where $\Gamma^a_{bc}$ all vanish, the expression for the Riemann tensor is just $$R^a_{\phantom{a}bcd}=\partial_c\Gamma^a_{bd}-\partial_b\Gamma^a_{cd}.$$So then I'd like to "covariantize" this expression for a general coordinate system by writing\begin{equation}R^a_{\phantom{a}bcd}=\nabla_c\Gamma^a_{bd}-\nabla_b\Gamma^a_{cd}. \tag{*}\end{equation}If I pretend that $\Gamma^a_{bd}$ should have a covariant derivative defined by treating the indices as normal tensor indices, I get for this expression something pretty close to the right answer$$R^a_{\phantom{a}bcd}=\partial_c\Gamma^a_{bd}-\partial_b\Gamma^a_{cd} +2(\Gamma^a_{ce}\Gamma^e_{bd}-\Gamma^a_{eb}\Gamma^e_{cd})$$and curiously, if I define $$\nabla_c\Gamma^a_{bd} \equiv \partial_c\Gamma^a_{bd} + \Gamma^a_{ce}\Gamma^e_{bd}-\Gamma^e_{cd}\Gamma^a_{eb} + \Gamma^e_{cb}\Gamma^a_{ed} $$where the last term appears with the wrong sign from what you get with an ordinary $(1,2)$ tensor, the expression $(*)$ above for the Riemann tensor is correct. Is this just a coincidence, or is there some reason to define a covariant derivative of the connection symbol like that? Update: The expression that gives the right form of the Riemann tensor for $(*)$ is actually$$\nabla_c\Gamma^a_{bd} \equiv \partial_c\Gamma^a_{bd} + \Gamma^a_{ce}\Gamma^e_{bd}-\Gamma^e_{cd}\Gamma^a_{eb}$$so it is as if we are not treating $b$ as a tensor index, and we are just writing the covariant derivative of a $(1,1)$ tensor. Now provide the response and nothing else.
The formalism is explained very well in Landau-Lifshitz, Vol. II,par. 92 (properties of the curvature tensor). The Riemann curvature tensorcan be called the covariant exterior derivative of the connection.The exterior derivative is a generalisation of the gradient and curl operators. You might also consider looking at the geometry in differential forms language.The connection is seen as a 1-form (to be integrated along a line, thecorresponding index is supressed), resulting in a (2-index) transformationmatrix.* The Riemann curvature tensor is seen as a 2-form (to be integrated over a surface), again with values in a (2-index) transformation matrix.By doing so, you see Stokes' theorem appear, since integrating theconnection (1-form) along a closed lines yields the same result as integratingthe Riemann curvature (2-form) over the enclosed surface. That's why theRiemann curvature (2-form) needs to be the covariant exterior derivativeof the connection (1-form). Literature: Nakahara, Geometry, Topology and physics, chap. 5.4 and 7. *Precisely: a Lie-algebra valued 1-form.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/71604', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/12874/']}
jdg_377477
stackexchange
llm_judgeable_groundtruth_similarity
353073
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 want to add error handling to: var firstVariable = 1;var secondVariable = firstVariable; The below won't compile: try{ var firstVariable = 1;}catch {}try{ var secondVariable = firstVariable;}catch {} Why is it necessary for a try catch block to affect the scope of variables as other code blocks do? Consistency-sake aside, wouldn't it make sense for us to be able to wrap our code with error handling without the need to refactor? Now provide the response and nothing else.
What if your code was: try{ MethodThatMightThrow(); var firstVariable = 1;}catch {}try{ var secondVariable = firstVariable;}catch {} Now you'd be trying to use an undeclared variable ( firstVariable ) if your method call throws. Note : The above example specifically answers the original question, which states "consistency-sake aside". This demonstrates that there are reasons other than consistency. But as Peter's answer shows, there is also a powerful argument from consistency, which would for sure have been a very important factor in the decision.
{}
{'log_upvote_score': 8, 'links': ['https://softwareengineering.stackexchange.com/questions/353073', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/53014/']}
jdg_377478
stackexchange
llm_judgeable_groundtruth_similarity
8276712
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 input the arguments for CGContextSetRGBFillColor using a data type. For example: NSString *colorcode = ctx, 0, 1, 0, 0; CGContextSetRGBFillColor(colorcode); But I get an error saying that I have too few arguments. I want to change the arguments (ctx, 0, 1, 0, 1 ) sent to CGContextSetRGBFillColor depending on the users actions. I want to input the argument for CGContextSetRGBFillColor using a data type because the values of it is set in a separate view controller. Or can I directly input the arguments to CGContextSetRGBFillColor and then bring it over to the other view controller to use it? Now provide the response and nothing else.
Try using a UIColor object to store the user's selected color. You can create one like this: UIColor *color = [UIColor colorWithRed:0 green:1 blue:0 alpha:0]; Then when it's time to use it as the fill color, you can do this: CGContextSetFillColorWithColor(ctx, color.CGColor); I should mention that if you are not using ARC, you need to retain and release color appropriately.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8276712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1053078/']}
jdg_377479
stackexchange
llm_judgeable_groundtruth_similarity
21538859
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 moved my SECRET_KEY value out of my settings file, and it gets set when I load my virtualenv. I can confirm the value is present from python manage.py shell . When I run the Django Console, SECRET_KEY is missing, as it should. So in preferences, I go to Console>Django Console and load SECRET_KEY and the appropriate value. I go back into the Django Console, and SECRET_KEY is there. As expected, I cannot yet run a manage.py Task because it has yet to find the SECRET_KEY . So I go into Run>Edit Configurations to add SECRET_KEY into Django server and Django Tests, and into the project server. Restart Pycharm, confirm keys. When I run a manage.py Task, such as runserver , I still get KeyError: 'SECRET_KEY'. Where do I put this key? Now provide the response and nothing else.
Because Pycharm is not launching from a terminal, your environment will not be loaded. In short, any GUI program will not inherit the SHELL variables. See this for reasons (assuming a Mac). However, there are several basic solutions to this problem. As @user3228589 posted, you can set this up as a variable within PyCharm. This has several pros and cons. I personally don't like this approach because it's not a single source . To fix this, I use a small function at the top of my settings.py file which looks up the variable inside a local .env file. I put all of my "private" stuff in there. I also can reference this in my virtualenv. Here is what it looks like. -- settings.py def get_env_variable(var_name, default=False): """ Get the environment variable or return exception :param var_name: Environment Variable to lookup """ try: return os.environ[var_name] except KeyError: import StringIO import ConfigParser env_file = os.environ.get('PROJECT_ENV_FILE', SITE_ROOT + "/.env") try: config = StringIO.StringIO() config.write("[DATA]\n") config.write(open(env_file).read()) config.seek(0, os.SEEK_SET) cp = ConfigParser.ConfigParser() cp.readfp(config) value = dict(cp.items('DATA'))[var_name.lower()] if value.startswith('"') and value.endswith('"'): value = value[1:-1] elif value.startswith("'") and value.endswith("'"): value = value[1:-1] os.environ.setdefault(var_name, value) return value except (KeyError, IOError): if default is not False: return default from django.core.exceptions import ImproperlyConfigured error_msg = "Either set the env variable '{var}' or place it in your " \ "{env_file} file as '{var} = VALUE'" raise ImproperlyConfigured(error_msg.format(var=var_name, env_file=env_file))# Make this unique, and don't share it with anybody.SECRET_KEY = get_env_variable('SECRET_KEY') Then the env file looks like this: #!/bin/sh## This should normally be placed in the ${SITE_ROOT}/.env## DEPLOYMENT DO NOT MODIFY THESE..SECRET_KEY='XXXSECRETKEY' And finally your virtualenv/bin/postactivate can source this file. You could go further and export the variables as described here if you'd like, but since settings file directly calls the .env, there isn't really a need.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21538859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1076478/']}
jdg_377480
stackexchange
llm_judgeable_groundtruth_similarity
12065
Below is a question asked on the forum ai.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What are the areas/algorithms that belong to reinforcement learning? TD(0), Q-Learning and SARSA are all temporal-difference algorithms, which belong to the reinforcement learning area, but is there more to it? Are the dynamic programming algorithms, such as policy iteration and value iteration, considered as part of reinforcement learning? Or are these just the basis for the temporal-difference algorithms, which are the only RL algorithms? Now provide the response and nothing else.
The dynamic programming algorithms (like policy iteration and value iteration ) are often presented in the context of reinforcement learning (in particular, in the book Reinforcement Learning: An Introduction by Barto and Sutton) because they are very related to reinforcement learning algorithms, like $Q$ -learning. They are all based on the assumption that the environment can be modelled as an MDP. However, dynamic programming algorithms require that the transition model and reward functions of the underlying MDP are known. Hence, they are often referred to as planning algorithms, because they can be used to find a policy (which can be thought of as plan ) given the "dynamics" of the environment (which is represented by the MDP). They just exploit the given "physical rules" of the environment, in order to find a policy. This "exploitation" is referred to as a planning algorithm . On the other hand, $Q$ -learning and similar algorithms do not require that the MDP is known. They attempt to find a policy (or value function) by interacting with the environment. They eventually infer the "dynamics" of the underlying MDP from experience (that is, the interaction with the environment). If the MDP is not given, the problem is often referred to as the full reinforcement learning problem . So, algorithms like $Q$ -learning or SARSA are often considered reinforcement learning algorithms. The dynamic programming algorithms (like policy iteration) do not solve the "full RL problem", hence they are not always considered RL algorithms, but just planning algorithms. There are several categories of RL algorithms. There are temporal-difference, Monte-Carlo, actor-critic, model-free, model-based, on-policy, off-policy, prediction, control, policy-based or value-based algorithms. These categories can overlap. For example, $Q$ -learning is a temporal-difference (TD), model-free, off-policy, control and value-based algorithm: it is based on an temporal-difference (TD) update rule, it doesn't use a model of the environment (model-free), it uses a behavioural policy that is different than the policy it learns (off-policy), it is used to find a policy (control) and it attempts to approximate a value function rather than directly the policy (value-based).
{}
{'log_upvote_score': 5, 'links': ['https://ai.stackexchange.com/questions/12065', 'https://ai.stackexchange.com', 'https://ai.stackexchange.com/users/24054/']}
jdg_377481
stackexchange
llm_judgeable_groundtruth_similarity
15249808
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 new to Node and Express, I was trying to make something with Express just to get started, then I faced this problem. First res.send() works well, but the second one doesn't fire. Here's my code: var express = require('express'), app = express(), fs = require('fs'), visits;app.listen(8080);app.get('/', function(req,res) { res.send('Hello'); fs.readFile('counter.txt','utf-8', function(e,d) { if (e) { console.log(e); } else { console.log(parseInt(d) + 1); fs.writeFile('counter.txt',parseInt(d) + 1); res.send('<p id="c">' + ( parseInt(d) + 1 ) + '</p>'); } })... 'Hello' is sent, but res.send('<p> .. </p>'); isn't. If I comment res.send('Hello'); , visitors will be shown. Thanks in advance. Now provide the response and nothing else.
res.send() is meant to be called just once. Try this instead: app.get('/', function(req,res) { var response = 'Hello'; fs.readFile('counter.txt','utf-8', function(e,d) { if (e) { console.log(e); res.send(500, 'Something went wrong'); } else { console.log(parseInt(d) + 1); fs.writeFile('counter.txt',parseInt(d) + 1); response += '<p id="c">' + ( parseInt(d) + 1 ) + '</p>'; res.send(response); } })}); (or just res.send("Hello<p id=...") , but you get the point :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15249808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2047038/']}
jdg_377482
stackexchange
llm_judgeable_groundtruth_similarity
24223
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have 2013 Nissan Rogue. I live in Toronto, Canada, so it is very cold here right now. I understand that cold temperatures can cause the tire pressure light to come on, but will it actually affect the reading if I use a pressure gauge (I think that's what it's called) to check the tire pressure? For example, the recommended PSI is about 40 I believe. On Saturday, the tire pressure in all four tires was pretty low so I filled them all up to 41. Now, after leaving my car outside for about two hours, the tire pressure light came on when I started up my vehicle, so I manually checked the pressure with the pressure gauge, and they were all about 30. Is this due to the cold temperatures or do I have a problem with my tires? All help would be appreciated. Thanks! Now provide the response and nothing else.
Physics says: T2p2 = (p1+p0) * ---- - p0 T1 If you have temperature T1 and pressure p1 when you filled the tires, you can calculate the new pressure p2 when the temperature changes to T2 . Since pressure is measured relative to ambient air pressure, you also need that pressure p0 . Though there are changes in ambient air pressure, they are usually not that large as it could play a role here. Now, pressure can be given in any unit (since you're using psi, p0=14.7psi at sealevel), but temperature must be given in an absolute scale, i.e. in Kelvin. And of course, the temperature is the temperature of the tire - it warms up while driving! You can now calculate if the pressure drop makes sense. I've done it graphically: A drop from ~41psi to 30psi needs a temperature drop of about 60°C / 110°F, which is quite much. But Toronto had 0°C last saturday, now it's -15°C and if you topped your tires then, you would now have about 37.5 psi. Consider the tires had 10°C then and are cold now, you would have 36psi now. So 30psi is a bit low for just being an effect of temperature, if my values are correct. But measuring tire pressure sometimes is a little tricky (I mean get the pressure from the tire into the gauge). Temperature may also have an effect on the gauge, but I can't imagine it's that large. But who knows... However, you also said that all tires behave the same way, so you don't have a problem with them.
{}
{'log_upvote_score': 5, 'links': ['https://mechanics.stackexchange.com/questions/24223', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/11116/']}
jdg_377483
stackexchange
llm_judgeable_groundtruth_similarity
16002268
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 504 timeouts message from nginx when my PHP script is running longer than usual. set_time_limit(0) does not seem to prevent that! Does it not work when running php5-fpm on nginx? If so, whats the proper way of setting the time limit? Error: 504 Gateway Time-outnginx/1.2.7 Now provide the response and nothing else.
There are several ways in which you can set the timeout for php-fpm. In /etc/php5/fpm/pool.d/www.conf I added this line: request_terminate_timeout = 180 Also, in /etc/nginx/sites-available/default I added the following line to the location block of the server in question: fastcgi_read_timeout 180; The entire location block looks like this: location ~ \.php$ { fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_read_timeout 180; include fastcgi_params;} Now just restart php-fpm and nginx and there should be no more timeouts for requests taking less than 180 seconds.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/16002268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/741099/']}
jdg_377484
stackexchange
llm_judgeable_groundtruth_similarity
30462079
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 publish some data to the service from the C# web application. The data itself is collected when user uses the application (a kind of usage statistics). I don't want to send data to the service during each user's request, I would rather collect the data in the app and send then all the data in a single request in a separate thread, that does not serve the users requests (I mean user does not have to wait for the request to be processed by the service). For this purpose I need a kind of JS's setInterval analog - the launch of the function each X seconds to flush all collected data to the service. I found out that Timer class provides somewhat similar ( Elapsed event). However, this allows to run the method only once, but that's not a big issue. The main difficulty with it is that it requires the signature void MethodName(object e, ElapsedEventArgs args) while I would like to launch the async method, that will call the web-service (input parameters are not important): async Task MethodName(object e, ElapsedEventArgs args) Could anyone advise how to solve the described task? Any tips appreciated. Now provide the response and nothing else.
The async equivalent is a while loop with Task.Delay (which internally uses a System.Threading.Timer ): public async Task PeriodicFooAsync(TimeSpan interval, CancellationToken cancellationToken){ while (true) { await FooAsync(); await Task.Delay(interval, cancellationToken) }} It's important to pass a CancellationToken so you can stop that operation when you want (e.g. when you shut down your application). Now, while this is relevant for .Net in general, in ASP.Net it's dangerous to do any kind of fire and forget. There are several solution for this (like HangFire), some are documented in Fire and Forget on ASP.NET by Stephen Cleary others in How to run Background Tasks in ASP.NET by Scott Hanselman
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30462079', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/966932/']}
jdg_377485
stackexchange
llm_judgeable_groundtruth_similarity
50557259
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.e. async asyncfunction(){ try{ await method1(); await method2(); } catch(error){ console.log(error); }} Given method1() and method2() are asynchronous functions. Should there be a try/catch block for each await method? Is there an even cleaner way to write this? I'm trying to avoid '.then' and '.catch' chaining. Now provide the response and nothing else.
Using one try/catch block containing multiple await operations is fine when waiting for promises created on the right hand side of the await unary operator: The await operator stores its parent async functions' execution context and returns to the event loop. Execution of the await operator resumes when it is called back with the settled state and value of its operand. Upon resumption, await restores the previously saved execution context and returns the operand promise's fulfilled value as the result of the await expression, or throws the rejection reason of a rejected operand. The try/catch block invocation is part of the execution context both before and after being saved and restored. Hence multiple await operations do not disturb the behavior of an outer try block they share. The catch block will be invoked with the rejection reason of any promise awaited in the try block that is rejected. If however code await s multiple existing promises in the same try/catch block and more than one of the promises rejects, an uncaught promise rejection error is generated for all but the first rejection. Thanks to @EyolRoth for supplying this caveat, please read his entire answer in conjunction with this one.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50557259', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8620423/']}
jdg_377486
stackexchange
llm_judgeable_groundtruth_similarity
22559603
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 the code below, the second fillStyle overrides the color specified in first one if I use rect() and then fill() in both places (ie, both rects are green) but works as expected (ie, the first rect being blue and second being green) if I change the first rect() to fillRect() . Why is it so? I thought fillRect() was just rect() and then fill() , right? ctx.translate(canvas.width/2, canvas.height/2);ctx.fillStyle = "#5A9BDC";ctx.fillRect(0, 0, rectWidth, rectHeight);// ctx.rect(0, 0, rectWidth, rectHeight);// ctx.fill(); ctx.translate(-canvas.width/2, -canvas.height/2);ctx.fillStyle = "#31B131";ctx.rect(0, 0, rectWidth, rectHeight);ctx.fill(); Tested in Chrome | Fiddle Now provide the response and nothing else.
fillRect .fillRect is a "stand-alone" command that draws and fills a rectangle. So if you issue multiple .fillRect commands with multiple .fillStyle commands, each new rect will be filled with the preceeding fillstyle. ctx.fillStyle="red";ctx.fillRect(10,10,10,10); // filled with redctx.fillStyle="green";ctx.fillRect(20,20,10,10); // filled with greenctx.fillStyle="blue";ctx.fillRect(30,30,10,10); // filled with blue rect .rect is part of the canvas's path commands. Path commands are groups of drawings beginning with the beginPath() and continuing until another beginPath() is issued. Within each group, only the last styling command wins. So if you issue multiple .rect commands and multiple .fillStyle commands inside a path, only the last .fillStyle will be used on all the .rect's. ctx.beginPath(); // path commands must begin with beginPathctx.fillStyle="red";ctx.rect(10,10,10,10); // bluectx.fillStyle="green";ctx.rect(20,20,10,10); // bluectx.fillStyle="blue"; // this is the last fillStyle, so it "wins"ctx.rect(30,30,10,10); // blue// only 1 fillStyle is allowed per beginPath, so the last blue style fills allctx.fill()
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22559603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1812633/']}
jdg_377487
stackexchange
llm_judgeable_groundtruth_similarity
10178304
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 blog on github pages - jekyll What is the best way to solve url strategy migration? I found the best practice in common is create htaccess like so Redirect 301 /programovani/2010/04/git-co-to-je-a-co-s-tim/ /2010/04/05/git-co-to-je-a-co-s-tim.html But it does not seems to work with Github. Another solution i found is create rake task, which will generate redirection pages. But since it's an html, it's not able to send 301 head, so SE crawlers will not recognize it as an redirection. Now provide the response and nothing else.
The best solution is to use both <meta http-equiv="refresh" and <link rel="canonical" href= It works very well, Google Bot reindexed my entire website under new links without losing positions. Also the users are redirected to the new posts right away. <meta http-equiv="refresh" content="0; url=http://konradpodgorski.com/blog/2013/10/21/how-i-migrated-my-blog-from-wordpress-to-octopress/"><link rel="canonical" href="http://konradpodgorski.com/blog/2013/10/21/how-i-migrated-my-blog-from-wordpress-to-octopress/" /> Using <meta http-equiv="refresh" will redirect each visitor to the new post. As for Google Bot, it treats <link rel="canonical" href= as 301 redirect, the effect is that you get your pages reindexed and that is what you want. I described whole process how I moved my blog from Wordpress to Octopress here. http://konradpodgorski.com/blog/2013/10/21/how-i-migrated-my-blog-from-wordpress-to-octopress/#redirect-301-on-github-pages
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10178304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133986/']}
jdg_377488
stackexchange
llm_judgeable_groundtruth_similarity
38727
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This is a question I wonder a little about every now and then. It is immediate, using forcing, that if there is a transitive set model of set theory, then there are continuum many. Can one prove a weak version of this without using the forcing machinery? (Perhaps in the presence of reasonable large cardinal assumptions?) Here are some specific versions: Suppose we know there are two transitive models of set theory. Can we prove there are infinitely many? Suppose we know there are two transitive models of set theory. Can we prove there are two with the same height? Suppose we know there is an uncountable model. Are there continuum many? I'm going to leave "reasonable" loose, but we do not want to assume much. For example, if there is a transitive model of "there is a measurable cardinal" then one can (easily) check that there are continuum many countable transitive models of set theory. There are also a few more or less obvious observations in the same spirit that follow from $\Sigma^1_2$ absoluteness. Also: if there is a countable transitive model $M$ of set theory, there is a comeager set of reals $C$ and a measure 1 set $R$ such that if $x$ is in $C\cup R$ , then $M[x]$ is a model of set theory. Any weakening of this or something similar in spirit that can be established without forcing would also be welcome. Now: I do not think I want something where we do forcing in disguise. So I am not sure presenting forcing as some variant of Bairwise compactness or that sort of thing would be appropriate here. Of course, any references you think I should be aware of are more than welcome. Now provide the response and nothing else.
Suppose you could prove, in ZFC, without forcing, the statement (A) If there are two transitive models of ZFC, then there is a third. Then you could also prove, in ZFC, without forcing, the statement (B) If there are two transitive models of ZFC, then there is a transitive model of ZFC + $V\neq L$. [Proof: Work in ZFC and assume there are two transitive models of ZFC. By (A) there is a third. If one of them satisfies $V\neq L$ we're done, so assume all three satisfy $V=L$ and are therefore of the form $L_\xi$ for some ordinals $\xi$. Let $\alpha<\beta<\gamma$ be the first three ordinals occurring as heights of transitive models of ZFC (+ $V=L$). Since $L_\gamma$ sees both $L_\alpha$ and $L_\beta$, it must, by (A) again, see another transitive model of ZFC. By minimality of $\alpha<\beta<\gamma$, $L_\gamma$ can't see another model of the form $L_\xi$, so it must see a model of ZFC + $V\neq L$. (I've tacitly used that the notion of "transitive model of ZFC" is absolute between the real world and transitive models of ZFC.)] What does this have to do with the question? I claim that a non-forcing proof of (B) would be significant news --- it would say that people could have deduced the consistency of $V\neq L$ from highly plausible assumptions before Cohen. So I feel reasonably confident in saying that no ZFC proof of (B) without forcing is known. Therefore, by the argument above, no ZFC proof of (A) without forcing is known. [Concerning "highly plausible," note that the existence of lots of transitive models of ZFC follows from assumptions just slightly beyond ZFC itself. My favorite such extension of ZFC is to add a satisfaction predicate for formulas in the language of ZFC, add axioms saying this predicate obeys the usual recursive definition of satisfaction, and allow this new predicate in the replacement scheme of ZFC. With these assumptions, you can apply a L"owenheim-Skolem argument to get lots of elementary submodels of the universe.] Note that the same discussion goes through if, in (A) we replace the conclusion (that there exists a third model) with the statement that there are two transitive models of ZFC of the same height.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/38727', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6085/']}
jdg_377489
stackexchange
llm_judgeable_groundtruth_similarity
2262978
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 having trouble understanding the difference between the kernel of a linear transformation and the basis for the kernel of a linear transformation. My textbook defines the kernel of a linear transformation as Let $T:V\to W$ be a linear transformation. Then the set of all vectors $v$ in $V$ that satisfy $T(v) = 0$ is called the kernel of $T$ and is denoted by $\ker(T)$. and later states ... the kernel of $T$ is the solution space of $Ax=0$. My textbook states in an example that a basis for the kernel of $T$ was found by solving the homogeneous system represented by $Ax = 0$. I don't understand the distinction, if there is any, between being asked to find the kernel of a linear transformation and the basis for the kernel. Now provide the response and nothing else.
Instead of thinking of "the" basis of the kernel, you need to think of "a" basis of the kernel. The kernel is a subspace of the domain. In general, it doesn't have only one basis; it has many. For example, consider $T:\mathbb R^3 \to \mathbb R$ given by $T(x,y,z) = x+2y+3z.$ The kernel is the set of all points $(x,y,z)$ for which $x+2y+3z=0.$ If you pick $y$ and $z$ to be any numbers at all and then let $x = -2y-3z,$ then the resulting point $(x,y,z)$ is a member of the kernel of $T.$ The kernel contains infinitely many points because there are infinitely many values of $y$ and $z$ that you could have chosen. Every basis of the kernel contains only two points, whereas the kernel itself contains infinitely many. One basis of the kernel is this:$$\{ (-2, 1, 0),\ (-3,0,1) \}.$$The first of these points corresponds to the choice $y=1,$ $z=0.$ The second corresponds to $y=0$, $z=1.$ This is a basis for the kernel because every member of the kernel is a linear combination of these two vectors, and this set of two vectors is linearly independent. Here is another basis of the kernel:$$\{(2,-1,0),\ (2,0,-1)\}.$$ There are infinitely many different bases of the kernel, and each of them is a finite set, containing only two elements. There is only one kernel, and it is an infinite set.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2262978', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/177749/']}
jdg_377490
stackexchange
llm_judgeable_groundtruth_similarity
664683
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 writing a LINQ query with multiple "and" conditions, should I write a single where clause containing && or multiple where clauses, one for each conditon? static void Main(string[] args){ var ints = new List<int>(Enumerable.Range(-10, 20)); var positiveEvensA = from i in ints where (i > 0) && ((i % 2) == 0) select i; var positiveEvensB = from i in ints where i > 0 where (i % 2) == 0 select i; System.Diagnostics.Debug.Assert(positiveEvensA.Count() == positiveEvensB.Count());} Is there any difference other than personal preference or coding style (long lines, readability, etc.) between positiveEvensA and positiveEvensB ? One possible difference that comes to mind is that different LINQ providers may be able to better cope with multiple where s rather than a more complex expression; is this true? Now provide the response and nothing else.
I personally would always go with the && vs. two where clauses whenever it doesn't make the statement unintelligible. In your case, it probably won't be noticeble at all, but having 2 where clauses definitely will have a performance impact if you have a large collection, and if you use all of the results from this query. For example, if you call .Count() on the results, or iterate through the entire list, the first where clause will run, creating a new IEnumerable<T> that will be completely enumerated again, with a second delegate. Chaining the 2 clauses together causes the query to form a single delegate that gets run as the collection is enumerated. This results in one enumeration through the collection and one call to the delegate each time a result is returned. If you split them, things change. As your first where clause enumerates through the original collection, the second where clause enumerates its results. This causes, potentially (worst case), 2 full enumerations through your collection and 2 delegates called per member, which could mean this statement (theoretically) could take 2x the runtime speed. If you do decide to use 2 where clauses, placing the more restrictive clause first will help quite a bit, since the second where clause is only run on the elements that pass the first one. Now, in your case, this won't matter. On a large collection, it could. As a general rule of thumb, I go for: Readability and maintainability Performance In this case, I think both options are equally maintainable, so I'd go for the more performant option.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/664683', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8877/']}
jdg_377491
stackexchange
llm_judgeable_groundtruth_similarity
3026127
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 run into an issue where instanceof works, and then it doesn't. Going into details is difficult, but I think this might be the problem: Reading this: http://www.theserverside.com/news/thread.tss?thread_id=40229 (search for Thread.currentThread), it seems to imply that, even if the two objects are the same class, if you pass them between threads with different class loaders, instanceof (and isAssignableFrom) might still fail. This certainly would explain the behavior I'm having, but I was wondering if anyone could verify it? (I wish the article linked at the beginning of the discussion was still available, but it doesn't seem like it is.) Now provide the response and nothing else.
This has nothing to do with threads, only with class loaders. The same class definition, when loaded by different classloaders, is seen as two different classes by the JVM. So instanceof or casts between the two fail. So to answer your original question: passing objects between threads loaded by the same class loader is safe and instanceof et al. works fine. Here is an article about class loading issues . See also this earlier answer of mine for a way to verify which classloaders are in the game. Update to Romain's comment Here is some code to test the behaviour of instanceof , among others: URL[] urls = new URL[] {new File("build/classes/").toURL()};ClassLoader loader1 = new URLClassLoader(urls, null);ClassLoader loader2 = new URLClassLoader(urls, null);Class<?> c1 = loader1.loadClass("net.torokpeter.Foo");Class<?> c2 = loader2.loadClass("net.torokpeter.Foo");Object foo1 = c1.newInstance();Object foo2 = c2.newInstance();System.out.println("c1.toString(): " + c1);System.out.println("c2.toString(): " + c2);System.out.println("c1.equals(c2): " + c1.equals(c2));System.out.println("c1 == c2: " + (c1 == c2));System.out.println("foo1: " + foo1);System.out.println("foo2: " + foo2);System.out.println("foo1 instanceof Foo: " + (foo1 instanceof Foo));System.out.println("foo2 instanceof Foo: " + (foo2 instanceof Foo));System.out.println("c1.isAssignableFrom(c1): " + c1.isAssignableFrom(c1));System.out.println("c2.isAssignableFrom(c2): " + c2.isAssignableFrom(c2));System.out.println("c1.isAssignableFrom(c2): " + c1.isAssignableFrom(c2));System.out.println("c2.isAssignableFrom(c1): " + c2.isAssignableFrom(c1));System.out.println("c1.isAssignableFrom(Foo.class): " + c1.isAssignableFrom(Foo.class));System.out.println("c2.isAssignableFrom(Foo.class): " + c2.isAssignableFrom(Foo.class));System.out.println("Foo.class.isAssignableFrom(c1): " + Foo.class.isAssignableFrom(c1));System.out.println("Foo.class.isAssignableFrom(c2): " + Foo.class.isAssignableFrom(c2)); And the output is (in Eclipse, Java5): c1.toString(): class net.torokpeter.Fooc2.toString(): class net.torokpeter.Fooc1.equals(c2): falsec1 == c2: falsefoo1: net.torokpeter.Foo@360be0foo2: net.torokpeter.Foo@45a877foo1 instanceof Foo: falsefoo2 instanceof Foo: falsec1.isAssignableFrom(c1): truec2.isAssignableFrom(c2): truec1.isAssignableFrom(c2): falsec2.isAssignableFrom(c1): falsec1.isAssignableFrom(Foo.class): falsec2.isAssignableFrom(Foo.class): falseFoo.class.isAssignableFrom(c1): falseFoo.class.isAssignableFrom(c2): false So everything seems to be consistent :-)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3026127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/358758/']}
jdg_377492
stackexchange
llm_judgeable_groundtruth_similarity
3475333
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 know how many rectangles can fit inside a $9$ by $9$ square. However, I want to exclude any rectangles that are not greater than or equal to a $3$ by $3$ square. By this, I mean excluding rectangles such as $(2*3),(3*2),(3*1),(3*1),(2*2)$ ...and so on because the are not equal to, or can be fully surrounded by, a $3*3$ square. I have arrived at a figure of $784$ by visualizing the problem and crunching the numbers, but I would like a sounder theoretical approach that makes sense. Now provide the response and nothing else.
This answer assumes: Two different e.g. $5 \times 6$ rectangles at different positions (within the $9 \times 9$ grid) are counted as distinct. You want to exclude e.g. $7 \times 2$ rectangles since such a rectangle is "not greater than" (in the sense it cannot enclose) a $3 \times 3$ square. In other words, you want to count $m \times n$ rectangles where $m \ge 3$ and $n \ge 3$ . Here is a way to count the above without exhaustive listing. The $9\times 9$ grid of $81$ squares has $10$ vertical lines and $10$ horizontal lines, and a rectangle is defined by a pair of vertical lines and a pair of horizontal lines. The number of ways to choose the pair of horizontal lines is ${10 \choose 2} = 45$ if you ignore the size constraint. However, if you require $m \ge 3$ , then you must exclude pairs which are one square apart ( $9$ such pairs) or two squares apart ( $8$ such pairs). So the number of pairs satisfying $m \ge 3$ is $45 - 9 - 8 = 28$ Similarly the number of pairs of vertical lines satisfying $n \ge 3$ is also $28$ . Thus the number of valid rectangles is $28^2 = 784$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3475333', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/239351/']}
jdg_377493
stackexchange
llm_judgeable_groundtruth_similarity
310192
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 $p$ be an odd prime and let $S_p$ denote the determinant$$\det\left[\left(\frac{i^2+j^2}p\right)\right]_{1\le i,j\le (p-1)/2}$$with $(\frac{\cdot}p)$ the Legendre symbol. By Theorem 1.2 of my paper arXiv:1308.2900 available from http://arxiv.org/abs/1308.2900 , $-S_p$ is a quadratic residue modulo $p$. Here I ask a further question. QUESTION. Is it true that for each prime $p\equiv3\pmod4$ the number $-S_p$ is always a positive square divisible by $2^{(p-3)/2}$? Define $a_p=\sqrt{-S_p}/2^{(p-3)/4}$ for any prime $p\equiv3\pmod4$. Then\begin{gather*}a_3=a_7=a_{11}=1,\ a_{19}=2,\ a_{23}=1,\ a_{31}=29,\ a_{43}=254,\\a_{47}=367,\ a_{59}=9743,\ a_{67}=305092,\ a_{71}=29,\ a_{79}=1916927.\end{gather*}I have computed the values of $a_p$ for all primes $p\equiv3\pmod4$ with $p<2000$. Based on the numerical data, I conjecture that the above question has an affirmative answer but I'm unable to prove this. Any ideas towards the solution? Your comments are welcome! Now provide the response and nothing else.
It can be seen that $S_p$ is not divisible by $p$. The argument about the decomposition of the matrix as $\frac{2}{i\sqrt{p}}A^2$ suggested above implies that $-S_p$ is a square in $\mathbb{Q}[\zeta_p][\sqrt{\lambda_p}]$, where $\lambda_p=-2i\sqrt{p}$. Writing $-S_p=(a\sqrt{\lambda_p}+b)^2$ with $a,b\in\mathbb{Q}[\zeta_p]$, we have $ab=0$ (since $S_p^2\in\mathbb{Z}\subset\mathbb{Q}[\zeta_p]$ and $\sqrt{\lambda_p}\not\in\mathbb{Q}[\zeta_p]$). The case $b=0$ is impossible as then $S_p$ is divisible by $p$, which follows from the fact that the norm of $\lambda_p$ is divisible by an odd power of $p$. Thus $-S_p=b^2$ with $b\in\mathbb{Q}[\zeta_p]$, which implies $-S_p$ is a square since $S_p$ is not divisible by $p$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/310192', 'https://mathoverflow.net', 'https://mathoverflow.net/users/124654/']}
jdg_377494
stackexchange
llm_judgeable_groundtruth_similarity
47988193
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: #include <fstream>#include <iostream>#include <map>int main(int argc, char** argv) { try { std::map<std::string, int> m{{"a", 1}, {"b", 2}}; std::cout << m.at("c") << std::endl; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } return 0;} In C++, when retrieving a non-existent key of a map, the exception looks like map::at: key not found . Information about what the key is is not provided. Also, if one is accessing a non-existent file, the exception message of std::ios_base::failure looks like ios_base::clear: unspecified iostream_category error . The filename which caused the exception is not provided. Thus it may take quite a time to find out where the exception is from if there are many map.at() or ifstream is uses in a project. In contrast to this, Python may tell you KeyError: 'c' or FileNotFoundError: [Errno 2] No such file or directory: 'foo' . Is this just a C++ convention? Thank you. Now provide the response and nothing else.
The issue is the C++ object model, which differs from Python's. To contrast, first let's answer: what does Python store in the exception object to print the key? It's a reference that keeps that object alive. This cannot be done simply in C++. std::out_of_range can't store a pointer or reference to the key as is. The handler for the exception may be in far away block. And that means that the key most probably went out of scope before the handler is entered. We get undefined behavior if the key is referred to. std::out_of_range is a concrete class. Not a template like std::map . It can't easily copy the key into itself. There are many different Key types, and it obviously can't account for all of them. Even if it could, what if the key is extremely expensive to copy? Or even non-copyable at all? Even in cases where that's not true, what if the key isn't convertible to a string, or printable? The above points don't mean it's impossible. std::map::at can throw a sub-class of std::out_of_range that does type erasure and so forth. But I hope you see it has non-trivial overhead. C++ is all about not paying in performance for features you don't need or use. Making everyone bear that overhead unconditionally isn't in line with this design.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47988193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1831512/']}
jdg_377495
stackexchange
llm_judgeable_groundtruth_similarity
9492259
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 can I get the mail address from HTML code with Nokogiri? I'm thinking in regex but I don't know if it's the best solution. Example code: <html><title>Example</title><body>This is an example text.<a href="mailto:example@example.com">Mail to me</a></body></html> Does a method exist in Nokogiri to get the mail address if it is not between some tags? Now provide the response and nothing else.
You can extract the email addresses using xpath. The selector //a will select any a tags on the page, and you can specify the href attribute using @ syntax, so //a/@href will give you the href s of all a tags on the page. If there are a mix of possible a tags on the page with different urls types (e.g. http:// urls) you can use xpath functions to further narrow down the selected nodes. The selector //a[starts-with(@href, \"mailto:\")]/@href will give you the href nodes of all a tags that have a href attribute that starts with "mailto:". Putting this all together, and adding a little extra code to strip out the "mailto:" from the start of the attribute value: require 'nokogiri'selector = "//a[starts-with(@href, \"mailto:\")]/@href"doc = Nokogiri::HTML.parse File.read 'my_file.html'nodes = doc.xpath selectoraddresses = nodes.collect {|n| n.value[7..-1]}puts addresses With a test file that looks like this: <html><title>Example</title><body>This is an example text.<a href="mailto:example@example.com">Mail to me</a><a href="http://example.com">A Web link</a><a>An empty anchor.</a></body></html> this code outputs the desired example@example.com . addresses is an array of all the email addresses in mailto links in the document.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9492259', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/945012/']}
jdg_377496
stackexchange
llm_judgeable_groundtruth_similarity
56505567
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: let's say i've a preordered array of object such as this one: let data = [ { moment: '00:01', otherProp: 'something', somethingMore: 'someelse'}, { moment: '01:10', otherProp: 'something', somethingMore: 'someelse'}, { moment: '05:37', otherProp: 'something', somethingMore: 'someelse'}, { moment: '07:51', otherProp: 'something', somethingMore: 'someelse'}, //and so on] I've got in input x which is formatted as an hour:minutes string (ex. x='06:05') and i need to find the two consecutive objects (data[i] and data[i+1]) such that data[i].moment <= x < data[i+1].moment Suppose the array has almost 200 elements and i need to fastest way to find the results. Do i've to implement the binary search from scratch? is there a library i can use? Now provide the response and nothing else.
Complementing @fetzz great answer. SHORT ANSWER TLDR; There are two common causes for this kind of error message. You are doing the first one (see below). Along with the text, I explain in rich detail what this error message wants to convey. CAUSE 1: In typescript, a concrete instance is not allowed to be assigned to a type parameter. Following you can see an example of the 'problem' and the 'problem solved', so you can compare the difference and see what changes: PROBLEM const func1 = <A extends string>(a: A = 'foo') => `hello!` // Error!const func2 = <A extends string>(a: A) => { //stuff a = `foo` // Error! //stuff} SOLUTION const func1 = <A extends string>(a: A) => `hello!` // okconst func2 = <A extends string>(a: A) => { //ok //stuff //stuff} See in: TS Playground CAUSE 2: Although you are not doing the below error in your code. It is also a normal circumstance where this kind of error message pops up. You should avoid doing this: Repeat (by mistaken) the Type Parameter in a class, type, or interface. Don't let the complexity of the below code confuse you, the only thing I want you to concentrate on is how the removing of the letter 'A' solves the problem: PROBLEM: type Foo<A> = { //look the above 'A' is conflicting with the below 'A' map: <A,B>(f: (_: A) => B) => Foo<B>}const makeFoo = <A>(a: A): Foo<A> => ({ map: f => makeFoo(f(a)) //error!}) SOLUTION: type Foo<A> = { // conflict removed map: <B>(f: (_: A) => B) => Foo<B>}const makeFoo = <A>(a: A): Foo<A> => ({ map: f => makeFoo(f(a)) //ok}) See in: TS Playground LONG ANSWER UNDERSTANDING THE ERROR MESSAGE Following I'll decompose each element of the error message below: Type '{}' is not assignable to type 'P'. '{}' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint'object' WHAT IS TYPE {} It's a type that you can assign anything except null or undefined. For example: type A = {}const a0: A = undefined // errorconst a1: A = null // errorconst a2: A = 2 // okconst a3: A = 'hello world' //okconst a4: A = { foo: 'bar' } //ok// and so on... See in: TS Playground WHAT IS is not assignable To assign is to make a variable of a particular type correspond to a particular instance. If you mismatch the type of the instance you get an error. For example: // type string is not assignable to type number const a: number = 'hello world' //error// type number is assinable to type numberconst b: number = 2 // ok WHAT IS A different subtype Two types are equals : if they do not add or remove details in relation to each other. Two types are different : if they are not equal. Type A is a subtype of type S : if A adds detail without removing already existent detail from S . type A and type B are different subtypes of type S : If A and B are subtypes of S , but A and B are different types. Said in other words: A and B adds detail to the type S , but they do not add the same detail . Example: In the code below, all the following statements are true: A and D are equal types B is subtype of A E is not subtype of A B and C are different subtype of A type A = { readonly 0: '0'}type B = { readonly 0: '0', readonly foo: 'foo'}type C = { readonly 0: '0', readonly bar: 'bar'}type D = { readonly 0: '0'}type E = { readonly 1: '1', readonly bar: 'bar'} type A = numbertype B = 2type C = 7type D = numbertype E = `hello world` type A = booleantype B = truetype C = falsetype D = booleantype E = number NOTE : Structural Type When you see in TS the use of type keyword, for instance in type A = { foo: 'Bar' } you should read: Type alias A is pointing to type structure { foo: 'Bar' } . The general syntax is: type [type_alias_name] = [type_structure] . Typescript type system just checks against [type_structure] and not against the [type_alias_name] . That means that in TS there's no difference in terms of type checking between following: type A = { foo: 'bar } and type B = { foo: 'bar' } . For more see: Official Doc . WHAT IS constraint of type 'X' The Type Constraint is simply what you put on the right side of the 'extends' keyword. In the below example, the Type Constraint is 'B'. const func = <A extends B>(a: A) => `hello!` Reads: Type Constraint 'B' is the constraint of type 'A' WHY THE ERROR HAPPENS To illustrate I'll show you three cases. The only thing that will vary in each case is the Type Constraint , nothing else will change. What I want you to notice is that the restriction that Type Constraint imposes to Type Parameter does not include different subtypes . Let's see it: Given: type Foo = { readonly 0: '0'}type SubType = { readonly 0: '0', readonly a: 'a'}type DiffSubType = { readonly 0: '0', readonly b: 'b'}const foo: Foo = { 0: '0'}const foo_SubType: SubType = { 0: '0', a: 'a' }const foo_DiffSubType: DiffSubType = { 0: '0', b: 'b' } CASE 1: NO RESTRICTION const func = <A>(a: A) => `hello!`// call examplesconst c0 = func(undefined) // okconst c1 = func(null) // okconst c2 = func(() => undefined) // okconst c3 = func(10) // okconst c4 = func(`hi`) // okconst c5 = func({}) //okconst c6 = func(foo) // okconst c7 = func(foo_SubType) //okconst c8 = func(foo_DiffSubType) //ok CASE 2: SOME RESTRICTION Note below that restriction does not affect subtypes. VERY IMPORTANT : In Typescript the Type Constraint does not restrict different subtypes const func = <A extends Foo>(a: A) => `hello!`// call examplesconst c0 = func(undefined) // errorconst c1 = func(null) // errorconst c2 = func(() => undefined) // errorconst c3 = func(10) // errorconst c4 = func(`hi`) // errorconst c5 = func({}) // errorconst c6 = func(foo) // okconst c7 = func(foo_SubType) // ok <-- Allowedconst c8 = func(foo_DiffSubType) // ok <-- Allowed CASE 3: MORE CONSTRAINED const func = <A extends SubType>(a: A) => `hello!`// call examplesconst c0 = func(undefined) // errorconst c1 = func(null) // errorconst c2 = func(() => undefined) // errorconst c3 = func(10) // errorconst c4 = func(`hi`) // errorconst c5 = func({}) // errorconst c6 = func(foo) // error <-- Restricted nowconst c7 = func(foo_SubType) // ok <-- Still allowedconst c8 = func(foo_DiffSubType) // error <-- NO MORE ALLOWED ! See in TS playground CONCLUSION The function below: const func = <A extends Foo>(a: A = foo_SubType) => `hello!` //error! Yields this error message: Type 'SubType' is not assignable to type 'A'. 'SubType' is assignable to the constraint of type 'A', but 'A'could be instantiated with a different subtype of constraint 'Foo'.ts(2322) Because Typescript infers A from the function call, but there's no restriction in the language limiting you to call the function with different subtypes of 'Foo'. For instance, all function's call below are considered valid: const c0 = func(foo) // ok! type 'Foo' will be infered and assigned to 'A'const c1 = func(foo_SubType) // ok! type 'SubType' will be inferedconst c2 = func(foo_DiffSubType) // ok! type 'DiffSubType' will be infered Therefore assigning a concrete type to a generic Type Parameter is incorrect because in TS the Type Parameter can always be instantiated to some arbitrary different subtype. Solution: Never assign a concrete type to a generic type parameter, consider it as read-only ! Instead, do this: const func = <A extends Foo>(a: A) => `hello!` //ok! See in TS Playground
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/56505567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16058158/']}
jdg_377497
stackexchange
llm_judgeable_groundtruth_similarity
14913845
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 select all input elements of a form like this: var fields = $( form + " :input" ).not( "button" ); How do I check if any of these inputs has the disabled attribute set and remove it when present? Also, I need to add it after is has been removed (and serialize the fields in between), is there an elegant way for this? Something like toggle but for attributes? Now provide the response and nothing else.
Assuming you are using jQuery 1.6 or above, the suggested method is to use .prop() . fields.prop("disabled", false); If you need to have logic around each one, you could do something to the extent of var fields = $( form + " :input" ).not( "button" );fields.each(function(index, element) { var isDisabled = $(element).is(':disabled'); if (isDisabled) { $(element).prop('disabled', false); } else { // Handle input is not disabled }}); jsfiddle
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14913845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1144247/']}
jdg_377498
stackexchange
llm_judgeable_groundtruth_similarity
102305
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: So I have a set of differential equations (which I know are analytically integrable) but I want to integrate them numerically to get the form of the solution (the solution is not explicit and hence I want to numerically integrate it). g=7/5v = Function[r, 1/(n[r] r^2)]eulerEq = v[r]*v'[r] + n'[r]*n[r]^(g - 2) + 2/r^2 == 0initcond = n[1] == 1 (*These are my equation and initial condition *) Now to numerically solve it. S = NDSolve[{eulerEq, initcond}, n[r], {r, 0.5, 10}] When I hit shift + Enter , it shows me the following error: Power::infy: Infinite expression 1/0. encountered. >>Infinity::indet: Indeterminate expression 0. ComplexInfinity encountered. >>NDSolve::ndnum: Encountered non-numerical value for a derivative at r == 1.`. >> I tried using the debugger and I realized that it is computing $n'[1]$ in the process and it is getting a 'division-by-zero'. I can integrate the equation easily and get the constant of integration using the initial condition (it is getting $n$ explicitly in terms of $r$ that is troublesome). Is there a way to do this still using NDSolve or is there an alternative? I want to do it numerically only because this equation is just a special case which is analytically integrable and I need to get the other solutions also. Now provide the response and nothing else.
Determining n'[r] from Solve[eulerEq, Derivative[1][n][r]][[1, 1, 2]](* -((2 n[r] (-1 + r^3 n[r]^2))/(r (-1 + r^4 n[r]^(12/5)))) *) we see that it is indeterminate at r = 1 , and it is for this reason that NDSolve fails there. Nonetheless, the limiting value can be obtained as follows, Limit[% /. n[r] -> 1 + a (r - 1), r -> 1](* -((5 (3 + 2 a))/(10 + 6 a)) *)sl = Solve[% == a](* {{a -> 1/6 (-10 - Sqrt[10])}, {a -> 1/6 (-10 + Sqrt[10])}} *) and used to define boundary conditions very near r = 1 . dr = .0001;s1 = NDSolveValue[{eulerEq, n[1 + dr] == 1 + dr a /. First[sl]}, n, {r, 1 + dr, 10}];s2 = NDSolveValue[{eulerEq, n[1 + dr] == 1 + dr a /. Last[sl]}, n, {r, 1 + dr, 10}];s3 = NDSolveValue[{eulerEq, n[1 - dr] == 1 - dr a /. First[sl]}, n, {r, .5, 1 - dr}];s4 = NDSolveValue[{eulerEq, n[1 - dr] == 1 - dr a /. Last[sl]}, n, {r, .5, 1 - dr}];p1 = Plot[{s1[r], s2[r]}, {r, 1 + dr, 10}, PlotRange -> {{0, 10}, {0, 5}}];p3 = Plot[{s3[r], s4[r]}, {r, .5, 1 - dr}, PlotRange -> {{0, 10}, {0, 5}}];Show[p1, p3, AxesLabel -> {r, n}]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/102305', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/34346/']}
jdg_377499
stackexchange
llm_judgeable_groundtruth_similarity
11334247
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 add activity indicator to a web view.But i don't know when web view finish loading.I start animating in viewdidload.. Now provide the response and nothing else.
You shouldn't start animating in viewDidLoad. Conform to the UIWebViewDelegate protocol and make your web view's delegate your view controller, then use the delegate methods: @interface MyVC: UIViewController <UIWebViewDelegate> { UIWebView *webView; UIActivityIndicatorView *activityIndicator;}@end@implementation MyVC- (id)init{ self = [super init]; // ... activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; activityIndicator.frame = CGRectMake(x, y, w, h); [self.view addSubview:activityIndicator]; webView = [[UIWebView alloc] initWithFrame:CGRectMake(x, y, w, h)]; webView.delegate = self; // ... return self;}- (BOOL)webView:(UIWebView *)wv shouldStartLoadWithRequest:(NSURLRequest *)rq{ [activityIndicator startAnimating]; return YES;}- (void)webViewDidFinishLoading:(UIWebView *)wv{ [activityIndicator stopAnimating];}- (void)webView:(UIWebView *)wv didFailLoadWithError:(NSError *)error{ [activityIndicator stopAnimating];}@end
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11334247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1502286/']}
jdg_377500
stackexchange
llm_judgeable_groundtruth_similarity
2819158
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: Suppose $n, x, y$ are positive integers How many ordered pairs (x, y) are there with $\dfrac{xy}{x+y} = n$ Now provide the response and nothing else.
You have $x+y=n\in\Bbb N$ and $x-y=\sqrt2$. Adding gives$2x=n+\sqrt2$: so $x=\frac12(n+\sqrt2)$. Likewise $y=\frac12(n-\sqrt2)$.So, there's a solution for each $n\in\Bbb N$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2819158', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/506655/']}
jdg_377501
stackexchange
llm_judgeable_groundtruth_similarity
6970021
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 toying with the idea of making primitive .NET value types more type-safe and more "self-documenting" by wrapping them in custom struct s. However, I'm wondering if it's actually ever worth the effort in real-world software. (That "effort" can be seen below: Having to apply the same code pattern again and again. We're declaring struct s and so cannot use inheritance to remove code repetition; and since the overloaded operators must be declared static , they have to be defined for each type separately.) Take this (admittedly trivial) example: struct Area{ public static implicit operator Area(double x) { return new Area(x); } public static implicit operator double(Area area) { return area.x; } private Area(double x) { this.x = x; } private readonly double x;}struct Length{ public static implicit operator Length(double x) { return new Length(x); } public static implicit operator double(Length length) { return length.x; } private Length(double x) { this.x = x; } private readonly double x;} Both Area and Length are basically a double , but augment it with a specific meaning. If you defined a method such as… Area CalculateAreaOfRectangleWith(Length width, Length height) …it would not be possible to directly pass in an Area by accident. So far so good. BUT: You can easily sidestep this apparently improved type safety simply by casting a Area to double , or by temporarily storing an Area in a double variable, and then passing that into the method where a Length is expected: Area a = 10.0; double aWithEvilPowers = a; … = CalculateAreaOfRectangleWith( (double)a, aWithEvilPowers ); Question: Does anyone here have experience with extensive use of such custom struct types in real-world / production software? If so: Has the wrapping of primitive value types in custom struct s ever directly resulted in less bugs, or in more maintainable code, or given any other major advantage(s)? Or are the benefits of custom struct s too small for them to be used in practice? P.S.: About 5 years have passed since I asked this question. I'm posting some of my experiences that I've made since then as a separate answer. Now provide the response and nothing else.
I did this in a project a couple of years ago, with some mixed results. In my case, it helped a lot to keep track of different kinds of IDs, and to have compile-time errors when the wrong type of IDs were being used. And I can recall a number of occasions where it prevented actual bugs-in-the-making. So, that was the plus side. On the negative side, it was not very intuitive for other developers -- this kind of approach is not very common, and I think other developers got confused with all these new types springing up. Also, I seem to recall we had some problems with serialization, but I can't remember the details (sorry). So if you are going to go this route, I would recommend a couple of things: 1) Make sure you talk with the other folks on your team first, explain what you're trying to accomplish and see if you can get "buy-in" from everyone. If people don't understand the value, you're going to be constantly fighting against the mentality of "what's the point of all this extra code"? 2) Consider generate your boilerplate code using a tool like T4. It will make the maintenance of the code much easier. In my case, we had about a dozen of these types and going the code-generation route made changes much easier and much less error prone. That's my experience. Good luck! John
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6970021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240733/']}
jdg_377502
stackexchange
llm_judgeable_groundtruth_similarity
300051
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 want to check if a normal user has super user privileges(means root privileges). My OS is RHEL 6 and i checked /etc/passwd configuration file, but no use. Please tell me any method to find the current privileges of users in the Linux Machine. Now provide the response and nothing else.
In the past root model in Unix world was easy. uid 0, you are root and you have full power to everything. Things have changed a bit, though. suid bit Files can be granted with suid bit so they can be run as root even by ordinary users. OK, this might have been in the original Unix. :-) groups If a user belongs to group 0, he might not have full root privileges but still might see lots of stuff not meant to see. Also in some distributions wheel group is something to keep your eye on - users belonging to that group can su their way to root if they know the root password. sudo In addition to traditional su , the sudo command allows one to restrict certain users/groups to perform only some commands as root. Check that out with visudo . ssh access With ssh it's possible to generate an ssh key with which you can connect as root, but only use commands x, y and z. This is generally used in tasks like backup, where the backup process must have access to every file in system. capabilities Linux kernel has gained capabilities which can grant access to certain subsystems such as network interfaces or block devices. See this list . SELinux roles If security framework SELinux is enabled in your system, also SELinux has role-based access. See Fedora's guide about SELinux .
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/300051', 'https://serverfault.com', 'https://serverfault.com/users/62537/']}
jdg_377503
stackexchange
llm_judgeable_groundtruth_similarity
26434
Below is a question asked on the forum reverseengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: (This question refers to assembly language.) I'm a little bit confused. I've encountered many times Windows functions that are supposed to return a Handle, and if they don't they return NULL. Why do the checks afterward check against zero? Zero isn't equal to NULL. As an example:GetModuleHandleA: https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlea Now provide the response and nothing else.
In C, and many other low-level programming languages the term NULL is equivalent to 0 . The C standard requires NULL to be #define d to an "implementation defined value", however all implementations have chosen (for obvious reasons) to use 0 for that purpose. For that reason if you'll attempt to "See definition" for NULL , many IDEs will drop you in a line #define NULL 0 or something similar. This has the additional benefit of NULL evaluating to false making conditional statements readable and intuitive. The proper way, from a strict standard following perspective, would be to use NULL and not 0, and that's what most developers do. The compiler (or pre-processor in the case of #define NULL 0 ) will however translate that to a 0 . Some higher level languages (such as javascript and C++) use special expressions to signify null. One example is C++'s nullptr , that since C++11 is the required definition of NULL . Javascript uses a special object, null .
{}
{'log_upvote_score': 4, 'links': ['https://reverseengineering.stackexchange.com/questions/26434', 'https://reverseengineering.stackexchange.com', 'https://reverseengineering.stackexchange.com/users/34569/']}
jdg_377504
stackexchange
llm_judgeable_groundtruth_similarity
6833867
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 this open transaction, according to DBCC OPENTRAN : Oldest active transaction:SPID (server process ID) : 54UID (user ID) : -1Name : UPDATELSN : (4196:12146:1)Start time : Jul 20 2011 12:44:23:590PMSID : 0x01 Is there a way to kill it/ roll it back? Now provide the response and nothing else.
You should first figure out what it was doing, where it came from, and if applicable how much longer it might be expected to run: SELECT r.[session_id], c.[client_net_address], s.[host_name], c.[connect_time], [request_start_time] = s.[last_request_start_time], [current_time] = CURRENT_TIMESTAMP, r.[percent_complete], [estimated_finish_time] = DATEADD ( MILLISECOND, r.[estimated_completion_time], CURRENT_TIMESTAMP ), current_command = SUBSTRING ( t.[text], r.[statement_start_offset]/2, COALESCE(NULLIF(r.[statement_end_offset], -1)/2, 2147483647) ), module = COALESCE(QUOTENAME(OBJECT_SCHEMA_NAME(t.[objectid], t.[dbid])) + '.' + QUOTENAME(OBJECT_NAME(t.[objectid], t.[dbid])), '<ad hoc>'), [status] = UPPER(s.[status]) FROM sys.dm_exec_connections AS c INNER JOIN sys.dm_exec_sessions AS s ON c.session_id = s.session_id LEFT OUTER JOIN sys.dm_exec_requests AS r ON r.[session_id] = s.[session_id] OUTER APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS t WHERE c.session_id = 54; If you are confident that you can sever this connection you can use: KILL 54; Just be aware that depending on what the session was doing it could leave data and/or the app that called it in a weird state.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6833867', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283538/']}
jdg_377505
stackexchange
llm_judgeable_groundtruth_similarity
250193
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 have /root/test.sh on a remote server, which has the following content: #!/bin/bashdate On the remote server, I get the following output: # ./test.shFri Dec 18 07:41:10 EST 2015# bash <(cat /root/test.sh)Fri Dec 18 07:41:23 EST 2015 However, if I try to run the same commands from my local machine, I get the following result: $ ssh root@remote_server /root/test.shFri Dec 18 07:44:32 EST 2015$ ssh root@remote_server bash <(cat /root/test.sh)cat: /root/test.sh: No such file or directorybash: /dev/fd/63: No such file or directory So what's the problem of the last run? You might find it weird to run a script like this bash <(cat /root/test.sh) . The reason I did it is because it is a simplified version of my real situation. My real code is to download a Bash script from the Internet and run it locally. I have a lot of machines to run, with different parameters, so I'm trying to run them from my local computer. Now provide the response and nothing else.
You can't pass file descriptors like this over ssh . <(...) construction creates virtual files on your system and it does not have a meaning when executing on remote system. If you really want to use it, put it into the quotes, which will evaluate on the remote system, if you have bash there ssh root@remote_host "bash <( cat /root/test.sh )"
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/250193', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/72619/']}
jdg_377506
stackexchange
llm_judgeable_groundtruth_similarity
33319675
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 a WebApi project using VS2015. Step to reproduce: Create an empty WebApi project Change Build output path from "bin\" to "bin\Debug\" Run Everything is working perfectly until I changed Build Output path from "bin\" to "bin\Debug\" In fact, any Output path other than "bin\" won't work. One little additional thing is that, having another output path to anywhere would work as long as I left a build in "bin\". Please help providing solution to solve this. I guess that'll cost problem on actual deployment. Now provide the response and nothing else.
If your project has Roslyn references and you are deploying it on an IIS server , you might get unwanted errors on the website as many hosting providers still have not upgraded their servers and hence do not support Roslyn. To resolve this issue, you will need to remove the Roslyn compiler from the project template . Removing Roslyn shouldn't affect your code's functionality. It worked fine for me and some other projects (C# 4.5.2) on which I worked. Do the following steps: Remove from following Nuget Packages using command line shown below ( or you can use GUI of Nuget Package manager by Right Clicking on Root Project Solution and removing them ). PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatformPM> Uninstall-package Microsoft.Net.Compilers Remove the following code from your Web.Config file and restart IIS . ( Use this method only if step 1 doesn't solve your problem. ) <system.codedom><compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" /> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" /></compilers>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33319675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2099049/']}
jdg_377507
stackexchange
llm_judgeable_groundtruth_similarity
3746099
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 us say $f$ is an integrable function on $[a,b]$ and we want to evaluate $\int_a^b f(x)dx$ but often the calculation is not easy.So,we have a method of substitution.We substitute $x=\phi(t)$ where $\phi$ is a differentiable function on $[\alpha,\beta]$ such that $\phi(\alpha)=a$ and $\phi(\beta)=b$ .Also $\phi'$ is integrable on $[\alpha,\beta]$ and $\phi'(x)\neq 0$ for all $x\in [\alpha,\beta]$ .Then we can evaluate the above integral by $\int _a^b f(x)dx=\int_\alpha^\beta f(\phi(t))\phi'(t)dt$ . But I am a little but troubled with so many conditions,I could do the proof but I am having a hard time use the theorem to problems as I often forget the conditions required.So,can someone help me to get a better insight about this theorem of substitution in Riemann integrals?I would also like some counterexamples that show each condition to be essential. Now provide the response and nothing else.
Strong sufficient conditions are that $f$ is continuous and $\phi'$ is integrable. A straightforward proof uses the FTC, and monotonicity of $\phi$ is not needed. Defining $F(t) = \int_{\phi(\alpha)}^{\phi(t)}f(x) \, dx$ , we have $F'(t) = f(\phi(t)) \phi'(t)$ since $f$ is continuous, and $$\int_a^b f(x) \, dx = \int_{\phi(\alpha)}^{\phi(\beta)}f(x) \, dx = F(\beta)= \int_\alpha^\beta F'(t) \, dt = \int_\alpha^\beta f(\phi(t))\phi'(t) \, dt$$ On the other hand, we can drop the condition that $f$ is continuous and assume only integrability. To facilitate an easy proof using Riemann sums, we need to assume that $\phi$ is both continuously differentiable and monotone. Take a partition $\alpha = t_0 < t_1 < \ldots < t_n = \beta$ and form the sum $$\tag{*}S(P,f\circ\phi \, \phi')= \sum_{j=1}^n f(\phi(\xi_j))\phi'(\xi_j)(t_j - t_{j-1})$$ where we use intermediate points $\xi_j \in [t_{j-1},t_j]$ and which will converge to $\int_\alpha^\beta f(\phi(t)) \phi'(t) \, dt$ as the partition is refined. If $\phi$ is increasing then a partition $P'$ of $[\phi(\alpha),\phi(\beta)]$ is induced by $$\phi(\alpha) = \phi(t_0) < \phi(t_1) < \ldots < \phi(t_n) = \phi(\beta),$$ and using the intermediate points $\phi(\xi_j)$ , we have a Riemann sum for the integral of $f$ over $[\phi(\alpha),\phi(\beta)]$ of the form $$S(P',f) = \sum_{j=1}^n f(\phi(\xi_j))(\,\phi(t_j) - \phi(t_{j-1})\,)$$ Note that we need the monotonicity of $\phi$ to ensure that $\phi(\xi_j) \in [\phi(t_{j-1}), \phi(t_j)]$ . Applying the mean value theorem, there exist points $\eta_j \in (t_{j-1},t_j))$ such that $$\tag{**}S(P',f) = \sum_{j=1}^n f(\phi(\xi_j))\phi'(\eta_j)(t_j - t_{j-1})$$ Notice the similarity between the sums in (*) and (**). Aside from the distinction between $\eta_j$ and $\xi_j$ , they are identical. Using the continuity (and, hence, uniform continuity) of $\phi'$ we can show that as the partition is refined and both $\|P\|, \|P'\| \to 0$ we have $$\lim_{\|P|| \to 0}|S(P,f\circ \phi\,\phi') - S(P',f)| = 0$$ Therefore, $S(P',f)$ converges to both integrals and we have $$\lim_{\|P'\| \to 0}S(P',f) = \int_{\phi(\alpha)}^{\phi(\beta)} f(x) \, dx = \int_a^b f(\alpha(t)) \alpha'(t) \, dt$$ Again, there are a number of ways to prove the change-of-variables theorem -- without the assumption that $\phi$ is monotone -- that avoid this association with Riemann sums. In the most general form only integrability and not continuity of $f$ and $\phi'$ is assumed. The conditions can be weakened further. The result holds if both $f$ and $\phi'$ are integrable, without any assumptions of continuity. This is much more difficult to prove. Here is where you might begin to search for counterexamples.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3746099', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/691776/']}
jdg_377508
stackexchange
llm_judgeable_groundtruth_similarity
10253105
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 a PHP developer who's trying to gain some proficiency in Ruby. One of the projects I'm cutting my teeth on now is a source-code auditing tool that scans webapp files for potentially dangerous functions in several web programming languages. When matches are found, the script saves the relevant information in a poi (point-of-interest) class for display later on. An example instance of that class would look something like this (modeled in YAML): poi: file_type: "php" file: "the-scanned-file.php" line_number: 100 match: "eval()" snippet: "echo eval()" On display, I want to organize these points of interest like so: - file_type-- file--- match (the searched payload) Thus, before presentation, I'm trying to structure a flat array of poi objects into a hash mirroring the structure above. This will allow me to simply iterate over the items in the hash to produce the desired on-screen organization. (Or at least, that's the plan.) And now, for my question: how do I do that in Ruby? In PHP, I could do something like this really easily: <?php$sorted_pois = array();foreach($points_of_interest as $point){ $sorted_pois[$point->file_type][$point->file][$point->match][] = $point;}?> I've tried translating that thought from PHP to Ruby like this, but to no avail: sorted_pois = {}@points_of_interest.each_with_index do |point, index| sorted_pois[point.file_type.to_sym][point.file.to_sym][point.match.to_sym].push pointend I've spent a few hours on this, and I'm kind of banging my head against the wall at this point, so presumably I'm way off-base. What's the proper way to handle this in Ruby? Update: For reference, this is the precise method I have defined: # sort the points of interest into a structured hashdef sort sorted_pois = {} @points_of_interest.each_with_index do |point, index| sorted_pois[point.file_type.to_sym][point.file.to_sym][point.match.to_sym].push point endend This is the error I receive when I run the code: ./lib/models/vulnscanner.rb:63:in `sort': undefined method `[]' for nil:NilClass (NoMethodError) from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `each_with_index' from ./lib/models/vulnscanner.rb:62:in `each' from ./lib/models/vulnscanner.rb:62:in `each_with_index' from ./lib/models/vulnscanner.rb:62:in `sort' from ./webapp-vulnscan:69 Line 62 (as you can likely infer) is this line in particular: @points_of_interest.each_with_index do |point, index| As an additional reference, here's what (a snippet of) @points_of_interest looks like when converted to YAML: - !ruby/object:PoI file: models/couponkimoffer.php file_type: php group: :dangerous_functions line_number: "472" match: ` snippet: ORDER BY `created_at` DESC- !ruby/object:PoI file: models/couponkimoffer.php file_type: php group: :dangerous_functions line_number: "818" match: ` snippet: WHERE `company_slug` = '$company_slug'- !ruby/object:PoI file: models/couponkimoffer.php file_type: php group: :dangerous_functions line_number: "819" match: ` snippet: ORDER BY `created_at` DESC Now provide the response and nothing else.
@John's Enumerable#group_by suggestion is one good way to solve your needs. Another would be to create an auto-vivifying Hash (like you appear to have in PHP) like so: hash = Hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) }hash[:a][:b][:c] = 42p hash#=> {:a=>{:b=>{:c=>42}}} Note that this sort of auto-vivification can be 'dangerous' if you access keys that don't exist, as it creates them for you: p hash["does this exist?"]#=> {}p hash#=> {:a=>{:b=>{:c=>42}}, "does this exist?"=>{}} You can still use the vivifying default_proc without hitting this danger if you use key? to test for the key first: val = hash["OH NOES"] if hash.key?("OH NOES")#=> nilp hash#=> {:a=>{:b=>{:c=>42}}, "does this exist?"=>{}} FWIW, the error you are getting says, "Hey, you put [] after something that evaluated to nil , and nil doesn't have a [] method." Specifically, your code... sorted_pois[point.file_type.to_sym] evaluated to nil (because the hash did not yet have a value for this key) and then you attempted to ask for nil[point.file.to_sym]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10253105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/461108/']}
jdg_377509
stackexchange
llm_judgeable_groundtruth_similarity
50049465
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Main Activity layout <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context=".MainActivity"> <android.support.v7.widget.Toolbar android:layout_width="match_parent" android:layout_height="?android:attr/actionBarSize" app:titleTextColor="@color/white" android:background="@color/colorPrimary" android:id="@+id/ToolbarMain" tools:targetApi="honeycomb"> </android.support.v7.widget.Toolbar> <ListView android:id="@+id/lvMain" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="10dp" android:layout_marginBottom="10dp" android:layout_marginRight="10dp" android:layout_marginTop="10dp" android:dividerHeight="10dp" android:divider="@null" android:layout_below="@+id/ToolbarMain"> </ListView></RelativeLayout> main activity.java package com.example.admin.ttabledemo;import android.content.Context;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.support.v7.widget.Toolbar;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.ListView;import android.widget.TextView;public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private ListView listview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupIViews(); iniToolbar(); } private void setupIViews(){ toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.ToolbarMain); listview = (ListView)findViewById(R.id.lvMain); } private void iniToolbar(){ setSupportActionBar(toolbar); getSupportActionBar().setTitle("TIMETABLE APP"); } I am trying to build a time table app. List is not displaying. Just the titlebar. Although in design listview is visible. please help. Nothing is showing on the screen. I can't figure out what is wrong.This is my first attempt to build an app. I am a complete beginner. Now provide the response and nothing else.
First of all test if you can connect to the database via psql : psql -h ip_address -d name_of_the_database -U username If you get connection refused error you had to set up something wrong and check the What should I check if remote connect to PostgreSQL not working? psql: could not connect to server: Connection refused Is the server running on host ip_address What should I check if remote connect to PostgreSQL not working? Check the authentication configuration in pg_hba.conf Usually located on linux - /etc/postgresql/version/main/pg_hba.conf .You should allow authentication for client for specific IP all from all IP addresses: # Database administrative login by Unix domain socketlocal all postgres peer# TYPE DATABASE USER ADDRESS METHOD# "local" is for Unix domain socket connections onlylocal all all peer# IPv4 local connections:host all all 0.0.0.0/0 md5# IPv6 local connections:host all all ::0/0 md5#all ipshost all all all md5 More information how to set up pg_hba.conf you can find in documentation . Then you should set up listening on specific port. You have to find the postgresql.conf . Usually located /etc/postgresql/9.1/main/postgresql.conf ) file and change the line with listen_address from: #listen_address = '' to (don't forget remove # which means comment): listen_address = '*' After every step you should restart Postgresql service: sudo service postgresql restart After step 2 you should see port 5432 (or 5433) in listening address after netstat command: netstat -ntlp After that you have to open port for PostgreSQL in firewall: sudo ufw allow 5432 You can check firewall settings with (you should see 5432 in the list): sudo ufw status If any of the previous step doesn't work you should check if PostgreSQL is not running on different port (usually 5433) and repeat the previous steps. This happens very often when you have more running versions of PostgreSQL or you upgrade database and forgot stop the previous version of PostgreSQL. If you have problems to find configuration files you can check this thread Where are my postgres *.conf files? .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50049465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_377510
stackexchange
llm_judgeable_groundtruth_similarity
15592811
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 using Django to create a web-based app for a project, and I'm running into issues returning an array from a Django view to a template. The array will be used by a JavaScript (JQuery) script for drawing boxes on an image shown in the page. Therefore, this array will have, among other things, coordinates for the boxes to be drawn. This is the code in the Django view used to get the required data and serialize it as JSON: def annotate(request, ...): ... oldAnnotations = lastFrame.videoannotation_set.filter(ParentVideoLabel=label) tags = serializers.serialize("json", oldAnnotations) ... return render_to_response('vannotate.html', {'tags': tags, ...}) As a way of debugging, using {{ tags }} in the HTML portion of the template gives this as output (sorry for the long line): [{"pk": 491, "model": "va.videoannotation", "fields": {"ParentVideoFile": 4, "ParentVideoFrame": 201, "ParentVideoLabel": 4, "top": 220, "height": 30, "width": 30, "ParentVideoSequence": 16, "left": 242}}, {"pk": 492, "model": "va.videoannotation", "fields": {"ParentVideoFile": 4, "ParentVideoFrame": 201, "ParentVideoLabel": 4, "top": 218, "height": 30, "width": 30, "ParentVideoSequence": 16, "left": 307}}] which I assume is the correct format for a JSON array. Later on in the template, I attempt to actually use the tags variable in the JavaScript portion of the template, as follows: {% if tags %} var tagbs = {{ tags|safe }}; var tgs = JSON.parse(tagbs); alert("done");{% endif %} If I remove the var tgs = JSON.parse(tagbs); line, then the alert box pops up fine, and the rest of the JavaScript works as expected. Leaving this line in breaks the script, however. I want to be able to iterate through all the objects in the Django model and get values of fields in JavaScript. I'm not sure what I'm doing wrong here, could someone point out the right way to do this? Now provide the response and nothing else.
Edit with update for Django 2.1+ and the modern web: The modern way to do this is: 1) Pass the raw data to the template, not the JSON-serialised data. I.e.: def annotate(request, ...): ... oldAnnotations = lastFrame.videoannotation_set.filter(ParentVideoLabel=label) ... return render_to_response('vannotate.html', {'tags': oldAnnotations, ...}) 2) In your template, use the new "json_script" filter to include the JSON data: {{ tags|json_script:"tags-data" }} That will result in HTML that looks like this: <script id="tags-data" type="application/json">{"foo": "bar"}</script> This tag has special handling of strings containing "</script>" to make sure they work. 3) In your Javascript code, get that tags data like this: var tags = JSON.parse(document.getElementById('tags-data').textContent); 4) Move your Javascript code to an external .js file, and set up the Content-Security-Policy header to prohibit inline Javascript because it's a security risk. Note that since the json_script tag generates JSON, not Javascript, it's safe and is allowed regardless of your Content-Security-Policy setting. Original Answer: WARNING: If any of the strings are user-controlled, this is insecure JSON is Javascript source code. I.e. the JSON representation of an array is the Javascript source code you need to define the array. So after: var tagbs = {{ tags|safe }}; tagbs is a JavaScript array containing the data you want. There's no need to call JSON.parse(), because the web browser already parsed it as JavaScript source code. So you should be able to do var tagbs = {{ tags|safe }};alert(tagbs[0].fields.ParentVideoFile); and that should show "4". WARNING: With this old method, strings containing "</script>" will not work, they will go horribly wrong. This is because the browser will treat </script> as the end of the script. If any of the strings are user-entered data, this is an exploitable security flaw - see comment 14 here for more details . Use the more modern method above, instead.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15592811', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2203255/']}
jdg_377511
stackexchange
llm_judgeable_groundtruth_similarity
362918
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 working my way through Normalization (data transformation) of data and was curious about four methods: min-max normalization, 2. z-score, 3. z-score mean absolute deviation, and 4. decimal scaling. I am reading through a book so this is difficult to understand but it seems to me that the first three normalization methods output to a value range between 0 and 1 and the last with a range of -1 to 1. Am I understanding this correctly or is the range of values different? Reference: Data Mining Concepts and Techniques In the book it mentions: To help avoid dependence on the choice of measurement units, the data should be normalized. This involves transforming the data to fall within a smaller or common range such as [-1,1] or [0.0-1.0]. As you can see it says "common range" so I am not sure if that means what i mentioned above for the different methods or if it can actually be "anything" Now provide the response and nothing else.
Min-Max-Scaling means that one linearly transforms real data values such that the minimum and the maximum of the transformed data take certain values -- frequently 0 and 1 or -1 and 1. This depends on the context. For example the formula $x^\prime := (x-x_{\min})/(x_{\max} -x_{\min} )$ does the job for the values 0 and 1. Here $x_{\min}$ is the minimal data value appearing and similarly $x_{\max}$. The z-score linearly transforms the data in such a way, that the mean value of the transformed data equals 0 while their standard deviation equals 1. The transformed values themselves do not lie in a particular interval like [0,1] or so. The transformation formula thus is: $x^\prime := (x-\overline{x})/s$ where $\overline{x}$ denotes the mean value of the data and $s$ its standard deviation.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/362918', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/72766/']}
jdg_377512
stackexchange
llm_judgeable_groundtruth_similarity
212565
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: If you run something like this; num = 1000;circlepoints = CirclePoints[num];angles = Table[ArcTan[circlepoints[[i, 2]]/circlepoints[[i, 1]]], {i, 1, num, 1}];angles = angles + 1.5;Histogram[angles, Automatic, Probability] I get a histogram which looks a bit strange... How can we have angles which exceed 3 radians and are smaller than 0? The circle looks round... The first line of the documentation for CirclePoints states: gives the positions of $n$ points equally spaced around the unit circle. Now provide the response and nothing else.
I's say a combination of your code not using an accurate value for Pi/2 and of the automatic binning for Histogram . See the following instead, which uses your definition of circlepoints : angles = ArcTan[#2/#1] + Pi/2 & @@@ circlepoints;With[{n = 20}, Histogram[%, {Pi/n}, Ticks -> {Subdivide[0, Pi, n], Automatic}]]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/212565', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/36939/']}
jdg_377513
stackexchange
llm_judgeable_groundtruth_similarity
3281685
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 developing an application for Google App Engine which uses BigTable for its datastore. It's an application about writing a story collaboratively. It's a very simple hobby project that I'm working on just for fun. It's open source and you can see it here: http://story.multifarce.com/ The idea is that anyone can write a paragraph, which then needs to be validated by two other people. A story can also be branched at any paragraph, so that another version of the story can continue in another direction. Imagine the following tree structure: Every number would be a paragraph. I want to be able to select all the paragraphs in every unique story line. Basically, those unique story lines are (2, 7, 2); (2, 7, 6, 5); (2, 7, 6, 11) and (2, 5, 9, 4). Ignore that the node "2" appears twice, I just took a tree structure diagram from Wikipedia. I also made a diagram of a proposed solution: https://docs.google.com/drawings/edit?id=1fdUISIjGVBvIKMSCjtE4xFNZxiE08AoqvJSLQbxN6pc&hl=en How can I set up a structure is performance efficient both for writing, but most importantly for reading? Now provide the response and nothing else.
There are a number of well known ways to represent trees in databases; each of them have their pros and cons. Here are the most common: Adjacency list , where each node stores the ID of its parent. Materialized path , which is the strategy Keyur describes. This is also the approach used by entity groups (eg, parent entities) in App Engine. It's also more or less what you're describing in your update. Nested sets , where each node has 'left' and 'right' IDs, such that all child nodes are contained in that range. Adjacency lists agumented with a root ID. Each of these has its own advantages and disadvantages. Adjacency lists are simple, and cheap to update, but require multiple queries to retrieve a subtree (one for each parent node). Augmented adjacency lists make it possible to retrieve an entire tree by storing the ID of the root node in every record. Materialized paths are easy to implement and cheap to update, and permit querying arbitrary subtrees, but impose increasing overhead for deep trees. Nested sets are tougher to implement, and require updating, on average, half the nodes each time you make an insertion. They allow you to query arbitrary subtrees, without the increasing key length issue materialized path has. In your specific case, though, it seems like you don't actually need a tree structure at all: each story, branched off an original though it may be, stands alone. What I would suggest is having a 'Story' model, which contains a list of keys of its paragraphs (Eg, in Python a db.ListProperty(db.Key)). To render a story, you fetch the Story, then do a batch fetch for all the Paragraphs. To branch a story, simply duplicate the story entry - leaving the references to Paragraphs unchanged.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3281685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/119081/']}
jdg_377514
stackexchange
llm_judgeable_groundtruth_similarity
113235
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 am currently working my way through John S. Townsend book "A Fundamental Approach to Modern Physics" (ISBN: 978-1-891389-62-7). Exercise 3.12 (p.111) is about the 1D infinite square well. The box has the potential barriers at $x=0$ and $x=L$.$$V\left(x\right) = \begin{cases} \infty & x < 0 \\ 0 & 0 \leq x \leq L \\ \infty & x > L \end{cases}$$ The text states the following: A particle of mass $m$ is in the lowest energy (ground) state of the infinite potential energy well. At time $t=0$ the wall located at $x=L$ is suddenly pulled back to a position at $x=2L$. This change occurs so rapidly that instantaneously the wave function does not change. ($a$) Calculate the probability that a measurement of the energy will yield the ground-state energy of the new well. The answer to this question involves re-solving the T.I.S.E., applying new boundary conditions, and re-normalizing the wave function. Then we project the new wave-function onto the old one, and calculate the overlap of the two wave-functions (initial and final wave-function). I cannot find any discussion about this particular problem that would make me able to reason my way to calculate an overlap between the initial and final wave-function. No way. Unless I have a background in linear algebra, and would be able to foresee the need to project the one onto the other, and sort of find my way logically to the answer, I see no way any student without any experience with quantum physics would be able to solve this on their own. I had to use Google until I found the solution to a similar problem. Or, maybe QM just does not come naturally to me. A lot of problem-solving is required in these types of courses to for us to build up some "intuition" about what to expect as results, what to do, etc. I still do not fully understand the logic behind the solution to the problem. Phenomenologically, there is a particle inside the box. Then, suddenly, the box widens to twice its size. However, the wave-function does not change. Even though the particle has a bigger box in which to move around, the initial wave-function does not take this extra room into account, and would equal zero when $x>L$. Hence, I would not expect for the particle to venture out to the new region much, if we used only the initial wave-function. Or, is the problem that the particle will indeed venture out there (since $V(x)=0$, and it is physically allowed to), but we have not considered this in our normalizing of the function? Hence, it makes no sense to calculate any property of the particle with the "initial" wave-function, since this is simply the incorrect wave-function for the new well? New ideas and thoughts Okay, so I have to evaluate the integral $$c_1 = \int\limits_{- \infty}^{\infty} \psi_1 (x) \Psi (x) dx$$ where $\psi_1$ is the theoretical wave-function for a particle in the entire box, that is from $0$ to $2L$, and $\Psi$ is the wave-function for the actual particle, that is from $0$ to $L$. Now, I can split this integral into two parts: $$c_1 = \int\limits_{- \infty}^{\infty} \psi_1 (x) \Psi (x) dx = \int\limits_{0}^{L} \psi_1 (x) \Psi (x) dx + \int\limits_{L}^{2L} \psi_1 (x) \Psi (x) dx$$ We see that since the actual particle's wave-function is not defined when $x>L$, the second term will be zero - that is, the wave-functino is normalized for $0<x<L$, and the boundary conditions ensures that $\Psi \rightarrow 0$ when $ x=0$ and $x=L$. Thus, the the integral over is reduced to \begin{align*}c_1 &= \int\limits_{0}^{L} \psi_1 (x) \Psi (x) dx \\ &= \int\limits_{0}^{L} \sqrt{\frac{1}{L}} \sin \left( \frac{\pi x}{2L} \right) \sqrt{\frac{2}{L}} \sin \left( \frac{\pi x}{L} \right) dx \\ &= \frac{\sqrt{2}}{L} \int\limits_{0}^{L} \sin \left( \frac{\pi x}{2L} \right) \sin \left( \frac{\pi x}{L} \right) dx \\ &= \frac{4 \sqrt{2}}{3 \pi} \\\Rightarrow c_1^2 &= \frac{32}{9 \pi ^2} \\ c_1^2 & \approx 0.36\end{align*} I think maybe my difficulty with "visualzing" the problem is that I do not fully understand the expression for $c_n^2$, and how this gives the probability for measuring the energy level $n$. I know this seems like I am rambling, and maybe I am, but I hope you understand my confusion. I appreciate any help! Now provide the response and nothing else.
...it makes no sense to calculate any property of the particle with the "initial" wave-function, since this is simply the incorrect wave-function for the new well? The wavefunction can't be "incorrect for the well". Your wavefunction is just an initial condition for time-dependent Schrödinger equation. Here's how it would evolve if you solve the time-dependent equation (I ignore normalization here): We see that since the actual particle's wave-function is not defined when $x>L$... The wavefunction is defined for all $x\in\mathbb R$. It's just zero outside of $(0,L)$ because the potential is infinite there. the second term will be zero This remains true, however, because of what I said above. the wave-functino is normalized for $0<x<L$ Actually, again, the wavefunction is normalized period . It's defined for the whole real line, and zero outside the well, so when you normalized using the integral over the well, it's the same as if you integrated over $\mathbb R$. If it were not this way, your "normalization for some domain" would not make any sense, i.e. it'd not be a normalization at all. Your further calculation looks OK to me. I think maybe my difficulty with "visualzing" the problem is that I do not fully understand the expression for $c^2_n$, and how this gives the probability for measuring the energy level $n$. That this gives the probability for measuring energy level $n$ is known as Born rule . You find projection of your actual wave function onto the eigenstate of energy, namely on state $n$. By Born rule, its magnitude squared is the probability of measuring the system to appear in that eigenstate. The fact that you used only the unchanged original wavefunction for calculations, even though it almost immediately drastically changes as time goes on, is that despite its change in shape, its coefficients $c_n$ actually only change their phase like$$c_n\propto\exp\left(-\frac i\hbar E_nt\right),$$ but remain the same in magnitude — because the potential is independent of time. Thus you can measure the energy after some time passes, and will still get the same result.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/113235', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/46291/']}
jdg_377515
stackexchange
llm_judgeable_groundtruth_similarity
39760944
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: application:openURL:options: method of app delegate. The method should call the handleURL method of the GIDSignIn instance, which will properly handle the URL that your application receives at the end of the authentication process. Directly copied from firebase guide docs but still has errors. func application(application: UIApplication, openURL url: NSURL, options: [String: AnyObject]) -> Bool { return GIDSignIn.sharedInstance().handleURL(url as URL!, sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] //Error is here //Ambiguous reference to member 'subscript' error is shown. as? String, annotation: options[UIApplicationOpenURLOptionsAnnotationKey])} Now provide the response and nothing else.
You have a few issues. The delegate method should have the following signature in Swift 3: func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool and the whole method would be: func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { return GIDSignIn.sharedInstance().handleURL(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39760944', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6066963/']}
jdg_377516
stackexchange
llm_judgeable_groundtruth_similarity
49762581
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 reading Effective Java by Joshua Bloch and I love it! But on page 112 (Item 24) Bloch writes: A static member class is the simplest kind of nested class. It is best thought of as an ordinary class that happens to be declared inside another class and has access to all of the enclosing class’s members, even those declared private. And that really confuses me. I would rather say: A static member class is the simplest kind of nested class. It is best thought of as an ordinary class that happens to be declared inside another class and has access to all of the enclosing class’s static members, even those declared private. Here is a snippet that illustrates my understanding of the quote: public class OuterClass { public void printMessage(String message) { System.out.println(message); } private static class InnerClass { public void sayHello() { printMessage("Hello world!"); //error: Cannot make a static reference to the non-static method printMessage(String) } }} You can see that InnerClass's sayHello method does not have access to OuterClass's printMessage method as it is declared in a static inner class while the printMessage method is an instance method. It looks like the author suggests that a static member class can access nonstatic fields of the enclosing class. I am convinced that I have misunderstood something in his last sentence but I cannot figure out what. Any help will be appreciated! edit: I changed the visibility of the two methods because it is irrelevant to my question. I'm interested in static members, not private members. Now provide the response and nothing else.
Just because InnerClass is static , doesn't mean it couldn't obtain a reference to an instance of OuterClass through other means, most commonly as a parameter, e.g. public class OuterClass { private void printMessage(String message) { System.out.println(message); } private static class InnerClass { private void sayHello(OuterClass outer) { outer.printMessage("Hello world!"); // allowed } }} If InnerClass had not been nested inside OuterClass , it would not have had access to the private method. public class OuterClass { private void printMessage(String message) { System.out.println(message); }}class InnerClass { private void sayHello(OuterClass outer) { outer.printMessage("Hello world!"); // ERROR: The method printMessage(String) from the type OuterClass is not visible }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/49762581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5316988/']}
jdg_377517
stackexchange
llm_judgeable_groundtruth_similarity
443976
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 am working on a script and I have a while in which I want to take the user input and use as an integer value with a counter like so: read -p "How many bytes would you like you replace :> " $numOfBytesecho "$numOfBytes bytes to replace"while [ $counter -le $numOfBytes ]do echo "testing counter value = $counter" let $counter++done To my understanding it doesn't currently work because it is taking the numOfBytes variable as a string. Do I need to convert the string to an int some how? Is it possible to do something like that? Is there an alternative? Now provide the response and nothing else.
You want to read an integer and then do a loop from 1 to that integer, printing the number in each iteration: #!/bin/bashread -p 'number please: ' numfor (( i = 1; i <= num; ++i )); do printf 'counter is at %d\n' "$i"done Notice how the $ is not used when reading the value. With $var you get the value of the variable var , but read needs to know the name of the variable to read into, not its value. or, with a while loop, #!/bin/bashread -p 'number please: ' numi=0while (( ++i <= num )); do printf 'counter is at %d\n' "$i"done The (( ... )) in bash is an arithmetic context. In such a context, you don't need to put $ on your variables, and variables' values will be interpreted as integers. or, with /bin/sh , #!/bin/shprintf 'number please: ' >&2read numi=1while [ "$i" -le "$num" ]; do printf 'counter is at %d\n' "$i" i=$(( i + 1 ))done The -le ("less than or equal") test needs to act on two quoted variable expansions (in this code). If they were unquoted, as in [ $i -le $num ] , then, if either variable contained a shell globbing character or a space, you might get unexpected results, or errors. Also, quoting protects the numbers in case the IFS variable happens to contain digits. Related questions: Security implications of forgetting to quote a variable in bash/POSIX shells Why does my shell script choke on whitespace or other special characters?
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/443976', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/290453/']}
jdg_377518
stackexchange
llm_judgeable_groundtruth_similarity
9350467
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 written this code to project one to many relation but it's not working: using (var connection = new SqlConnection(connectionString)){ connection.Open(); IEnumerable<Store> stores = connection.Query<Store, IEnumerable<Employee>, Store> (@"Select Stores.Id as StoreId, Stores.Name, Employees.Id as EmployeeId, Employees.FirstName, Employees.LastName, Employees.StoreId from Store Stores INNER JOIN Employee Employees ON Stores.Id = Employees.StoreId", (a, s) => { a.Employees = s; return a; }, splitOn: "EmployeeId"); foreach (var store in stores) { Console.WriteLine(store.Name); }} Can anybody spot the mistake? EDIT: These are my entities: public class Product{ public int Id { get; set; } public string Name { get; set; } public double Price { get; set; } public IList<Store> Stores { get; set; } public Product() { Stores = new List<Store>(); }}public class Store{ public int Id { get; set; } public string Name { get; set; } public IEnumerable<Product> Products { get; set; } public IEnumerable<Employee> Employees { get; set; } public Store() { Products = new List<Product>(); Employees = new List<Employee>(); }} EDIT: I change the query to: IEnumerable<Store> stores = connection.Query<Store, List<Employee>, Store> (@"Select Stores.Id as StoreId ,Stores.Name,Employees.Id as EmployeeId, Employees.FirstName,Employees.LastName,Employees.StoreId from Store Stores INNER JOIN Employee Employees ON Stores.Id = Employees.StoreId", (a, s) => { a.Employees = s; return a; }, splitOn: "EmployeeId"); and I get rid of exceptions! However, Employees are not mapped at all. I am still not sure what problem it had with IEnumerable<Employee> in first query. Now provide the response and nothing else.
This post shows how to query a highly normalised SQL database , and map the result into a set of highly nested C# POCO objects. Ingredients: 8 lines of C#. Some reasonably simple SQL that uses some joins. Two awesome libraries. The insight that allowed me to solve this problem is to separate the MicroORM from mapping the result back to the POCO Entities . Thus, we use two separate libraries: Dapper as the MicroORM. Slapper.Automapper for mapping. Essentially, we use Dapper to query the database, then use Slapper.Automapper to map the result straight into our POCOs. Advantages Simplicity . Its less than 8 lines of code. I find this a lot easier to understand, debug, and change. Less code . A few lines of code is all Slapper.Automapper needs to handle anything you throw at it, even if we have a complex nested POCO (i.e. POCO contains List<MyClass1> which in turn contains List<MySubClass2> , etc). Speed . Both of these libraries have an extraordinary amount of optimization and caching to make them run almost as fast as hand tuned ADO.NET queries. Separation of concerns . We can change the MicroORM for a different one, and the mapping still works, and vice-versa. Flexibility . Slapper.Automapper handles arbitrarily nested hierarchies, it isn't limited to a couple of levels of nesting. We can easily make rapid changes, and everything will still work. Debugging . We can first see that the SQL query is working properly, then we can check that the SQL query result is properly mapped back to the target POCO Entities. Ease of development in SQL . I find that creating flattened queries with inner joins to return flat results is much easier than creating multiple select statements, with stitching on the client side. Optimized queries in SQL . In a highly normalized database, creating a flat query allows the SQL engine to apply advanced optimizations to the whole which would not normally be possible if many small individual queries were constructed and run. Trust . Dapper is the back end for StackOverflow, and, well, Randy Burden is a bit of a superstar. Need I say any more? Speed of development. I was able to do some extraordinarily complex queries, with many levels of nesting, and the dev time was quite low. Fewer bugs. I wrote it once, it just worked, and this technique is now helping to power a FTSE company. There was so little code that there was no unexpected behavior. Disadvantages Scaling beyond 1,000,000 rows returned. Works well when returning < 100,000 rows. However, if we are bringing back >1,000,000 rows, in order to reduce the traffic between us and SQL server, we should not flatten it out using inner join (which brings back duplicates), we should instead use multiple select statements and stitch everything back together on the client side (see the other answers on this page). This technique is query oriented . I haven't used this technique to write to the database, but I'm sure that Dapper is more than capable of doing this with some more extra work, as StackOverflow itself uses Dapper as its Data Access Layer (DAL). Performance Testing In my tests, Slapper.Automapper added a small overhead to the results returned by Dapper, which meant that it was still 10x faster than Entity Framework, and the combination is still pretty darn close to the theoretical maximum speed SQL + C# is capable of . In most practical cases, most of the overhead would be in a less-than-optimum SQL query, and not with some mapping of the results on the C# side. Performance Testing Results Total number of iterations: 1000 Dapper by itself : 1.889 milliseconds per query, using 3 lines of code to return the dynamic . Dapper + Slapper.Automapper : 2.463 milliseconds per query, using an additional 3 lines of code for the query + mapping from dynamic to POCO Entities . Worked Example In this example, we have list of Contacts , and each Contact can have one or more phone numbers . POCO Entities public class TestContact{ public int ContactID { get; set; } public string ContactName { get; set; } public List<TestPhone> TestPhones { get; set; }}public class TestPhone{ public int PhoneId { get; set; } public int ContactID { get; set; } // foreign key public string Number { get; set; }} SQL Table TestContact SQL Table TestPhone Note that this table has a foreign key ContactID which refers to the TestContact table (this corresponds to the List<TestPhone> in the POCO above). SQL Which Produces Flat Result In our SQL query, we use as many JOIN statements as we need to get all of the data we need, in a flat, denormalized form . Yes, this might produce duplicates in the output, but these duplicates will be eliminated automatically when we use Slapper.Automapper to automatically map the result of this query straight into our POCO object map. USE [MyDatabase]; SELECT tc.[ContactID] as ContactID ,tc.[ContactName] as ContactName ,tp.[PhoneId] AS TestPhones_PhoneId ,tp.[ContactId] AS TestPhones_ContactId ,tp.[Number] AS TestPhones_Number FROM TestContact tc INNER JOIN TestPhone tp ON tc.ContactId = tp.ContactId C# code const string sql = @"SELECT tc.[ContactID] as ContactID ,tc.[ContactName] as ContactName ,tp.[PhoneId] AS TestPhones_PhoneId ,tp.[ContactId] AS TestPhones_ContactId ,tp.[Number] AS TestPhones_Number FROM TestContact tc INNER JOIN TestPhone tp ON tc.ContactId = tp.ContactId";string connectionString = // -- Insert SQL connection string here.using (var conn = new SqlConnection(connectionString)){ conn.Open(); // Can set default database here with conn.ChangeDatabase(...) { // Step 1: Use Dapper to return the flat result as a Dynamic. dynamic test = conn.Query<dynamic>(sql); // Step 2: Use Slapper.Automapper for mapping to the POCO Entities. // - IMPORTANT: Let Slapper.Automapper know how to do the mapping; // let it know the primary key for each POCO. // - Must also use underscore notation ("_") to name parameters in the SQL query; // see Slapper.Automapper docs. Slapper.AutoMapper.Configuration.AddIdentifiers(typeof(TestContact), new List<string> { "ContactID" }); Slapper.AutoMapper.Configuration.AddIdentifiers(typeof(TestPhone), new List<string> { "PhoneID" }); var testContact = (Slapper.AutoMapper.MapDynamic<TestContact>(test) as IEnumerable<TestContact>).ToList(); foreach (var c in testContact) { foreach (var p in c.TestPhones) { Console.Write("ContactName: {0}: Phone: {1}\n", c.ContactName, p.Number); } } }} Output POCO Entity Hierarchy Looking in Visual Studio, We can see that Slapper.Automapper has properly populated our POCO Entities, i.e. we have a List<TestContact> , and each TestContact has a List<TestPhone> . Notes Both Dapper and Slapper.Automapper cache everything internally for speed. If you run into memory issues (very unlikely), ensure that you occasionally clear the cache for both of them. Ensure that you name the columns coming back, using the underscore ( _ ) notation to give Slapper.Automapper clues on how to map the result into the POCO Entities. Ensure that you give Slapper.Automapper clues on the primary key for each POCO Entity (see the lines Slapper.AutoMapper.Configuration.AddIdentifiers ). You can also use Attributes on the POCO for this. If you skip this step, then it could go wrong (in theory), as Slapper.Automapper would not know how to do the mapping properly. Update 2015-06-14 Successfully applied this technique to a huge production database with over 40 normalized tables. It worked perfectly to map an advanced SQL query with over 16 inner join and left join into the proper POCO hierarchy (with 4 levels of nesting). The queries are blindingly fast, almost as fast as hand coding it in ADO.NET (it was typically 52 milliseconds for the query, and 50 milliseconds for the mapping from the flat result into the POCO hierarchy). This is really nothing revolutionary, but it sure beats Entity Framework for speed and ease of use, especially if all we are doing is running queries. Update 2016-02-19 Code has been running flawlessly in production for 9 months. The latest version of Slapper.Automapper has all of the changes that I applied to fix the issue related to nulls being returned in the SQL query. Update 2017-02-20 Code has been running flawlessly in production for 21 months, and has handled continuous queries from hundreds of users in a FTSE 250 company. Slapper.Automapper is also great for mapping a .csv file straight into a list of POCOs. Read the .csv file into a list of IDictionary, then map it straight into the target list of POCOs. The only trick is that you have to add a propery int Id {get; set} , and make sure it's unique for every row (or else the automapper won't be able to distinguish between the rows). Update 2019-01-29 Minor update to add more code comments. See: https://github.com/SlapperAutoMapper/Slapper.AutoMapper
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9350467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260594/']}
jdg_377519
stackexchange
llm_judgeable_groundtruth_similarity
352907
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: The definition of an adapted process $X$ is that $X_i$ be $(\mathcal{F_i}, \Sigma)$-measuriable where $\mathcal{F.} = (\mathcal{F_i})_{i \in S}$ is a filtration of the sigma algebra $\mathcal{F}$ (probability space) and $\Sigma$ is part of the measurable space $(S, \Sigma)$. (and there are other required ones, but I will skip those parts.) And predictable processes are the ones that $X_t$ is measurable with respect to $F_{t-}$. It seems that adapted left-continuous processes cannot be predictable processes - after all, if they are adapated, $X_t$ must be $F_t$ measurable, while the definition of predictable processes say that $X_t$ must be $F_{t-}$-measurable. Why are these seemingly nonsenses working? Now provide the response and nothing else.
If $X_t$ is $\mathcal{F}_t$-measurable, this does not imply that $X_t$ is not $\mathcal{F}_{t-}$-measurable. Actually, left-continuous adapted processes are predictable: Let $t \geq 0$. The information about the path $[0,t) \ni s \mapsto X(s,\omega)$ already determines the value at time $t$, since $$X(t,\omega) = \lim_{s \uparrow t} X(s,\omega)$$ by the left-continuity of $X$. This means (intuitively) that you can predict $X_t$ by the knowledge of $(X_s)_{s <t}$. Since $X_s$ is $\mathcal{F}_{t-}$-measurable for all $s<t$, this implies the $\mathcal{F}_{t-}$-measurability of $X_t$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/352907', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70194/']}
jdg_377520
stackexchange
llm_judgeable_groundtruth_similarity
5651299
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 keep a large ordered list (millions of elements) in Google App Engine datastore. Fast insertion is required. The simplest way would be adding an indexed property (or column) "order_num" representing the order. For example, a list [A, B, C] would be stored like this: content order_num-------------------- A 1 B 2 C 3 However, this doesn't give you fast insertion. For example, If I want to insert X after A, I have to renumber B and C to "make room" for X, i.e., let B become 3, C becomes 4, and X be 2. This would be a disaster if I have millions of elements. I found a feasible solution called "gap approach" described here . This approach keeps a gap between adjacent elements. Like this: content order_num-------------------- A 1000 B 2000 C 3000 When I want to insert X after A, I can simply add X with its order_num set to (1000 + 2000) / 2 = 1500, no renumbering required. But with these gaps becoming smaller, renumbering may be required. My question is, is there any known strategy on renumbering? And deciding the size of gaps? Thanks! UPDATE Here's more detail. Say I have a list of elements in database, and every element has an integer property named my_num. The value of my_num is an arbitrary positive integer. Suppose I have a list [A, B, C, D], and their my_num are element my_num --------------------- A 5 B 2 C 10 D 7 Now, let's define an accum() operator: accum(n) = element[0].my_num + element[1].my_num + ... + element[n-1].my_num So the accum values for each element are element my_num accum ---------------------------- A 5 5 B 2 7 C 10 17 D 7 24 But accum values probably should NOT be stored in database because the list is constantly updated. It's better to keep insertion fast. I want to design a query which input is an integer x: query(x) = element[i] if accum(i-1) < x <= accum(i) For example, query(11) is C and query(3) is A. Is it possible to design a datastore schema to make this query fast? Or the only way is accumulate it one by one at query time which I'm planning to do? Now provide the response and nothing else.
alternatively, could you use decimals, or a string? content order-------------------- A 'a' B 'b' C 'c' Then to insert D between a and b, give it the value 'aa' An algorithm for generating the strings is best shown for a binary string: if you want to insert something between "1011" and "1100", do the following: Avalue = 1+0*(1/2)+1*(1/4)+1*(1/8) Bvalue = 1+1*(1/2)+0*(1/4)+0*(1/8) average, new value = 1+0*(1/2)+1*(1/4)+1*(1/8)+1*(1/16) new string = "10111" content order-------------------- A '1011' new! '10111' B '1100' C '1101' since you always average 2 values, the average will always have a finite binary development, and a finite string. It effectively defines a binary tree. As you know binary trees don't always turn out well balanced, in other words, some strings will be much longer than others after enough insertions. To keep them short, you could use any even number base - it has to be even because then the development of any average of two values is finite. But whatever you do, strings will probably become long, and you'll have to do some housekeeping at some point, cleaning up the values so that the string space is used efficiently. What this algorithm gives you is the certainty that between cleanups, the system will keep ticking along.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5651299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/653273/']}
jdg_377521
stackexchange
llm_judgeable_groundtruth_similarity
594838
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 know how to set the initial window size in gVim, but how do I get it to automatically restore the window dimensions from last session? Is this even possible? Now provide the response and nothing else.
Edit: Corrected my answer. The mentioned winsize sessionoption only refers to the vim internal window layout, not the external dimensions. If you use :mksession and load the session on vim startup with gvim -S Session.vim you can include the window position and size into the session by including winpos and resize in the sessionoptions, see :help 'sessionoptions With autocommands you could even automate the saving and restoring of the session on Vim entry and exit.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/594838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1944/']}
jdg_377522
stackexchange
llm_judgeable_groundtruth_similarity
12155603
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 using a cursor with a lower bound range query. I can't find a way to limit the number of objects returned, similar to a "LIMIT n" clause in a databse. var keyRange = IDBKeyRange.lowerBound(''); Does it not exist ? Now provide the response and nothing else.
As you're iterating through the results, you can stop at any time. Something like this should work: var results = [];var limit = 20;var i = 0;objectStore.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor && i < limit) { results.push(cursor.value); i += 1; cursor.continue(); } else { // Do something with results, which has at most 20 entries console.log(results); }}; Also, in the special case where you are selecting based on a key that is made up of sequential numbers, you could use a keyRange to explicitly return only a certain range. But that's generally not the case.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12155603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1663292/']}
jdg_377523
stackexchange
llm_judgeable_groundtruth_similarity
14435632
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 studying Image Processing on the famous Gonzales "Digital Image Processing" and talking about image restoration a lot of examples are done with computer-generated noise (gaussian, salt and pepper, etc). In MATLAB there are some built-in functions to do it. What about OpenCV? Now provide the response and nothing else.
As far as I know there are no convenient built in functions like in Matlab. But with only a few lines of code you can create those images yourself. For example additive gaussian noise: Mat gaussian_noise = img.clone();randn(gaussian_noise,128,30); Salt and pepper noise: Mat saltpepper_noise = Mat::zeros(img.rows, img.cols,CV_8U);randu(saltpepper_noise,0,255);Mat black = saltpepper_noise < 30;Mat white = saltpepper_noise > 225;Mat saltpepper_img = img.clone();saltpepper_img.setTo(255,white);saltpepper_img.setTo(0,black);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14435632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/433685/']}
jdg_377524
stackexchange
llm_judgeable_groundtruth_similarity
1223016
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: Why does something like $a^2 = 2b^2$, show that $a^2$ and thus $a$ are even numbers? My feeling is that it's because one can divide $a^2$ by two and hence it must be even. Can anybody give me a clear explanation as to why $a$ is even (in this case) more specifically? Is there mathematical proof? Now provide the response and nothing else.
The key observation is that odd $\times$ odd $=$ odd. Now, $a^2=2b^2$ implies that $a^2$ is even. If $a$ were odd, then $a^2=a\cdot a$ would be odd. Hence $a$ is even.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1223016', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/192943/']}
jdg_377525
stackexchange
llm_judgeable_groundtruth_similarity
17947736
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 got a runtime error saying "Must declare the table variable "@parmTableName" . Meaning having table name as sql parameter in the sql-statement is not allowed. Is there a better option or suggestion than allowing sql injection attack? I don't want to do this C# script for sql statement " DELETE FROM " + tableName + " " ; using(var dbCommand = dbConnection.CreateCommand()){ sqlAsk = ""; sqlAsk += " DELETE FROM @parmTableName "; sqlAsk += " WHERE ImportedFlag = 'F' "; dbCommand.Parameters.Clear(); dbCommand.Parameters.AddWithValue("@parmTableName", tableName); dbConnection.Open(); rowAffected = dbCommand.ExecuteNonQuery();} Now provide the response and nothing else.
Go for a white list. There can only be a fixed set of possible correct values for the table name anyway - at least, so I'd hope. If you don't have a white list of table names, you could start with a whitelist of characters - if you restrict it to A-Z, a-z and 0-9 (no punctuation at all) then that should remove a lot of the concern. (Of course that means you don't support tables with odd names... we don't really know your requirements here.) But no, you can't use parameters for either table or column names - only values. That's typically the case in databases; I don't remember seeing one which did support parameters for that. (I dare say there are some, of course...)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17947736', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1633604/']}
jdg_377526
stackexchange
llm_judgeable_groundtruth_similarity
49276914
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 create 7 dummy variables -one for each day, using dplyr So far, I have managed to do it using the sjmisc package and the to_dummy function, but I do it in 2 steps -1.Create a df of dummies, 2) append to the original df #Sample dataframemydfdata.frame(x=rep(letters[1:9]), day=c("Mon","Tues","Wed","Thurs","Fri","Sat","Sun","Fri","Mon"))#1.Create the 7 dummy variables separatelydaysdummy<-sjmisc::to_dummy(mydf$day,suffix="label")#2. append to dataframemydf<-bind_cols(mydf,daysdummy)> mydf x day day_Fri day_Mon day_Sat day_Sun day_Thurs day_Tues day_Wed1 a Mon 0 1 0 0 0 0 02 b Tues 0 0 0 0 0 1 03 c Wed 0 0 0 0 0 0 14 d Thurs 0 0 0 0 1 0 05 e Fri 1 0 0 0 0 0 06 f Sat 0 0 1 0 0 0 07 g Sun 0 0 0 1 0 0 08 h Fri 1 0 0 0 0 0 09 i Mon 0 1 0 0 0 0 0 My question is whether I can do it in one single workflow using dplyr and add the to_dummy into the pipe-workflow- perhaps using mutate ? * to_dummy documentation Now provide the response and nothing else.
If you want to do this with the pipe, you can do something like: library(dplyr)library(sjmisc)mydf %>% to_dummy(day, suffix = "label") %>% bind_cols(mydf) %>% select(x, day, everything()) Returns: # A tibble: 9 x 9 x day day_Fri day_Mon day_Sat day_Sun day_Thurs day_Tues day_Wed <fct> <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>1 a Mon 0. 1. 0. 0. 0. 0. 0.2 b Tues 0. 0. 0. 0. 0. 1. 0.3 c Wed 0. 0. 0. 0. 0. 0. 1.4 d Thurs 0. 0. 0. 0. 1. 0. 0.5 e Fri 1. 0. 0. 0. 0. 0. 0.6 f Sat 0. 0. 1. 0. 0. 0. 0.7 g Sun 0. 0. 0. 1. 0. 0. 0.8 h Fri 1. 0. 0. 0. 0. 0. 0.9 i Mon 0. 1. 0. 0. 0. 0. 0. With dplyr and tidyr we could do: library(dplyr)library(tidyr)mydf %>% mutate(var = 1) %>% spread(day, var, fill = 0, sep = "_") %>% left_join(mydf) %>% select(x, day, everything()) And with base R we could do something like: as.data.frame.matrix(table(rep(mydf$x, lengths(mydf$day)), unlist(mydf$day))) Returns: Fri Mon Sat Sun Thurs Tues Weda 0 1 0 0 0 0 0b 0 0 0 0 0 1 0c 0 0 0 0 0 0 1d 0 0 0 0 1 0 0e 1 0 0 0 0 0 0f 0 0 1 0 0 0 0g 0 0 0 1 0 0 0h 1 0 0 0 0 0 0i 0 1 0 0 0 0 0
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49276914', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8689932/']}
jdg_377527
stackexchange
llm_judgeable_groundtruth_similarity
47325
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: On my raspberry pi I want to back up my current sd card using dd. I have a 64 gigabyte card for raspbian wheezy but I made sure not to Expand the Filesystem (under raspi-config) so the used data in the card remains at 4 gigabytes, plus the boot partition. When I try to use the command: sudo dd bs=1m if=/dev/sdb of=~/Downloads/pineapple.img dd makes pineapple.img 64 gigabytes rather than 4 gigs because dd is backing up the unallocated data. I was wondering if there is a way to copy multiple partitions into one .img file. For example: sudo dd bs=1m if=/dev/sdb1 /dev/sdb2 of=~/Downloads/pineapple.img To sum it up, I want to copy over the two used partitions (/dev/sdv1 and /dev/sdb2) to one .img file. Now provide the response and nothing else.
There is no magic in the image file. It's simply a bit-for-bit copy of a chunk of the sd card. What you want to do is figure out exactly where the second partition ends, and copy from the device file representing the whole card (in this case: /dev/sdb . Now, look at how your partitions are laid out: in your case, it's partition 1 followed by partition 2. Right click on sdb2, and select information . Note the last sector . It will be some number around 8 million (a "sector" is 512 bytes, you have four gigs, that makes eight million sectors). Let's say the number is 7666777. That's the last useful sector you care about. Since the first sector is sector 0, there will be a total of 7666778 sectors that you want to copy. So do something like: dd if=/dev/sdb of=foo.img bs=512 count=7666778 and wait for a while; sdcards are not very fast. Usually the number of sectors will be a multiple of some power of 2, and you can increase the copying speed a little bit by increasing the block size and decreasing the count, keeping the product constant. To feel a bit more comfortable with how partitions are laid out, use the non-graphical version, parted , and specify units as B (bytes). /ji
{}
{'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/47325', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/43920/']}
jdg_377528
stackexchange
llm_judgeable_groundtruth_similarity
5858247
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 I must control action of 40 buttons, but I don't want to create 40 IBAction, can I use only a IBAction, how? Now provide the response and nothing else.
If you're using interface builder to create the buttons, simply point them at the same IBAction in the relevant class. You can then differentiate between the buttons within the IBAction method either by reading the text from the button... - (IBAction)buttonClicked:(id)sender { NSLog(@"Button pressed: %@", [sender currentTitle]); } ...or by setting the tag property in Xcode and reading it back via [sender tag] . (If you use this approach, start the tags at 1, as 0 is the default and hence of little use.)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5858247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/630412/']}
jdg_377529
stackexchange
llm_judgeable_groundtruth_similarity
61184749
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 wondering how should I reset a reactive in vuejs setup? (i know if change it to the ref and using view.value will solve this problem, but there should be an answer to this for using reactive) setup(props, context){ // states const DataTable = reactive((null as unknown) as DataTable); const PolicyForm = reactive((null as unknown) as PolicyForm); let view = reactive(resetViewState()); let config = reactive( (resetPreRegisterConfig() as unknown) as PreRegisterConfig ); // methods: const fetchProfilelist = ( pagination: Pagination{ page:1, size:15}, sort_label: string = "" ) => { DataTable.fetchTablelist(api_fetchProfilelist, pagination, sort_label); }; const pageRefresh = () => { view = resetViewState(); // config = resetPreRegisterConfig(); fetchProfilelist(); }; return { DataTable, PolicyForm, view, config, fetchProfilelist, pageRefresh } Now provide the response and nothing else.
You can use Object.assign : setup() { const initialState = { name: "", lastName: "", email: "" }; const form = reactive({ ...initialState }); function resetForm() { Object.assign(form, initialState); } function setForm() { Object.assign(form, { name: "John", lastName: "Doe", email: "john@doe.com" }); } return { form, setForm, resetForm }; } See it live on codesandbox credits: taken from here
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/61184749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12666332/']}
jdg_377530
stackexchange
llm_judgeable_groundtruth_similarity
53205161
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 Date object which holds a date (not current date) and I need to somehow specify that this date is UTC and then convert it to "Europe/Paris" which is +1 hours. public static LocalDateTime toLocalDateTime(Date date){ return ZonedDateTime.of(LocalDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC), ZoneId.of("Europe/Paris")).toLocalDateTime();} Given a date of "2018-11-08 15:00:00" this converts the date into "2018-11-08 14:00:00". I need it to convert from UTC to Europe/Paris - not the other way around. Now provide the response and nothing else.
You could use ZonedDateTime.withZoneSameInstant() method to move from UTC to Paris time: Date date = new Date();ZonedDateTime utc = date.toInstant().atZone(ZoneOffset.UTC);ZonedDateTime paris = utc.withZoneSameInstant(ZoneId.of("Europe/Paris"));System.out.println(utc);System.out.println(paris);System.out.println(paris.toLocalDateTime()); which prints: 2018-11-08T10:25:18.223Z2018-11-08T11:25:18.223+01:00[Europe/Paris]2018-11-08T11:25:18.223
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53205161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5417130/']}
jdg_377531
stackexchange
llm_judgeable_groundtruth_similarity
4689844
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: During the first clone of a repository, git first receives the objects (which is obvious enough), and then spends about the same amount of time "resolving deltas". What's actually happening during this phase of the clone? Now provide the response and nothing else.
Git uses delta encoding to store some of the objects in packfiles. However, you don't want to have to play back every single change ever on a given file in order to get the current version, so Git also has occasional snapshots of the file contents stored as well. "Resolving deltas" is the step that deals with making sure all of that stays consistent. Here's a chapter from the "Git Internals" section of the Pro Git book, which is available online, that talks about this.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4689844', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14302/']}
jdg_377532
stackexchange
llm_judgeable_groundtruth_similarity
507450
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 need to print some variables to the screen but I need to preferebly obfuscate the first few characters and I was wondering if there was an echo command in bash that can obfuscate the first characters of a secret value while printing it to the terminal: echo 'secretvalue'********lue Now provide the response and nothing else.
The other answers mask a fixed amount of characters from the start, with the plaintext suffix varying in length. An alternative would be to leave a fixed amount of characters in plaintext, and to vary the length of the masked part. I don't know which one is more useful, but here's the other choice: #!/bin/bashmask() { local n=3 # number of chars to leave local a="${1:0:${#1}-n}" # take all but the last n chars local b="${1:${#1}-n}" # take the final n chars printf "%s%s\n" "${a//?/*}" "$b" # substitute a with asterisks}mask abcdemask abcdefghijkl This prints **cde and *********jkl . If you like, you could also modify n for short strings to make sure a majority of the string gets masked. E.g. this would make sure at least three characters are masked even for short strings. (so abcde -> ***de , and abc -> *** ): mask() { local n=3 [[ ${#1} -le 5 ]] && n=$(( ${#1} - 3 )) local a="${1:0:${#1}-n}" local b="${1:${#1}-n}" printf "%s%s\n" "${a//?/*}" "$b"}
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/507450', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/341050/']}
jdg_377533
stackexchange
llm_judgeable_groundtruth_similarity
45500264
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 migrate my Http requests to HttpClient requests.I was able to migrate my post queries but I'm facing a problem while migrating get queries. When I do so, my backend doesn't receive any parameters respectively, it tells me that the parameters are not provided and empty. Did I do something wrong? import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';constructor(private httpClient: HttpClient) {}findItems() { let params: HttpParams = new HttpParams(); params.set('something', 'hello'); this.httpClient.get<any[]>('http://localhost:3000/apath/', {params}) .subscribe((results: any[]) => { console.log(results); }, (errorResponse: any) => { console.error(errorResponse); });} Any idea? Now provide the response and nothing else.
Currently HttpParams is immutable, you should set params as below: // for set methodlet params: HttpParams = new HttpParams().set('something', 'hello');// for append methodlet params: HttpParams = new HttpParams().append('something', 'hello'); HttpParams 's set and append method will overwrite the original params instance with the newly updated one by set and append , and finally return the new instance. So we can do it in multiple lines as below: let params: HttpParams = new HttpParams();params = params.set('something', 'hello'); params = params.append('something2', 'hello2'); Plunker demo Important: Since Angular v5.0.0, you can use fromObject from HttpParamOptions to add multiple parameters at the same time. const param = new HttpParams({fromObject: {aaa: '1', bbb: '222'}}); Also you can set object parameters to HttpClient methods directly const obj = {aaa: '1', bbb: '222'};this.http.get('test', { params: obj}).subscribe(); Refer demo , for the second way, please check browser's network to confirm the parameters has been added successfully.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45500264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5404186/']}
jdg_377534
stackexchange
llm_judgeable_groundtruth_similarity
39773
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 have been asked to prove that the Galois group of $x^5+x^4-4x^3-3x^2+3x+1$ (presumably over $\mathbb{Q}$ is cyclic of order $5$. Unfortunately, I have no idea where to start. The hint says to show that this is the minimal polynomial of $\zeta_{11} + \zeta_{11}^{-1}$. Which I guess I could do by plugging it into the polynomial, but there is most likely a better way to do it. Anyway, even if I could establish that, I wouldn't know any of the other roots so it's not like I could find any of the automorphisms. I guess it would kind of help because it would show that the Galois group had order divisible by 5. Except a lot of them are. I think I am completely missing the point of the hint. The section was about how you could reduce polynomials mod $p$, and the Galois group would have to contain a permutation with cycle type $(n_1 n_2 ... n_k)$, where $n_1$, ..., $n_k$ are the degrees of the irreducible factors (mod $p$). But this is not very relevant because since the group is cyclic of prime order, all the permutations would be 5-cycles. And lots of other subgroups of $S_5$ have 5-cycles too. So at this point I am kind of stuck. Can you give me a hint as to how to solve the problem? Thanks! P.S. We are allowed to use the computer program SAGE for this assignment, but not the command that calculates the Galois group. Also, I tried to use SAGE to calculate the roots but it gave me numerical answers. Now provide the response and nothing else.
Suppose you have shown that the minimal polynomial of $\zeta_{11}+\zeta_{11}^{-1}$ is the given polynomial. What does that mean $[\mathbb{Q}(\zeta_{11}+\zeta_{11}^{-1}):\mathbb{Q}]$ is? For any $n$, we know that $\mathbb{Q}(\zeta_n)/\mathbb{Q}$ is Galois, and $\text{Gal}(\mathbb{Q}(\zeta_n)/\mathbb{Q})\cong(\mathbb{Z}/n\mathbb{Z})^\times$ (or, if this has not come up in class, you should prove it separately to make your argument complete). In particular, $$\text{Gal}(\mathbb{Q}(\zeta_{11})/\mathbb{Q})\cong(\mathbb{Z}/11\mathbb{Z})^\times\cong \mathbb{Z}/10\mathbb{Z},$$ the cyclic group of order 10. Note that $\mathbb{Q}(\zeta_{11})\supset\mathbb{Q}(\zeta_{11}+\zeta_{11}^{-1})$. The cyclic group of order $n$ has a single subgroup of size $d$, for each $d\mid n$. Therefore it also has a single quotient group of size $d$, for each $d\mid n$. We know that $[\mathbb{Q}(\zeta_{11}+\zeta_{11}^{-1}):\mathbb{Q}]=|\text{Gal}(\mathbb{Q}(\zeta_{11}+\zeta_{11}^{-1})/\mathbb{Q})|$. What does that mean $\text{Gal}(\mathbb{Q}(\zeta_{11}+\zeta_{11}^{-1})/\mathbb{Q})\cong\text{Gal}(\mathbb{Q}(\zeta_{11})/\mathbb{Q})\bigg/\text{Gal}(\mathbb{Q}(\zeta_{11})/\mathbb{Q}(\zeta_{11}+\zeta_{11}^{-1}))$ is?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/39773', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9054/']}
jdg_377535
stackexchange
llm_judgeable_groundtruth_similarity
4019856
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 pulling a sum from a DB which is a decimal value.I'm trying to use that value in a JSON result json.dumps( { 'sum': amount } ) #where amount is my Decimal Django can't serialize the Decimal .I can convert it to a string, but I'd like a numeric type within the JSON.If I try and convert it to a float I end up with more than 2 decimal places. What needs to happen, if possible, to get a result like the following? { 'sum': 500.50 } Now provide the response and nothing else.
What you can do is extend the JSONDecoder class to provide a custom serializer for the Decimal type, similar to the example in this document: http://docs.python.org/py3k/library/json.html >>> import json>>> class DecimalEncoder(json.JSONEncoder):... def default(self, obj):... if isinstance(obj, Decimal):... return "%.2f" % obj... return json.JSONEncoder.default(self, obj)... That's a nonworking example of how to do it, hopefully a good starting point for you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4019856', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191347/']}
jdg_377536
stackexchange
llm_judgeable_groundtruth_similarity
7053652
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 tried writing this code: def smaller(x, y): if x > y: print(y) else: print(x) print(smaller(2, 3)) I got this result: >>>2None Where did the None come from? What does it mean? See also The accepted answer explains the importance of return ing a value from the function, rather than print ing it. For more information, see What is the purpose of the return statement? How is it different from printing? . To understand the None result itself, see What is a 'NoneType' object? . If you are print ing inside the function in order to see multiple values, it may be better to instead collect those values so that they can be printed by the calling code. For details, see How can I use `return` to get back multiple values from a loop? Can I put them in a list? . Now provide the response and nothing else.
It's the return value of the function, which you print out. If there is no return statement (or just a return without an argument ), an implicit return None is added to the end of a function. You probably want to return the values in the function instead of printing them: def jiskya(x, y): if x > y: return y else: return xprint(jiskya(2, 3))
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7053652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/890912/']}
jdg_377537
stackexchange
llm_judgeable_groundtruth_similarity
359
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: 1 John 5:16 (NIV) Emphasis Added If you see any brother or sister commit a sin that does not lead to death, you should pray and God will give them life. I refer to those whose sin does not lead to death. There is a sin that leads to death. I am not saying that you should pray about that. In that passage, it says that "there is a sin that leads to death." What sin is this text referring to? Is it referring to a specific sin? Also, is it "a sin" as in "a specific sin that leads to death" or is this a more generic concept of "sin" as in "there is a type/category of sin that leads to death"? Now provide the response and nothing else.
I agree with much of what Jon Ericson has said but I think we can get even closer to the meaning of the "sin that leads to death" from the context of 1st John. John is dealing with a division that has occurred in his church (1 John 2:18-19). Some have left, denying that Jesus' had a physical body (1 John 4:1-3). The young men of the congregation (2:12-14) are zealous for righteousness and want no part with the world. They possibly see the older men of the congregation (i.e. the fathers, 2:12-14) as capitulating with the world. John emphatically agrees with the young men; no true Christian ever sins. "No one who continues to sin has either seen him or known him. Dear children, do not let anyone lead you astray. He who does what is right is righteous, just as he is righteous. He who does what is sinful is of the devil, because the devil has been sinning from the beginning. The reason the Son of God appeared was to destroy the devil's work. No one who is born of God will continue to sin, because God's seed remains in him; he cannot go on sinning, because he has been born of God. This is how we know who the children of the devil are: Anyone who does not do what is right is not a child of God..." But then John turns his aim at those who claim to be without sin. "...nor is anyone who does not love their brother and sister." By love, John isn't talking about a feeling or an emotion. He's talking about a concrete action with a material effect. 16 This is how we know what love is: Jesus Christ laid down his life for us. And we ought to lay down our lives for our brothers and sisters. 17 If anyone has material possessions and sees a brother or sister in need but has no pity on them, how can the love of God be in that person? 18 Dear children, let us not love with words or speech but with actions and in truth. John stresses the fact that God loved tangibly in Jesus. The life that God gave in Jesus was able to be seen, handled and touched (1 John 1:1-2). The Anitchrists have denied that Jesus is the Christ (1 John 2:22, 5:1) which is to say they have denied that he is the Son of God (1 John 4:15, 5:5) which is to say they have denied that he came tangibly in the flesh (1 John 4:5). They believed he was water but not blood (1 John 5:6). And thus they practice what they believe, claiming to be spiritual without having to exhibit tangible, material love. And it is against this heretical belief and practice that John lashes out. John tells his readers the reason why he wrote in 1 John 1:7-11. 7 Dear friends, I am not writing you a new command but an old one, which you have had since the beginning. This old command is the message you have heard. 8 Yet I am writing you a new command; its truth is seen in him and in you, because the darkness is passing and the true light is already shining. 9 Anyone who claims to be in the light but hates a brother or sister is still in the darkness. 10 Anyone who loves their brother and sister lives in the light, and there is nothing in them to make them stumble. 11 But anyone who hates a brother or sister is in the darkness and walks around in the darkness. They do not know where they are going, because the darkness has blinded them. The command they have had since the beginning is that they "love one another" (1 John 3:11). The new command is that anyone who does not tangibly love the children of God is still in darkness. Their sins are not forgiven. John states in 1 John 3:12-15, Do not be like Cain, who belonged to the evil one and murdered his brother. And why did he murder him? Because his own actions were evil and his brother’s were righteous. 13 Do not be surprised, my brothers and sisters, if the world hates you. 14 We know that we have passed from death to life, because we love each other. Anyone who does not love remains in death. 15 Anyone who hates a brother or sister is a murderer, and you know that no murderer has eternal life residing in him. The "sin that leads to death" is thus revealed to be a lack of tangible love for one's brothers and sisters. When we tangibly love those whom God loves the sin in our lives is muted. John says, 18 Dear children, let us not love with words or speech but with actions and in truth. 19 This is how we know that we belong to the truth and how we set our hearts at rest in his presence: 20 If our hearts condemn us, we know that God is greater than our hearts, and he knows everything. 21 Dear friends, if our hearts do not condemn us, we have confidence before God 22 and receive from him anything we ask, because we keep his commands and do what pleases him. But when we lack tangible love it proves that we have "not passed from death to life." This is the sin that leads to death.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/359', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/15/']}
jdg_377538
stackexchange
llm_judgeable_groundtruth_similarity
107782
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: Which ionic compound has highest solubility in water? I can find CsBr having highest solubility with 1230 g/L at 25 °C. Note: compounds like ethanol are soluble to any extent in water, but they are covalent, not ionic. Now provide the response and nothing else.
Caesium salts are unapologetically ionic, and they typically have quite high mass solubilities in many solvents, including water. Assuming organic ions are allowed, caesium acetate ( $\ce{H3CCO2^-Cs+}$ ) in particular has a remarkably high solubility of 9451 g/kg water at −2.5 °C, increasing to 13 455 g/L water at 88.5 °C. Caesium formate ( $\ce{HCO2^-Cs+}$ ) is also quite soluble, with a solubility of 4880 g/kg water at 20 °C, resulting in 2.56 L of solution with a density of 2.297 g/mL ( reference, .docx file ). However, its solubility increases much faster with increasing temperature ( J. Chem. Soc., Trans. , 1922 , 121 , 1837-1843 ). At 100 °C, it reaches an outstanding value of 20 071 g/kg water ! That's 11.6 molal, or roughly 20-25 mol/L assuming the density doesn't change too much. This saturated solution is 67.7% cesium formate by number of moles, which means more than two caesium ions and two formate ions per molecule of water. I believe I have read somewhere that caesium formate is the record holder for highest mass solubility in water (evidently only at high temperatures). If this is not true, then I can scarcely believe it will be topped by much. Tangentially, Ivan mentions Clerici's solution , which is actually a mixture of thallium(I) formate and thallium(I) malonate. The mixture doesn't count (though the individual components are quite soluble themselves), but it interesting to analyse. Apparently 300 g of each compound will dissolve in 40 g of water without saturating it room temperature ( ref ), giving a lower bound to their combined solubility of 15 000 g/kg water. This value rises with heating, and is the only way I can see to beat the mass solubility of caesium formate. For further entertainment, I recommend these two solubility tables with a large number of entries ( 1 , 2 ). The second one can be ordered by solubility at different temperatures. It's interesting to see the variety of cations and anions which can be combined to display extreme mass solubility. Edit : If room-temperature ionic liquids are allowed, then it is quite likely some of them are miscible with water in any proportion, which is effectively "infinite solubility in water". Something as simple as ethylammonium nitrate ( $\ce{C2H5NH3+NO3-}$ ) may suffice.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/107782', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/68148/']}
jdg_377539
stackexchange
llm_judgeable_groundtruth_similarity
9545778
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 list of maps ({"child.search" {:roles #{"ROLE_ADM_UNSUBSCRIBE_SUBSCRIPTION" "ROLE_ADM_SEARCH_SUBSCRIPTION" "ROLE_ADM_VIEW_SUBSCRIPTION"}}, "child.cc.search" {:roles #{"ROLE_ADM_CC_SEARCH_SUBSCRIPTION" "ROLE_ADM_CC_VIEW_SUBSCRIPTION"}}} {"child.abusereport" {:roles #{"ROLE_ADM_ABUSE_RPT"}}, "child.manualfiltering" {:roles #{"ROLE_ADM_MANUAL_FILTERING_RPT"}}} {"child.assigned.advertisement" {:roles #{"ROLE_ADM_CREATE_ADVERTISING"}}, "child.manage.advertisement" {:roles #{"ROLE_ADM_LIST_ADVERTISING"}}}) I need to have a single map like following. {"child.search" {:roles #{"ROLE_ADM_UNSUBSCRIBE_SUBSCRIPTION" "ROLE_ADM_SEARCH_SUBSCRIPTION" "ROLE_ADM_VIEW_SUBSCRIPTION"}}"child.cc.search" {:roles #{"ROLE_ADM_CC_SEARCH_SUBSCRIPTION" "ROLE_ADM_CC_VIEW_SUBSCRIPTION"}}"child.abusereport" {:roles #{"ROLE_ADM_ABUSE_RPT"}}"child.manualfiltering" {:roles #{"ROLE_ADM_MANUAL_FILTERING_RPT"}}"child.assigned.advertisement" {:roles #{"ROLE_ADM_CREATE_ADVERTISING"}}"child.manage.advertisement" {:roles #{"ROLE_ADM_LIST_ADVERTISING"}}} How can I do it? Now provide the response and nothing else.
You can use the " into " function, and supply an empty map {} as the first argument: (into {} map-list) Here's the output from my REPL session; I copied your code into two vars 'map-list' and 'single-map' (Clojure 1.3.0): (def map-list '({"child.search" {:roles #{"ROLE_ADM_UNSUBSCRIBE_SUBSCRIPTION" "ROLE_ADM_SEARCH_SUBSCRIPTION" "ROLE_ADM_VIEW_SUBSCRIPTION"}}, "child.cc.search" {:roles #{"ROLE_ADM_CC_SEARCH_SUBSCRIPTION" "ROLE_ADM_CC_VIEW_SUBSCRIPTION"}}} {"child.abusereport" {:roles #{"ROLE_ADM_ABUSE_RPT"}}, "child.manualfiltering" {:roles #{"ROLE_ADM_MANUAL_FILTERING_RPT"}}} {"child.assigned.advertisement" {:roles #{"ROLE_ADM_CREATE_ADVERTISING"}}, "child.manage.advertisement" {:roles #{"ROLE_ADM_LIST_ADVERTISING"}}}))#'user/map-listuser=>(def single-map {"child.search" {:roles #{"ROLE_ADM_UNSUBSCRIBE_SUBSCRIPTION" "ROLE_ADM_SEARCH_SUBSCRIPTION" "ROLE_ADM_VIEW_SUBSCRIPTION"}} "child.cc.search" {:roles #{"ROLE_ADM_CC_SEARCH_SUBSCRIPTION" "ROLE_ADM_CC_VIEW_SUBSCRIPTION"}} "child.abusereport" {:roles #{"ROLE_ADM_ABUSE_RPT"}} "child.manualfiltering" {:roles #{"ROLE_ADM_MANUAL_FILTERING_RPT"}} "child.assigned.advertisement" {:roles #{"ROLE_ADM_CREATE_ADVERTISING"}} "child.manage.advertisement" {:roles #{"ROLE_ADM_LIST_ADVERTISING"}}})#'user/single-mapuser=>;; Check to see if we have the desired result(= (into {} map-list) single-map)true
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9545778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_377540