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
492013
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: Updating repositories with apt update fails since the public keys of several signatures are not available. $ sudo apt updateGet:1 http://security.debian.org/debian-security stretch/updates InRelease [94.3 kB]Ign:2 http://deb.debian.org/debian stretch InRelease Hit:3 http://deb.debian.org/debian stretch Release Ign:4 http://ftp.fr.debian.org/debian stretch InRelease Ign:6 http://ftp.fr.debian.org/debian jessie InRelease Hit:7 https://fr.archive.ubuntu.com/ubuntu bionic InRelease Hit:8 http://ftp.fr.debian.org/debian stretch Release Get:5 http://ftp.fr.debian.org/debian stretch-updates InRelease [91.0 kB] Hit:9 https://riot.im/packages/debian stretch InRelease Hit:10 http://ftp.fr.debian.org/debian jessie Release Err:1 http://security.debian.org/debian-security stretch/updates InRelease The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 9D6D8F6BC857C906 NO_PUBKEY 8B48AD6246925553Get:11 https://mega.nz/linux/MEGAsync/Debian_9.0 ./ InRelease [1,480 B] Ign:12 http://download.opensuse.org/repositories/home:/strycore/Debian_9.0 ./ InRelease Hit:13 http://download.opensuse.org/repositories/home:/strycore/Debian_9.0 ./ Release Err:14 http://deb.debian.org/debian stretch Release.gpg The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 8B48AD6246925553 NO_PUBKEY 7638D0442B90D010 NO_PUBKEY EF0F382A1A7B6500Get:15 https://content.runescape.com/downloads/ubuntu trusty InRelease [2,236 B]Err:16 http://ftp.fr.debian.org/debian stretch Release.gpg The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 8B48AD6246925553 NO_PUBKEY 7638D0442B90D010 NO_PUBKEY EF0F382A1A7B6500Err:9 https://riot.im/packages/debian stretch InRelease The following signatures couldn't be verified because the public key is not available: NO_PUBKEY E019645248E8F4A1Err:5 http://ftp.fr.debian.org/debian stretch-updates InRelease The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 8B48AD6246925553 NO_PUBKEY 7638D0442B90D010Err:17 http://ftp.fr.debian.org/debian jessie Release.gpg The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 8B48AD6246925553 NO_PUBKEY 7638D0442B90D010 NO_PUBKEY CBF8D6FD518E17E1Err:11 https://mega.nz/linux/MEGAsync/Debian_9.0 ./ InRelease The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 4B4E7A9523ACD201Err:18 http://download.opensuse.org/repositories/home:/strycore/Debian_9.0 ./ Release.gpg The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 2F7F0DA5FD5B64B9Err:15 https://content.runescape.com/downloads/ubuntu trusty InRelease The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 7373B12CE03BEB4BReading package lists... Done W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://security.debian.org/debian-security stretch/updates InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 9D6D8F6BC857C906 NO_PUBKEY 8B48AD6246925553W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://deb.debian.org/debian stretch Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 8B48AD6246925553 NO_PUBKEY 7638D0442B90D010 NO_PUBKEY EF0F382A1A7B6500W: Skipping acquire of configured file 'xenial/binary-amd64/Packages' as repository 'https://fr.archive.ubuntu.com/ubuntu bionic InRelease' doesn't have the component 'xenial' (component misspelt in sources.list?)W: Skipping acquire of configured file 'xenial/binary-i386/Packages' as repository 'https://fr.archive.ubuntu.com/ubuntu bionic InRelease' doesn't have the component 'xenial' (component misspelt in sources.list?)W: Skipping acquire of configured file 'xenial/i18n/Translation-en_US' as repository 'https://fr.archive.ubuntu.com/ubuntu bionic InRelease' doesn't have the component 'xenial' (component misspelt in sources.list?)W: Skipping acquire of configured file 'xenial/i18n/Translation-en' as repository 'https://fr.archive.ubuntu.com/ubuntu bionic InRelease' doesn't have the component 'xenial' (component misspelt in sources.list?)W: Skipping acquire of configured file 'xenial/dep11/Components-amd64.yml' as repository 'https://fr.archive.ubuntu.com/ubuntu bionic InRelease' doesn't have the component 'xenial' (component misspelt in sources.list?)W: Skipping acquire of configured file 'xenial/dep11/icons-64x64.tar' as repository 'https://fr.archive.ubuntu.com/ubuntu bionic InRelease' doesn't have the component 'xenial' (component misspelt in sources.list?)W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://ftp.fr.debian.org/debian stretch Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 8B48AD6246925553 NO_PUBKEY 7638D0442B90D010 NO_PUBKEY EF0F382A1A7B6500W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: https://riot.im/packages/debian stretch InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY E019645248E8F4A1W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://ftp.fr.debian.org/debian stretch-updates InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 8B48AD6246925553 NO_PUBKEY 7638D0442B90D010W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://ftp.fr.debian.org/debian jessie Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 8B48AD6246925553 NO_PUBKEY 7638D0442B90D010 NO_PUBKEY CBF8D6FD518E17E1W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: https://mega.nz/linux/MEGAsync/Debian_9.0 ./ InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 4B4E7A9523ACD201W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://download.opensuse.org/repositories/home:/strycore/Debian_9.0 ./ Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 2F7F0DA5FD5B64B9W: GPG error: https://content.runescape.com/downloads/ubuntu trusty InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 7373B12CE03BEB4BE: The repository 'https://content.runescape.com/downloads/ubuntu trusty InRelease' is not signed.N: Updating from such a repository can't be done securely, and is therefore disabled by default.N: See apt-secure(8) manpage for repository creation and user configuration details. I tried to update the keys without keyring.debian.org $ gpg --recv-keys 9D6D8F6BC857C906gpg: key 9D6D8F6BC857C906: 12 signatures not checked due to missing keysgpg: key 9D6D8F6BC857C906: "Debian Security Archive Automatic Signing Key (8/jessie) <[email protected]>" not changedgpg: Total number processed: 1gpg: unchanged: 1 and with $ gpg --keyserver keyring.debian.org --recv-keys 9D6D8F6BC857C906gpg: no valid OpenPGP data found.gpg: Total number processed: 0 ca-certificates is up-to-date with version 20180409 as well as debian-keyring with version 2018.03.24 . I have also deleted /etc/apt/trusted.gpg as per https://serverfault.com/q/851724 . @Stephen Kitt's request: $ ls -la /etc/apt/trusted.gpg.dtotal 28drwxr-xr-x 2 root root 4096 Jan 2 10:42 .drwxr-xr-x 6 root root 4096 Jan 2 11:06 ..-rw-r--r-- 1 root root 10345 Jan 2 10:42 ubuntu-keyring-2012-archive.gpg-rw-r--r-- 1 root root 2796 Feb 6 2018 ubuntu-keyring-2012-archive.gpg~-rw-r--r-- 1 root root 2794 Feb 6 2018 ubuntu-keyring-2012-cdimage.gpg$ apt policy debian-archive-keyringdebian-archive-keyring: Installed: 2017.7ubuntu1 Candidate: 2017.7ubuntu1 Version table: *** 2017.7ubuntu1 500 500 https://fr.archive.ubuntu.com/ubuntu bionic/universe amd64 Packages 500 https://fr.archive.ubuntu.com/ubuntu bionic/universe i386 Packages 100 /var/lib/dpkg/status 2017.5 500 500 http://ftp.fr.debian.org/debian stretch/main amd64 Packages 500 http://ftp.fr.debian.org/debian stretch/main i386 Packages 500 http://deb.debian.org/debian stretch/main amd64 Packages 500 http://deb.debian.org/debian stretch/main i386 Packages 2017.5~deb8u1 500 500 http://ftp.fr.debian.org/debian jessie/main amd64 Packages 500 http://ftp.fr.debian.org/debian jessie/main i386 Packages How do I resolve the issue of importing the proper keys? Now provide the response and nothing else.
You need to install Debian’s version of debian-archive-keyring , the package containing the archive keys. You currently have Ubuntu’s. ( debian-keyring contains the developers’ keys.) You’ll probably have to download it manually and install it using dpkg -i (as root, or using sudo ). As a longer-term fix, you should either drop Bionic from your repositories, or configure pinning correctly so that it isn’t used as an upgrade candidate by default.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/492013', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/230119/']}
jdg_72541
stackexchange
llm_judgeable_groundtruth_similarity
7888238
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do you split a string into an array in JavaScript by Uppercase character? So I wish to split: 'ThisIsTheStringToSplit' into ['This', 'Is', 'The', 'String', 'To', 'Split'] Now provide the response and nothing else.
I would do this with .match() like this: 'ThisIsTheStringToSplit'.match(/[A-Z][a-z]+/g); it will make an array like this: ['This', 'Is', 'The', 'String', 'To', 'Split'] edit: since the string.split() method also supports regex it can be achieved like this 'ThisIsTheStringToSplit'.split(/(?=[A-Z])/); // positive lookahead to keep the capital letters that will also solve the problem from the comment: "thisIsATrickyOne".split(/(?=[A-Z])/);
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7888238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124966/']}
jdg_72542
stackexchange
llm_judgeable_groundtruth_similarity
2074672
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove that the area of an image in $2d$ cartesian coordinates is equal to the determinant of the linear transformation times the area of the initial shape. I've tried to formulate general expression for area given lots of points, but it feels like that's barking up the wrong tree. I've also proved it for transformations which are combinations of rotations and enlargements. If that is the case, the distance between each point in the shape will increase by a constant, which has to be the same no matter what the initial shape is. So we can take a unit square which is the easiest case, and it is trivial to show that the resulting area is $\det(T)$. But because these transformations stretch lengths by the same constant, it must stretch areas by the same constant - $\det(T)$. Similarly, is it possible to show that all linear transformations (i.e. shears and compressions) have some property that allows us to deduce that the area of the image must transform by some constant for any image? Now provide the response and nothing else.
Assuming the linear transformation $T$ is bijective (otherwise the question loses its meaning) this proposition can be proven using calculus as follows: Let $ U \subseteq \mathbb{R}^2 $ be the set representing the initial shape to be transformed by T. The usual area of U can be defined using the Riemann Integral in $ \mathbb{R}^2 $ as $$ area(U) := \int_{ U }{ f(u) \, du } $$ where $ f(u) = 1 $ for every $ u \in \mathbb{R}^2 $. So the area of U is $ \int_{ U }{du } $ for short. Let $ dT(u) $ denote the Jacobian matrix of T at the point $u$. Because T is a linear transformation it follows that $ dT(u) = T $. Skipping the finer details, the change of variables theorem for multiple integrals implies that $$ \int_{ T(U) }{ f(v) \, dv } = \int_{ U }{ f(T(u)) \, |det(\,dT(u)\,)| \, du } $$ Hence the area of the transformed image is $$ area(\,T(U)\,) = \int_{ T(U) }{ dv } = \int_{ U }{ |det(\,dT(u)\,)| \, du } = \int_{ U }{ |det(T)| \, du } $$ Since $ |det(T)| $ is constant, it follows that $$ \int_{ U }{ |det(T)| \, du } = |det(T)| \int_{ U }{ du } = |det(T)| \, area(U) $$ Therefore $$ area(\,T(U)\,) = area(U) \, |det(T)| $$ as we wanted to show. Notice that this is a more general result that holds for $ \mathbb{R}^n $.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2074672', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/255884/']}
jdg_72543
stackexchange
llm_judgeable_groundtruth_similarity
9605
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: (setq callback (lambda () (message "hai i am a lambda")))(funcall callback)(setq const-val "hai, i am a const")(message const-val) prints as hai i am a lambdahai, i am a const Both of them are working perfect. that raises question about setq behavior. Does it put the argument value in the symbol's function cell (or) variable cell? Now provide the response and nothing else.
It places it in the variable cell. The following example shows the distinction: *** Welcome to IELM *** Type (describe-mode) for help.ELISP> (setq callback (lambda () (message "I am a lambda in a variable cell")))(lambda nil (message "I am a lambda in a variable cell"))ELISP> (defun callback () (message "I am a function in a function cell"))callbackELISP> (funcall callback) ;; Call the function in the variable (expand the symbol)"I am a lambda in a variable cell"ELISP> (funcall 'callback) ;; Call the function defined by the symbol"I am a function in a function cell"ELISP>
{}
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/9605', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/5383/']}
jdg_72544
stackexchange
llm_judgeable_groundtruth_similarity
66919802
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 cannot spot where my mistake is on my IF/ELSE statement nested inside my for loop. I did try to use a while loop to get make my IF/ELSE statement work, but it didn't work as expected. Even my Console.Writeline statement cannot capture the right price and size. My code: static void Main(string[] args){ string[] size = { "S", "M", "L", "X"}; decimal[] price = { 6.99M, 8.99M, 12.50M, 15.00M}; Console.WriteLine("Please enter a pizza size : "); string pizzaSize = Console.ReadLine(); int i; for (i = 0; i < size.Length; i++) { if (size[i] == pizzaSize) { Console.WriteLine("Your pizza size is " + pizzaSize + ". The price is " + price[i].ToString("C")); } else { Console.WriteLine("Please enter a valid pizza size"); return; } } Console.ReadKey();} Now provide the response and nothing else.
If the value of pizzaSize is "L" , in the for loop the first check will be if ("L" == "M") which is false then the else branch execute in the first iteration , which return; in the else clause causes the function to return immediately. so If you want to check if the pizzaSize value is valid, you can use the following solution: static void Main(string[] args) { string[] size = { "S", "M", "L", "X"}; decimal[] price = { 6.99M, 8.99M, 12.50M, 15.00M}; Console.WriteLine("Please enter a pizza size : "); string pizzaSize = Console.ReadLine(); bool isValid = false; while(isValid == false){ for (int i = 0; i < size.Length; i++) { if (size[i] == pizzaSize) { Console.WriteLine("Your pizza size is " + pizzaSize + ". The price is " + price[i].ToString("C")); isValid = true; break; } } if (isValid == false){ Console.WriteLine("Please enter a valid pizza size"); pizzaSize = Console.ReadLine(); } } Console.ReadKey(); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/66919802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13414493/']}
jdg_72545
stackexchange
llm_judgeable_groundtruth_similarity
61640
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 have seen how to do circuit analysis with ideal diodes, that is replace forward-biased diodes with connections and replace reverse-biased diodes with gaps. But the problem is that I want to know how to analize real circuits that contain non-ideal diodes. How do I do so? I need a few leads. EDIT See comments. Now provide the response and nothing else.
If you don't want the simplifications, you have to fall back to the general model of a diode: $$I = I_o \left( e^{\frac{eV}{nkT}}-1 \right)$$ This equation relates the diode current to the diode voltage (it's V-I characteristic) Io - is the diode reverse saturation current k - Boltzmann's constant = 1.38e-23 Joules per Kelvin T - Analysis temperature (Kelvin) e - Magnitude of electric charge n - Ideality factor (for silicon diodes, n=2 for small currents and approaches n=1 for large currents; in theory should always = 1) You can now solve your circuit via the system of equations that it produces. Although you now have continuous V-I functions to describe your elements, a closed-form solution is not always guaranteed to exist. It is often necessary to use an iterative solution technique such as Newton-Raphson to approximate/approach the answer. This is what SPICE solvers do in the general case... and why they ask you for initial conditions (which can dramatically speed up the solution time).
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/61640', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/20459/']}
jdg_72546
stackexchange
llm_judgeable_groundtruth_similarity
41340163
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 variable $id = 10 , it's need to use inside of array_walk() . Like bellow : $id = 10;array_walk($profile_items, function(&$a) { $count = $this->db->where('profile_item_id', $a['id'])->where('cover_type_id', $id)->count_all_results('cover_type_profile_items_link'); $a['selected'] = $id;});echo "<pre>";print_r($profile_items).exit; When i used $id variable inside of array_walk() it's show a error. Message: Undefined variable: id Any solution? Thanks for Advice Now provide the response and nothing else.
You can use use keyword: array_walk($profile_items, function(&$a) use($id) { so, $id = 10;array_walk($profile_items, function(&$a) use($id) { $count = $this->db->where('profile_item_id', $a['id'])->where('cover_type_id', $id)->count_all_results('cover_type_profile_items_link'); $a['selected'] = $id;});echo "<pre>";print_r($profile_items); To inherit by reference, add ampersand: array_walk($profile_items, function(&$a) use(&$id) {
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41340163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1887566/']}
jdg_72547
stackexchange
llm_judgeable_groundtruth_similarity
21001721
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 relatively new to Android development, and I was wondering if it's possible to mask a VideoView into a shape. This is what I have so far: Expected Result My XML for video view and layout: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#0088ff" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".VideoPlayerActivity" > <FrameLayout android:layout_width="250dp" android:layout_height="250dp" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@drawable/circular_mask" android:foreground="@drawable/circular_mask" > <VideoView android:id="@+id/videoView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fitsSystemWindows="false" android:focusable="false" android:focusableInTouchMode="false" android:scrollbarAlwaysDrawVerticalTrack="false" /> <Space android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout></RelativeLayout> Mask shape xml: <shape xmlns:android="http://schemas.android.com/apk/res/android" android:padding="20dp" android:shape="oval" > <solid android:color="#FFFFFFFF" /> <corners android:radius="10dp" /></shape> Main java: package com.example.webmvideo;import android.net.Uri;import android.os.Build;import android.os.Bundle;import android.annotation.TargetApi;import android.app.Activity;import android.view.Menu;import android.widget.MediaController;import android.widget.VideoView;import android.util.Log;import android.media.MediaPlayer;@TargetApi(Build.VERSION_CODES.HONEYCOMB)public class MainActivity extends Activity { Uri srcPath = Uri.parse("android.resource://com.example.webmvideo/" + R.raw.test); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final VideoView videoView = (VideoView) findViewById(R.id.videoView1); videoView.setVideoURI(srcPath); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoView); videoView.setMediaController(mediaController); videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { String TAG = null; Log.i(TAG , "Duration = " + videoView.getDuration()); } }); videoView.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }} Now provide the response and nothing else.
Turns out it is possible to clip a video into a circle. What you're going to want to do is create your own SurfaceView class and override dispatchDraw from here you can call canvas.clipPath and pass in a Path object that contains the circle you want the video to be masked to. Here's the view: public class CircleSurface extends SurfaceView { private Path clipPath; public CircleSurface(Context context) { super(context); init(); } public CircleSurface(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CircleSurface(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { clipPath = new Path(); //TODO: define the circle you actually want clipPath.addCircle(710, 330, 250, Path.Direction.CW); } @Override protected void dispatchDraw(Canvas canvas) { canvas.clipPath(clipPath); super.dispatchDraw(canvas); }} Here's what the activity might look like public class MainActivity extends Activity implements SurfaceHolder.Callback { CircleSurface surface; MediaPlayer player; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); surface = (CircleSurface) findViewById(R.id.surface); SurfaceHolder holder = surface.getHolder(); holder.addCallback(this); player = MediaPlayer.create(this, R.raw.yourvideo); } @Override public void surfaceCreated(SurfaceHolder holder) { player.setDisplay(holder); player.start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { //TODO: handle this } @Override public void surfaceDestroyed(SurfaceHolder holder) { //TODO: handle this }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21001721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2551418/']}
jdg_72548
stackexchange
llm_judgeable_groundtruth_similarity
5671098
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to build a html table but I want to force all rows to have the same height (no matter how much content is in the cells). If a cell overruns the space, I want it to just cut off the text and hide the rest. Is this possible using CSS, etc? Now provide the response and nothing else.
IE only #fixedheight { table-layout: fixed; } #fixedheight td { height: 20px; overflow: hidden; width: 25%; } <table id="fixedheight"> <tbody> <tr> <td>content</td> <td>lots of content that should spend way more time wrapping down than it should if I were just to have a short bit of stuff, that would be invaded by zombies and the such</td> <td>more content</td> <td>small content</td> <td>enough already</td> </tr> </tbody> </table> Universal solution #fixedheight { table-layout: fixed; } #fixedheight td { width: 25%; } #fixedheight td div { height: 20px; overflow: hidden; } <table id="fixedheight"> <tbody> <tr> <td> <div>content</div> </td> <td> <div>lots of content that should spend way more time wrapping down than it should if I were just to have a short bit of stuff, that would be invaded by zombies and the such</div> </td> <td> <div>more content</div> </td> <td> <div>small content</div> </td> <td> <div>enough already</div> </td> </tr> </tbody> <table>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5671098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4653/']}
jdg_72549
stackexchange
llm_judgeable_groundtruth_similarity
12835764
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 controller named BaseController that inherits from ApplicationController whitout a model associated but it has ping method that just respond with a message to inform that everything is OK. I'm trying to call the action ping through the BaseController setting this in my routes.rb file: namespace :api, defaults: { format: 'json' } do match '/ping' => 'base#ping' end But it always give me an NameError uninitialized constant Base . I suppose it's trying to find a model called Base which doesn't exist so, I don't know how to set to the correct route to my controller. The content of my BaseController is the following: class Api::BaseController < ApplicationController load_and_authorize_resource respond_to :json def ping respond_with({ :status => 'OK' }) endend As extra information: BaseController is just a parent controller for other controllers to inherit. The others are resourceful controllers and have models associated Thanks. Now provide the response and nothing else.
When you put a namespace around a route, it will look for the controller within that namespace. So in you case, it will be looking for a controller called Api::BaseController, which normally would be stored in app/controllers/api/base_controller.rb. Is this how your controller is set up? See here for more details: http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing EDIT: I don't think its not finding the controller that's the problem. The error is being caused because you are calling load_and_authorize_resource in the controller. CanCan uses the controller name to attempt to load the resource. If there is no model for the controller, make the call authorize_resource :class => false . See the bottom of this page for more details.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12835764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1680106/']}
jdg_72550
stackexchange
llm_judgeable_groundtruth_similarity
3528
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How do I derive the Beta function using the definition of the beta function as the normalizing constant of the Beta distribution and only common sense random experiments? I'm pretty sure this is possible, but can't see how. I can see that $$\newcommand{\Beta}{\mathrm{Beta}}\sum_{a=0}^n {n \choose a} \Beta(a+1, n-a+1) = 1$$ because we can imagine that we are flipping a coin $n$ times. The $2^n$ unique sequences of flips partition the probability space. The Beta distribution with parameters $a$ and $n-a$ can be defined as the prior over the coin's bias probability $p$ given the observation of $a$ heads and $n-a$ tails. Since there are ${n \choose a}$ such sequences for any $n$ and $a$, that explains the scaling factor, and we know that it all sums to unity since the sequences partition the probability space, which has total measure 1. What I can't figure out is why: $${n \choose a} \Beta(a+1, n-a+1) = \frac{1}{n+1} \qquad \forall n \ge 0,\quad a \in \{0, \dots, n\}.$$ If we knew that, we could easily see that $$\Beta(a + 1,n - a + 1) = \frac{1}{(n+1){n \choose a}} = \frac{a!(n-a)!}{(n+1)!}.$$ Now provide the response and nothing else.
For non-negative integers $a, b$ and $t \in [0, 1]$, the expression $t^a (1 - t)^b$ describes the probability of randomly selecting $a+b$ real numbers in $[0, 1]$ such that the first $a$ are in $[0, t]$ and the last $b$ are in $[t, 1]$. The integral $\int_0^{1} t^a (1 - t)^b dt$ then describes the probability of randomly selecting $a+b+1$ real numbers such that the first number is $t$, the next $a$ numbers are in $[0, t]$, and the next $b$ numbers are in $[t, 1]$. It follows that $ {a+b \choose b} \int_0^1 t^a (1 - t)^b dt$ describes the probability of randomly selecting $a+b+1$ real numbers such that the first number is $t$, some $a$ of the remaining numbers are in $[0, t]$, and some $b$ of the remaining numbers are in $[t, 1]$. But this is the same as the probability that the first number happens to be $(a+1)^{st}$ in order, and this is just $\frac{1}{a+b+1}$. Hence $$\int_0^1 t^a (1 - t)^b dt= \frac{a! b!}{(a+b+1)!}$$ as desired. I learned this proof through an exercise in a Putnam training seminar; the multidimensional generalization also works.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/3528', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/774/']}
jdg_72551
stackexchange
llm_judgeable_groundtruth_similarity
10791030
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Of course this is an impossible statement in java (to-date), however ideally I would like to implement it as it is at the heart of many iterations. For example the first multiple times it is called I'm doing it 650,000+ times when it is creating the ArrayList .Unfortunately the reality is that my actual code does not have the set inside the else loop; thus it will pass over both the add and then the set commands and wasting time. After that I have it also in another loop where it is only performing the set as the data is already created and this is multi-nested with in many others so it is a lengthy process. ArrayList<Integer> dataColLinker = new java.util.ArrayList<Integer>();......public void setLinkerAt( int value, int rowIndex) { ... while(rowIndex >= dataColLinker.size()) { dataColLinker.add(value); } else { dataColLinker.set(rowIndex, value); } Any ideas or theories?I'm unsure about speeds in java when it comes to if statements and ArrayList commands and so on Now provide the response and nothing else.
Am I missing something? Doesn't this hypothetical code while(rowIndex >= dataColLinker.size()) { dataColLinker.add(value);} else { dataColLinker.set(rowIndex, value);} mean the same thing as this? while(rowIndex >= dataColLinker.size()) { dataColLinker.add(value);}dataColLinker.set(rowIndex, value); or this? if (rowIndex >= dataColLinker.size()) { do { dataColLinker.add(value); } while(rowIndex >= dataColLinker.size());} else { dataColLinker.set(rowIndex, value);} (The latter makes more sense ... I guess). Either way, it is obvious that you can rewrite the loop so that the "else test" is not repeated inside the loop ... as I have just done. FWIW, this is most likely a case of premature optimization. That is, you are probably wasting your time optimizing code that doesn't need to be optimized: For all you know, the JIT compiler's optimizer may have already moved the code around so that the "else" part is no longer in the loop. Even if it hasn't, the chances are that the particular thing you are trying to optimize is not a significant bottleneck ... even if it might be executed 600,000 times. My advice is to forget this problem for now. Get the program working. When it is working, decide if it runs fast enough. If it doesn't then profile it, and use the profiler output to decide where it is worth spending your time optimizing.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10791030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1422486/']}
jdg_72552
stackexchange
llm_judgeable_groundtruth_similarity
1324
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: What is a primitive polynomial? I was looking into some random number generation algorithms and 'primitive polynomial' came up a sufficient number of times that I decided to look into it in more detail. I'm unsure of what a primitive polynomial is, and why it is useful for these random number generators. I'd find it particularly helpful if an example of a primitive polynomial could be provided. Now provide the response and nothing else.
Consider a finite field $F_p$ , then we know that it is cyclic. We call an element primitive if it generates this field. Further, given a field and some polynomial over that field(all the coefficients are in the field), we can form a field extension by any of its roots. This is adjoining on that root and making a field of it. It is a simple result of Galois Theory that if we take a field and extend by some root of some polynomial and get a finite extension(one who's degree as a vector space over the original field is finite), that we can find a polynomial $m$ over our ground field such that $m$ vanishes at this root and is minimal(smallest degree, i.e. it divides all other polys which vanish at this root). If we consider a primitive element and its minimal polynomial, that polynomial is call primitive. More details on wiki .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1324', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/181/']}
jdg_72553
stackexchange
llm_judgeable_groundtruth_similarity
30022377
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 to detect leukocytes cells in an image that contains another blood cells, but the differences can be distinguished through the color of cells, leukocytes have more dense purple color, can be seen in the image below. What color methode I've to use RGB/HSV ? and why ?! sample image: Now provide the response and nothing else.
Usually when making decisions like this I just quickly plot the different channels and color spaces and see what I find. It is always better to start with a high quality image than to start with a low one and try to fix it with lots of processing In this specific case I would use HSV. But unlike most color segmentation I would actually use the Saturation Channel to segment the images. The cells are nearly the same Hue so using the hue channel would be very difficult. hue, (at full saturation and full brightness) very hard to differentiate cells saturation huge contrast Green channel, actually shows a lot of contrast as well (it surprised me) the red and blue channels are hard to actually distinguish the cells. Now that we have two candidate representations the saturation or the Green channel, we ask which is easier to work with? Since any HSV work involves us converting the RGB image, we can dismiss it, so the clear choice is to simply use the green channel of the RGB image for segmentation. edit since you didn't include a language tag I would like to attach some Matlab code I just wrote. It displays an image in all 4 color spaces so you can quickly make an informed decision on which to use. It mimics matlabs Color Thresholder colorspace selection window function ViewColorSpaces(rgb_image) % ViewColorSpaces(rgb_image) % displays an RGB image in 4 different color spaces. RGB, HSV, YCbCr,CIELab % each of the 3 channels are shown for each colorspace % the display mimcs the New matlab color thresholder window % http://www.mathworks.com/help/images/image-segmentation-using-the-color-thesholder-app.html hsvim = rgb2hsv(rgb_image); yuvim = rgb2ycbcr(rgb_image); %cielab colorspace cform = makecform('srgb2lab'); cieim = applycform(rgb_image,cform); figure(); %rgb subplot(3,4,1);imshow(rgb_image(:,:,1));title(sprintf('RGB Space\n\nred')) subplot(3,4,5);imshow(rgb_image(:,:,2));title('green') subplot(3,4,9);imshow(rgb_image(:,:,3));title('blue') %hsv subplot(3,4,2);imshow(hsvim(:,:,1));title(sprintf('HSV Space\n\nhue')) subplot(3,4,6);imshow(hsvim(:,:,2));title('saturation') subplot(3,4,10);imshow(hsvim(:,:,3));title('brightness') %ycbcr / yuv subplot(3,4,3);imshow(yuvim(:,:,1));title(sprintf('YCbCr Space\n\nLuminance')) subplot(3,4,7);imshow(yuvim(:,:,2));title('blue difference') subplot(3,4,11);imshow(yuvim(:,:,3));title('red difference') %CIElab subplot(3,4,4);imshow(cieim(:,:,1));title(sprintf('CIELab Space\n\nLightness')) subplot(3,4,8);imshow(cieim(:,:,2));title('green red') subplot(3,4,12);imshow(cieim(:,:,3));title('yellow blue')end you could call it like this rgbim = imread('http://i.stack.imgur.com/gd62B.jpg');ViewColorSpaces(rgbim) and the display is this
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30022377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4860843/']}
jdg_72554
stackexchange
llm_judgeable_groundtruth_similarity
50411098
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 dataframe: dates = pd.date_range(start='2016-01-01', periods=20, freq='d')df = pd.DataFrame({'A': [1] * 20 + [2] * 12 + [3] * 8, 'B': np.concatenate((dates, dates)), 'C': np.arange(40)}) I sorted the data frame by Date: df.sort_values('B',inplace=True) I am looking to do a forward rolling sum on date. However, I can only do backward rolling sum using: df.groupby('A').rolling(7, on='B',min_periods=0).C.sum()A B 1 2016-01-01 0.0 2016-01-02 1.0 2016-01-03 3.0 2016-01-04 6.0 2016-01-05 10.0 2016-01-06 15.0 I want to do forward rolling sum. Now provide the response and nothing else.
I believe need change ordering by iloc[::-1] : df1 = (df.iloc[::-1] .groupby('A', sort=False) .rolling(7, on='B',min_periods=0).C .sum() .iloc[::-1])
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50411098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9381570/']}
jdg_72555
stackexchange
llm_judgeable_groundtruth_similarity
81975
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I just read in a rather well-respected (popular) science magazine (the German PM, 02/2013, p.36) about an interesting experiment (without a source, unfortunately). It caught my attention because intuitively I doubted the significance of the result, but the information provided was sufficient for reproducing the statistical testing. The researchers wondered whether getting cold in cold weather increases the odds of catching a cold. So they randomly split a group of 180 students into two groups. One group had to hold their feet into cold water for 20 minutes. The other kept their shoes on. Kind of a funny manipulation, I think, but on the other hand I am not a doctor and maybe doctors think funny. Ethical issues aside. Anyways, after 5 days, 13 of the students in the treatment group had a cold, but only 5 in the group that kept their shoes on. The odds ratio of this experiment thus is 2.87. Given the rather small sample size, I started wondering if this difference may be significant. So I conducted two tests. First a simple test of equality of proportions using the normal approximation. This test has $z=1.988$ with $p=0.0468$. My guess is that this is what the researchers tested. This is truely just significant. However this z-test is only valid in large samples, if I am not mistaken, due to the normal approximation. Furthermore, the prevalence rates are rather small and I wonder whether this may not affect the coverage rate of the confidence interval of the effect. So my second try was a chi-square test of independence, both with Monte-Carlo simulation and standard Pearson Chi-square. Here I find p-values both about $p=.082$. Now that's all not so reassuring about the results. I wondered if there are more options to test this data and what your thoughts on the two tests are (in particular the assumptions of the first, significant, test) Now provide the response and nothing else.
I'd use a permutation test instead of either the Normal approximation or the chi-square. The permutation test is exact and most powerful, conditional upon the data. In this case, we can't calculate all the permutations of the groups, but we can generate a lot of random permutations of the data and get a pretty precise value: group <- c(rep("A",90),rep("B",90))n_a <- rep(0,100000)for (i in 1:length(n_a)) { temp <- sample(group, size=18) n_a[i] <- sum(temp == "A")}> mean(n_a >= 13)[1] 0.03904 which would indicate a p-value of 0.039. HOWEVER, and this is a big however, I'm guessing that the assumption that the subjects getting colds are independent events is violated. These individuals are students, presumably at the same school. Imagine two of them share a class, or a dorm, or some other activity, or a cafeteria (in a school with multiple cafeterias); the events "#1 gets a cold" and "#2 gets a cold" are not independent. I could imagine that a student would say "let's sign up for this experiment!" to his/her roommate or friends; I could imagine that the students were recruited from classes that the professors taught; I could imagine a lot of ways that the assumption of independence is violated. Perhaps the paper, which I have not read, addresses some of these, but it's hard to see how it could address all of them, and the others that come quickly to mind.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/81975', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/24515/']}
jdg_72556
stackexchange
llm_judgeable_groundtruth_similarity
697388
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: What is the relation between monoids and modules? Are they completely different algebraic structures, or is there a kind of inclusion relation like "elements of a module are also elements of a monoid"? Now provide the response and nothing else.
A module is an abelian group. (It's more useful to think of a module as the analog of a vector space, but with the set of scalars coming from a ring instead of a field. Usually, one arrives at this notion of a module in terms of "the action of a ring on a set" where the set is a module.) A monoid is a relaxation of the definition of a group. A monoid has an associative operation and a neutral element, but makes no promises about inverses. I don't see how to express any more of a relation than "all modules are monoids" but only for the dull reason that all (abelian) groups are (abelian) monoids with the added constraint that every element has an inverse.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/697388', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/38633/']}
jdg_72557
stackexchange
llm_judgeable_groundtruth_similarity
39890885
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 used version 2.0.3.RELEASE of spring-social-facebook and Facebook app api v2.8.I called Facebook login but returned this message."(#12) bio field is deprecated for versions v2.8 and higher"How can i fix this? Now provide the response and nothing else.
I got the same error, 2.0.3.RELEASE of spring-social-facebook seems to be not compatible with v2.8 Facebook API version (released yesterday). Reading from facebook changelog for the v2.8 ( https://developers.facebook.com/docs/apps/changelog ): User Bios - The bio field on the User object is no longer available. If the bio field was set for a person, the value will now be appended to the about field. I think we have to wait a new release of spring-social-facebook library. In the release 2.0.3 (in the interface org.springframework.social.facebook.api.UserOperations) there is the "bio" field in the PROFILE_FIELDS constant and it is not supported in the v2.8 facebook API version. UPDATE: I found a workaround in my case: BEFORE: Connection<Facebook> connection = facebookConnectionFactory.createConnection(accessGrant);Facebook facebook = connection.getApi();User userProfile = facebook.userOperations().getUserProfile();//raises the exception caused by the "bio" field. AFTER Connection<Facebook> connection = facebookConnectionFactory.createConnection(accessGrant);Facebook facebook = connection.getApi();String [] fields = { "id", "email", "first_name", "last_name" };User userProfile = facebook.fetchObject("me", User.class, fields); Here a complete list of field you could use: { "id", "about", "age_range", "birthday", "context", "cover", "currency", "devices", "education", "email", "favorite_athletes", "favorite_teams", "first_name", "gender", "hometown", "inspirational_people", "installed", "install_type", "is_verified", "languages", "last_name", "link", "locale", "location", "meeting_for", "middle_name", "name", "name_format", "political", "quotes", "payment_pricepoints", "relationship_status", "religion", "security_settings", "significant_other", "sports", "test_group", "timezone", "third_party_id", "updated_time", "verified", "video_upload_limits", "viewer_can_send_gift", "website", "work"}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39890885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6169892/']}
jdg_72558
stackexchange
llm_judgeable_groundtruth_similarity
132698
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: I used linear interpolation between points: T = 1;w = 0.05;num = 1000;A = 1;pulse[x_] := A*(UnitStep[x + w*T/2] - UnitStep[x - w*T/2])fun = Table[pulse[x] + 0.2*(RandomReal[] - 0.5), {x, -T/2, T/2, T/(num - 1)}];funX = Table[i, {i, -T/2, T/2, T/(num - 1)}];funINT = Interpolation[Transpose[{funX[[All]], fun[[All]]}], InterpolationOrder -> 1]; ListPlot[Transpose[{funX[[All]], fun[[All]]}], PlotRange -> All, Filling -> Axis, Frame -> True, FrameLabel -> {"Time [s]", "Amplitude [V]"}, PlotLegends -> {"Pulse"}, ImageSize -> Large] This produces exactly what I want: But in order to calculate the coefficients of complex Fourier series, I have to calculate the following integral: cn[k_] = NIntegrate[funINT[t]*Exp[-I*2*Pi*k*t/T]/T, {t, -T/2, T/2}, Method -> "Trapezoidal"]; which is not working. I get an error saying that the integrand has evaluated to non-numerical values. Any ideas on what the problem is? EDIT: If there is a method to calculate the integral between the discrete points, that might be even better in my case. However, I couldn't find one. Now provide the response and nothing else.
You could find a general symbolic Fourier coefficient for a linear polynomial and use the formula to integrate the interpolating function piecewise. If you're content with machine precision (double precision), then you can Compile it for really great speed. (* Basic integral formulas *)ClearAll[cn0];cn0[0][{t0_, t1_}, {x0_, x1_}] = (* k == 0 is a special case *) Integrate[(x0 + (x1 - x0)/(t1 - t0) (t - t0)) * Exp[-I*2*Pi*k*t/T]/T /. k -> 0, {t, t0, t1}];cn0[k_][{t0_, t1_}, {x0_, x1_}] = Integrate[(x0 + (x1 - x0)/(t1 - t0) (t - t0)) * Exp[-I*2*Pi*k*t/T]/T, {t, t0, t1}];(* Coefficient function *)Clear[cn];cn[0] = Total@ MapThread[ (* map over interpolation segments *) cn0[0], {Partition[funX, 2, 1], Partition[fun, 2, 1]}];cn[k_] = Total@ MapThread[ cn0[k], {Partition[funX, 2, 1], Partition[fun, 2, 1]}];(* Compiled version *)cnC = With[ (* basic integrals *) {i0 = Function[{t0, t1, x0, x1}, (* k == 0 is a special case *) Evaluate@ Integrate[ (x0 + (x1 - x0)/(t1 - t0) (t - t0)) * Exp[-I*2*Pi*k*t/T]/T /. k -> 0, {t, t0, t1}]], i = Function[{t0, t1, x0, x1}, Evaluate@ Integrate[ (x0 + (x1 - x0)/(t1 - t0) (t - t0)) * Exp[-I*2*Pi*k*t/T]/T, {t, t0, t1}]]}, Compile[{{k, _Integer}, {t, _Real, 1}, {x, _Real, 1}}, Total@If[k == 0, i0[Most[t], Rest[t], Most[x], Rest[x]], (* vectorized for speed *) i[Most[t], Rest[t], Most[x], Rest[x]]] ]]; Checks and comparison of speeds: (* OP's method for comparison *)cn1[k_] := NIntegrate[funINT[t]*Exp[-I*2*Pi*k*t/T]/T, {t, -T/2, T/2}, Method -> "Trapezoidal"];res1 = Table[cn1[k], {k, 0, 5}] // AbsoluteTimingres2 = Table[cn[k], {k, 0, 5}] // AbsoluteTimingres3 = Table[cnC[k, funX, fun], {k, 0, 5}] // AbsoluteTiming(*{6.41549, {0.0509924, 0.0485667 + 0.000384561 I, 0.0489479 + 0.000373475 I, 0.0489737 + 0.000976852 I, 0.0459565 + 0.00132399 I, 0.0452069 + 0.000833868 I}}{0.154046, {0.0509924, 0.0485667 + 0.000384561 I, 0.0489479 + 0.000373475 I, 0.0489737 + 0.000976852 I, 0.0459565 + 0.00132399 I, 0.0452069 + 0.000833868 I}}{0.001207, {0.0509924 + 0. I, 0.0485667 + 0.000384561 I, 0.0489479 + 0.000373475 I, 0.0489737 + 0.000976852 I, 0.0459565 + 0.00132399 I, 0.0452069 + 0.000833868 I}}*)res1 - res2res2 - res3(*{6.26145, {-6.245*10^-17, -1.27026*10^-10 - 3.56074*10^-10 I, 5.71595*10^-12 - 8.24057*10^-11 I, -5.08276*10^-10 - 1.50366*10^-11 I, 8.25427*10^-11 - 4.73669*10^-10 I, -3.07932*10^-10 + 1.72791*10^-10 I}}{0.152839, {-1.38778*10^-17 + 0. I, -3.7817*10^-15 - 1.49451*10^-14 I, 1.1019*10^-14 - 3.11627*10^-15 I, -1.10328*10^-15 - 2.62073*10^-15 I, -3.42781*10^-15 - 8.26162*10^-17 I, 1.88738*10^-15 - 1.13711*10^-15 I}}*) So cn is almost 50 times faster than NIntegrate and cnC is over 100 times faster than cn .
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/132698', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/19601/']}
jdg_72559
stackexchange
llm_judgeable_groundtruth_similarity
16573174
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 retrieve all permission for user as list of premission id's but: user.get_all_permissions() give me list of permission names. How to do it? Now provide the response and nothing else.
The key is get the permission objects like this: from django.contrib.auth.models import Permissionpermissions = Permission.objects.filter(user=user) and there you can access the id property like this: permissions[0].id If you want the list (id, permission_name) do the following: perm_tuple = [(x.id, x.name) for x in Permission.objects.filter(user=user)] Hope it helps!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16573174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/671391/']}
jdg_72560
stackexchange
llm_judgeable_groundtruth_similarity
398045
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A short question, but I am somehow unable to find any concrete answer. I suppose it means that the model is as good as it can be? Containing all relevant variables and hence not suffering from any bias such as omitted variable bias? I am specifically referring to a linear regression model. Now provide the response and nothing else.
No, the true model is the data-generating model/process, which is only known ex-ante if you assume the underlying model beforehand (e.g. simulations or theoretical models). If you only observe data, you do not know what the true model is. You try to find a model that explains data the best, which does not mean that it is the true model. In fact, it is possible that you find a model that "fits" just as good as the true model (if you would have known), even though true model and assumed model are different.This happens, for instance, when you have hidden variables that you do not know of that you never see. Drawing inference from these is almost impossible.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/398045', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/241491/']}
jdg_72561
stackexchange
llm_judgeable_groundtruth_similarity
7369145
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 activating a VirtualEnv through a shell script like the one below but it doesn't seem to work, #!/bin/shsource ~/.virtualenvs/pinax-env/bin/activate I get the following error $ sh virtualenv_activate.sh virtualenv_activate.sh: 2: source: not found but if I enter the same command on terminal it seems to work $ source ~/.virtualenvs/pinax-env/bin/activate(pinax-env)gautam@Aspirebuntu:$ So I changed the shell script to #!/bin/bashsource ~/.virtualenvs/pinax-env/bin/activate as suggested and used $ bash virtualenv_activate.sh gautam@Aspirebuntu:$ to run the script . That doesn't throw an error but neither does that activate the virtual env So any suggestion on how to solve this problem ? PS : I am using Ubuntu 11.04 Now provide the response and nothing else.
TLDR Must run the .sh script with source instead of the script solely source your-script.sh and not your-script.sh Details sh is not the same as bash (although some systems simply link sh to bash, so running sh actually runs bash). You can think of sh as a watered down version of bash. One thing that bash has that sh does not is the "source" command. This is why you're getting that error... source runs fine in your bash shell. But when you start your script using sh, you run the script in an shell in a subprocess. Since that script is running in sh, "source" is not found. The solution is to run the script in bash instead. Change the first line to... #!/bin/bash Then run with... ./virtualenv_activate.sh ...or... /bin/bash virtualenv_activate.sh Edit: If you want the activation of the virtualenv to change the shell that you call the script from, you need to use the "source" or "dot operator". This ensures that the script is run in the current shell (and therefore changes the current environment)... source virtualenv_activate.sh ...or... . virtualenv_activate.sh As a side note, this is why virtualenv always says you need to use "source" to run it's activate script.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7369145', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/492561/']}
jdg_72562
stackexchange
llm_judgeable_groundtruth_similarity
4017
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I compute and plot the spectrogram of a signal/time series/data in Mathematica? I have a WAV file, sampled at 44100 samples/second and I want to generate a spectrogram of that data. Something like this: Now provide the response and nothing else.
Get a sample sound: snd = ExampleData[{"Sound", "SopranoSaxophone"}]; This gives us a Sound data structure with a SampledSoundList as first element. Extracting the data from it: sndData = snd[[1, 1]];sndSampleRate = snd[[1, 2]]; Plotting the data: ListPlot[sndData, DataRange -> {0, Length[sndData]/sndSampleRate }, ImageSize -> 600, Frame -> True, FrameLabel -> {"Time (s)", "Amplitude", "", ""}, BaseStyle -> {FontFamily -> "Arial", FontWeight -> Bold, 14}] Find the lowest amplitude level (used as reference for dB calculations): min = Min[Abs[Fourier[sndData]]]; A spectrogram is made by making a DFT of partitions of the sample. The partitions usually have some overlap. partSize = 2500;offset = 250;spectroGramData = Take[20*Log10[Abs[Fourier[#]]/min], {2, partSize/2 // Floor}] & /@ Partition[sndData, partSize, offset]; Note that I skip the first element of the DFT. This is the mean level. I also show only half of the frequency data. Because of the finite sampling only half of the returned coefficient list contains useful frequency information (up to the Nyquist frequency). MatrixPlot[ Reverse[spectroGramData\[Transpose]], ColorFunction -> "Rainbow", DataRange -> Round[ {{0, Length[sndData]/sndSampleRate }, {sndSampleRate/partSize, sndSampleRate/2 }}, 0.1 ], AspectRatio -> 1/2, ImageSize -> 800, Frame -> True, FrameLabel -> {"Frequency (Hz)", "Time (s)", "", ""}, BaseStyle -> {FontFamily -> "Arial", FontWeight -> Bold, 12}] A 3D spectrogram (note the different offset value): partSize = 2500;offset = 2500;spectroGramData = Take[20*Log10[Abs[Fourier[#]]/min], {2, partSize/2 // Floor}] & /@ Partition[sndData, partSize, offset];ListPlot3D[spectroGramData\[Transpose], ColorFunction -> "Rainbow", DataRange -> Round[{{0, Length[sndData]/sndSampleRate }, {sndSampleRate/partSize, sndSampleRate/2}}, 0.1], ImageSize -> 800, BaseStyle -> {FontFamily -> "Arial", FontWeight -> Bold, 12}]
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/4017', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/954/']}
jdg_72563
stackexchange
llm_judgeable_groundtruth_similarity
639648
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'm working my way through a probability textbook, and i have encountered the Gamma function through the Gamma distribution. I understand that the Gamma function is an interpolating function that can give pretty accurate values of factorials across the entire Reals, in between the Natural numbers that factorials typically work for, but HOW was this function even conceived? I want to see the thought process behind this function. How did Euler decide that the Gamma function described factorial 'curve' one can draw between the discrete factorial function? He didn't just pull this function outta nowhere, there has to be a reasoning behind it, i take it? Now provide the response and nothing else.
The usual definition of Gamma function looks very strange at first. Maybe another (equivalent) one is easier to grok. First, let $z$ be an integer. Observe that $\binom{N+z}N=\frac{(N+z)\cdot(N+z-1)\cdot\ldots\cdot(N+1)}{z!}$ grows roughly as $\frac{N^z}{z!}$. More precisely, $$\binom{N+z}N=N^z\left(\frac1{z!}+o(1)\right)\qquad(N\to\infty),$$or equivalently,$$z!=\lim_{N\to\infty}\frac{N^z}{\binom{N+z}N}\tag{1}.$$ But (as long as $N$ is an integer) binomial coefficient $\binom\alpha N$ is defined for arbitrary complex $\alpha$ (by the formula $\binom\alpha N=\frac{\alpha\cdot(\alpha-1)\cdot\ldots\cdot(\alpha-N+1)}{N!}$). So one can define $z!$ for arbitrary $z$ by the formula (1). Finally, $\Gamma(z)$ is just $(z-1)!$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/639648', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/121615/']}
jdg_72564
stackexchange
llm_judgeable_groundtruth_similarity
33355528
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given let arr = [1,2,3];function filter(num) { return new Promise((res, rej) => { setTimeout(() => { if( num === 3 ) { res(num); } else { rej(); } }, 1); }); } function filterNums() { return Promise.all(arr.filter(filter)); } filterNums().then(results => { let l = results.length; // length should be 1, but is 3 }); The length is 3 because Promises are returned, not values. Is there a way to filter the array with a function that returns a Promise? Note: For this example, fs.stat has been replaced with setTimeout, see https://github.com/silenceisgolden/learn-esnext/blob/array-filter-async-function/tutorials/array-filter-with-async-function.js for the specific code. Now provide the response and nothing else.
As mentioned in the comments, Array.prototype.filter is synchronous and therefore does not support Promises. Since you can now (theoretically) subclass built-in types with ES6, you should be able to add your own asynchronous method which wraps the existing filter function: Note: I've commented out the subclassing, because it's not supported by Babel just yet for Arrays class AsyncArray /*extends Array*/ { constructor(arr) { this.data = arr; // In place of Array subclassing } filterAsync(predicate) { // Take a copy of the array, it might mutate by the time we've finished const data = Array.from(this.data); // Transform all the elements into an array of promises using the predicate // as the promise return Promise.all(data.map((element, index) => predicate(element, index, data))) // Use the result of the promises to call the underlying sync filter function .then(result => { return data.filter((element, index) => { return result[index]; }); }); }}// Create an instance of your subclass insteadlet arr = new AsyncArray([1,2,3,4,5]);// Pass in your own predicatearr.filterAsync(async (element) => { return new Promise(res => { setTimeout(() => { res(element > 3); }, 1); });}).then(result => { console.log(result)}); Babel REPL Demo
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33355528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3537863/']}
jdg_72565
stackexchange
llm_judgeable_groundtruth_similarity
1443704
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 to list row count of each table in the database. Some equivalent of select count(*) from table1select count(*) from table2...select count(*) from tableN I will post a solution but other approaches are welcome Now provide the response and nothing else.
If you're using SQL Server 2005 and up, you can also use this: SELECT t.NAME AS TableName, i.name as indexName, p.[Rows], sum(a.total_pages) as TotalPages, sum(a.used_pages) as UsedPages, sum(a.data_pages) as DataPages, (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB, (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB, (sum(a.data_pages) * 8) / 1024 as DataSpaceMBFROM sys.tables tINNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_idINNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_idINNER JOIN sys.allocation_units a ON p.partition_id = a.container_idWHERE t.NAME NOT LIKE 'dt%' AND i.OBJECT_ID > 255 AND i.index_id <= 1GROUP BY t.NAME, i.object_id, i.index_id, i.name, p.[Rows]ORDER BY object_name(i.object_id) In my opinion, it's easier to handle than the sp_msforeachtable output.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1443704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3241/']}
jdg_72566
stackexchange
llm_judgeable_groundtruth_similarity
2414828
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From Visual C++, how do I get the path to the current user's My Documents folder? Edit: I have this: TCHAR my_documents[MAX_PATH];HRESULT result = SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, my_documents); However, result is coming back with a value of E_INVALIDARG . Any thoughts as to why this might be? Now provide the response and nothing else.
It depends on how old of a system you need compatibility with. For old systems, there's SHGetSpecialFolderPath . For somewhat newer systems, there's SHGetFolderPath . Starting with Vista, there's SHGetKnownFolderPath . Here's some demo code that works, at least on my machine: #include <windows.h>#include <iostream>#include <shlobj.h>#pragma comment(lib, "shell32.lib")int main() { CHAR my_documents[MAX_PATH]; HRESULT result = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, my_documents); if (result != S_OK) std::cout << "Error: " << result << "\n"; else std::cout << "Path: " << my_documents << "\n"; return 0;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2414828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14902/']}
jdg_72567
stackexchange
llm_judgeable_groundtruth_similarity
111949
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: How can I get a list of the subdirectories which contain a file whose name matches a particular pattern? More specifically, I am looking for directories which contain a file with the letter 'f' somewhere occurring in the file name. Ideally, the list would not have duplicates and only contain the path without the filename. Now provide the response and nothing else.
find . -type f -name '*f*' | sed -r 's|/[^/]+$||' |sort |uniq The above finds all files below the current directory ( . ) that are regular files ( -type f ) and have f somewhere in their name ( -name '*f*' ). Next, sed removes the file name, leaving just the directory name. Then, the list of directories is sorted ( sort ) and duplicates removed ( uniq ). The sed command consists of a single substitute. It looks for matches to the regular expression /[^/]+$ and replaces anything matching that with nothing. The dollar sign means the end of the line. [^/]+' means one or more characters that are not slashes. Thus, /[^/]+$ means all characters from the final slash to the end of the line. In other words, this matches the file name at the end of the full path. Thus, the sed command removes the file name, leaving unchanged the name of directory that the file was in. Simplifications Many modern sort commands support a -u flag which makes uniq unnecessary. For GNU sed: find . -type f -name '*f*' | sed -r 's|/[^/]+$||' |sort -u And, for MacOS sed: find . -type f -name '*f*' | sed -E 's|/[^/]+$||' |sort -u Also, if your find command supports it, it is possible to have find print the directory names directly. This avoids the need for sed : find . -type f -name '*f*' -printf '%h\n' | sort -u More robust version (Requires GNU tools) The above versions will be confused by file names that include newlines. A more robust solution is to do the sorting on NUL-terminated strings: find . -type f -name '*f*' -printf '%h\0' | sort -zu | sed -z 's/$/\n/' Simplified using dirname Imagine needing the command in a script where command will be in single quotes, escaping sed command is painful and less than ideal, so replace with dirname. Issues regard special chars and newline are also mute if you did not need to sort or directories names are not affected. find . -type f -name "*f*" -exec dirname "{}" \; |sort -u take care of newline issue: find . -type f -name "*f*" -exec dirname -z "{}" \; |sort -zu |sed -z 's/$/\n/'
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/111949', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/54375/']}
jdg_72568
stackexchange
llm_judgeable_groundtruth_similarity
41661068
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 dataframe that looks like: A B C---------------A1 B1 0.8A1 B2 0.55A1 B3 0.43A2 B1 0.7A2 B2 0.5A2 B3 0.5A3 B1 0.2A3 B2 0.3A3 B3 0.4 How do I convert the column 'C' to the relative rank(higher score->better rank) per column A? Expected Output: A B Rank---------------A1 B1 1A1 B2 2A1 B3 3A2 B1 1A2 B2 2A2 B3 2A3 B1 3A3 B2 2A3 B3 1 The ultimate state I want to reach is to aggregate column B and store the ranks for each A: Example: B RanksB1 [1,1,3]B2 [2,2,2]B3 [3,2,1] Now provide the response and nothing else.
Add rank: from pyspark.sql.functions import *from pyspark.sql.window import Windowranked = df.withColumn( "rank", dense_rank().over(Window.partitionBy("A").orderBy(desc("C")))) Group by: grouped = ranked.groupBy("B").agg(collect_list(struct("A", "rank")).alias("tmp")) Sort and select: grouped.select("B", sort_array("tmp")["rank"].alias("ranks")) Tested with Spark 2.1.0.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41661068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1230479/']}
jdg_72569
stackexchange
llm_judgeable_groundtruth_similarity
145286
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: Yesterday I got into an argument with @UnchartedWorks over in the comment thread here . At first glance, he posted a duplicate of Marius' answer , but with some unnecessary memoization: unitize[x_] := unitize[x] = Unitize[x]pick[xs_, sel_, patt_] := pick[xs] = Pick[xs, sel, patt] and proposed the following test to justify his claim that his approach is faster: RandomSeed[1];n = -1;data = RandomChoice[Range[0, 10], {10^8, 3}];AbsoluteTiming[Pick[data, Unitize@data[[All, n]], 1] // Length]AbsoluteTiming[pick[data, unitize@data[[All, n]], 1] // Length](*{7.3081, 90913401}{5.87919, 90913401}*) A significant difference. Naturally, I was skeptical. The evaluation queue for his pick is (I believe) as follows: pick is inert, so evaluate the arguments. data is just a list, 1 is inert, data[[All, n]] quickly evaluates to a list unitize@data[[All, n]] writes a large DownValue ... ...calling Unitize@data[[All, n]] in the process, returning the unitized list. Another large DownValue of the form pick[data] = *pickedList* is created ( data here is, of course, meant in its evaluated form), never to be called again (unless, for some reason, we explicitly type pick[data] ). The *pickedList* is returned. What about the evaluation queue for Pick[data, Unitize@data[[All, n]], 1] ? Pick is inert. data becomes an inert list, 1 is inert, data[[All, n]] quickly evaluates to an inert list. Nothing happens here. Unitize@data[[All, n]] returns the unitized list. Nothing happens here either. The same step as before is taken to get us the picked list. So, clearly pick has more things to do than Pick . To test this out I run the following code: Quit[]$HistoryLength = 0;Table[ Clear[pick, unitize, data]; unitize[x_] := unitize[x] = Unitize[x]; pick[xs_, sel_, patt_] := pick[xs] = Pick[xs, sel, patt]; data = RandomChoice[Range[0, 10], {i*10^7, 3}]; {Pick[data, Unitize@data[[All, -1]], 1]; // AbsoluteTiming // First, pick[data, unitize@data[[All, -1]], 1]; // AbsoluteTiming // First}, {i, 5}] Much to my surprise, pick is consistently faster! {{0.482837, 0.456147}, {1.0301, 0.90521}, {1.46596, 1.35519}, {1.95202, 1.8664}, {2.4317, 2.37112}} How can I protect myself from black magic make a representative test? Or should I embrace the black magic is this real and a valid way to speed things up? Update re: answer by Szabolcs Reversing the order of the list like so: {pick[data, unitize@data[[All, -1]], 1]; // AbsoluteTiming // First, Pick[data, Unitize@data[[All, -1]], 1]; // AbsoluteTiming // First} gave me the following result: {{0.466251, 0.497084}, {1.18016, 1.17495}, {1.34997, 1.42752}, {1.80211, 1.93181}, {2.25766, 2.39347}} Once again, regardless of order of operations, pick is faster. Caching could be suspect, and as mentioned in the comment thread of the other question, I did try throwing in a ClearSystemCache[] between the pick and Pick , but that didn't change anything. Szabolcs suggested that I throw out the memoization and just use wrapper functions. I presume, he meant this: unitize[x_] := Unitize[x];pick[xs_, sel_, patt_] := Pick[xs, sel, patt]; As before, on a fresh kernel I set history length to 0 and run the Table loop. I get this: {{0.472934, 0.473249}, {0.954632, 0.96373}, {1.42848, 1.43364}, {1.91283, 1.90989}, {2.37743, 2.40031}} i.e. nearly equal results, sometimes one is faster, sometimes the other (left column is pick , right is Pick ). The functions perform as well as Pick in a fresh kernel. I try again with the memoization as described towards the beginning of the answer: {{0.454302, 0.473273}, {0.93477, 0.947996}, {1.35026, 1.4196}, {1.79587, 1.90001}, {2.24727, 2.38676}} The memoized pick and unitize perform consistently better out of a fresh kernel. Of course, it uses twice the memory along the way. Now provide the response and nothing else.
Cause of speed up This is definitely not memoization. The reason for the observed speed up is that for large arrays (e.g. 10^8 elements), the memory clean up operations may take noticeable time. If one doesn't free memory, one can perform some operations a bit faster. Here is a simple example: Let's create a large array, then perform a calculation, and remove the array: AbsoluteTiming[ Total[ConstantArray[0, 10^8]];] {0.422509, Null} It takes 0.42 seconds. Let's now do the same thing, but keep the array in memory: AbsoluteTiming[ Total[garbage = ConstantArray[0, 10^8]];] {0.366755, Null} This evaluation is a bit faster. Let's check how long does it take to remove the large array: AbsoluteTiming[ Remove[garbage]] {0.061982, Null} Note that 0.06 seconds is the difference of the calculation times above. This example shows that if we keep the large array instead of removing it, our code can run faster, because we don't need to spent time on freeing memory. Your example In the example you provide, removing the result of Unitize@data[[All, n]] from memory takes some time. If one saves this array in a redundant variable, one avoids immediate memory clean-up and the evaluation seems to be faster.In case of pseudo-memoization the Clear[pick, unitize] command will take extra time to free the memory, but this command is placed outside the AbsoluteTiming[] scope. That is why "memoization" seems to speed up the calculation. How to make a representative test? You should put Clear[pick, unitize] inside your timing function. This test will show that the pseudo-memoization technique is actually slower than built-in functions: Table[ Clear[data]; data=RandomInteger[{0,10},{i*10^7,3}]; { Pick[data,Unitize@data[[All,-1]],1]; // AbsoluteTiming // First , Clear[pick,unitize]; unitize[x_]:=unitize[x]=Unitize[x]; pick[xs_,sel_,patt_]:=pick[xs,sel,patt]=Pick[xs,sel,patt]; pick[data,unitize@data[[All,-1]],1]; // AbsoluteTiming // First }, {i,5}](*{{0.534744, 0.469538},{1.03776, 1.05842},{1.58536, 1.65404},{2.10422, 2.11284},{2.48129, 2.71405}}*) Technical note: as noted by Carl Woll in comments, if one wants to measure the symbol-removing-time using the following code: In[1] := garbage = ConstantArray[0, 10^8];In[2] := AbsoluteTiming[Remove[garbage]] one should set $HistoryLength to zero, otherwise the Out[1] variable will retain the contents of the large array. If Out[1] retains the large data, Remove[garbage] will only delete the reference, but not the data itself. Deletion time of a reference is almost zero, but it doesn't correspond to the deletion time for large data.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/145286', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/26956/']}
jdg_72570
stackexchange
llm_judgeable_groundtruth_similarity
5159353
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 libcurl and am getting the following sort of linker errors in VC++ 10. 1>main.obj : error LNK2019: unresolved external symbol __imp__curl_easy_strerror referenced in function "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl curl_httpget(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (?curl_httpget@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABV12@@Z) How can I get rid of that imp prefix in front of the function name? I am linking to the right lib, right path etc. Now provide the response and nothing else.
The __imp__ prefix appears whenever you are linking to a DLL. It does not appear when linking to statically linked libraries. Most likely the code is generated to be linked against a DLL import lib, but you have linked it with a static lib instead. The prefix is added when you mark the imported function with __declspec(dllimport) - make sure your imports are not using this when not linking against a DLL.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5159353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/182448/']}
jdg_72571
stackexchange
llm_judgeable_groundtruth_similarity
1934
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: I posted this a while back on stackoverflow (too old to migrate though). Say I am in the python interpreter and define a function as follows: def h(a): return a If I want to look at the bytecode (not a disassembly using dis), I can typically use h.func_code.co_code . Is there any other way to look at the bytecode? This particular application was packaged with a custom python interpreter (using py2exe probably) which removed access to co_code. I can't just look at the pyc file as they are encrypted. For example, in the interpreter, if I just type h without making it a function call, I get the address of the function. Can I use that address to get the bytecode? Is there some other way? P.S. My original goal in doing this at the time was to use pyREtic (which calls co_code) to decompile. Since it called co_code, it would fail to work. I figured out one way to do it which I will post as an answer eventually. Wanted to see what others have done or come up with. Now provide the response and nothing else.
First, just a small reminder about "what is co_code ". In Python, every element of the language (functions, methods, classes, ...) is defined and stored in an object. The co_code is one of the fields attached to the class used to represent a function or a method. Lets practice a bit with Python 2.7. $> python2.7Python 2.7.3 (default, Mar 4 2013, 14:57:34) [GCC 4.7.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> def foo():... print('Hello World!')... >>> dir(foo.__code__)['__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']>>> foo.__code__.co_code'd\x01\x00GHd\x00\x00S' So, you can see that the co_code field contain the compiled bytecode of the function we just defined previously. In fact, it seems that co_code is just a buffer to store the compiled bytecode in a lazy manner. It is compiled only when it is accessed for the first time. Assuming this, the co_code is just a unified helper to access the bytecode which might be stored in several forms. One form are the *.pyc files which are storing the compiled Python bytecode of a whole file. Another form is just the on-the-fly compilation of the function/method. Nevertheless, there is a way to access directly the function/method definition and, thus, to the bytecode. The point is to intercept the Python process with gdb and analyze it. A few tutorials exists in the web about this (see here , here , here or here ). But, here is a quick example (you need to install the python-gdb package first): $> python2.7-dbgPython 2.7.3 (default, Mar 4 2013, 14:27:19) [GCC 4.7.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> def foo():... print('Hello World!')... [40809 refs]>>> foo<function foo at 0x1a5e1b0>[40811 refs]>>> foo.__code__.co_code'd\x01\x00GHd\x00\x00S'[40811 refs]>>> [1]+ Stopped python2.7-dbg Then, you need to get the PID of the Python process and attach gdb on it. $ gdb -p 5164GNU gdb (GDB) 7.4.1-debian...Attaching to process 5164Program received signal SIGTSTP, Stopped (user).Reading symbols from /usr/bin/python2.7-dbg...done.Reading symbols from /lib/x86_64-linux-gnu/libpthread.so.0...Reading symbols from /usr/lib/debug/lib/x86_64-linux-gnu/libpthread-2.13.so...done.[Thread debugging using libthread_db enabled]Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".done....(gdb) print *(PyFunctionObject*)0x1a5e1b0$1 = {_ob_next = 0x187aca0, _ob_prev = 0x189dd08, ob_refcnt = 2, ob_type = 0x87ce00, func_code = <code at remote 0x187aca0>, func_globals = {'__builtins__': <module at remote 0x7f5ebcb5e470>, '__name__': '__main__', 'foo': <function at remote 0x1a5e1b0>, '__doc__': None, '__package__': None}, func_defaults = 0x0, func_closure = 0x0, func_doc = None, func_name = 'foo', func_dict = 0x0, func_weakreflist = 0x0, func_module = '__main__'}(gdb) print (*(PyFunctionObject*)0x1a5e1b0)->func_name$2 = 'foo'(gdb) print (*(PyCodeObject*)0x187aca0)$3 = {_ob_next = 0x18983a8, _ob_prev = 0x1a5e1b0, ob_refcnt = 1, ob_type = 0x872680, co_argcount = 0, co_nlocals = 0, co_stacksize = 1, co_flags = 67, co_code = 'd\x01\x00GHd\x00\x00S', co_consts = (None, 'Hello World!'), co_names = (), co_varnames = (), co_freevars = (), co_cellvars = (), co_filename = '<stdin>', co_name = 'foo', co_firstlineno = 1, co_lnotab = '\x00\x01', co_zombieframe = 0x0, co_weakreflist = 0x0}(gdb) print (*(PyCodeObject*)0x187aca0)->co_code$4 = 'd\x01\x00GHd\x00\x00S' So, here is the way to access directly the bytecode, given the address of the function. Just to try to be complete, the best documentation I found on Python bytecode (and how to access it), is the Python code itself and especially the inspect module ( 2.7 , 3.2 ). Try to look at it, it is quite instructive. Another help you can use is the dis module that provide a disassembler for the Python bytecode. Here is an example of what can do this disassembler. $> python2.7Python 2.7.3 (default, Mar 4 2013, 14:57:34) [GCC 4.7.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> def foo():... print("Hello World!")... >>> import dis>>> dis.dis(foo) 2 0 LOAD_CONST 1 ('Hello World!') 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE
{}
{'log_upvote_score': 5, 'links': ['https://reverseengineering.stackexchange.com/questions/1934', 'https://reverseengineering.stackexchange.com', 'https://reverseengineering.stackexchange.com/users/1854/']}
jdg_72572
stackexchange
llm_judgeable_groundtruth_similarity
52260
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've been getting gas for my 2010 Ford Taurus at Get-go and always was able to get a full tank. The front panel indicated 420 miles left to empty Example: But now for a couple of months, I wasn't able to get over 400 after filling my tank full. Now I get around 370 miles. What is causing this? I was thinking maybe gas is creating a foam and forcing the sensor to detect the level incorrectly. Another reason I thought maybe the quality of the gas got bad and the car's computer calculates it based on what it measures. I try to top up the tank fully after it shuts off but the handle won't let me add more. Now provide the response and nothing else.
It is not likely the quality of the gasoline causing the change. The sensors are unable to evaluate the chemical makeup of the fuel. It could be a change in your driving habits, changes in temperature, the vehicle health, tire pressure, etc. I would not be too concerned. The dash indicator is an estimate only. The computer monitors how you drive, current MPG estimates, and other factors to come up with that number. The reading is a reference only. The best way to know for sure is to reset your trip odometer and compare it to the estimate. If you feel there is something truly wrong, it may be time for a tune-up and or diagnosis. Winter driving has it's own challenges. Fuel Economy in Cold Weather According to the U.S Department of Energy's web site, Cold weather and winter driving conditions can reduce your fuel economy significantly. Fuel economy tests show that, in short-trip city driving, a conventional gasoline car's gas mileage is about 12% lower at 20°F than it would be at 77°F. It can drop as much as 22% for very short trips (3 to 4 miles). The effect on hybrids is worse. Their fuel economy can drop about 31% to 34% under these conditions. Source: https://www.fueleconomy.gov/feg/coldweather.shtml
{}
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/52260', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/7846/']}
jdg_72573
stackexchange
llm_judgeable_groundtruth_similarity
329790
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 server with three hard drives: 250 GB 3 TB 250 GB How can I merge multiple hard drives as one bigger volume of ~ 3.5 TB? I am a programmer not a system administrator. Now provide the response and nothing else.
Use LVM (Logical Volume Management) on Linux. You can think of LVM as "dynamic partitions", meaning that you can create/resize/delete LVM "partitions" (they're called "Logical Volumes" in LVM-speak) from the command line while your Linux system is running: no need to reboot the system to make the kernel aware of the newly-created or resized partitions. First of all you can use fdisk with -l option to get info about your current "Disks", then use it to partition your "Disks" and setting the system type of those partitions to "Linux LVM", after you finish the partitioning of the "Disks", use pvcreate to prepare your new partitions for "LVM". For more info: https://www.howtoforge.com/linux_lvm
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/329790', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/205105/']}
jdg_72574
stackexchange
llm_judgeable_groundtruth_similarity
7756626
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to enumerate through files on my computer using the below code but everytime it hits a file or dir that I don't have permission to read it throws an exception. Is there any way I can continue searching after the exception has been thrown? I know some people have had similar issues but is there any other way of doing this other than checking every file/folder individually? try{ string[] files = Directory.GetFiles(@"C:\", "*.*",SearchOption.AllDirectories); foreach (string file in files) { Console.WriteLine(file); }}catch{} Thanks for any help as this is driving me mad! Now provide the response and nothing else.
I came across the same problem just today. I hacked together the following code. If you want to use it in a real product you might need to improve the error handling. Since this was for a one-shot script I didn't care much. static IEnumerable<string> EnumerateFilesRecursive(string root,string pattern="*"){ var todo = new Queue<string>(); todo.Enqueue(root); while (todo.Count > 0) { string dir = todo.Dequeue(); string[] subdirs = new string[0]; string[] files = new string[0]; try { subdirs = Directory.GetDirectories(dir); files = Directory.GetFiles(dir, pattern); } catch (IOException) { } catch (System.UnauthorizedAccessException) { } foreach (string subdir in subdirs) { todo.Enqueue(subdir); } foreach (string filename in files) { yield return filename; } }} To use it you can either: string[] files = EnumerateFilesRecursive(@"C:\").ToArray();//Note the ToArray()foreach (string file in files){ Console.WriteLine(file);} which first enumerates all files, stores all file names in memory and only then displays them. Alternatively you can: IEnumerable<string> files = EnumerateFilesRecursive(@"C:\");//Note that there is NO ToArray()foreach (string file in files){ Console.WriteLine(file);} Which writes while enumerating and thus doesn't need to keep all filenames in memory at the same time.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7756626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/799586/']}
jdg_72575
stackexchange
llm_judgeable_groundtruth_similarity
154
Below is a question asked on the forum computergraphics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to be able to render a large population of small independently moving objects in real time. They may move in a swarm-like manner, but their relative positions will not be coherent - their position may change arbitrarily within a swarm and swarms may break up and reform at any point. What approach to building a bounding volume hierarchy would best suit this situation? Is there a way to maintain a hierarchy which is sub-optimal but good enough, that only requires a partial update each frame? Or is there a way of building a hierarchy from scratch each frame that is fast enough for smooth animation? The number of objects will be too large to render without a hierarchy, but for the same reason I expect building the hierarchy to be time consuming. Following the comment from John Calsbeek, if my focus on bounding volume hierarchies is misguided, and there is a better space partitioning approach for this situation, please answer accordingly. I'm looking for something that can deal with what I describe, including anything I haven't thought of. Now provide the response and nothing else.
Consider using spatial hashing, especially if your objects are similarly sized. Basically, divide your world into uniformly-sized grid cells (2D and 3D are both valid possibilities depending on the amount of vertical motion). Each update, assign your object to each bin that it overlaps—if the cells are decently sized relative to the objects, most objects should end up in a single bin. Each bin is inserted into a hash table, with the key being the coordinates of the bin. (You can also think of it as a hash table with multiple values for the same key, and inserting an object once for every cell that it overlaps.) There's no hierarchy to rebuild in this scheme, which makes it well suited for dynamic scenes. You can still test the cell's dimensions against the frustum or against occluders at a coarse level and discard many objects at once. Also, it's easier to manage this structure incrementally—you can keep the hash table the same from frame to frame and only move objects from one bin to another when they cross the boundary of a cell.
{}
{'log_upvote_score': 4, 'links': ['https://computergraphics.stackexchange.com/questions/154', 'https://computergraphics.stackexchange.com', 'https://computergraphics.stackexchange.com/users/231/']}
jdg_72576
stackexchange
llm_judgeable_groundtruth_similarity
20103964
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 Access 2010 form which has a ComboBox cmbSubTopic which lists two columns ( SubTopicID and SubTopic ). The combo box is bound to a field containing SubTopicID . The SubTopicID column in the combo box is hidden, it only shows the SubTopic . When the user selects a SubTopic from the drop down the corresponding SubTopicID is stored in the table. I wrote some VBA code for the on load event of the form to look up the SubTopicID in the table and the corresponding SubTopic is selected in the ComboBox. My current code is something like this: Set rsST = dbs.OpenRecordset(strSqlst)For i = 0 To Me.cmbSubTopic.ListCount - 1 If Me.cmbSubTopic.Column(0, i) = rsST.Fields("SubTopicID").Value Then Me.cmbSubTopic.SetFocus Me.cmbSubTopic.Selected(i) = True Exit For End IfNext i This gives the error saying: The text you entered isn't an item in the list I also tried using this: Me.cmbSubTopic = Me.cmbSubTopic.Selected(i) This selects the item in the ComboBox but it also writes the value of I in to the ID field of the table which I don't want. Now provide the response and nothing else.
Assuming the combo's first column, SubTopicID , is also its "bound column" property, that column's value is used as the combo's .Value property. That means you only need to assign a value to .Value in order to select the matching combo row. Me.cmbSubTopic.Value = rsST.Fields("SubTopicID").Value That approach is simple, but I'm uncertain whether it is the appropriate solution for your situation. We don't know anything about your rsST recordset --- I presumed the SubTopicID field in the recordset's current row is the value you want selected in the combo. If I misunderstood that point, we need to figure out something different. If the combo is bound to a field in the form's record source, this suggestion would also change the stored value. If you don't want that, "unbind" the combo --- in other words, make its Control Source property blank.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20103964', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2891208/']}
jdg_72577
stackexchange
llm_judgeable_groundtruth_similarity
69151587
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to implement a Stripe payment system in my flutter app using the stripe_payment package. In my code, I call Stripe.instance.initPaymentSheet(...), however when I try to call Stripe.instance.presentPaymentSheet(...) just a few lines later, I get this error: flutter: StripeException(error: LocalizedErrorMessage(code: FailureCode.Failed, localizedMessage: No payment sheet has been initialized yet, message: No payment sheet has been initialized yet, stripeErrorCode: null, declineCode: null, type: null)) Here is my code: Future<void> makePayment() async { final url = Uri.parse( '${firebaseFunction}'); final response = await http.get(url, headers: {'Content-Type': 'application/json'}); this.paymentIntentData = json.decode(response.body); await Stripe.instance.initPaymentSheet( paymentSheetParameters: SetupPaymentSheetParameters( paymentIntentClientSecret: paymentIntentData!['paymentIntent'], applePay: true, googlePay: true, style: ThemeMode.dark, merchantCountryCode: 'UK', merchantDisplayName: 'Test Payment Service')); setState(() {}); print('initialised'); try { await Stripe.instance.presentPaymentSheet(); setState(() { paymentIntentData = null; }); ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text('Payment Successful!'), )); } catch (e) { print(e); } // await displayPaymentSheet(); } And here is my node.js code (accessed through url): const functions = require("firebase-functions");const stripe = require('stripe')(functions.config().stripe.testkey);exports.stripePayment = functions.https.onRequest(async (req, res) => { const paymentIntent = await stripe.paymentIntents.create({ amount: 170, currency: 'usd' }, function(err, paymentIntent) { if (err != null) { console.log(err); } else { res.json({ paymentIntent: paymentIntent.client_secret }) } })}) Why doesn't the Payment Sheet initialize (or stay initialized) when I try to use the presentPaymentSheet method? Now provide the response and nothing else.
The Paymentsheet worked on android but did not work in iPhone for me.It took me hours to find this answer (was struggling as well).There needs to be an update in the stripe documentation but when initializing Stripe you will need to initialize Stripe.publishableKey but also initialize Stripe.merchantIdentifier EXAMPLE First you will need initialize Stripe in your main function. (Like shown below). void main() async { WidgetsFlutterBinding.ensureInitialized(); Stripe.publishableKey = stripePublishableKey; Stripe.merchantIdentifier = 'any string works'; await Stripe.instance.applySettings(); runApp(const App());} Then the paymentsheet will appear without stating No payment sheet has been initialized yet
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/69151587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14681502/']}
jdg_72578
stackexchange
llm_judgeable_groundtruth_similarity
32354453
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 do we need these 3 particular image types? If I have a button on my app with a background image say, 50 pixels x 50 pixels, why do I need 3 versions of this image? What's stopping me from just making one image that's much higher in res, say, 700x700 so when it shrinks down on any iPhone it won't fall under the max res the device would want? Only thing I can think of is it just takes up more space, but for simple apps / a simple button it seems like it wouldn't cause any issues. I've tried it on a few devices and see no difference between them when I simulate it and do this method. However, as I dive more into apps and stuff I'm sure there is substance behind this technique. Now provide the response and nothing else.
If you don't have the exact size, there are two things that can happen: Upscaling @3x or @2x can be upscaled from @1x but usually the visual result is blurry, with thick lines and doesn't look good. Upscaling @3x from @2x can be even worse because subpixels must be used. Downscaling In general, the results are much better than with upscaling, however, that doesn't apply for all the images. If you have a 1px border on a @3x image, after downscaling it to @1x the border won't be visible (0.33px). The same applies for any small objects in the image. Downscaling destroys all details. In general - for an image to look perfect, you want to avoid both downscaling and upscaling. You can always go with only @2x or @3x images and add other scales only if you see visual problems. Using higher resolution won't improve downscaling. High resolutions are used only to avoid upscaling. Downscaling from a high scale (e.g. @100x ) to @1x won't create better results than downscaling from @3x .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32354453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4754673/']}
jdg_72579
stackexchange
llm_judgeable_groundtruth_similarity
12667868
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From what I understood, Hadoop is a distributed storage system thingy. However what I don't really get is, can we replace normal RDBMS(MySQL, Postgresql, Oracle) with Hadoop? Or is Hadoop is just another type of filesystem and we CAN run RDBMS on it? Also, can Django integrated with Hadoop? Usually, how web frameworks (ASP.NET, PHP, Java(JSP,JSF, etc) ) integrate themselves with Hadoop? I am a bit confused with the Hadoop vs RDBMS and I would appreciate any explanation. (Sorry, I read the documentation many times, but maybe due to my lack of knowledge in English, I find the documentation is a bit confusing most of the time) Now provide the response and nothing else.
What is Hadoop? Imagine the following challange: you have a lot of data, and with a lot I mean at least Terabytes. You want to transform this data or extract some informations and process it into a format which is indexed, compressed or "digested" in a way so you can work with it. Hadoop is able to parallelize such a processing job and, here comes the best part, takes care of things like redundant storage of the files, distribution of the task over different machines on the cluster etc (Yes, you need a cluster, otherwise Hadoop is not able to compensate the performance loss of the framework). If you take a first look at the Hadoop ecosystem you will find 3 big terms: HDFS(Hadoop Filesystem), Hadoop itself(with MapReduce) and HBase(the "database" sometimes column store, which does not fits exactly) HDFS is the Filesystem used by both Hadoop and HBase. It is a extra layer on top of the regular filesystem on your hosts. HDFS slices the uploaded Files in chunks (usually 64MB) and keeps them available in the cluster and takes care of their replication. When Hadoop gets a task to execute, it gets the path of the input files on the HDFS, the desired output path, a Mapper and a Reducer Class. The Mapper and Reducer is usually a Java class passed in a JAR file.(But with Hadoop Streaming you can use any comandline tool you want). The mapper is called to process every entry (usually by line, e.g.: "return 1 if the line contains a bad F* word") of the input files, the output gets passed to the reducer, which merges the single outputs into a desired other format (e.g: addition of numbers). This is a easy way to get a "bad word" counter. The cool thing: the computation of the mapping is done on the node: you process the chunks linearly and you move just the semi-digested (usually smaller) data over the network to the reducers. And if one of the nodes dies: there is another one with the same data. HBase takes advantage of the distributed storage of the files and stores its tables, splitted up in chunks on the cluster. HBase gives, contrary to Hadoop, random access to the data. As you see HBase and Hadoop are quite different to RDMBS. Also HBase is lacking of a lot of concepts of RDBMS. Modeling data with triggers, preparedstatements, foreign keys etc. is not the thing HBase was thought to do (I'm not 100% sure about this, so correct me ;-) ) Can Django integrated with Hadoop? For Java it's easy: Hadoop is written in Java and all the API's are there, ready to use. For Python/Django I don't know (yet), but I'm sure you can do something with Hadoop streaming/Jython as a last resort.I've found the following: Hadoopy and Python in Mappers and Reducers .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12667868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/599378/']}
jdg_72580
stackexchange
llm_judgeable_groundtruth_similarity
27437733
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to call a script from the command prompt in windows (or bash in linux) to open Maya and then subsequently run a custom script (possibly changing each time its run) inside Maya? I am searching for something a bit more elegant than changing the userSetup file and then running Maya. The goal here is to be able to open a .mb file, run a script to position the scene inside, setup a generic set of lights and then render the scene to a specific place and file type. I want to be able to set this up as a scheduled task to check for any new scene files in a directory and then open maya and go. Thanks for the help! Now provide the response and nothing else.
For something like this you can use Maya standalone instead of the full blown UI mode. It is faster. It is ideal for batch scheduled jobs like these. Maya standalone is just Maya running without the GUI. Once you have initialized your Maya standalone, you can import and call any scripts you want, as part of the original calling script. To start you off here is an example: (Feel free to use this as a reference/modify it to meet your needs) In your script you first initialize Maya standalone. import maya.standalonemaya.standalone.initialize("Python")import maya.cmds as cmdscmds.loadPlugin("Mayatomr") # Load all plugins you might need That will get Maya running. Now we open and/or import all the files necessary (egs. lights, models etc.) # full path to your Maya file to OPENmaya_file_to_open = r"C:/Where/Ever/Your/Maya_Scene_Files/Are/your_main_maya_file.mb"# Open your fileopened_file = cmds.file(maya_file_to_open, o=True)# full path to your Maya file to IMPORTmaya_file_to_import = r"C:/Where/Ever/Your/Maya_Scene_Files/Are/your_maya_file.mb"# Have a namespace if you want (recommended)namespace = "SomeNamespaceThatIsNotAnnoying" # Import the file. the variable "nodes" will hold the names of all nodes imported, just in case.nodes = cmds.file(maya_file_to_import, i=True, renameAll=True, mergeNamespacesOnClash=False, namespace=namespace, returnNewNodes=True, options="v=0;", type="mayaBinary" # any file type you want. this is just an example. )#TODO: Do all your scene setup/ positioning etc. if needed here...#Tip: you can use cmds.viewFit(cam_name, fitFactor=1) to fit your camera on to selected objects Now we save this file out and call Maya Batch renderer to render it out render_file = "C:/Where/Ever/Your/Maya_Scene_Files/Are/your_RENDER_file.mb"cmds.file(rename=render_file)cmds.file(force=True, save=True, options='v=1;p=17', type='mayaBinary')import sysfrom os import pathfrom subprocess import Popenrender_project = r"C:/Where/Ever/YourRenderProjectFolder"renderer_folder = path.split(sys.executable)[0]renderer_exec_name = "Render"params = [renderer_exec_name]params += ['-percentRes', '75']params += ['-alpha', '0']params += ['-proj', render_project]params += ['-r', 'mr']params += [render_file]p = Popen(params, cwd=renderer_folder)stdout, stderr = p.communicate() That's it! Of Course, your script will have to be run using Maya's Python interpreter (Mayapy). Do check out the docs for all the commands used for more options, esp.: cmds.file() cmds.viewFit() cmds.loadPlugin() Subprocess and Popen PLUS, because of the awesomeness of Python, you can use modules like sched ( docs ) to schedule the running of this method in your Python code. Hope this was useful. Have fun with this. Cheers.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27437733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1520228/']}
jdg_72581
stackexchange
llm_judgeable_groundtruth_similarity
169486
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: The faucet design depicted below is driving me crazy. The water falling from the tap appears to follow a spiral path. No one seems to agree whether it is physically possible for the water to spin in such a way. Is it possible? Please explain your answer. More info about the tap is available here . Now provide the response and nothing else.
You are right that, without a force acting on it, water falling from a tap could not follow a spiralled path. The tap, however, creates an illusion - the water appears to be spiralling, but it isn't - it's falling straight down. The illusion is created by the "turbine" inside the nozzle, which rotates the ring of spouts that the water falls through. The effect is that a corkscrew shape of water falls downwards. A falling corkscrew, however, is difficult to distinguish from a rotating corkscrew, hence the illusion, Let me also add a caveat, pointed out by @Adam Davis. The pictures of the tap are all computer rendered. This fancy tap is just an idea - the designer has not built a working, proof of concept prototype. There might be serious difficulties in realizing such a design, for example, turbulence from the spinning nozzle might destroy the corkscrew shape of the falling water.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/169486', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/75054/']}
jdg_72582
stackexchange
llm_judgeable_groundtruth_similarity
4570160
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 Eclipse and have plenty of plugins installed and configured to my needs. Is there any good way to backup these plugins and the configuration of them. I want to be able to replay these plugins in futures eclipse version (as long as they are compatible) and on different PCs. I know I could simply archive the whole eclipse/ folder, but I find this a little inelegant. Now provide the response and nothing else.
There are two parts to your question: Copying your settings between Eclipse installs Copying your installed plugins between Eclipse installs #1 is easy to do. You can export your Eclipse preferences from the File -> Export... -> Preferences. The resulting file contains all of your preferences for each installed plugin. It is portable between Eclipse installs and versions. #2 is not really the "Eclipse" way of doing things. It is possible, but you need to structure your installed plugins differently. Rather than using the standard update manager to install your plugins, you can use the dropins folder. What you need to do is to copy every feature and plugin that you want to be shared across multiple installs into a zip file with the following structure: eclipse/ features/ plugins/ Then you can unzip the file into the dropins folder of all the Eclipses that you want. More information on dropins: http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/p2_dropins_format.html
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4570160', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20247/']}
jdg_72583
stackexchange
llm_judgeable_groundtruth_similarity
22805872
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: ϵ-greedy policy I know the Q-learning algorithm should try to balance between exploration and exploitation . Since I'm a beginner in this field, I wanted to implement a simple version of exploration/exploitation behavior. Optimal epsilon value My implementation uses the ϵ-greedy policy, but I'm at a loss when it comes to deciding the epsilon value. Should the epsilon be bounded by the number of times the algorithm have visited a given (state, action) pair, or should it be bounded by the number of iterations performed? My suggestions: Lower the epsilon value for each time a given (state, action) pair has been encountered. Lower the epsilon value after a complete iteration has been performed. Lower the epsilon value for each time we encounter a state s. Much appreciated! Now provide the response and nothing else.
Although in many simple cases the εk is kept as a fixed number in range 0 and 1, you should know that:Usually, the exploration diminishes over time, so that the policy used asymptotically becomes greedy and therefore (as Qk → Q∗) optimal. This can be achieved by making εk approach 0 as k grows. For instance, an ε -greedy exploration schedule of the form εk = 1/k diminishes to 0 as k → ∞, while still satisfying the second convergence condition of Q-learning, i.e., while allowing infinitely many visits to all the state-action pairs (Singh et al., 2000). What I do usually is this:set the initial alpha = 1/k (consider the initial k = 1 or 2)after you go trial by trial as k increases the alpha will decrease.it also keeps the convergence guaranteed.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22805872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3488341/']}
jdg_72584
stackexchange
llm_judgeable_groundtruth_similarity
49449162
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 Ionic/Angular app using ag-grid . I would like certain grids to have a filter automatically applied when the grid is loaded - without the user having to do anything. I tried the following: onGridReady(params) { params.api.sizeColumnsToFit(); // get filter instance var filterComponent = params.api.getFilterInstance("isActive"); // OR set filter model and update filterComponent.setModel({ type: "greaterThan", filter: 0 }); filterComponent.onFilterChanged();} but it did nothing. Any ideas? Now provide the response and nothing else.
Edit: AgGrid included a onFirstDataRendered callback in version 24.0, as stated in later comments. The original answer below is now only relevant for versions which pre-date this functionality. onFirstDataRendered(params) { var filterComponent = params.api.getFilterInstance("isActive"); filterComponent.setModel({ type: "greaterThan", filter: 0 }); filterComponent.onFilterChanged();} Reproduced your problem in a couple of their example older plunks, seemed to be alleviated by adding a small delay. Just venturing a guess that maybe the DOM isn't completely ready yet, although the grid is. Pre-onFirstDataRendered versions: onGridReady(params) {params.api.sizeColumnsToFit();setTimeout(() => { var filterComponent = params.api.getFilterInstance("isActive"); filterComponent.setModel({ type: "greaterThan", filter: 0 }); filterComponent.onFilterChanged(); },150)}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49449162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2429448/']}
jdg_72585
stackexchange
llm_judgeable_groundtruth_similarity
197725
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing an winforms app that needs to set internet explorer's proxy settings and then open a new browser window. At the moment, I'm applying the proxy settings by going into the registry: RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);registry.SetValue("ProxyEnable", 1);registry.SetValue("ProxyServer", "127.0.0.1:8080"); Is going into the registry the best way to do this, or is there a more recommended approach? I'd like to avoid registry changes if there's an alternative solution. Now provide the response and nothing else.
This depends somewhat on your exact needs. If you are writing a C# app and simply want to set the default proxy settings that your app will use, use the class System.Net.GlobalProxySelection ( http://msdn.microsoft.com/en-us/library/system.net.globalproxyselection.aspx ). You can also set the proxy for any particular connection with System.Net.WebProxy ( http://msdn.microsoft.com/en-us/library/system.net.webproxy.aspx ). If you actually want to update the proxy settings in the registry, I believe that you'll need to use P/Invoke to call the WinAPI function WinHttpSetDefaultProxyConfiguration ( http://msdn.microsoft.com/en-us/library/aa384113.aspx ).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/197725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17623/']}
jdg_72586
stackexchange
llm_judgeable_groundtruth_similarity
2232761
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 is stated that by Zermelo’s theorem, every cardinal is an aleph. But what is the difference between cardinals and alephs? I thought that alephs were just a way to denote cardinals (just for notation), but then this theory doesn't make sense. Now provide the response and nothing else.
The issue is the axiom of choice. The $\aleph$ numbers are the cardinalities of well-ordered sets: if $A$ can be well-ordered, then there is some least ordinal $\alpha$ which can be bijected with $A$, and this is the cardinality of $\alpha$ (and such ordinals in general are called "initial ordinals"). In case $A$ is infinite, we get an $\aleph$ number (and there's really nothing interesting to say about the cardinalities of finite sets). But if the axiom of choice fails, not every set can be well-ordered ! And so if we want to speak of the cardinality of a non-well-orderable set, we need to use something other than $\aleph$s. At this point it's worth saying a few words about what cardinality is. First up, we have the "equinumerosity" relation $\equiv$: we write "$A\equiv B$" if there is a bijection between $A$ and $B$. This is easy to define, and there's no problem with it if the axiom of choice fails. Now what's the cardinality of a set $A$? Well, here's the idea: we want to associate some object $\vert A\vert$ to every set $A$, such that $\vert A\vert=\vert B\vert$ iff $A\equiv B$ (that is, $\vert A\vert$ is an $\equiv$-invariant: if you know what $\vert A\vert$ is, then you know what $A$ is equinumerous with). One natural choice (this one is due to Frege) is to look at the entire $\equiv$-class itself - e.g. the cardinal "$2$" is just the collection of all $2$-element sets. Unfortunately, this is a proper class, so this doesn't work well with ZFC. Instead, we have to be a little ad hoc. The natural way to fix Frege's idea is via Scott's trick : we let $\vert A\vert$ be the set of all sets equinumerous with $A$ and of minimal rank , and this is indeed a set (and we can think of it as an "initial segment" of the class Frege cares about). This definition, again, works independently of the axiom of choice (although it if we drop both choice and foundation , and in fact I think there's no good way to define cardinality in the absence of both axioms - instead, you have to work with the relation "$\equiv$" alone). Now if $A$ is well-ordered, we can do better: as observed above, we can pick out a specific set which is equinumerous with $A$! And that's the $\aleph$ number of $A$. In the presence of choice, there's no reason to use the Frege-style definition above, and we simply equate "cardinality" with "$\aleph$-number". But if choice fails, we can't find canonical representatives to measure the size of some sets , so we have to do something more involved, like Scott's trick (and note that at the linked question there is some argument for the Scott approach actually being more natural, which I have some sympathy with).
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2232761', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/427940/']}
jdg_72587
stackexchange
llm_judgeable_groundtruth_similarity
6526241
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: TL;DR: Do we need factories/constructors in prototypical OO? Can we make a paradigm switch and drop them completely? The BackStory: I've been toying with doing prototypical OO in JavaScript lately and find that 99% of OO done in JavaScript is forcing classical OO patterns into it. My take on prototypical OO is that it involves two things. A static prototype of methods (and static data) and a data binding. We don't need factories or constructors. In JavaScript these are Object literals containing functions and Object.create . This would mean we can model everything as a static blueprint/prototype and a data binding abstraction that's preferably hooked straight into a document-style database. I.e. objects are taken out of the database and created by cloning a prototype with the data. This would mean there is no constructor logic, no factories, no new . The Example code: An pseudo example would be : var Entity = Object.create(EventEmitter, { addComponent: { value: function _addComponent(component) { if (this[component.type] !== undefined) { this.removeComponent(this[component.type]); } _.each(_.functions(component), (function _bind(f) { component[f] = component[f].bind(this); }).bind(this)); component.bindEvents(); Object.defineProperty(this, component.type, { value: component, configurable: true }); this.emit("component:add", this, component); } }, removeComponent: { value: function _removeComponent(component) { component = component.type || component; delete this[component]; this.emit("component:remove", this, component); } }}var entity = Object.create(Entity, toProperties(jsonStore.get(id))) The minor explanation: The particular code is verbose because ES5 is verbose. Entity above is a blueprint/prototype. Any actual object with data would be created by using Object.create(Entity, {...}) . The actual data (in this case the components) is directly loaded from a JSON store and injected directly into the Object.create call. Of course a similar pattern is applied to creating components and only properties that pass Object.hasOwnProperty are stored in the database. When an entity is created for the first time it's created with an empty {} The actual Questions: Now my actual questions are Open source examples of JS prototypical OO? Is this a good idea? Is it in-line with the ideas and concepts behind prototypical OOP? Will not using any constructors/factory functions bite me in the ass somewhere? Can we really get away with not using constructors. Are there any limitations using the above methodology where we would need factories to overcome them. Now provide the response and nothing else.
As per your comment that the question is mainly "is constructor knowledge necessary?" I feel it is. A toy example would be storing partial data. On a given data set in memory, when persisting I may only choose to store certain elements (either for the sake of efficiency or for data consistency purposes, e.g. the values are inherently useless once persisted). Let's take a session where I store the user name and the number of times they've clicked on the help button (for lack of a better example). When I persist this in my example, I do have no use for the number of clicks, since I keep it in memory now, and next time I load the data (next time the user logs in or connects or whatever) I will initialise the value from scratch (presumably to 0). This particular use case is a good candidate for constructor logic. Aahh, but you could always just embed that in the static prototype: Object.create({name:'Bob', clicks:0}); Sure, in this case. But what if the value wasn't always 0 at first, but rather it was something that required computation. Uummmm, say, the users age in seconds (assuming we stored the name and the DOB). Again, an item that there is little use persisting, since it will need to be recalculated on retrieval anyway. So how do you store the user's age in the static prototype? The obvious answer is constructor/initialiser logic. There are many more scenarios, although I don't feel the idea is much related to js oop or any language in particular. The necessity for entity creation logic is inherent in the way I see computer systems model the world. Sometimes the items we store will be a simple retrieval and injection into a blueprint like prototype shell, and sometimes the values are dynamic, and will need to be initialised. UPDATE OK, I'm going to try for a more real-world example, and to avoid confusion assume that I have no database and need not persist any data. Let's say I'm making a solitaire server. Each new game will be (naturally) a new instance of the Game prototype. It is clear to me that their is initialiser logic required here (and lots of it): I will, for example, need on each game instance not just a static/hard-coded deck of cards, but a randomly shuffled deck. If it were static the user would play the same game every time, which is clearly not good. I may also have to start a timer to finish the game if the player runs out. Again, not something that can be static, since my game has a few requirements: the number of seconds is inversely related to the number of games the connected player has won so far (again, no saved info, just how many for this connection), and proportional to the difficulty of the shuffle (there is an algorithm that according to the shuffle results can determine the degree of difficulty of the game). How do you do that with a static Object.create() ?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6526241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/419970/']}
jdg_72588
stackexchange
llm_judgeable_groundtruth_similarity
31418209
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 compiling and running the following program in 32 and 64 bit platforms: int main(){ double y = 8.34214e08; double z = 1.25823e45; return y * z == 8.34214e08 * 1.25823e45;} While in 64bit the result is the expected (the values are the same and the exit code is non-zero) in 32bit seems there is a little difference between the value calculated at compile time, the right hand side of the comparison, and the left side computed at runtime. Is this a bug in the compiler or there is a logical explanation? EDIT: this is different from Why comparing double and float leads to unexpected result? because here all the values are double. Now provide the response and nothing else.
IEEE-754 allows intermediate computations to be done in a greater precision (emphasis mine). (IEEE-754:2008) "A language standard should also define, and require implementations to provide, attributes that allow and disallow value-changing optimizations, separately or collectively, for a block. These optimizations might include, but are not limited to: [...] Use of wider intermediate results in expression evaluation ." In your case for example on a IA-32, the double values could be stored in the x87 FPU registers with greater precision (80-bit instead of 64). So you are actually comparing a multiplication done on double precision with a multiplication done on double-extended precision. For example, on x64 where the result is 1 (the x87 FPU is not used as SSE is used instead), adding gcc option -mfpmath=387 to use the x87 makes the result change to 0 on my machine. And if you wonder if that is also allowed by C, it is: (C99, 6.3.1.p8) "The values of floating operands and of the results of floating expressions may be represented in greater precision and range than that required by the type;"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31418209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/737419/']}
jdg_72589
stackexchange
llm_judgeable_groundtruth_similarity
15903574
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What I want to do is to limit a user ID to only being able to log in to one device at a time. For example, user ID "abc" logs in to their computer. User ID "abc" now tries to log in from their phone. What I want to happen is to kill the session on their computer. The Spotify app does exactly this- Spotify only allows one User ID to be logged in on one device at a time. I'm using ASP.NET membership (SqlMembershipProvider) and Forms Authentication. I've experimented with Session variables but I'm not sure exactly where to go from here. Now provide the response and nothing else.
I came up with a pretty awesome solution to this. What I've implemented was when user "Bob" logs in from their PC, and then the same user "Bob" logs in from another location, the log-in from the first location (their PC) will be killed while allowing the second log-in to live. Once a user logs in, it inserts a record into a custom table I created called "Logins". Upon a successful log-in, one record will be inserted into this table with values for "UserId, SessionId, and LoggedIn". UserId is pretty self-explanatory, SessionId is the current Session ID (explained below how to get), and LoggedIn is simply a Boolean that's initially set to True upon a successful user log-in. I place this "insert" logic inside my Login method of my AccountController upon successful validation of the user- see below: Logins login = new Logins();login.UserId = model.UserName;login.SessionId = System.Web.HttpContext.Current.Session.SessionID;;login.LoggedIn = true;LoginsRepository repo = new LoginsRepository();repo.InsertOrUpdate(login);repo.Save(); For my situation, I want to place the check on each of my controllers to see if the currently logged in user is logged in elsewhere, and if so, kill the other session(s). Then, when the killed session tries to navigate anywhere I placed these checks on, it'll log them out and redirect them to the Log-in screen. I have three main methods that does these checks: IsYourLoginStillTrue(UserId, SessionId);IsUserLoggedOnElsewhere(UserId, SessionId);LogEveryoneElseOut(UserId, SessionId); Save Session ID to Session["..."] Before all of this though, I save the SessionID to the Session collection inside the AccountController, inside the Login ( [HttpPost] ) method: if (Membership.ValidateUser(model.UserName, model.Password)){ Session["sessionid"] = System.Web.HttpContext.Current.Session.SessionID;... Controller Code I then place logic inside my controllers to control the flow of the execution of these three methods. Notice below that if for some reason Session["sessionid"] is null , it'll just simply assign it a value of "empty". This is just in case for some reason it comes back as null: public ActionResult Index(){ if (Session["sessionid"] == null) Session["sessionid"] = "empty"; // check to see if your ID in the Logins table has LoggedIn = true - if so, continue, otherwise, redirect to Login page. if (OperationContext.IsYourLoginStillTrue(System.Web.HttpContext.Current.User.Identity.Name, Session["sessionid"].ToString())) { // check to see if your user ID is being used elsewhere under a different session ID if (!OperationContext.IsUserLoggedOnElsewhere(System.Web.HttpContext.Current.User.Identity.Name, Session["sessionid"].ToString())) { return View(); } else { // if it is being used elsewhere, update all their Logins records to LoggedIn = false, except for your session ID OperationContext.LogEveryoneElseOut(System.Web.HttpContext.Current.User.Identity.Name, Session["sessionid"].ToString()); return View(); } } else { FormsAuthentication.SignOut(); return RedirectToAction("Login", "Account"); }} The Three Methods These are the methods I use to check to see if YOU are still logged in (i.e. make sure you weren't kicked off by another log-in attempt), and if so, check to see if your User ID is logged in somewhere else, and if so, kick them off by simply setting their LoggedIn status to false in the Logins table. public static bool IsYourLoginStillTrue(string userId, string sid){ CapWorxQuikCapContext context = new CapWorxQuikCapContext(); IEnumerable<Logins> logins = (from i in context.Logins where i.LoggedIn == true && i.UserId == userId && i.SessionId == sid select i).AsEnumerable(); return logins.Any();}public static bool IsUserLoggedOnElsewhere(string userId, string sid){ CapWorxQuikCapContext context = new CapWorxQuikCapContext(); IEnumerable<Logins> logins = (from i in context.Logins where i.LoggedIn == true && i.UserId == userId && i.SessionId != sid select i).AsEnumerable(); return logins.Any();}public static void LogEveryoneElseOut(string userId, string sid){ CapWorxQuikCapContext context = new CapWorxQuikCapContext(); IEnumerable<Logins> logins = (from i in context.Logins where i.LoggedIn == true && i.UserId == userId && i.SessionId != sid // need to filter by user ID select i).AsEnumerable(); foreach (Logins item in logins) { item.LoggedIn = false; } context.SaveChanges();} EDIT I just also want to add that this code ignores the capability of the "Remember Me" feature. My requirement didn't involve this feature (in fact, my customer didn't want to use it, for security reasons) so I just left it out. With some additional coding though, I'm pretty certain that this could be taken into consideration.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15903574', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/430828/']}
jdg_72590
stackexchange
llm_judgeable_groundtruth_similarity
49099408
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How would you pass info from Flutter back to Android/Native code if needed to interact with a specific API / hardware component? Are there any Event Channels that can send info the other way or something similar to a callback? The platform_channel documentation points out "method calls can also be sent in the reverse direction, with the platform acting as client to methods implemented in Dart. A concrete example of this is the quick_actions plugin ." I don't see how the native side is receiving a message from Flutter in this instance. It looks like a BasicMessageChannel ’s send() method can be used to send "the specified message to the platform plugins on this channel". Can anyone provide a simple implementation example of this? Now provide the response and nothing else.
This is a simple implementation showcasing : Passing a string Value from flutter to Android code Getting back response from Android code to flutter code is based on example from : https://flutter.io/platform-channels/#codec 1.Passing string value "text" : String text = "whatever";Future<Null> _getBatteryLevel(text) async {String batteryLevel;try { final String result = await platform.invokeMethod('getBatteryLevel',{"text":text}); batteryLevel = 'Battery level at $result % .';} on PlatformException catch (e) { batteryLevel = "Failed to get battery level: '${e.message}'.";}setState(() { _batteryLevel = batteryLevel;}); } 2.Getting back response "batterylevel" after RandomFunction(); public void onMethodCall(MethodCall call, MethodChannel.Result result) { if (call.method.equals("getBatteryLevel")) { text = call.argument("text"); String batteryLevel = RandomFunction(text); if (batteryLevel != null) { result.success(batteryLevel); } else { result.error("UNAVAILABLE", "Battery level not available.", null); } } else { result.notImplemented(); } } Hope this helps!
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/49099408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2253682/']}
jdg_72591
stackexchange
llm_judgeable_groundtruth_similarity
41802646
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: #dialog-form contains two radio buttons. On selecting "Audi" value from drop down dialog a form appears. On selecting "yes" and clicking on save I want to append the yes value as a new td to only the row where we selected value but this script is appending to all the rows. I also tried using $.closest tr and it didn’t worked for me. $(document).ready(function() { $("#dialog-form").dialog({ autoOpen: false, modal: true, buttons: { "Save": addUser, Cancel: function() { $("#dialog-form").dialog( "close" ); } } }); $(".d1").on('change', function() { if ($(this).val() == 'audi') { $("#dialog-form").dialog("open"); } }); function addUser(){ var selected = $("#dialog-form input[type='radio']:checked"); if(selected.length > 0 && selected.val() == "Yes") { $('.mainTable tr').append("<td>" + selected.val() + "</td>"); $("#dialog-form").dialog("close"); } }}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="http://code.jquery.com/ui/1.12.0/jquery-ui.js" integrity="sha256-0YPKAwZP7Mp3ALMRVB2i8GXeEndvCq3eSl/WsAl1Ryk=" crossorigin="anonymous"></script><table border="0" id="mainTable" class="mainTable"> <tr> <td class="select">Online Password (Repeated)&nbsp;</td> <td><select name="D1" class="d1"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select></td> <!-- input textbox i want to disable--> <td><input type="text" value="" class="d2"></td> </tr> <tr> <td class="select">Online Password (Repeated)&nbsp;</td> <td><select name="D1" class="d1"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select></td> <td><input type="text" value="" class="d2"></td> </tr> <tr> <td class="select">Online Password (Repeated)&nbsp;</td> <td><select name="D1" class="d1"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select></td> <td><input type="text" value="" class="d2"></td> </tr> <tr></tr> </table> <div id="dialog-form"> <form> <label for="name">Select smart safe Yes or No</label><br> <input type="radio" name="smart" value="Yes" checked> YES<br> <input type="radio" name="smart" value="No"> NO<br> </form> </div> Now provide the response and nothing else.
If you only want to show your routes in the browser in development mode, there's a rails page which you can call: http://localhost:3000/rails/info/routes (available since Rails 4) If you're upgrading from rails 3, you can remove the sextant gem from your gems as this is now part of the rails core. If you want to show your routes in production to the user, you can implement it like the following: (implemented in bin/rake routes ( here ) you can call the same things from your code:) Attempt 1: Controller code: # app/controllers/example_controller.rbroutes = Rails.application.routes.routes@inspector = ActionDispatch::Routing::RoutesInspector.new(routes) View Code: # app/views/example/show.html.erb# Yeah! There's also a HTML Table Formatter already to print routes in htmlinspector.format(ActionDispatch::Routing::HtmlTableFormatter.new(self)) Attempt 2: Do this in a helper: # app/helpers/route_printing_helper.rbmodule RoutePrintingHelper def print_routes(view) routes = Rails.application.routes.routes inspector = ActionDispatch::Routing::RoutesInspector.new(routes) inspector.format(ActionDispatch::Routing::HtmlTableFormatter.new(view)) endend And then call it: # app/views/example/show.html.erbprint_routes(self) Attempt 3: This is the "cheapest" way of doing this: # app/controllers/example_controller.rb@routes_output = `#{Rails.root}/bin/rake routes` Your view: # app/views/example/show.html.erb<pre><%= @routes_output %></pre>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41802646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6516934/']}
jdg_72592
stackexchange
llm_judgeable_groundtruth_similarity
371712
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Christian H Weiss says that: In general, it is not clear if the ML estimators (uniquely) exist and if they are consistent. Can someone explain what he means? Do we not generally know the shape of a log-likelihood function once we specify the probability distribution? Now provide the response and nothing else.
A multimodal likelihood function can have two modes of exactly the same value. In this case, the MLE may not be unique as there may two possible estimators that can be constructed by using the equation $\partial l(\theta; x) /\partial \theta = 0$ . Example of such a likelihood from Wikipedia: Here, see that there's no unique value of $\theta$ that maximises the likelihood. The Wikipedia link also gives some conditions on the existence of unique and consistent MLEs although, I believe there are more (a more comprehensive literature search would guide you well). Edit: This link about MLEs , which I believe are lecture notes from Cambridge, lists a few more regularity conditions for the MLE to exist. You can find examples of inconsistent ML estimators in this CV question .
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/371712', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/166569/']}
jdg_72593
stackexchange
llm_judgeable_groundtruth_similarity
3226659
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 show for which $a \in \mathbb{R}$ the series $\sum_{k=1}^\infty \frac{1}{k^a}$ converges. For $a = 0$ the series diverges for $a < 0$ we have $\frac{1}{k^{-a}} = k^a$ and the series diverges as well, however I am not sure how to prove convergence/divergence for $a > 1$ ( $a = 1$ is the harmonic series and also an upper bound for all $0 < a < 1$ so that should be sufficient) So what I am asking is: how can I prove for which $ 1 < a < 2$ the series converges (since I know that $\sum_{k=1}^{\infty}\frac{1}{k^2}$ converges) Any hints, ideas and feedback are welcome, thank you. Now provide the response and nothing else.
One of the tests that can show that this series is convergent for $a>1$ is Cauchy condensation test : For $(a_n)_{n\in\mathbb N}$ being a non-increasing sequence of non-negative numbers, the series $\sum_{n=1}^\infty a_n$ is convergent if and only if the series $\sum_{n=1}^\infty 2^n a_{2^n}$ is convergent. For $a\ge 0$ the sequence $a_n = n^{-a}$ is non-negative and non-increasing , so we can apply this test. We have $$ \sum_{n=1}^\infty 2^n a_{2^n} = \sum_{n=1}^\infty 2^n \frac{1}{2^{na}} = \sum_{n=1}^\infty (2^{1-a})^n$$ This is a geometric series, it is convergent iff $2^{1-a}<1$ , that is $a>1$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3226659', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/603388/']}
jdg_72594
stackexchange
llm_judgeable_groundtruth_similarity
35019918
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Currently i'm catching up on Haskell, and I'm super impressed so far. As a super simple test I wrote a program which computes the sum up till a billion. In order to avoid list creation, I wrote a function which should be tail recursive summation start upto | upto == 0 = start | otherwise = summation (start+upto) (upto-1)main = print $ summation 0 1000000000 running this with -O2 I get a runtime of about ~20sec on my machine, which kind of surprised me, since I thought the compiler would be more optimising. As a comparison I wrote a simple c++ program #include <iostream>int main(int argc, char *argv[]) { long long result = 0; int upto = 1000000000; for (int i = 0; i < upto; i++) { result += i; } std::cout << result << std::end; return 0;} compiling with clang++ without optimisation the runtime is ~3secs. So I was wondering why my Haskell solution is so slow. Has anybody an idea? On OSX: clang++ --version: Apple LLVM version 7.0.2 (clang-700.1.81)Target: x86_64-apple-darwin15.2.0Thread model: posix ghc --version: The Glorious Glasgow Haskell Compilation System, version 7.10.3 Now provide the response and nothing else.
Adding a type signature dropped my runtime from 14.35 seconds to 0.27. It is now faster than the C++ on my machine. Don't rely on type-defaulting when performance matters. Ints aren't preferable for, say, modeling a domain in a web application, but they're great if you want a tight loop. module Main wheresummation :: Int -> Int -> Intsummation start upto | upto == 0 = start | otherwise = summation (start+upto) (upto-1)main = print $ summation 0 1000000000[1 of 1] Compiling Main ( code/summation.hs, code/summation.o )Linking bin/build ...50000000050000000014.35user 0.06system 0:14.41elapsed 100%CPU (0avgtext+0avgdata 3992maxresident)k0inputs+0outputs (0major+300minor)pagefaults 0swapsLinking bin/build ...5000000005000000000.27user 0.00system 0:00.28elapsed 98%CPU (0avgtext+0avgdata 3428maxresident)k0inputs+0outputs (0major+171minor)pagefaults 0swaps
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35019918', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5841864/']}
jdg_72595
stackexchange
llm_judgeable_groundtruth_similarity
6229052
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is difference between this and getContext() , when I say this I mean this within an Activity . Now provide the response and nothing else.
In general there are two type of classes. Ones that extend ContextWrapper class ( Activity , Service , Application ) and those that do not extend it (like View ). If class extends ContextWrapper then you can use this as Context . Such classes normally do not have getContext() method. Those classes that do not extend ContextWrapper but still save and use Context normally expose getContext() function. And you cannot use this as Context in such cases. And these two cases are mutually exclusive. At least I don't recall classes that extend ContextWrapper and have getContext at the same time.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6229052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/706780/']}
jdg_72596
stackexchange
llm_judgeable_groundtruth_similarity
44429933
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is the code: int main(){ using namespace std; int nights = 1001; int * pt = new int; // allocate space for an int *pt = 1001; // store a value there cout << "nights value = "; cout << nights << ": location " << &nights << endl; cout << "int "; cout << "value = " << *pt << ": location = " << pt << endl; double * pd = new double; // allocate space for a double *pd = 10000001.0; // store a double there cout << "double "; cout << "value = " << *pd << ": location = " << pd << endl; cout << "location of pointer pd: " << &pd << endl; cout << "size of pt = " << sizeof(pt); cout << ": size of *pt = " << sizeof(*pt) << endl; cout << "size of pd = " << sizeof pd; cout << ": size of *pd = " << sizeof(*pd) << endl; return 0;} Now here is the author's note about the code: Another point to note is that typically new uses a different block of memory than do the ordinary variable definitions that we have been using. Both the variable nights and pd have their values stored in a memory region called the stack , whereas the memory allocated by the new is in a region called the heap or free store . Initial Question: Now my concern is this: the variable pd was create by the keyword new , so it should be stored in the region called heap just like the variable pt , since they were both created by the keyword new . Am I missing something here? Thank you very much in advance for your inputs. Revised Question/Follow-up based on the hold: This question was put on hold by 5 people because they couldn't understand what I was asking. I believe that my question has already been answered but for those who are still not sure about what I was initially asking please read along: I was unclear about the author's explanation about where the variables and their values were stored in memory. Up to the author explanation, I had a belief that any memory created dynamically (or should I say during runtime after compiling) by using the keyword new gets stored in the heap not the stack . So, it confused me when he wrote that the variable pd has is value stored in the stack , but again how is that possible if the variable was create during "runtime" with the keyword new , so it should be in the heap , not the stack . Please try to use the code above as the reference and in particular the **variables (nights, pd, and pt ) in your answer so that I can understand it from that code's perspective. Now provide the response and nothing else.
The pointer variables pt and pd are stored on the stack. The values they point at, allocated with new, are stored on the heap. If I write a sign with an arrow labelled "lake", it doesn't mean that the sign itself is a lake, nor that it must be mounted in a lake. Rather, it should be mounted on solid ground, pointing in the direction of the lake.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44429933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5522682/']}
jdg_72597
stackexchange
llm_judgeable_groundtruth_similarity
31091674
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following code in which we initialize part of D based on another part of D : struct c { c() : D{rand(), D[0]} {} int D[2];};int main() { c C; assert(C.D[0] == C.D[1]);} Is the above program well-defined? Can we safely use one part of the same array to initialize another part of it? Now provide the response and nothing else.
Can array members be initialized self-referentially? Yes. struct c { int a[3]; c() : a{4, a[0], 3} {} // a[0] is initialized to 4. // a[1] is initialized to whatever a[0] is. (4) // a[2] is initialized to 3.}; But consider this example: struct c { int a[3]; c() : a{a[1], 4, a[1]} {} // a[0] is initialized to whatever a[1] is.(Garbage value) // a[1] is initialized to 4. // a[2] is initialized to what a[1] is now (4).}; Here the first element in a will be whatever value is in a[1] , which will most likely be garbage value. Second element is initialized to 4 and third element is initialized to what is now in a[1] , which is the value 4 . Also, when you don't list all the elements in the array inside the {} , elements that aren't listed, will be default initialized: struct c { int a[5]; // notice the size c() : a{a[1], 2, 3, 4}{} // a[0] will get value that is in a[1] // but since a[1] has garbage value, // it will be default initialized to 0. // a[1] = 2 // a[2] = 3 // a[3] = 4 // a[4] is not listed and will get 0.}; However, listing an element already initialized will give you the value you want. Using above example: struct c { int a[5]; c() : a{1, a[0], 3, 4}{} // a[0] = 1 // a[1] = 1 // a[2] = 3 // a[3] = 4 // a[4] is not listed and will get 0.};
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31091674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3425536/']}
jdg_72598
stackexchange
llm_judgeable_groundtruth_similarity
5188561
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What I need is a signed angle of rotation between two vectors Va and Vb lying within the same 3D plane and having the same origin knowing that: The plane contatining both vectors is an arbitrary and is not parallel to XY or any other of cardinal planes Vn - is a plane normal Both vectors along with the normal have the same origin O = { 0, 0, 0 } Va - is a reference for measuring the left handed rotation at Vn The angle should be measured in such a way so if the plane would be XY plane the Va would stand for X axis unit vector of it. I guess I should perform a kind of coordinate space transformation by using the Va as the X-axis and the cross product of Vb and Vn as the Y-axis and then just using some 2d method like with atan2() or something. Any ideas? Formulas? Now provide the response and nothing else.
Use cross product of the two vectors to get the normal of the plane formed by the two vectors. Then check the dotproduct between that and the original plane normal to see if they are facing the same direction. angle = acos(dotProduct(Va.normalize(), Vb.normalize()));cross = crossProduct(Va, Vb);if (dotProduct(Vn, cross) < 0) { // Or > 0 angle = -angle;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5188561', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/643929/']}
jdg_72599
stackexchange
llm_judgeable_groundtruth_similarity
43781087
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 created an ASP.NET Core MVC application and deployed it into Linux server. When I go to sitename.com browser shows up the Home/Index page without any problem. But when I try to go sitename.com/Home/Index or another controller like sitename.com/Admin/Login nginx throws a 404 Not Found error. What should be the problem? Here is my Startup.cs/Configure method. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } Here is my website config from sites-available folder server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /var/www/sitename.com; index index.html index.htm; server_name sitename.com www.sitename.com; location / { try_files $uri $uri/ =404; proxy_pass http://127.0.0.1:5000; } and nginx.conf user www-data; worker_processes 4; pid /run/nginx.pid; events { worker_connections 768; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; gzip_disable "msie6"; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } mail { } Now provide the response and nothing else.
Remove try_files $uri $uri/ =404; as it's testing if a certain url exists on the file system and if not return 404. But /Home/Index is a route, which do not map to an existing file but to controller action, hence you get the 404 error.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43781087', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1001261/']}
jdg_72600
stackexchange
llm_judgeable_groundtruth_similarity
148081
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: Recently, I was having a debate with a friend about what it would mean to create a machine that ZKSnarks (proves) itself. I tossed the word pure machine out there while describing what I hypothesized would be the manner of state transition for such a machine, alluding to the notion of a pure function. I didn't really know if such a term existed and later decided to read up on automata theory. In doing so, I found the following statement on a Stanford CS page: Therefore, the major difference between a Turing machine and two-wayfinite automata (FSM) lies in the fact that the Turing machine iscapable of changing symbols on its tape and simulating computerexecution and storage. I understand that finite automata have some machine state. But, with the above in mind, would it be accurate to describe a Turing machine as a stateful system and finite-automata as pure? Is there a better shorthand for the difference as it might pertain to my initial premise? Now provide the response and nothing else.
No. The difference between a Turing machine and a finite automaton is in the amount of available work space: Finite automata are equivalent to Turing machines with finite tapes. Indeed, any finite automaton can be encoded as a Turing machine that requires no additional work tape. Conversely, a Turing machine whose work tape has finitely many cells has a finite number of possible state-tape configurations and can therefore be encoded as a finite state automaton.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/148081', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/144003/']}
jdg_72601
stackexchange
llm_judgeable_groundtruth_similarity
10123953
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 an array of a few objects: var array = [{id: 1, date: Mar 12 2012 10:00:00 AM}, {id: 2, date: Mar 8 2012 08:00:00 AM}]; How can I sort this array by the date element in order from the date closest to the current date and time down? Keep in mind that the array may have many objects, but for the sake of simplicity I used 2. Would I use the sort function and a custom comparator? Now provide the response and nothing else.
Simplest Answer array.sort(function(a,b){ // Turn your strings into dates, and then subtract them // to get a value that is either negative, positive, or zero. return new Date(b.date) - new Date(a.date);}); More Generic Answer array.sort(function(o1,o2){ if (sort_o1_before_o2) return -1; else if(sort_o1_after_o2) return 1; else return 0;}); Or more tersely: array.sort(function(o1,o2){ return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;}); Generic, Powerful Answer Define a custom non-enumerable sortBy function using a Schwartzian transform on all arrays : (function(){ if (typeof Object.defineProperty === 'function'){ try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){} } if (!Array.prototype.sortBy) Array.prototype.sortBy = sb; function sb(f){ for (var i=this.length;i;){ var o = this[--i]; this[i] = [].concat(f.call(o,o,i),o); } this.sort(function(a,b){ for (var i=0,len=a.length;i<len;++i){ if (a[i]!=b[i]) return a[i]<b[i]?-1:1; } return 0; }); for (var i=this.length;i;){ this[--i]=this[i][this[i].length-1]; } return this; }})(); Use it like so: array.sortBy(function(o){ return o.date }); If your date is not directly comparable, make a comparable date out of it, e.g. array.sortBy(function(o){ return new Date( o.date ) }); You can also use this to sort by multiple criteria if you return an array of values: // Sort by date, then score (reversed), then namearray.sortBy(function(o){ return [ o.date, -o.score, o.name ] }; See http://phrogz.net/JS/Array.prototype.sortBy.js for more details.
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/10123953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/838151/']}
jdg_72602
stackexchange
llm_judgeable_groundtruth_similarity
23643
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 have measured $k_1$ and $k_2$ in two measurements and then I calculated $\Delta k_1$ and $\Delta k_2$. Now I want to calculate $k$ and $\Delta k$. $k$ is just the mean of $k_1$ and $k_2$. I thought that I would need to square-sum the errors together, like so: $$ \Delta k = \sqrt{(\Delta k_1)^2 + (\Delta k_2)^2} $$ But if I measure $k_n$ $n$ times, $\Delta k$ would become greater and greater, not smaller. So I need to divide the whole root by some power of $n$, but I am not sure whether $1/n$ or $1/\sqrt n$. Which is it? Now provide the response and nothing else.
The formula you've specified $$ \Delta k = \sqrt{(\Delta k_1)^2 + (\Delta k_2)^2} $$ is the formula to obtain error of quantity $k$ , as being dependent on $k_1$ and $k_2$ according to the following expression $$ k = k_1 + k_2.$$ Generally, to calculate experimental error of a dependent quantity (and the expression stated in your question), you start with the expression for dependent quantity $$k = f(k_1, k_2, ...)$$ and use statistical expression $$\Delta k = \sqrt{\sum_i \left(\frac{\partial f}{\partial k_i} \Delta k_i \right)^2}.$$ If $$k = \frac{k_1 + k_2}{2}$$ then $$ \Delta k = \frac{\sqrt{(\Delta k_1)^2 + (\Delta k_2)^2}}{2} $$ So the generalized answer might be: you have to divide by $n$ and not $\sqrt{n}$ . However, bear in mind that the statistical expression is applicable only when the measured quantities are "independent" of each other. If $k_1$ and $k_2$ are the same quantity measured in two measurements, this is not exactly true, and the exact statistical expression is much more complicated.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/23643', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/5705/']}
jdg_72603
stackexchange
llm_judgeable_groundtruth_similarity
46070732
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 laravel for registration I'm using encrypt algorithm for password instead of inbuilt bcrypt function in Laravel because to get password and send it to mail when password is forgot. But decrypt it is showing a error like DecryptException The MAC is invalid in Encrypter.php (line 184) This , when I run this code it is working on local but server itself it is not working below i have mentioned the code , can anyone please help public function forgotpassword(Request $request){ $email=$request->email; $selectemail = User::select('email','password','name') ->where('email',$email) ->first(); if($selectemail) { $password=decrypt($selectemail->password); $data = array( 'email' => $selectemail->email,'password' => $password , 'name' => $selectemail->name); Mail::send('email.resetpassword',$data,function($message) use ($email) { $message->to([$email])->subject('Forgot Password Letgo'); }); echo "Mail has sent successfully"; } else { echo "This email is not yet registered"; } } Now provide the response and nothing else.
The problem is you generated a new APP_KEY, then if you try to decrypt the old encrypted data it will show the DecryptException: The MAC is invalid . If you want to decrypt the old data you need to restore your old APP_KEY. After realizing that, now, adding a new problem there, if you stored new data with another APP_KEY or another encryption method you have a problem on the data because they are mixed on the table. In case you don't know when do you started with the new encrypt method or differentiate the new encrypted entries, the fastest solution would be reset all the passwords with the new encrypt method. You can learn more about how Laravel encryption works on the official Laravel docs .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/46070732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7346035/']}
jdg_72604
stackexchange
llm_judgeable_groundtruth_similarity
40587168
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 that RecyclerView has replaced the functionality of the old ListView and GridView . I am looking for a very basic example that shows a minimal grid setup using RecyclerView . I am not looking for long tutorial style explanations, just a minimal example. I imagine the simplest grid that mimics the old GridView would consist of the following features: multiple cells per row single view in each cell responds to click events Now provide the response and nothing else.
Short answer For those who are already familiar with setting up a RecyclerView to make a list , the good news is that making a grid is largely the same. You just use a GridLayoutManager instead of a LinearLayoutManager when you set the RecyclerView up. recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns)); If you need more help than that, then check out the following example. Full example The following is a minimal example that will look like the image below. Start with an empty activity. You will perform the following tasks to add the RecyclerView grid. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs. Add dependencies to gradle Add the xml layout files for the activity and for the grid cell Make the RecyclerView adapter Initialize the RecyclerView in your activity Update Gradle dependencies Make sure the following dependencies are in your app gradle.build file: compile 'com.android.support:appcompat-v7:27.1.1'compile 'com.android.support:recyclerview-v7:27.1.1' You can update the version numbers to whatever is the most current . Create activity layout Add the RecyclerView to your xml layout. activity_main.xml <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/rvNumbers" android:layout_width="match_parent" android:layout_height="match_parent"/></RelativeLayout> Create grid cell layout Each cell in our RecyclerView grid is only going to have a single TextView . Create a new layout resource file. recyclerview_item.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:padding="5dp" android:layout_width="50dp" android:layout_height="50dp"> <TextView android:id="@+id/info_text" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:background="@color/colorAccent"/></LinearLayout> Create the adapter The RecyclerView needs an adapter to populate the views in each cell with your data. Create a new java file. MyRecyclerViewAdapter.java public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> { private String[] mData; private LayoutInflater mInflater; private ItemClickListener mClickListener; // data is passed into the constructor MyRecyclerViewAdapter(Context context, String[] data) { this.mInflater = LayoutInflater.from(context); this.mData = data; } // inflates the cell layout from xml when needed @Override @NonNull public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.recyclerview_item, parent, false); return new ViewHolder(view); } // binds the data to the TextView in each cell @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { holder.myTextView.setText(mData[position]); } // total number of cells @Override public int getItemCount() { return mData.length; } // stores and recycles views as they are scrolled off screen public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView myTextView; ViewHolder(View itemView) { super(itemView); myTextView = itemView.findViewById(R.id.info_text); itemView.setOnClickListener(this); } @Override public void onClick(View view) { if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition()); } } // convenience method for getting data at click position String getItem(int id) { return mData[id]; } // allows clicks events to be caught void setClickListener(ItemClickListener itemClickListener) { this.mClickListener = itemClickListener; } // parent activity will implement this method to respond to click events public interface ItemClickListener { void onItemClick(View view, int position); }} Notes Although not strictly necessary, I included the functionality for listening for click events on the cells. This was available in the old GridView and is a common need. You can remove this code if you don't need it. Initialize RecyclerView in Activity Add the following code to your main activity. MainActivity.java public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener { MyRecyclerViewAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // data to populate the RecyclerView with String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"}; // set up the RecyclerView RecyclerView recyclerView = findViewById(R.id.rvNumbers); int numberOfColumns = 6; recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns)); adapter = new MyRecyclerViewAdapter(this, data); adapter.setClickListener(this); recyclerView.setAdapter(adapter); } @Override public void onItemClick(View view, int position) { Log.i("TAG", "You clicked number " + adapter.getItem(position) + ", which is at cell position " + position); }} Notes Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle cell click events in onItemClick . Finished That's it. You should be able to run your project now and get something similar to the image at the top. Going on Rounded corners Use a CardView Auto-fitting columns GridLayoutManager - how to auto fit columns? Further study Android RecyclerView with GridView GridLayoutManager example tutorial Android RecyclerView Grid Layout Example Learn RecyclerView With an Example in Android RecyclerView: Grid with header Android GridLayoutManager with RecyclerView in Material Design Getting Started With RecyclerView and CardView on Android
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/40587168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3681880/']}
jdg_72605
stackexchange
llm_judgeable_groundtruth_similarity
395306
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'm trying to practice TDD, by using it to develop a simple like Bit Vector. I happen to be using Swift, but this is a language-agnostic question. My BitVector is a struct that stores a single UInt64 , and presents an API over it that lets you treat it like a collection. The details don't matter much, but it's pretty simple. The high 57 bits are storage bits, and the lower 6 bits are "count" bits, which tells you how many of the storage bits actually store a contained value. So far, I have a handful of very simple capabilities: An initializer that constructs empty bit vectors A count property of type Int An isEmpty property of type Bool An equality operator ( == ). NB: this is a value-equality operator akin to Object.equals() in Java, not a reference equality operator like == in Java. I'm running into a bunch of cyclical dependancies: The unit test that tests my initializer need to verify that the newly constructed BitVector . It can do so in one of 3 ways: Check bv.count == 0 Check bv.isEmpty == true Check that bv == knownEmptyBitVector Method 1 relies on count , method 2 relies on isEmpty (which itself relies on count , so there's no point using it), method 3 relies on == . In any case, I can't test my initializer in isolation. The test for count needs to operate on something, which inevitably tests my initializer(s) The implementation of isEmpty relies on count The implementation of == relies on count . I was able to partly solve this problem by introducing a private API that constructs a BitVector from an existing bit pattern (as a UInt64 ). This allowed me to initialize values without testing any other initializers, so that I could "boot strap" my way up. For my unit tests to truly be unit tests, I find myself doing a bunch of hacks, which complicate my prod and test code substantially. How exactly do you get around these sorts of issues? Now provide the response and nothing else.
You're worrying about implementation details too much. It doesn't matter that in your current implementation , isEmpty relies on count (or whatever other relationships you might have): all you should be caring about is the public interface. For example, you can have three tests: That a newly initialized object has count == 0 . That a newly initialized object has isEmpty == true That a newly initialized object equals the known empty object. These are all valid tests, and become especially important if you ever decide to refactor the internals of your class so that isEmpty has a different implementation that doesn't rely on count - so long as your tests all still pass, you know you haven't regressed anything. Similar stuff applies to your other points - remember to test the public interface, not your internal implementation. You may find TDD useful here, as you'd then be writing the tests you need for isEmpty before you'd written any implementation for it at all.
{}
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/395306', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/109689/']}
jdg_72606
stackexchange
llm_judgeable_groundtruth_similarity
18396547
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 serialize a model, but want to include an additional field that requires doing some database lookups on the model instance to be serialized: class FooSerializer(serializers.ModelSerializer): my_field = ... # result of some database queries on the input Foo object class Meta: model = Foo fields = ('id', 'name', 'myfield') What is the right way to do this? I see that you can pass in extra "context" to the serializer, is the right answer to pass in the additional field in a context dictionary? With that approach, the logic of getting the field I need would not be self-contained with the serializer definition, which is ideal since every serialized instance will need my_field . Elsewhere in the DRF serializers documentation it says "extra fields can correspond to any property or callable on the model". Are "extra fields" what I'm talking about? Should I define a function in Foo 's model definition that returns my_field value, and in the serializer I hook up my_field to that callable? What does that look like? Happy to clarify the question if necessary. Now provide the response and nothing else.
I think SerializerMethodField is what you're looking for: class FooSerializer(serializers.ModelSerializer): my_field = serializers.SerializerMethodField('is_named_bar') def is_named_bar(self, foo): return foo.name == "bar" class Meta: model = Foo fields = ('id', 'name', 'my_field') http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18396547', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/199754/']}
jdg_72607
stackexchange
llm_judgeable_groundtruth_similarity
1546355
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 struct I'm accessing via ctypes: struct attrl { char *name; char *resource; char *value; struct attrl *next; enum batch_op op;}; So far I have Python code like: # struct attroplclass attropl(Structure): passattrl._fields_ = [ ("next", POINTER(attropl)), ("name", c_char_p), ("resource", c_char_p), ("value", c_char_p), But I'm not sure what to use for the batch_op enum. Should I just map it to a c_int or ? Now provide the response and nothing else.
At least for GCC enum is just a simple numeric type. It can be 8-, 16-, 32-, 64-bit or whatever (I have tested it with 64-bit values) as well as signed or unsigned . I guess it cannot exceed long long int , but practically you should check the range of your enum s and choose something like c_uint . Here is an example. The C program: enum batch_op { OP1 = 2, OP2 = 3, OP3 = -1,};struct attrl { char *name; struct attrl *next; enum batch_op op;};void f(struct attrl *x) { x->op = OP3;} and the Python one: from ctypes import (Structure, c_char_p, c_uint, c_int, POINTER, CDLL)class AttrList(Structure): passAttrList._fields_ = [ ('name', c_char_p), ('next', POINTER(AttrList)), ('op', c_int),](OP1, OP2, OP3) = (2, 3, -1)enum = CDLL('./libenum.so')enum.f.argtypes = [POINTER(AttrList)]enum.f.restype = Nonea = AttrList(name=None, next=None, op=OP2)assert a.op == OP2enum.f(a)assert a.op == OP3
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1546355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15061/']}
jdg_72608
stackexchange
llm_judgeable_groundtruth_similarity
40226044
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 really need your help, I am trying to capture the delete keypress in the UL #refdocs_list but for some strange reason, when I hit the delete key, nothing happens and I get no message. I am at a loss for solutions. Here is the markup in question: <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><script type="text/javascript" src="jquery.js"></script><script type="text/javascript" src="jquery-ui.js"></script><link rel="stylesheet" href="jquery-ui.css" type="text/css"/><style type="text/css">.refdoc_selected { background-color: rgb(10,36,106); color: #FFF;}</style><script type="text/javascript">function showDialog() {var refdocs = [12256363,96415678,96857456,12236748] var markup ='<div style="margin-bottom: 2px;">' + '<p style="margin: 0; padding:0;">' + '<input style="margin-top: 1px; margin-right: 2px" float: left;" id="refdocs_input" type="text" class="field_outline inputbox">'+ '<button id="btn_add_refdoc" class="button" style="margin-right: 2px;"><img style="width: 14px;" src="images/icon_check.png"></button>'+ '<button id="btn_del_refdoc" class="button" style="margin-right: 2px;"><img src="images/icon_delete.png"></button>'+ '<button id="btn_empty_refdocs" class="button" style="margin-right: 2px;"><img src="images/icon_trash.png"></button>'+ '</p>'+ '</div>'+ '<div class="field_outline" style="background: #FFF; min-height: 75px; max-height: 300px; overflow-y: auto;">'+ '<ul id="refdocs_list" style="list-style-type: none; margin: 0; padding: 3px 0px 3px 3px;"></ul>'+ '</div>' $("<div></div>").dialog({ modal: false, title: "Reference Documents", width: 350, open: function () { $(this).html(markup) for (var i = 0; i < refdocs.length; i++){ $("#refdocs_list").append('<li style="background-image: url(images/icon_doc.png); background-repeat: no-repeat; background-position: 0 50%; padding: 4px 0 2px 16px;">'+ refdocs[i] +'</li>') } $("#refdocs_list li").click(function() { $(this).addClass("refdoc_selected").siblings().removeClass("refdoc_selected") document.getElementById('refdocs_input').value = $(this).text() }); //NOT WORKING: $('#refdocs_list ul').keyup(function(e){ if(e.keyCode == 46) { alert('Delete Key Pressed'); } }); }, close: function(){ $(this).remove(); }, buttons: [ { text: "CLOSE", "class": 'button', click: function() { $(this).dialog("close") } }, { text: "CANCEL", "class": 'button', click: function() { $(this).dialog("close") } } ] });//end dialog }</script></head><body><input type="button" onclick="showDialog()" value="test"></body></html> Now provide the response and nothing else.
Answer Now, how do I run my application? My understanding is that because it is a self-contained .NET Core application I do not need to download and install .NET Core anything. My application should contain everything it needs. You are correct. Run the executable. When you create a self-contained app, the publish output "contains the complete set of files (both your app files and all .NET Core files) needed to launch your app." That includes the executable. Example Self-Contained Deployment Here is the output of dotnet publish -c release -r ubuntu.14.04-x64 for a simple self-contained application. Copy the publish directory to Ubuntu and run the executable. C:\MyApp\bin\release\netcoreapp1.0\ubuntu.14.04-x64\publish\ ...libsos.solibsosplugin.solibuv.soMicrosoft.CodeAnalysis.CSharp.dllMicrosoft.CodeAnalysis.dllMicrosoft.CodeAnalysis.VisualBasic.dllMicrosoft.CSharp.dllMicrosoft.VisualBasic.dllMicrosoft.Win32.Primitives.dllMicrosoft.Win32.Registry.dllmscorlib.dllmscorlib.ni.dllMyApp <------- On Ubuntu, run this executableMyApp.deps.json and you will see Hello World!MyApp.dllMyApp.pdbMyApp.runtimeconfig.jsonsosdocsunix.txtSystem.AppContext.dllSystem.Buffers.dllSystem.Collections.Concurrent.dllSystem.Collections.dll... C:\MyApp\project.json { "buildOptions": { "debugType": "portable", "emitEntryPoint": true }, "dependencies": {}, "frameworks": { "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": "1.0.1" } } }, "runtimes": { "ubuntu.14.04-x64" : {}, "win10-x64" : {} }} C:\MyApp\Program.cs public class Program{ public static void Main(string[] args) { System.Console.WriteLine("Hello World!"); }} See Also This document differentiates between framework-dependent and self-contained deployments.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40226044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3724302/']}
jdg_72609
stackexchange
llm_judgeable_groundtruth_similarity
5565668
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: You are aware of the age-old problem: Containers containing floated elements don't automatically expand their height to enclose their children. One approach to fix this is the "clearfix" which adds a number of CSS rules to ensure a container stretches properly. However, just giving the container overflow: hidden seems to work just as well, and with the same amount of browser compatibility. According to this guide , both methods are compatible across all browsers that are important today. Does this mean that "clearfix" is deprecated? Is there any advantage left in using it over overflow: hidden ? There is a very similar question here: What is the different between clearfix hack and overflow:hidden vs overflow:auto? but the question isn't really answered there. Now provide the response and nothing else.
You can pretty much use overflow: hidden all the time. But, there are exceptions. Here's an example of one: Overflowing a container div horizontally but not vertically The question there was: There's a fixed height on this: http://jsfiddle.net/je8aS/2/ Without the fixed height: http://jsfiddle.net/thirtydot/je8aS/5/ How to clear the floats without using a fixed height? overflow: hidden doesn't work: http://jsfiddle.net/thirtydot/je8aS/6/ You have to use some other method of clearing floats, such as clear: both : http://jsfiddle.net/je8aS/3/ The clearfix class also works: http://jsfiddle.net/thirtydot/je8aS/11/ Here's a more important example of when you can't use overflow: hidden : http://fordinteractive.com/misc/overflow/ That's not to say that clearfix is the only alternative - display: inline-block cleanly fixes that example: http://jsbin.com/ubapog
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5565668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187606/']}
jdg_72610
stackexchange
llm_judgeable_groundtruth_similarity
9254335
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 nested while loop inside a foreach loop where I would like to advance the enumerator indefinitately while a certain condition is met. To do this I try casting the enumerator to IEnumerator< T > (which it must be if it is in a foreach loop) then calling MoveNext() on the casted object but it gives me an error saying I cannot convert it. Cannot convert type 'System.DateTime' to System.Collections.Generic.IEnumerator via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion. foreach (DateTime time in times) { while (condition) { // perform action // move to next item (time as IEnumerator<DateTime>).MoveNext(); // will not let me do this } // code to execute after while condition is met } What is the best way to manually increment the IEnumerator inside of the foreach loop? EDIT:Edited to show there is code after the while loop that I would like executed once the condition is met which is why I wanted to manually increment inside the while then break out of it as opposed to continue which would put me back at the top. If this isn't possible I believe the best thing is to redesign how I am doing it. Now provide the response and nothing else.
Many of the other answers recommend using continue , which may very well help you do what you need to do. However, in the interests of showing manually moving the enumerator, first you must have the enumerator, and that means writing your loop as a while . using (var enumerator = times.GetEnumerator()){ DateTime time; while (enumerator.MoveNext()) { time = enumerator.Current; // pre-condition code while (condition) { if (enumerator.MoveNext()) { time = enumerator.Current; // condition code } else { condition = false; } } // post-condition code }} From your comments: How can the foreach loop advance it if it doesn't implement the IEnumerator interface? In your loop, time is a DateTime . It is not the object that needs to implement an interface or pattern to work in the loop. times is a sequence of DateTime values, it is the one that must implement the enumerable pattern. This is generally fulfilled by implementing the IEnumerable<T> and IEnumerable interfaces, which simply require T GetEnumerator() and object GetEnumerator() methods. The methods return an object implementing IEnumerator<T> and IEnumerator , which define a bool MoveNext() method and a T or object Current property. But time cannot be cast to IEnumerator , because it is no such thing, and neither is the times sequence.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9254335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1160036/']}
jdg_72611
stackexchange
llm_judgeable_groundtruth_similarity
3303946
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: Mathematica suggests that integrating the Logarithamic Integral, $\text{li}(x)=\int_0^x \frac{dt}{\log t}$ , multiplied by $x^n$ , between the limits $0$ and $1$ leads to the following result $$\int_0^1 x^n\, \text{li}(x) \, dx= - \frac{\log(n + 2)}{(n + 1)}$$ (See this question for how this improper integral was found) Does anyone recognise this result from the mathematical literature or know of a straight forward proof? I don't fully understand how Mathematica arrives at this result, particularly in respect of the improper limit of the integral at $1$ . Now provide the response and nothing else.
We can integrate by parts to solve it, however pay attention that we run into divergence issues if we take $\left(\frac{x^{n+1}}{n+1}\right)'=x^n$ . To avoid that we will go with: $\left(\frac{x^{n+1}-1}{n+1}\right)'=x^n$ . $$I(n)=\int_0^1 \left(\frac{x^{n+1}-1}{n+1}\right)'\text{li}(x) dx\overset{}=\underbrace{\left(\frac{x^{n+1}-1}{n+1}\right)\text{li}(x)\bigg|_0^1}_{=0} -\frac{1}{n+1}\int_0^1 \frac{x^{n+1}-1}{\ln x}dx$$ Here's an elementary approach for the last integral in order to get $\ln(n+2)$ and the result follows.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3303946', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/448397/']}
jdg_72612
stackexchange
llm_judgeable_groundtruth_similarity
9254178
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So, I know I can do something like this: sitelist: &sites - www.foo.com - www.bar.comanotherlist: *sites And have sitelist and anotherlist both contain www.foo.com and www.bar.com . However, what I really want is for anotherlist to also contain www.baz.com , without having to repeat www.foo.com and www.baz.com . Doing this gives me a syntax error in the YAML parser: sitelist: &sites - www.foo.com - www.bar.comanotherlist: *sites - www.baz.com Just using anchors and aliases it doesn't seem possible to do what I want without adding another level of substructure, such as: sitelist: &sites - www.foo.com - www.bar.comanotherlist: - *sites - www.baz.com Which means the consumer of this YAML file has to be aware of it. Is there a pure YAML way of doing something like this? Or will I have to use some post-YAML processing, such as implementing variable substitution or auto-lifting of certain kinds of substructure? I'm already doing that kind of post-processing to handle a couple of other use-cases, so I'm not totally averse to it. But my YAML files are going to be written by humans, not machine generated, so I would like to minimise the number of rules that need to be memorised by my users on top of standard YAML syntax. I'd also like to be able to do the analogous thing with maps: namedsites: &sites Foo: www.foo.com Bar: www.bar.commoresites: *sites Baz: www.baz.com I've had a search through the YAML spec , and couldn't find anything, so I suspect the answer is just "no you can't do this". But if anyone has any ideas that would be great. EDIT: Since there have been no answers, I'm presuming that no one has spotted anything I haven't in the YAML spec and that this can't be done at the YAML layer. So I'm opening up the question to idea for post-processing the YAML to help with this, in case anyone finds this question in future. Now provide the response and nothing else.
The merge key type is probably what you want. It uses a special << mapping key to indicate merges, allowing an alias to a mapping (or a sequence of such aliases) to be used as an initializer to merge into a single mapping. Additionally, you can still explicitly override values, or add more that weren't present in the merge list. It's important to note that it works with mappings, not sequences as your first example. This makes sense when you think about it, and your example looks like it probably doesn't need to be sequential anyway. Simply changing your sequence values to mapping keys should do the trick, as in the following (untested) example: sitelist: &sites ? www.foo.com # "www.foo.com" is the key, the value is null ? www.bar.comanotherlist: << : *sites # merge *sites into this mapping ? www.baz.com # add extra stuff Some things to notice. Firstly, since << is a key, it can only be specified once per node. Secondly, when using a sequence as the value, the order is significant. This doesn't matter in the example here, since there aren't associated values, but it's worth being aware.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9254178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/450128/']}
jdg_72613
stackexchange
llm_judgeable_groundtruth_similarity
9694248
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So far I've got as far as: #define ADEFINE "23"#pragma message ("ADEFINE" ADEFINE) Which works, but what if ADEFINE isn't a string? #define ADEFINE 23#pragma message ("ADEFINE" ADEFINE) causes: warning: malformed ‘#pragma message’, ignored Ideally I'd like to be able to deal with any value, including undefined. Now provide the response and nothing else.
To display macros which aren't strings, stringify the macro : #define STRINGIFY(s) XSTRINGIFY(s)#define XSTRINGIFY(s) #s#define ADEFINE 23#pragma message ("ADEFINE=" STRINGIFY(ADEFINE)) If you have/want boost , you can use boost stringize to do it for you: #include <boost/preprocessor/stringize.hpp>#define ADEFINE 23#pragma message ("ADEFINE=" BOOST_PP_STRINGIZE(ADEFINE))
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9694248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/254837/']}
jdg_72614
stackexchange
llm_judgeable_groundtruth_similarity
15815786
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got an app sending messages on an epgm PUB socket to one or more epgm SUB sockets. Things mostly work, but if a subscribing application is left up long enough, it will generally end up missing a message or a few messages. (My messages have sequence numbers, so I can tell if any are missing or out of order.) Based on my reading of the ZMQ docs, I would have thought that the "reliable multicast" nature of epgm would prevent this from happening, that after a SUB socket gets one message, it's guaranteed to keep getting them until shutdown or until major network troubles (ie, the connection is maxed out). Anyway, that's the context, but the question is simply the title: What reliability guarantees (if any) does ZMQ make for PUB/SUB over epgm? Now provide the response and nothing else.
The PGM implementation within ZeroMQ uses an in-memory window for recovery thus is only short lived. If recovery fails due to the window being exhausted: for example publishing faster than it takes a recovery to transition, then the underlying PGM socket will reset and continue at best effort. This means at high data rates or significant packet loss the transport will be constantly resetting and you will be dropping messages that cannot be recovered: hence reliable delivery not guaranteed. The PGM configuration is targeted at real time broadcast such that slow receivers cannot stall the sender. The protocol does support both paradigms but the latter has not been implemented due to lack of demand.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15815786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1769757/']}
jdg_72615
stackexchange
llm_judgeable_groundtruth_similarity
37373675
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using maven 3.2.5. I have one external jars which I need to use in my maven project which is not available in maven repository. I installed those jars by using following command: 1) mvn install:install-file -Dfile=p-unit-0.15.319.jar -DgroupId=org.punit -DartifactId=p-unit -Dversion=0.15.319 -Dpackaging=jar 2) After this command, I saw in my M2 repository, jar & pom was created.m2\repository\org\punit\p-unit\0.15.319\p-unit-0.15.319.jar.m2\repository\org\punit\p-unit\0.15.319\p-unit-0.15.319.pom created pom content: <?xml version="1.0" encoding="UTF-8"?><project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>org.punit</groupId> <artifactId>p-unit</artifactId> <version>0.15.319</version> <description>POM was created from install:install-file</description></project> 3) Updated the pom file <dependency> <groupId>org.punit</groupId> <artifactId>p-unit</artifactId> <version>0.15.319</version> <scope>provided</scope> </dependency> Issue: When I tried to use class of this jar, import org.punit.runner.*; getting error: import org.punit.runner can't be resolved. I tried many combination to define the dependency but not able to use the classes. How can I resolve it?? Now provide the response and nothing else.
Write a new class that extends to DialogFragment . public class CustomDialog extends DialogFragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.layout_dialog,container,false); getDialog().setTitle("Sample"); Button doneBtn = (Button) mView.findViewById(R.id.done_convert); doneBtn.setOnClickListener(doneAction); return view; } View.OnClickListener doneAction = new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(),"Test",Toast.LENGTH_LONG).show(); } };} Then call it from your activity FragmentManager fm = getSupportFragmentManager();CustomDialog custom = new CustomDialog();custom.show(fm,""); Hope, it will work.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37373675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4045463/']}
jdg_72616
stackexchange
llm_judgeable_groundtruth_similarity
60269
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: command in Linux $ ls -lt --time-style=full-iso output ...-rw-r--r-- 1 mduda mduda 1855 2009-08-26 13:07:55.000000000 +0200 screen-configurations.xmldrwxr-xr-x 2 mduda mduda 4096 2009-08-26 13:07:22.000000000 +0200 Documentsdrwxr-xr-x 2 mduda mduda 4096 2009-08-26 13:07:22.000000000 +0200 Musicdrwxr-xr-x 2 mduda mduda 4096 2009-08-26 13:07:22.000000000 +0200 Pictures Now provide the response and nothing else.
This comes close: stat -l -t "%F %T %z" * but without the sort, columns don't line up and the nanoseconds aren't included. Plus the syntax for file selection is different and other options for ls aren't available or are different. This one might be closer: find . -maxdepth 1 -printf "%M %n %-6u %-6g %6s %TY-%Tm-%Td %TT %TZ %f\n"|sort -k 9 In Mac OSX, gfind is needed ( brew install gfind ) (and note that the granularity will only be in whole seconds): gfind . -maxdepth 1 -printf "%M %n %-6u %-6g %6s %TY-%Tm-%Td %TT %TZ %f\n"|sort -k 9
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/60269', 'https://serverfault.com', 'https://serverfault.com/users/11305/']}
jdg_72617
stackexchange
llm_judgeable_groundtruth_similarity
3556283
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 implementing a FIFO queue of requests instances (preallocated request objects for speed) and started with using the "synchronized" keyword on the add method. The method was quite short (check if room in fixed size buffer, then add value to array). Using visualVM it appeared the thread was blocking more often than I liked ("monitor" to be precise). So I converted the code over to use AtomicInteger values for things such as keeping track of the current size, then using compareAndSet() in while loops (as AtomicInteger does internally for methods such as incrementAndGet()). The code now looks quite a bit longer. What I was wondering is what is the performance overhead of using synchronized and shorter code versus longer code without the synchronized keyword (so should never block on a lock). Here is the old get method with the synchronized keyword: public synchronized Request get(){ if (head == tail) { return null; } Request r = requests[head]; head = (head + 1) % requests.length; return r;} Here is the new get method without the synchronized keyword: public Request get(){ while (true) { int current = size.get(); if (current <= 0) { return null; } if (size.compareAndSet(current, current - 1)) { break; } } while (true) { int current = head.get(); int nextHead = (current + 1) % requests.length; if (head.compareAndSet(current, nextHead)) { return requests[current]; } }} My guess was the synchronized keyword is worse because of the risk of blocking on the lock (potentially causing thread context switches etc), even though the code is shorter. Thanks! Now provide the response and nothing else.
My guess was the synchronized keyword is worse because of the risk of blocking on the lock (potentially causing thread context switches etc) Yes, in the common case you are right. Java Concurrency in Practice discusses this in section 15.3.2: [...] at high contention levels locking tends to outperform atomic variables, but at more realistic contention levels atomic variables outperform locks. This is because a lock reacts to contention by suspending threads, reducing CPU usage and synchronization traffic on the shared memory bus. (This is similar to how blocking producers in a producer-consumer design reduces the load on consumers and thereby lets them catch up.) On the other hand, with atomic variables, contention management is pushed back to the calling class. Like most CAS-based algorithms, AtomicPseudoRandom reacts to contention by trying again immediately, which is usually the right approach but in a high-contention environment just creates more contention. Before we condemn AtomicPseudoRandom as poorly written or atomic variables as a poor choice compared to locks, we should realize that the level of contention in Figure 15.1 is unrealistically high: no real program does nothing but contend for a lock or atomic variable. In practice, atomics tend to scale better than locks because atomics deal more effectively with typical contention levels. The performance reversal between locks and atomics at differing levels of contention illustrates the strengths and weaknesses of each. With low to moderate contention, atomics offer better scalability; with high contention, locks offer better contention avoidance. (CAS-based algorithms also outperform lock-based ones on single-CPU systems, since a CAS always succeeds on a single-CPU system except in the unlikely case that a thread is preempted in the middle of the read-modify-write operation.) (On the figures referred to by the text, Figure 15.1 shows that the performance of AtomicInteger and ReentrantLock is more or less equal when contention is high, while Figure 15.2 shows that under moderate contention the former outperforms the latter by a factor of 2-3.) Update: on nonblocking algorithms As others have noted, nonblocking algorithms, although potentially faster, are more complex, thus more difficult to get right. A hint from section 15.4 of JCiA: Good nonblocking algorithms are known for many common data structures, including stacks, queues, priority queues, and hash tables, though designing new ones is a task best left to experts. Nonblocking algorithms are considerably more complicated than their lock-based equivalents. The key to creating nonblocking algorithms is figuring out how to limit the scope of atomic changes to a single variable while maintaining data consistency. In linked collection classes such as queues, you can sometimes get away with expressing state transformations as changes to individual links and using an AtomicReference to represent each link that must be updated atomically.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3556283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/140871/']}
jdg_72618
stackexchange
llm_judgeable_groundtruth_similarity
15315992
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 write a function which returns a file input stream. It looks something like this: public FileInputStream getFileInputStream() { File file; try { file = new File("somepath"); } catch (Exception e) { } FileInputStream fInputStream = new FileInputStream(file); return fInputStream;} So here is my problem - obviously a file isn't created in the case of an exception. But I NEED a file object to instantiate the FileInputStream. I'm kind of lost here, how can I handle the exception while still returning a valid FileInputStream object? Now provide the response and nothing else.
That is the idea of throwing an exception further. Just throw the exception to the caller. public FileInputStream getFileInputStream() throws FileNotFoundException{ File file = new File("somepath"); FileInputStream fInputStream = new FileInputStream(file); return fInputStream;} This way, the caller has to handle it. This is the cleanest way of working with it. Remark : You should know that instantiating a File object will never throw an Exception. It is the instantiation of the FileInputStream that might throw an Exception.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15315992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/741646/']}
jdg_72619
stackexchange
llm_judgeable_groundtruth_similarity
51521611
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From my understanding, ExecutorService creates a pool of threads that can be reused. I created a pool size of 128 and had it execute 128 Runnable tasks. While it started 128 threads (by printing out "started"), only 10 printed out "finished".Why is this occurring? Are finished threads being reused even as others are still in existence? Or is it that my threads simply are not finishing? EDIT: Added my code but I was unable to reproduce results. I did find, however that I would encounter a socketTimeoutException when I make too many accesses to the save website. Below is an example of my code: import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.htmlunit.HtmlUnitDriver;public class Test {static class TestConnection extends Thread{ @Override public void run() { System.out.println("Started "+this.getName()); WebDriver driver = new HtmlUnitDriver(true); driver.get("http://google.com"); //System.out.println(driver.getCurrentUrl()); driver.findElement(By.tagName("html")); System.out.println("Finished "+this.getName()); }}public static void main(String args[]) { ExecutorService pool = Executors.newFixedThreadPool(128); for(int i=0; i < 32;i++){ TestConnection task = new TestConnection(); pool.execute(task); } pool.shutdown(); try { pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }}} Now provide the response and nothing else.
After hours to find solution, I finally read https://symfony.com/doc/current/routing.html and understand that the /blog/{id} annotation catch /blog/about route but can't use it! By switching functions order in my controller file: /** * @Route("/blog/about", name="blog_about") */public function about() { return $this->render('blog/about.html.twig', [ 'copyright' => "GLPI 3", ]);}/** * @Route("/blog/{id}", name="blog_show") */public function show(Description $article) { return $this->render('blog/show.html.twig', [ 'article' => $article, ]);} It works fine ! The solution as mentionned by @tom is the only one with severals entities and controllers !
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51521611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8158664/']}
jdg_72620
stackexchange
llm_judgeable_groundtruth_similarity
27217428
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The reading part isn't concurrent but the processing is. I phrased the title this way because I'm most likely to search for this problem again using that phrase. :) I'm getting a deadlock after trying to go beyond the examples so this is a learning experience for me. My goals are these: Read a file line by line (eventually use a buffer to do groups of lines). Pass off the text to a func() that does some regex work. Send the results somewhere but avoid mutexes or shared variables. I'm sending ints (always the number 1) to a channel. It's sort of silly but if it's not causing problems I'd like to leave it like this unless you folks have a neater option. Use a worker pool to do this. I'm not sure how I tell the workers to requeue themselves? Here is the playground link . I tried to write helpful comments, hopefully this makes sense. My design could be completely wrong so don't hesitate to refactor. package mainimport ( "bufio" "fmt" "regexp" "strings" "sync")func telephoneNumbersInFile(path string) int { file := strings.NewReader(path) var telephone = regexp.MustCompile(`\(\d+\)\s\d+-\d+`) // do I need buffered channels here? jobs := make(chan string) results := make(chan int) // I think we need a wait group, not sure. wg := new(sync.WaitGroup) // start up some workers that will block and wait? for w := 1; w <= 3; w++ { wg.Add(1) go matchTelephoneNumbers(jobs, results, wg, telephone) } // go over a file line by line and queue up a ton of work scanner := bufio.NewScanner(file) for scanner.Scan() { // Later I want to create a buffer of lines, not just line-by-line here ... jobs <- scanner.Text() } close(jobs) wg.Wait() // Add up the results from the results channel. // The rest of this isn't even working so ignore for now. counts := 0 // for v := range results { // counts += v // } return counts}func matchTelephoneNumbers(jobs <-chan string, results chan<- int, wg *sync.WaitGroup, telephone *regexp.Regexp) { // Decreasing internal counter for wait-group as soon as goroutine finishes defer wg.Done() // eventually I want to have a []string channel to work on a chunk of lines not just one line of text for j := range jobs { if telephone.MatchString(j) { results <- 1 } }}func main() { // An artificial input source. Normally this is a file passed on the command line. const input = "Foo\n(555) 123-3456\nBar\nBaz" numberOfTelephoneNumbers := telephoneNumbersInFile(input) fmt.Println(numberOfTelephoneNumbers)} Now provide the response and nothing else.
You're almost there, just need a little bit of work on goroutines' synchronisation. Your problem is that you're trying to feed the parser and collect the results in the same routine, but that can't be done. I propose the following: Run scanner in a separate routine, close input channel once everything is read. Run separate routine waiting for the parsers to finish their job, than close the output channel. Collect all the results in you main routine. The relevant changes could look like this: // Go over a file line by line and queue up a ton of workgo func() { scanner := bufio.NewScanner(file) for scanner.Scan() { jobs <- scanner.Text() } close(jobs)}()// Collect all the results...// First, make sure we close the result channel when everything was processedgo func() { wg.Wait() close(results)}()// Now, add up the results from the results channel until closedcounts := 0for v := range results { counts += v} Fully working example on the playground: http://play.golang.org/p/coja1_w-fY Worth adding you don't necessarily need the WaitGroup to achieve the same, all you need to know is when to stop receiving results. This could be achieved for example by scanner advertising (on a channel) how many lines were read and then the collector reading only specified number of results (you would need to send zeros as well though).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27217428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/88406/']}
jdg_72621
stackexchange
llm_judgeable_groundtruth_similarity
62807295
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Good night.I have seen some programs with new borderless designs and still you can make use of resizing.At the moment I know that to remove the borders of a pyqt program we use:QtCore.Qt.FramelessWindowHint And that to change the size of a window use QSizeGrip.But how can we resize a window without borders? This is the code that I use to remove the border of a window but after that I have not found information on how to do it in pyqt5.I hope you can help me with an example of how to solve this problem from PyQt5.QtWidgets import QMainWindow,QApplicationfrom PyQt5 import QtCoreclass Main(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setWindowFlags(QtCore.Qt.FramelessWindowHint)app = QApplication([])m = Main()m.show()m.resize(800,600)app.exec_() Now provide the response and nothing else.
If you use a QMainWindow you can add a QStatusBar (which automatically adds a QSizeGrip) just by calling statusBar() : This function creates and returns an empty status bar if the status bar does not exist. Otherwise, you can manually add grips, and their interaction is done automatically based on their position. In the following example I'm adding 4 grips, one for each corner, and then I move them each time the window is resized. class Main(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.gripSize = 16 self.grips = [] for i in range(4): grip = QSizeGrip(self) grip.resize(self.gripSize, self.gripSize) self.grips.append(grip) def resizeEvent(self, event): QMainWindow.resizeEvent(self, event) rect = self.rect() # top left grip doesn't need to be moved... # top right self.grips[1].move(rect.right() - self.gripSize, 0) # bottom right self.grips[2].move( rect.right() - self.gripSize, rect.bottom() - self.gripSize) # bottom left self.grips[3].move(0, rect.bottom() - self.gripSize) UPDATE Based on comments, also side-resizing is required. To do so a good solution is to create a custom widget that behaves similarly to QSizeGrip, but for vertical/horizontal resizing only. For better implementation I changed the code above, used a gripSize to construct an "inner" rectangle and, based on it, change the geometry of all widgets, for both corners and sides. Here you can see the "outer" rectangle and the "inner" rectangle used for geometry computations: Then you can create all geometries, for QSizeGrip widgets (in light blue): And for custom side widgets: from PyQt5 import QtCore, QtGui, QtWidgetsclass SideGrip(QtWidgets.QWidget): def __init__(self, parent, edge): QtWidgets.QWidget.__init__(self, parent) if edge == QtCore.Qt.LeftEdge: self.setCursor(QtCore.Qt.SizeHorCursor) self.resizeFunc = self.resizeLeft elif edge == QtCore.Qt.TopEdge: self.setCursor(QtCore.Qt.SizeVerCursor) self.resizeFunc = self.resizeTop elif edge == QtCore.Qt.RightEdge: self.setCursor(QtCore.Qt.SizeHorCursor) self.resizeFunc = self.resizeRight else: self.setCursor(QtCore.Qt.SizeVerCursor) self.resizeFunc = self.resizeBottom self.mousePos = None def resizeLeft(self, delta): window = self.window() width = max(window.minimumWidth(), window.width() - delta.x()) geo = window.geometry() geo.setLeft(geo.right() - width) window.setGeometry(geo) def resizeTop(self, delta): window = self.window() height = max(window.minimumHeight(), window.height() - delta.y()) geo = window.geometry() geo.setTop(geo.bottom() - height) window.setGeometry(geo) def resizeRight(self, delta): window = self.window() width = max(window.minimumWidth(), window.width() + delta.x()) window.resize(width, window.height()) def resizeBottom(self, delta): window = self.window() height = max(window.minimumHeight(), window.height() + delta.y()) window.resize(window.width(), height) def mousePressEvent(self, event): if event.button() == QtCore.Qt.LeftButton: self.mousePos = event.pos() def mouseMoveEvent(self, event): if self.mousePos is not None: delta = event.pos() - self.mousePos self.resizeFunc(delta) def mouseReleaseEvent(self, event): self.mousePos = Noneclass Main(QtWidgets.QMainWindow): _gripSize = 8 def __init__(self): QtWidgets.QMainWindow.__init__(self) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.sideGrips = [ SideGrip(self, QtCore.Qt.LeftEdge), SideGrip(self, QtCore.Qt.TopEdge), SideGrip(self, QtCore.Qt.RightEdge), SideGrip(self, QtCore.Qt.BottomEdge), ] # corner grips should be "on top" of everything, otherwise the side grips # will take precedence on mouse events, so we are adding them *after*; # alternatively, widget.raise_() can be used self.cornerGrips = [QtWidgets.QSizeGrip(self) for i in range(4)] @property def gripSize(self): return self._gripSize def setGripSize(self, size): if size == self._gripSize: return self._gripSize = max(2, size) self.updateGrips() def updateGrips(self): self.setContentsMargins(*[self.gripSize] * 4) outRect = self.rect() # an "inner" rect used for reference to set the geometries of size grips inRect = outRect.adjusted(self.gripSize, self.gripSize, -self.gripSize, -self.gripSize) # top left self.cornerGrips[0].setGeometry( QtCore.QRect(outRect.topLeft(), inRect.topLeft())) # top right self.cornerGrips[1].setGeometry( QtCore.QRect(outRect.topRight(), inRect.topRight()).normalized()) # bottom right self.cornerGrips[2].setGeometry( QtCore.QRect(inRect.bottomRight(), outRect.bottomRight())) # bottom left self.cornerGrips[3].setGeometry( QtCore.QRect(outRect.bottomLeft(), inRect.bottomLeft()).normalized()) # left edge self.sideGrips[0].setGeometry( 0, inRect.top(), self.gripSize, inRect.height()) # top edge self.sideGrips[1].setGeometry( inRect.left(), 0, inRect.width(), self.gripSize) # right edge self.sideGrips[2].setGeometry( inRect.left() + inRect.width(), inRect.top(), self.gripSize, inRect.height()) # bottom edge self.sideGrips[3].setGeometry( self.gripSize, inRect.top() + inRect.height(), inRect.width(), self.gripSize) def resizeEvent(self, event): QtWidgets.QMainWindow.resizeEvent(self, event) self.updateGrips()app = QtWidgets.QApplication([])m = Main()m.show()m.resize(240, 160)app.exec_()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62807295', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9243026/']}
jdg_72622
stackexchange
llm_judgeable_groundtruth_similarity
2728987
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 jQuery Dialog form and on submit I'm trying to validate the fields. I'm using jQuery Validation plugin to validate. In this I'm facing an issue, the validate function is not being called. I'm posting some snippet of my code: $("#register-dialog-form").dialog({ autoOpen: false, height: 350, width: 450, modal: true, buttons: { 'Register': function() { $("#registerFrm").validate({ rules: { accountid: "required", name: { required: true, minlength: 5 }, username: { required: true, minlength: 5 }, password: { required: true, minlength: 5 } }, messages: { firstname: "Please enter your firstname", accountid: "Please enter the lastname", name: "Please enter a user friendly name", username: { required: "Please enter a username", minlength: jQuery.format("Enter at least {0} characters") }, password: { required: "Please provide a password", minlength: jQuery.format("Password must be at least {0} characters long") } } }); //****************** //TODO: Need to submit my form here //****************** $(this).dialog('close'); }, Cancel: function() { $(this).dialog('close'); } }, close: function() { //$('registerFrm').clearForm(); }}); Can someone please tell me what I'm doing wrong here. I've also tried to put the validation into $(document).ready(function() {} , but without success. Here is the html code: <div id="register-dialog-form" title="Register Account - Master" align="center" style="display: none"> <s:form name="registerFrm" id="registerFrm" action="registermaster" method="POST"> <table width="90%" border="0" class="ui-widget"> <tr> <td> <s:textfield label="Account Id" name="accountid" id="accountid" cssClass="text ui-widget-content ui-corner-all" /> </td> </tr> <tr> <td> <s:textfield label="Name" name="name" id="name" cssClass="text ui-widget-content ui-corner-all" /> </td> </tr> <tr> <td> <s:textfield label="Username" name="username" id="username" cssClass="text ui-widget-content ui-corner-all" /> </td> </tr> <tr> <td> <s:password label="Password" name="password" id="password" cssClass="text ui-widget-content ui-corner-all" /> </td> </tr> </table> </s:form> </div><!--End of RegisterAcc form--> Here is the Page source: <div id="register-dialog-form" title="Register Account - Master" align="center" style="display: none"><form id="registerFrm" name="registerFrm" onsubmit="return true;" action="registermaster.action" method="POST"><table class="wwFormTable"> <table width="90%" border="0" class="ui-widget"> <tr> <td> <tr> <td class="tdLabel"><label for="accountid" class="label">Account Id:</label></td> <td><input type="text" name="accountid" value="" id="accountid" class="text ui-widget-content ui-corner-all"/></td></tr> </td> </tr> <tr> <td> <tr> <td class="tdLabel"><label for="name" class="label">Name:</label></td> <td><input type="text" name="name" value="" id="name" class="text ui-widget-content ui-corner-all"/></td></tr> </td> </tr> <tr> <td> <tr> <td class="tdLabel"><label for="username" class="label">Username:</label></td> <td><input type="text" name="username" value="" id="username" class="text ui-widget-content ui-corner-all"/></td></tr> </td> </tr> <tr> <td> <tr> <td class="tdLabel"><label for="password" class="label">Password:</label></td> <td><input type="password" name="password" id="password" class="text ui-widget-content ui-corner-all"/></td></tr> </td> </tr> </table> </table></form> </div><!--End of RegisterAcc form--> Now provide the response and nothing else.
To be honest, creating a form to perform the job of hyperlinks is a bit of a semantic no no. Codeigniter by default completely strips any $_GET parameters. So without enabling query strings in the config, you can't do the following: http://my-domain.com/script/?param=1&param2=foo For a beginner, segment based URLs are a bit of a learning curve, but soon make sense. A good production example of how segment based URLs work in practice is Stack Overflow! So if you wanted to copy Stack Overflow's question view page with the following URL in codeigniter: eg; http://stackoverflow.com/questions/2728978/codeigniter-passing-variables-via-url-alternatives-to-using-get In your default controller create the following method: public function questions(){ $question_id = $this->uri->segment(2); // now do something with our question_id} The third segment (question title slug) is effectively ignored. But you could grab it with the following: $question_title = $this->uri->segment(3); More information here . If you don't like the idea of having to name a method in your controller with the first URI segment. You could create a custom route in your routes configuration. So, imagine you create a controller called questions_controller.php , and have a method called show_question_by_id() . To keep the /questions/1234/some-text-here style URI but handle it with the controller/method above, you could create the following route: $route['question/(:num)'] = "questions_controller/show_question_by_id/$1"; More information here . If you wish to have an infinite number of parameters in your URL, or don't know what parameters to expect e.g. mysite.com/my_page/param1/12/param2/foo/param3/bar/param4/baz/another-param/xyz-123 You can split these into an associative array using the $this->uri->uri_to_assoc(1) URI method to get the following: [array]( 'param1' => '12' 'param2' => 'foo' 'param3' => 'bar' 'param3' => 'baz' 'another-param' => 'xyz-123') You could then handle this exactly as if you were using the $_GET array. You can then combine this approach, with custom routes to give you practically any URI and application structure you like. You also get the benefit that each parameter and segment has been automatically cleaned up. It's a bit of a learning curve, and can seem like extra work to begin with, but is actually pretty flexible and helps you to build a well structured application.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2728987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/185412/']}
jdg_72623
stackexchange
llm_judgeable_groundtruth_similarity
851996
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: On a Debian server, I'm having problem with hwclock : $ hwclock --show hwclock: Cannot access the Hardware Clock via any known method.hwclock: Use the --debug option to see the details of our search for an access method. System runs on backports kernel Debian 4.9.18-1~bpo8+1 (2017-04-10) . Here's debug output: $ hwclock --debughwclock from util-linux 2.25.2hwclock: cannot open /dev/rtc: Device or resource busyNo usable clock interface found.hwclock: Cannot access the Hardware Clock via any known method. clocksource: $ cat /sys/devices/system/clocksource/clocksource0/current_clocksourcetsc Finally, rtc device exists: $ ls -l /dev/rtc*lrwxrwxrwx 1 root root 4 Apr 29 16:41 /dev/rtc -> rtc0crw------- 1 root root 253, 0 Apr 29 16:41 /dev/rtc0 Now provide the response and nothing else.
The problem seems to be connected to clocksource , check available_clocksource : $ cat /sys/devices/system/clocksource/clocksource0/available_clocksourcetsc hpet acpi_pm Based on answer to "What does “clocksource tsc unstable” mean?" it looks like TSC (Time Stamp Counter) is not very reliable. By updating /etc/default/grub you can switch to another available clocksource. I'm using HPET . GRUB_CMDLINE_LINUX_DEFAULT="clocksource=hpet" and updating grub: update-grub2 After reboot hwclock works again (just reboot without any modification might have helped as well - it might be just question for how long). NOTE : Optimal clocksource might depend on your motherboard and CPU model.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/851996', 'https://serverfault.com', 'https://serverfault.com/users/65750/']}
jdg_72624
stackexchange
llm_judgeable_groundtruth_similarity
16259435
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The following java segment will result a NullPointException, since the variable list is null, which is pass to the for-each loop. List<> arr = null;for (Object o : arr) { System.out.println("ln "+o);} I think for (Object o : arr){ } is a equivalent to for (int i = 0; i < arr.length; i++) { } and/or for (Iterator<type> iter = arr.iterator(); iter.hasNext(); ){ type var = iter.next(); } In either cases arr is null will cause arr.length or arr.iterator() throws a NullPointException I'm just curious the reason why for (Object o : arr){ } is NOT translate to if (arr!=null){ for (int i = 0; i < arr.length; i++) { }}andif (arr!=null){ for (Iterator<type> iter = arr.iterator(); iter.hasNext(); ){ type var = iter.next(); }} Include arr!=null expression could reduce code nesting. Now provide the response and nothing else.
I see the following reasons, although I have no idea if anybody thought about this, when it was implemented, and what the actual reasons were. As you demonstrated the current behavior of the for(:)-loop is very easy to understand. The other behavior isn't It would be the only thing in the java universe behaving in this way. It wouldn't be equivalent to the simple for-loop so migrating between the two would actually not be equivalent Using null is a bad habit anyway, so NPEs are a nice way of telling the developer "you F***ed up, clean up your mess" with the proposed behavior the problem would just be hidden. What if you want to do anything else with the array before or after the loop ... now you would have the null check twice in your code.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16259435', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2210695/']}
jdg_72625
stackexchange
llm_judgeable_groundtruth_similarity
2291
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: Suppose I do two experiments to find the triple point of water, one in zero-g and one on Earth. On Earth, water in the liquid or solid phase has less gravitational potential per unit mass than water in the gas phase. Therefore, the solid and liquid phases should be favored slightly more on Earth than in zero-g. In a back-of-the-envelope calculation, how does the temperature of the triple-point of water depend on the gravitational acceleration and, if necessary, on the mass of water and volume and shape of container? Edit Let's say I have a box in zero-g. The box is one meter on a side. It has nothing in it but water. Its temperature and pressure are just right so that it's at the triple point. All the water and ice and steam are floating around the box because it's zero-g. Now I turn on gravity. The liquid water and ice fall to the bottom of the box, but the average height of the steam remains almost half a meter above the bottom of the box. So when gravity got turned on, the potential energy of the ice and liquid water went down significantly, but the potential energy of the steam didn't. Doesn't this mean that once gravity is turned on, water molecules would rather be part of the ice or liquid phase so that they can have lower energy? Wouldn't we no longer be at the triple point? Several people have posted saying the answer is "no". I don't disbelieve that. Maybe the answer is just "no". I don't understand why the answer is no. Answers such as "No, because gravity doesn't affect the triple point," or "No, because the triple point only depends on pressure and temperature" simply restate the answer "no" with more words. Now provide the response and nothing else.
This is perhaps similar to what mbq meant, but I will elaborate.The T-p phase diagram of water tells us, for a given temperature and pressure, what phase we will get if we have a bunch of that substance. If I apply different pressures to a bottle of water, I am moving around in the p-direction of the T-p plane. I am not changing the pressure of the triple point of water, just changing the pressure of that particular bottle of water! Similarly, if a tank of water is in a gravitational field, it affects the pressure. In fact, it leads to different pressures at different locations of the tank. It could lead some parts of the tank to freeze, for example. But it does not in any way change the triple point of water itself, which is an intrinsic property of that substance. So I would say that the question is ill-posed. It might be better to ask: what will happen to a tank of water at a given temperature and density if we now apply a gravitational field?
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/2291', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/74/']}
jdg_72626
stackexchange
llm_judgeable_groundtruth_similarity
121087
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: How is the random string M1uG*xgRCthKWwjIjWc*010iSthY9buc being detected as too simplistic/systematic for a password according to passwd and cracklib-check ? Try it on your machine and see echo "M1uG*xgRCthKWwjIjWc*010iSthY9buc" | cracklib-check Note that this is not my password, but another randomly generated string from the same random password generator that produces the same result. Now provide the response and nothing else.
Since cracklib is open source, the answer can be found in the source code . "Too simplistic/systematic" means that there are too many characters that are preceded by one of their alphabetical neighbors. Hence "ab" or "ba" are considered bad, but "ac" or "ca" are OK since the b is omitted. Before this patch from 2010-03-02 , it allows at most four characters that exhibit this trait. E.g., "bar12345" would fail, because the characters "a", "2", "3", "4" and "5" are alphabetical neighbors of the preceding characters. slm found out in his answer that M1uG*xgRCthKWwjIjWc*010iS was OK, while M1uG*xgRCthKWwjIjWc*010iSt is not. Let's analyze. Here are the characters that cracklib-check thinks are indications of a systematic password: M1uG*xgRCthKWwjIjWc*010iS ^^ ^^ which is below the max of four, but adding the t: M1uG*xgRCthKWwjIjWc*010iSt ^^ ^^ ^ pushes it above the limit, since T follows S (it appears the test is case insensitive). The patch changes the max limit so it depends on the total password length, to avoid false positives like this.
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/121087', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/41855/']}
jdg_72627
stackexchange
llm_judgeable_groundtruth_similarity
41961217
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 install netstat on my Docker container. I looked here https://askubuntu.com/questions/813579/netstat-or-alternative-in-docker-ubuntu-server-16-04-container so I'm trying to install it like this: apt-get install net-tools However, I'm getting: Reading package lists... DoneBuilding dependency treeReading state information... DoneE: Unable to locate package net-tools So how can I install netstat ? Now provide the response and nothing else.
You need to run apt-get update first to download the current state of the package repositories. Docker images do not include this to save space, and because they'd likely be outdated when you use it. If you are doing this in a Dockerfile, make sure to keep it as a single RUN command so that caching of the layers doesn't cache an old version of the update command with a new package install request: RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y \ net-tools \ && apt-get clean \ && rm -rf /var/lib/apt/lists/*
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41961217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3122885/']}
jdg_72628
stackexchange
llm_judgeable_groundtruth_similarity
16195986
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 determine whether a given string can be interpreted as a number (integer or floating point) in an SQL statement. As in the following: SELECT AVG(CASE WHEN x ~ '^[0-9]*.?[0-9]*$' THEN x::float ELSE NULL END) FROM test I found that Postgres' pattern matching could be used for this. And so I adapted the statement given in this place to incorporate floating point numbers. This is my code: WITH test(x) AS ( VALUES (''), ('.'), ('.0'), ('0.'), ('0'), ('1'), ('123'), ('123.456'), ('abc'), ('1..2'), ('1.2.3.4'))SELECT x , x ~ '^[0-9]*.?[0-9]*$' AS isnumericFROM test; The output: x | isnumeric ---------+----------- | t . | t .0 | t 0. | t 0 | t 1 | t 123 | t 123.456 | t abc | f 1..2 | f 1.2.3.4 | f(11 rows) As you can see, the first two items (the empty string '' and the sole period '.' ) are misclassified as being a numeric type (which they are not). I can't get any closer to this at the moment. Any help appreciated! Update Based on this answer (and its comments), I adapted the pattern to: WITH test(x) AS ( VALUES (''), ('.'), ('.0'), ('0.'), ('0'), ('1'), ('123'), ('123.456'), ('abc'), ('1..2'), ('1.2.3.4'), ('1x234'), ('1.234e-5'))SELECT x , x ~ '^([0-9]+[.]?[0-9]*|[.][0-9]+)$' AS isnumericFROM test; Which gives: x | isnumeric ----------+----------- | f . | f .0 | t 0. | t 0 | t 1 | t 123 | t 123.456 | t abc | f 1..2 | f 1.2.3.4 | f 1x234 | f 1.234e-5 | f(13 rows) There are still some issues with the scientific notation and with negative numbers, as I see now. Now provide the response and nothing else.
As you may noticed, regex-based method is almost impossible to do correctly. For example, your test says that 1.234e-5 is not valid number, when it really is. Also, you missed negative numbers. What if something looks like a number, but when you try to store it it will cause overflow? Instead, I would recommend to create function that tries to actually cast to NUMERIC (or FLOAT if your task requires it) and returns TRUE or FALSE depending on whether this cast was successful or not. This code will fully simulate function ISNUMERIC() : CREATE OR REPLACE FUNCTION isnumeric(text) RETURNS BOOLEAN AS $$DECLARE x NUMERIC;BEGIN x = $1::NUMERIC; RETURN TRUE;EXCEPTION WHEN others THEN RETURN FALSE;END;$$STRICTLANGUAGE plpgsql IMMUTABLE; Calling this function on your data gets following results: WITH test(x) AS ( VALUES (''), ('.'), ('.0'), ('0.'), ('0'), ('1'), ('123'), ('123.456'), ('abc'), ('1..2'), ('1.2.3.4'), ('1x234'), ('1.234e-5'))SELECT x, isnumeric(x) FROM test; x | isnumeric----------+----------- | f . | f .0 | t 0. | t 0 | t 1 | t 123 | t 123.456 | t abc | f 1..2 | f 1.2.3.4 | f 1x234 | f 1.234e-5 | t (13 rows) Not only it is more correct and easier to read, it will also work faster if data was actually a number.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/16195986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1025391/']}
jdg_72629
stackexchange
llm_judgeable_groundtruth_similarity
5447494
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the best way to remove an item from a dictionary by value, i.e. when the item's key is unknown? Here's a simple approach: for key, item in some_dict.items(): if item is item_to_remove: del some_dict[key] Are there better ways? Is there anything wrong with mutating (deleting items) from the dictionary while iterating it? Now provide the response and nothing else.
Be aware that you're currently testing for object identity ( is only returns True if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with == ). If you are doing this on purpose, then you could rewrite your code as some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove} But this may not do what you want: >>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}>>> value_to_remove = "You say yes">>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}>>> some_dict{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}>>> some_dict{1: 'Hello', 2: 'Goodbye', 4: 'I say no'} So you probably want != instead of is not .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5447494', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/565879/']}
jdg_72630
stackexchange
llm_judgeable_groundtruth_similarity
2554
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How does one plot Venn diagrams with Mathematica? I've searched quite a bit and I've found one source at MathWorld which provides the source code for doing them. But I don't understand this code, can someone help me? Now provide the response and nothing else.
Based on that outdated notebook, I did the following function: VennDiagram2[n_, ineqs_: {}] := Module[{i, r = .6, R = 1, v, grouprules, x, y, x1, x2, y1, y2, ve}, v = Table[Circle[r {Cos[#], Sin[#]} &[2 Pi (i - 1)/n], R], {i, n}]; {x1, x2} = {Min[#], Max[#]} &[ Flatten@Replace[v, Circle[{xx_, yy_}, rr_] :> {xx - rr, xx + rr}, {1}]]; {y1, y2} = {Min[#], Max[#]} &[ Flatten@Replace[v, Circle[{xx_, yy_}, rr_] :> {yy - rr, yy + rr}, {1}]]; ve[x_, y_, i_] := v[[i]] /. Circle[{xx_, yy_}, rr_] :> (x - xx)^2 + (y - yy)^2 < rr^2; grouprules[x_, y_] = ineqs /. Table[With[{is = i}, Subscript[_, is] :> ve[x, y, is]], {i, n}]; Show[ If[MatchQ[ineqs, {} | False], {}, RegionPlot[grouprules[x, y], {x, x1, x2}, {y, y1, y2}, Axes -> False] ], Graphics[v] , PlotLabel -> TraditionalForm[Replace[ineqs, {} | False -> ∅]], Frame -> False ] ] Which can have as inequallity any logical expression with subscripts: EDIT : It works with more than 3 groups! EDIT2 : As Brett says, some cases of 5 doesn't work, like VennDiagram2[5, Subscript[A, 1] && ! (Subscript[A, 2] || Subscript[A, 5]) && Subscript[A, 3] && Subscript[A, 4]] , but for example if you change the order to something else it works: VennDiagram2[5, Subscript[A, 1] && ! (Subscript[A, 3] || Subscript[A, 4]) && Subscript[A, 2] && Subscript[A, 5]] . So an intelligent way of sorting the circles should be needed for complex cases.
{}
{'log_upvote_score': 7, 'links': ['https://mathematica.stackexchange.com/questions/2554', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/603/']}
jdg_72631
stackexchange
llm_judgeable_groundtruth_similarity
40164908
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 below code and I am new to mongodb, I need help in finding an specific element in the collection. using MongoDB.Bson;using MongoDB.Driver;namespace mongo_console {public class User { public ObjectId Id { get; set; } public string name { get; set; } public string pwd { get; set; }}class Program { static void Main(string[] args) { MongoClient client = new MongoClient(); MongoServer server = client.GetServer(); MongoDatabase db = server.GetDatabase("Users"); MongoCollection<User> collection = db.GetCollection<User>("users"); User user = new User { Id = ObjectId.GenerateNewId(), name = "admin", pwd = "admin" }; User user2 = new User { Id = ObjectId.GenerateNewId(), name = "system", pwd = "system" }; collection.Save(user); collection.Save(user2); /* * How do I collection.Find() for example using the name */ }}} Once I find the user I will like to print it, is that posible or will find only return the position? if so, how do I print it? I have seen some examples collection.Find(x => x.something) but I do not know what that x is or mean Now provide the response and nothing else.
To find a record you could use Lambda in find, for example: var results = collection.Find(x => x.name == "system").ToList(); Alternatively you can use Builders which work with strongly typed Lambda or text: var filter = Builders<User>.Filter.Eq(x => x.name, "system") Or var filter = Builders<User>.Filter.Eq("name", "system") And then use find as above // results will be a collection of your documents matching your filter criteria// Sync syntaxvar results = collection.Find(filter).ToList();// Async syntaxvar results = await collection.Find(filter).ToListAsync();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40164908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2740157/']}
jdg_72632
stackexchange
llm_judgeable_groundtruth_similarity
417123
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'm reading Categories for the Working Mathematician by Saunders Mac Lane. At the section 5 from chapter 1, for a fixed category, he claims that every arrow with right inverse, is epic (right cancellable). He claims also that the converse is true in the category of Sets, but fails in the category of Groups. I tried by myself to find a pair of groups and an arrow having these properties, but I cannot find them. I also read that a given group, regarded as a category with one element, one arrow per element of the group, and the composition of arrows representing the group product, is not a concrete category. How can I prove that? Thanks in advance. Every help would be very appreciated. Now provide the response and nothing else.
If $f:Q_8 \to \{\pm 1\}$ is defined by $\{1,-1,i,-i\} \mapsto 1$ and $\{j,-j,k,-k\} \mapsto -1$ then $f$ is epic, but it has no right inverse, that is, there is no homomorphism $h: \{\pm 1 \} \to Q_8$ so that $f(h(-1))=-1$. This is simply because there are only two homomorphisms from $\{\pm 1\}$ to $Q_8$, $-1 \mapsto \pm 1$, but $f(\pm1)=1 \neq -1$. An abelian example is $f:\mathbb{Z}/4\mathbb{Z} \to \mathbb{Z}/2\mathbb{Z}:x+4\mathbb{Z} \mapsto x+2\mathbb{Z}$. It is epic (in any concrete category containing it), but has no right inverse since there are (at most) two $h:\mathbb{Z}/2\mathbb{Z} \to \mathbb{Z}/4\mathbb{Z}$, $h(n+2\mathbb{Z})=0+4\mathbb{ZZ}$ and $h(n+2\mathbb{Z}) = 2n + 4\mathbb{Z}$. However $f(h(1+2\mathbb{Z})) = 2n + 2\mathbb{Z} = 0 +2\mathbb{Z} \neq 1+2\mathbb{Z}$ in both cases, so $f$ has no right inverse. Most algebraic categories are like this: not being a zero-divisor is different from being a unit. Not all epics split. I believe a one object category in which all arrows are invertible (a “group”) is always a concrete category insofar as there is a faithful functor to the category of sets. My view of the object is as the set containing the group elements, and the arrows as either the left or right multiplication maps, which makes it a concrete category as well.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/417123', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/49329/']}
jdg_72633
stackexchange
llm_judgeable_groundtruth_similarity
13351032
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 C++ 11 code that uses lambda, this is an example. #include <iostream>using namespace std;int main(){ auto func = [] () { cout << "Hello world"; }; func(); // now call the function} When I compiled this code with clang 3.1 ( Apple clang version 3.1 (tags/Apple/clang-318.0.54) (based on LLVM 3.1svn) ), I got this error lambda.cpp:7:17: error: expected expressionauto func = [] () { cout << "Hello world"; }; What might be wrong? In this site , lambda seems to be supported with clang 3.1. ADDED With -std=gnu++11 or c++11 option, I got these error messages. 0. Program arguments: /usr/bin/clang -cc1 -triple x86_64-apple-macosx10.7.4 -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -main-file-name lambda.cpp -pic-level 1 -mdisable-fp-elim -relaxed-aliasing -masm-verbose -munwind-tables -target-cpu core2 -target-linker-version 128.2 -resource-dir /usr/bin/../lib/clang/3.1 -fmodule-cache-path /var/folders/ng/h2hkycqd2q5g2hz42c47bt4w0000gn/T/clang-module-cache -std=gnu++11 -fdeprecated-macro -fdebug-compilation-dir /Users/smcho/Desktop/C++test -ferror-limit 19 -fmessage-length 173 -stack-protector 1 -fblocks -fobjc-runtime-has-arc -fobjc-runtime-has-weak -fobjc-dispatch-method=mixed -fcxx-exceptions -fexceptions -fdiagnostics-show-option -fcolor-diagnostics -o /var/folders/ng/h2hkycqd2q5g2hz42c47bt4w0000gn/T/lambda-XvZzHg.o -x c++ lambda.cpp 1. lambda.cpp:7:49: current parser token ';'2. lambda.cpp:6:1: parsing function body 'main'3. lambda.cpp:6:1: in compound statement ('{}')clang: error: unable to execute command: Segmentation fault: 11clang: error: clang frontend command failed due to signal 2 (use -v to see invocation)clang: note: diagnostic msg: Please submit a bug report to http://developer.apple.com/bugreporter/ and include command line arguments and all diagnostic information.clang: note: diagnostic msg: Preprocessed source(s) and associated run script(s) are located at:clang: note: diagnostic msg: /var/folders/ng/h2hkycqd2q5g2hz42c47bt4w0000gn/T/lambda-roTwCZ.iiclang: note: diagnostic msg: /var/folders/ng/h2hkycqd2q5g2hz42c47bt4w0000gn/T/lambda-roTwCZ.sh Now provide the response and nothing else.
This is because clang++ by default compiles your code using ISO C++ 1998 standard (including the defects addressed in the ISO C++ 2003 standard) except for 'export' (which has been removed in C++11) Lambdas are part of Clang's C++11 Language Extension , therefore you need to compile your code with -std=c++11 or -std=gnu++11 Also see: Clang 3.1 and C++11 support status and Activating C++11 support in Clang EDIT: I think you are trying to compile your program with the C compiler ( clang ) rather than C++ compiler ( clang++ ) or your installation of Clang doesn't link to libc or libstdc++ . Try to link against each library to see which one works for you, it is possible that libc might not be installed on your system. Try to compile your program with C++11 mode using the clang++ executable (the C++ compiler) and link it either with Clang C++ Standard Library or the GNU Standard C++ Library 1) # Uses Clang C++ Library and enables C++11 modeclang++ -stdlib=libc++ -std=c++11 [input] 2) # Uses GNU Standard C++ Library and enables C++11 modeclang++ -stdlib=libstdc++ -std=c++11 [input] Another possible problem might be that you haven't compiled Clang with the right options to enable C++11 language extensions, try and check the documentation for correct flags to use when you configure the compilation process for Clang.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13351032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260127/']}
jdg_72634
stackexchange
llm_judgeable_groundtruth_similarity
201059
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Freiling's Axiom of Symmetry says that for any function $f:[0,1]\to \mathcal{P}([0,1])$ such that for every $x\in [0,1]$ we have $|f(x)|=\aleph_0$, then there exist $y,z\in [0,1]$ such that $z\notin f(y)$ and $y\notin f(z)$. This is equivalent to the negation of the continuum hypothesis (see this wiki page ). My question is whether one can produce an uncountable set $A$, using the axioms in ZFC, so that if we plug $A$ in place of $[0,1]$, it satisfies Freiling's Axiom. Now provide the response and nothing else.
Theorem. The following are equivalent for a set $A$ $A$ has the property of Freiling's axiom. That is, if $a\mapstoX_a$ is any map from $A$ to the countable subsets of $A$, thenthere are $a$ and $b$ with $a\notin X_b$ and $b\notin X_a$. $A$ has size at least $\aleph_2$. Proof. ($1\to 2$) We prove the contrapositive. If $A$ had sizeless than $\aleph_2$, then we can enumerate the elements of $A$ as$A=\{\ a_\alpha\mid\alpha<\omega_1\ \}$. For any $a\in A$, let $\alpha$ be least with $a=a_\alpha$, and map$a\mapsto X_a=\{a_\beta\mid\beta<\alpha\}$. For any $a\neq b$, oneof them appears first before the other, and so either $a\in X_b$or $b\in X_a$, contrary to statement $1$. ($2\to 1$) If $A$ has size at least $\aleph_2$, then suppose wehave any function $a\mapsto X_a$ where $X_a$ is a countable subsetof $A$. By applying the function $\omega_1$ many times, we mayfind a subset $Y\subset A$ of size $\omega_1$, which is closedunder the map, in the sense that $a\in Y\to X_a\subset Y$. Nowpick any $b\notin Y$. Since $X_b$ is countable, there is some$a\in Y$ with $a\notin X_b$, and since $b\notin Y$, it followsthat $b\notin X_a$, and so we have achieved Freiling's property. QED
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/201059', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3199/']}
jdg_72635
stackexchange
llm_judgeable_groundtruth_similarity
32318
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm struggling to understand the difference between the standard error and the standard deviation. How are they different and why do you need to measure the standard error? Now provide the response and nothing else.
Let $\theta$ be your parameter of interest for which you want to make inference. To do this, you have available to you a sample of observations $\mathbf{x} = \{x_1, \ldots, x_n \}$ along with some technique to obtain an estimate of $\theta$, $\hat{\theta}(\mathbf{x})$. In this notation, I have made explicit that $\hat{\theta}(\mathbf{x})$ depends on $\mathbf{x}$. Indeed, if you had had another sample, $\tilde{\mathbf{x}}$, you would have ended up with another estimate, $\hat{\theta}(\tilde{\mathbf{x}})$. This makes $\hat{\theta}(\mathbf{x})$ a realisation of a random variable which I denote $\hat{\theta}$. This random variable is called an estimator. The standard error of $\hat{\theta}(\mathbf{x})$ (=estimate) is the standard deviation of $\hat{\theta}$ (=random variable). It contains the information on how confident you are about your estimate. If it is large, it means that you could have obtained a totally different estimate if you had drawn another sample. The standard error is used to construct confidence intervals.
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/32318', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/12627/']}
jdg_72636
stackexchange
llm_judgeable_groundtruth_similarity
8839787
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 to create setter and getter Properties for nullable datetime.for example: private DateTime mTimeStamp;public DateTime TimeStamp{ get { return mTimeStamp; } set { mTimeStamp = value; }} Does nullable attributes support setter and getter or have i to declare it public? private DateTime? mTimeStamp;public DateTime TimeStamp{} Now provide the response and nothing else.
You can just do this instead: public DateTime? TimeStamp { get; set; } If you were having trouble with the compiler it's probably because you only changed one of the associated parts - either the private member variable or the property's data type. They need to match, of course, and auto-properties handles that for you nicely. EDIT Just to further clarify, DateTime? is not merely decorated with an ? attribute - it's entirely different from DateTime . DateTime? is shorthand for Nullable<DateTime> , which is a generic ( Nullable<T> ) that provides nullable support to non-reference types by wrapping the generic parameter T , which is a struct .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8839787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/714597/']}
jdg_72637
stackexchange
llm_judgeable_groundtruth_similarity
26289413
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 new in Swift. I have a base class: class foo{} I want to implement a foo collection class: class foos: Array<foo>{} But the compiler is complaining: inheritance from a non-protocol, non-class type of 'Array' I have tried other syntax (e.g. [foo] and NSMutableArray<foo> ) but none of them passes the compiler check. This should be simple but I have googled all day and could not figure it out. Does anyone know if it is possible and if it is, the correct syntax? Now provide the response and nothing else.
Swift's Array type is a structure, and in Swift, base classes must be actual classes (that is, class Foo ) and not structures. So you cannot do what you are trying to do via inheritance from Array , unfortunately. You could, however, store the array as a field within your class and forward methods to it, possibly implementing any protocols you want to support, et cetera.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26289413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/605747/']}
jdg_72638
stackexchange
llm_judgeable_groundtruth_similarity
12483753
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can I define functions in C++ inline? I am talking about lambda functions, not the inline keyword that causes a compiler optimization. Now provide the response and nothing else.
C++11 added lambda functions to the language. The previous versions of the language (C++98 and C++03), as well as all current versions of the C language (C89, C99, and C11) do not support this feature. The syntax looks like: [capture](parameters)->return-type{body} For example, to compute the sum of all of the elements in a vector: std::vector<int> some_list;int total = 0;for (int i=0;i<5;i++) some_list.push_back(i);std::for_each(begin(some_list), end(some_list), [&total](int x) { total += x;});
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12483753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1079110/']}
jdg_72639
stackexchange
llm_judgeable_groundtruth_similarity
135794
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: During the formation of Wittig reagent, BuLi is used as it is a VERY strong base (p K a = 50). According to Wikipedia, however, sulfur ylide is 'especially conveniently' made from dimsyl anion (p K a = 35), which is a relatively weaker base although it is also used for preparation of Wittig reagent. If there is a stronger base is allowed (BuLi), why is dimsyl anion used 'conveniently'? To prevent side reactions or just by what is available at hand? Typically phosphorus ylids are made from PPh 3 . What is the purpose of having 3 phenyl groups linked to the phosphorus atom in Wittig reagent? Can't be as small as sulfonium ylide molecule? I have no idea what is the use of adding 3 bulky and sterically-hindered groups in the ylide. Now provide the response and nothing else.
I am fairly sure that for both, there are practicality issues at hand. This is almost certainly so for the choice of phosphine. Even though PPh 3 is absolutely terrible from an atom economy point of view, and even though PPh 3 O can be a real pain to remove after the reaction is done, at least it's a nice white solid which doesn't smell. On the other hand, the simpler alternative PMe 3 is a volatile, pyrophoric, and extremely stinky liquid. PPh 3 is also substantially cheaper than other alternative phosphines. (There are similar considerations for the Mitsunobu reaction which I have some experience with.) As for the base, $\ce{BuLi}$ is just one of the most accessible strong bases to use. I don't think you can buy dimsyl sodium from the average chemical supplier. My suspicion is that the main reason why dimsyl anion is somewhat associated with the sulfur ylids is because E. J. Corey and his postdoc M. Chaykovsky popularised them together ( e.g. , Ref.1). Also note that $\ce{NaH/DMSO}$ mixtures are associated with significant explosion hazards (Ref.2). Others with more experience will be able to give fuller answers. References: E. J. Corey, Michael Chaykovsky, “Methylsulfinyl Carbanion ( $\ce{CH3-SO-CH2-}$ ). Formation and Applications to Organic Synthesis,” J. Am. Chem. Soc. 1965 , 87(6) , 1345–1353 ( https://doi.org/10.1021/ja01084a033 ). Qiang Yang, Min Sheng, James J. Henkelis, Siyu Tu, Eric Wiensch, Honglu Zhang, Yiqun Zhang, Craig Tucker, David E. Ejeh, “Explosion Hazards of Sodium Hydride in Dimethyl Sulfoxide, N,N -Dimethylformamide, and N,N -Dimethylacetamide,” Org. Process Res. Dev. 2019 , 23(10) , 2210–2217 ( https://doi.org/10.1021/acs.oprd.9b00276 ).
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/135794', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/94136/']}
jdg_72640