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
18654162
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recent NTFS and Windows implement symlinks: NTFS junction point can be used as directory symlink since NTFS 3.0 (Windows 2000) using linkd or junction tools. NTFS symbolic link can also be used as symlink (for both file and directory) since Windows Vista using mklink tool. But on Cygwin 1.7 (installed on Windows 7), ln -s creates a text file. on Cygwin: $ ln -s -v target mylink`mylink' -> `target' on MinGW (or your favorite editor): $ cat mylink!<symlink>ÿþt a r g e t Is it possible to tell Cygwing to use NTFS junction point or NTFS symbolic link ? other question: Is this available on MinGW? Now provide the response and nothing else.
⸻⸻  Short answer  ⸻⸻ Define environment variable: CYGWIN=winsymlinks:nativestrict As pointed out by mwm you may also have to go to the settings or to run bash as Administrator. See the Notes section. ⸻⸻  Long answer  ⸻⸻ Default Cygwin symlinks are just regular files By default Cygwin creates text files as workaround for Windows symlink flaw.These files are not really symlinks .Almost all Windows programs do not considers these files as symlinks. Native symlinks are available on recent Windows versions Recent NTFS and Windows implement symlinks: NTFS junction point can be used as directory symlinksince NTFS 3.0 (Windows 2000) using linkd or junction tools. NTFS symbolic link can also be used as symlink(for both file and directory) since Windows Vista using mklink tool. Cygwin can create native NTFS symlinks Simplified extract of the Cygwin documentation : Symbolic links [...] Cygwin creates symbolic links potentially in multiple different ways: The default symlinks are plain files containing a magic cookiefollowed by the path to which the link points. [...] The shortcut style symlinks are Windows .lnk [...] createdif the environment variable CYGWIN [...] is set to containthe string winsymlinks or winsymlinks:lnk . [...] Native Windows symlinks are only created on Windows Vista/2008 and later,and only on filesystems supporting reparse points.Due to to their weird restrictions and behaviour, they are only createdif the user explicitely requests creating them.This is done by setting the environment variable CYGWINto contain the string winsymlinks:native or winsymlinks:nativestrict .[...] On the NFS filesystem, Cygwin always creates real NFS symlinks. Configuring Cygwin Cygwin User's Guide presents variable CYGWIN and option winsymlinks : The CYGWIN environment variable is used to configure many global settings [...].It contains the options listed below, separated by blank characters. [...] [...] [...] [...] [...] winsymlinks:{lnk,native,nativestrict} -if set to just winsymlinks or winsymlinks:lnk , Cygwin creates symlinksas Windows shortcuts with a special headerand the R/O attribute set. If set to winsymlinks:native or winsymlinks:nativestrict ,Cygwin creates symlinks as native Windows symlinks on filesystemsand OS versions supporting them. If the OS is known not to supportnative symlinks (Windows XP, Windows Server 2003), a warning messageis produced once per session. The difference between winsymlinks:native and winsymlinks:nativestrict is this: If the filesystem supports nativesymlinks and Cygwin fails to create a native symlink for some reason,it will fall back to creating Cygwin default symlinks with winsymlinks:native , while with winsymlinks:nativestrict the symlink(2) system call will immediately fail. CYGWIN=winsymlinks:native always creates a link but uses a Cygwin fall-back when target does not exists on Cygwin: $ export CYGWIN="winsymlinks:native"$ ln -s -v target mylink`mylink' -> `target'$ echo content > target on MinGW: $ cat mylinkcontent People using both Windows and Cygwin programs may have issues when a symlink is created as a dummy file (Cygwin fallback when target is missing)... CYGWIN=winsymlinks:nativestrict always uses native-Windows symlink but fails when target does not exist on Cygwin: $ export CYGWIN="winsymlinks:nativestrict"$ rm -f a b$ ln -sv a bln: failed to create symbolic link `b': No such file or directory$ touch b$ ln -sv a bln: failed to create symbolic link `b': File exists$ rm b$ touch a$ ln -sv a b`b' -> `a' Because nativestrict requires the target exists before the symlink creation, some commands/scripts may fail when creating a link. Notes Since Windows 10 build 14972, native NTFS symlinks are available in a non-elevated shell by enabling the Developer Mode in the Developer Settings .Reference: https://blogs.windows.com/windowsdeveloper/2016/12/02/symlinks-windows-10/ In older versions, only administrators have the ability to create native NT symlinksso under Windows UAC, the Cygwin terminal emulator (mintty)should be run with elevated privileges(right-click the shortcut and choose Run as Administrator or set the mintty shortcut property, Advanced → Run as Administrator ). Special thanks to Guria , Spooky and Gene Pavlovsky for their contributions.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18654162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/938111/']}
jdg_378741
stackexchange
llm_judgeable_groundtruth_similarity
1978664
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm wondering before I attempt to refactor my page if its possible to have a double nested input array in html. I have an 8X5 group of elements in a form and it would be nice for me to be able to parse it using an array of arrays...something like <input type="text" name="list[][]" /><input type="checkbox" name="list[][]" /> and so on Now provide the response and nothing else.
You are going to need to supply indexes into the first part of each field or else there is nothing to nest, and if it did work, it wouldn't look like a grid on the other end: Row 1: name="list[0][]" Row 2: name="list[1][]" etc. Finally, your server needs to support this as PHP and Rails do out of the box. I am not sure about other server technologies. For an example, the following HTML when posted to PHP: <form action="post.php" method="POST" accept-charset="utf-8"> <input type="text" name="list[0][]" value="1" /> <input type="text" name="list[0][]" value="2" /> <input type="text" name="list[0][]" value="3" /> <input type="text" name="list[1][]" value="4" /> <input type="text" name="list[1][]" value="5" /> <input type="text" name="list[1][]" value="6" /> <input type="text" name="list[3][]" value="7" /> <input type="text" name="list[3][]" value="8" /> <input type="text" name="list[3][]" value="9" /> <input type="submit" name="Send" value="Send" id="Send" /></form> If in the PHP the following code exists: <?php print_r($_POST['list']); ?> The output is: Array( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [1] => Array ( [0] => 4 [1] => 5 [2] => 6 ) [3] => Array ( [0] => 7 [1] => 8 [2] => 9 ))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1978664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/186359/']}
jdg_378742
stackexchange
llm_judgeable_groundtruth_similarity
1657258
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's assume that I've got 2d array like : int[,] my_array = new int[100, 100]; The array is filled with ints. What would be the quickest way to check if a target-value element is contained within the array ? (* this is not homework, I'm trying to come up with most efficient solution for this case) Now provide the response and nothing else.
If the array isn't sorted in some fashion, I don't see how anything would be faster than checking every single value using two for statements. If it is sorted you can use a binary search. Edit:If you need to do this repeatedly, your approach would depend on the data. If the integers within this array range only up to 256, you can have a boolean array of that length, and go through the values in your data flipping the bits inside the boolean array. If the integers can range higher you can use a HashSet. The first call to your contains function would be a little slow because it would have to index the data. But subsequent calls would be O(1). Edit1: This will index the data on the first run, benchmarking found that the Contains takes 0 milliseconds to run after the first run, 13 to index. If I had more time I might multithread it and have it return the result, while asynchronously continuing indexing on the first call. Also since arrays are reference types, changing the value of data passed before or after it has been indexed will provide strange functionality, so this is just a sample and should be refactored prior to use. private class DataContainer{ private readonly int[,] _data; private HashSet<int> _index; public DataContainer(int[,] data) { _data = data; } public bool Contains(int value) { if (_index == null) { _index = new HashSet<int>(); for (int i = 0; i < _data.GetLength(0); i++) { for (int j = 0; j < _data.GetLength(1); j++) { _index.Add(_data[i, j]); } } } return _index.Contains(value); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1657258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/142168/']}
jdg_378743
stackexchange
llm_judgeable_groundtruth_similarity
103021
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: Why Magnifying glass(convex lens) produces heat when placed in front of sun? Now provide the response and nothing else.
When you focus light from the Sun you are actually creating an image of the Sun. If the focal length of the lens is $f$ the radius of the image is given by: $$ r = \frac{r_s}{d_s} f $$ where $d_s$ is the distance to the Sun and $r_s$ is the radius of the Sun. The fraction $r_s/d_s \approx 10^{-3}$, so if you choose a lens with a focal length of 10cm the radius of the image is about 0.1mm (assuming the lens is perfect). The intensity of sunlight is around 1kW per square metre - the exact value depends on latitude, season, time of day, cloud cover, etc, etc so let's just take 1kW/m$^2$ as a representative figure. All the light falling on your lens is being concentrated into the 0.1mm radius image of the Sun, so if the radius of your lens is $r_l$ the power per unit area in the image is: $$ I = \left(\frac{r_l}{0.1 mm} \right)^2 1kW/m^2 $$ So if the lens radius is 5 cm, which seems a fairly standard size for a lens, then the power per unit area in the focussed image of the Sun is about 250MW/m$^2$ or 250,000 times the intensity of Sunlight on the Earth. That's why it's hot! Of course the total power isn't very great, because even though the focussed light is very intense the area of the 0.1 mm image is only about $3 \times 10^{-8}$ square metres. The total power is just the area over which light is being collected (the area of your lens) times 1 kW. A bigger lens will capture more sunlight and focus more power.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/103021', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/41158/']}
jdg_378744
stackexchange
llm_judgeable_groundtruth_similarity
10135910
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 know if there are any constructors involved with inner classes. for example consider the code snippet given below class MyOuter{ private int x= 10; class MyInner { void dostuff(){ System.out.println("The value of x is "+x); } }} In another java file i create instances for both MyOuter and MyInner classes as shown below Class Program{ public static void main(String [] args) { MyOuter mo = new MyOuter(); MyOuter.MyInner mi = mo.new MyInner(); mi.dostuff(); }} The above code snippet compiles fine and gives output of "The value of x is 10". What i want to know here is whether a constructor is invoked when new() is used with MyInner class and MyOuter class. If yes, then is there any constructor chaining from inner class to outer class (like subclass calls constructor of super class and so on). Now provide the response and nothing else.
You can observe the constructor chain for the inner class when you extend an inner class. Take this example: public class MainClass { public MainClass(String value) { System.out.println("mainValue: " + value); } public class NestedClass { public NestedClass(String nestedValue) { System.out.println("nestedValue: " + nestedValue); } }} and then extend the NestedClass like this public class NestedClassExtension extends NestedClass { public NestedClassExtension(MainClass mainClass, String nestedValue) { mainClass.super(nestedValue); }} so you can see that you are able to call the super constructor of your nested class passing to that constructor the MainClass , and calling .super on mainClass object instance. Now you can create NestedClassExtension instances in this way: NestedClassExtension extension = new NestedClassExtension(new MainClass("main"), "nested"); So the main class has to exist, and its constructor it is called first. Then the constructors of the nested classes. Instead if you want create a NestedClass instance outside of the MainClass you have to write: MainClass mc = new MainClass("main");mc.new NestedClass("nested"); Another time, the MainClass has to be created first, then the nested classes.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10135910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1273282/']}
jdg_378745
stackexchange
llm_judgeable_groundtruth_similarity
301462
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: In this post on stackexchange, the answer states that "The purpose of cross-validation is model checking, not model building." A very good explanation for that is given as follows: "(...) selecting one of the surrogate models means selecting a subset of training samples and claiming that this subset of training samples leads to a superior model." While this is intuitive, usually we pick the best performing classifier of the cross-validation, and test this on a further set - usually called the test set. So, we do in fact use cross-validation for building a model in picking a particular one, often in combination with hyperparameter optimization we would chose a specific set of hyperparameters which led to the best validation-set-results. Is this not contradicting the above statement? if the results of the crossvalidation are just dependent on the particular validation-set, why is model selection justified this way? Now provide the response and nothing else.
we pick the best performing classifier of the cross-validation, and test this on a further set - usually called the test set. So, we do in fact use cross-validation for building a model in picking a particular one, often in combination with hyperparameter optimization we would chose a specific set of hyperparameters which led to the best validation-set-results. Is this not contradicting the above statement? The situation may be more easily explained if you divide it into a different set of building blocks. there are techniques to measure model performance , e.g. cross validation, testing a single held-out split of your data, auto-prediction, performing a fully blown validation study. They differ wrt. efficiency of data use, systematic (bias) and random (variance) uncertainty, cost/effort etc. But technically you can use any of these for the building block "estimate performance" Optimization , here: choose a good model from a variety of possible models. There are many criteria what a good model is. But one criterion that is widely applicable is predictive performance. So if you choose to use this optimization criterion, you then need to choose a suitable way of measuring/estimating the performance of the (surrogate) model you are considering. Doing a full validation study for lots of models isn't feasible, auto-prediction doesn't yield enough information, depending on your data, a single held-out split may be subject to too much random uncertainty, so in the end you settle for cross validation. So cross validation is used in model optimization just as a light switch is used in a car: you need something to make the light go on and off as needed and you use a solution that already (and primarily) exists outside cars. But thinking of light switches primarily as "something used inside cars" likely doesn't help much understanding how they work and the specific characteristics are. They exist independent of cars, but can be applied inside cars - just as they can be applied inside houses, other machines, etc. Similarly cross validation exists as a validation (actually: verification) technique, and this technique can be applied for calculating the target functional of your optimization. Or for verification of the optimized model (see below). Or ... Final Verification : (not really a new building block, but nevertheless necessary) Because we know that variance uncertainty in the target functional used for pick-the-maximum optimization tends to lead to overfitting, we get another independent measurement of the performance of the model we decided on. Again, we have the choice of the methods 1. I may choose to do another cross validation there (aka outer cross validation to distinguish it from the "inner" cross validation inside the optimization) - you may choose to go for the "further test set". if the results of the crossvalidation are just dependent on the particular validation-set, why is model selection justified this way? You should not base your decision on the result obtained on a single validation set. Neither a single cross validation surrogate, nor on a single held-out split of your data. Instead, you should judge those results taking into account their uncertainty. If you suspect that the surrogate models are unstable, i.e. the actual splitting having an influence on the result, you should calculate more splits and directly check this. E.g. by repeated/iterated cross validation. Keep in mind: The fact that many people happily overfit their models doesn't mean that this is good practice...
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/301462', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/-1/']}
jdg_378746
stackexchange
llm_judgeable_groundtruth_similarity
24956
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 heard references to dry sumps, usually in reference to racing engines. But more recently I came across an article about a 'supercar' which stated that it had a dry sump. What are the benefits of a dry sump? Could a regular oiling arrangement be upgraded to one? Now provide the response and nothing else.
You Asked What are the benefits of a dry sump? Simply put a wet sump crankcase has oil sitting in the bottom of the crankcase. It's affected by various forces as the car or motorcycle is driven. At times it is possible, during hard braking or cornering, that the oil pickup is not in oil, resulting in a low or no oil pressure condition that could temporarily leave the engine without good oil pressure for lubrication. IMO this would be rare, even under hard driving, on the street. By viewing the image below you can see how the oil sits at the bottom of the crankcase in a 'pool'. A dry sump engine will have a pickup along the bottom of the crankcase that oil typically will fall into thus scavenging all excess oil. This oil is pumped into an oil tank where another pump will drive oil pressure into the ice. This is primarily for race application and some motorcycles. Rotax has implemented this system with Aprilia. The BMW Dakar Edition on/off road motorcycles have this feature whereas the standard edition of the motorcycle does not. A motorcyclist can ride wheelies for miles, a Baja Desert Racer can jump their truck and drive through long off-camber turns at speed without worrying about loss of oil pressure and engine damage. Answer Dry sump oil delivery ensures oil pressure to the engine in most all conditions and reduces risk regarding low oil pressure to the engine.
{}
{'log_upvote_score': 5, 'links': ['https://mechanics.stackexchange.com/questions/24956', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/3138/']}
jdg_378747
stackexchange
llm_judgeable_groundtruth_similarity
244586
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Suppose we have Grothendieck abelian categories $\mathcal{A}, \mathcal{B}$. Suppose also we have given an exact functor of triangulated categories$$F \colon D(\mathcal{A}) \to D(\mathcal{B})$$where $D(\mathcal{A})$ and $D\mathcal({B})$ denote appropriate derived categories of complexes (possibly bounded below or both ways). Suppose that for any injective $I \in \mathcal{A}$ we have a functorial maps which are quasi-isomorphisms $F(I) \cong h^0F(I)$, and $F(D^{\geq 0}(\mathcal{A})) \subseteq D^{\geq 0}(\mathcal{B})$ ($F$ is $t$-left exact for the standard $t$-structure). Is it then true that $F$ is the right derived functor of is zeroth cohomology? I.e. $F \cong R(h^0F)$. If not, are there known counterexamples? Or which approporiate additional assumptions are needed so that such a statement holds? I believe that the above setup yields that the $i$th cohomology of $F$ is canonically isomorphic to the $i$th right derived functor of $h^0F$. However, I don't see how to extend the given quasi-isomorphism $F(I) \cong h^0F(I)$ for injectives in $\mathcal{A}$ to a natural transformation of functors $F \circ Q \to h^0F$ where $Q$ denotes the natural functor from the homotopy category $K(\mathcal{A})$ to $D(\mathcal{A})$. Once one has this, the universal porperty of the right derived functor should give the result. Some Background: In the situation I am interested in the functor $F$ arises as a composition of a left and right derived functor in a much bigger ambient category, whose restriction to $D(\mathcal{A})$ happens to be left exact and satisfy the condition $F(I) \cong h^0F(I)$ for injective objects of $\mathcal{A}$. I could imagine that this is not an uncommon situation... The result I.Proposition 7.4 in Residues and Duality (Hartshorne) is a statement of the type I am looking for. it says that under similar assumptions as above a right derived functor is (a shift of) the left derived functor of its highest non-vanishing cohomology... Now provide the response and nothing else.
Let $\mathcal{A}$ and $\mathcal{B}$ be abelian categories with enough injective objects. Let me use the notation $D^+(\mathcal{A})$ and $D^+(\mathcal{B})$ to denote the stable $\infty$-categories whose homotopy categories are the (cohomologically bounded below) derived categories of $\mathcal{A}$ and $\mathcal{B}$, respectively (you can also consider unbounded derived categories, but the situation is a bit more subtle). Let $\mathcal{C} \subseteq \mathrm{Fun}( D^{+}( \mathcal{A} ), D^{+}( \mathcal{B}) )$ be the full subcategory spanned by those functors which are exact, left t-exact, and carry injective objects of $\mathcal{A}$ into the heart of $D^{+}( \mathcal{B} )$. Then the construction$$F \in \mathcal{C} \mapsto h^0 F|_{ \mathcal{A} }$$ determines anequivalence from $\mathcal{C}$ to the category of left exact functors from $\mathcal{A}$ to $\mathcal{B}$. The inverse of this equivalence is "taking the right derived functor". Consequently, one can answer your question as follows: given a functor of triangulated categories $G: hD^{+}(\mathcal{A}) \rightarrow hD^{+}(\mathcal{B})$, it arises as a right derived functor (of a leftexact functor of abelian categories) if and only if a) The functor $G$ lifts to an exact functor of stable $\infty$-categories $D^{+}(\mathcal{A}) \rightarrow D^{+}(\mathcal{B})$ (anything that you build by composing derived functors will have this property). b) The functor $G$ is left t-exact and carries injective objects of$\mathcal{A}$ into the heart of $hD^{+}(\mathcal{B})$.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/244586', 'https://mathoverflow.net', 'https://mathoverflow.net/users/917/']}
jdg_378748
stackexchange
llm_judgeable_groundtruth_similarity
29714134
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 to Angular.js and am trying to create dynamic scope variables in AngularJs inside a for Loop. This is something as below: $scope.lists=[{listName:'list1'},{listName:'list2'}];for(var i=0;i<$scope.lists.length;i++){ var listName = $scope.lists[i].listName; listName = $parse(listName); listName.assign($scope,[]); $scope.$apply();} The above code throws an error saying: $digest already in progress. The code works ok when used without looping just for one as done in: Setting dynamic scope variables in AngularJs - scope.<some_string> I ultimately am looking for $scope.list1=[] and $scope.list2=[] as 2 separate arrays. Any leads would be awesome. Thanks. Now provide the response and nothing else.
The above code throws an error saying: $digest already in progress. You're already in the controller and in angular scope. So no need to trigger the digest loop using $scope.$apply() . Even if you have to must check the $$phase and then apply. if (!$scope.$$phase) $scope.$apply() But for your scenario, it's not required at all $scope.lists = [{listName: 'list1'}, {listName: 'list2'}];angular.forEach($scope.lists, function(item) { var listName = item.listName; $scope[listName] = [];});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29714134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5184225/']}
jdg_378749
stackexchange
llm_judgeable_groundtruth_similarity
16975859
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 use the media embed plugin for ckeditor. It works fine, the code is correctly saved in the database and youtube, soundcloud etd. players display ok on the page. But when the user goes to his administration, where he can edit the info, the text inside and with the tags is not showing, so when the user clicks on the save button, all previously saved iframes will be "erased" and only the rest of the formatted text will be saved. Is there any way to display the iframe code in the ckeditor? Now provide the response and nothing else.
I assume that you use CKEditor 4.1.x which comes with Advanced Content Filter (ACF). Most likely, the point is that you use different editors for frontend/backend editing. Each plugin extends allowedContent property with own rules for tags, attributes and classes. Using those rules, editor automatically strips out undesired contents, so for example, if your fronted editor allows <iframe> because it has mediaembed plugin loaded, then your backend editor without this plugin will remove your <iframe> from the content. Furthermore, ACF also observes your toolbar configuration so even if you include the plugin but you don't want the button in the toolbar, any content the button provides (i.e. <iframe> ) will also be disallowed in editor's output. You can easily check whether your editor accept <iframes> . Basically call the following and see the output: CKEDITOR.instances.yourInstance.filter.check( 'iframe' );>>> true // it's allowed If it's false , then there are several solutions for your problem: Enable mediaembed plugin in your backend editor (with button in the toolbar). Extend config.extraAllowedContent to have it back again. While the first solution is straightforward , the second one might be tricky for you. allowedContent rule for mediaembed plugin is as follows (see plugin's code ): allowedContent: 'iframe[*]' // stands for: iframe element with any attribute If you add the following to your backend editor's config, you will have iframes back in your content without loading mediaembed plugin: config.extraAllowedContent = 'iframe[*]' If this solution doesn't work for you, please provide editor configs and CKEditor version so that people could help you.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16975859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1573630/']}
jdg_378750
stackexchange
llm_judgeable_groundtruth_similarity
131065
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 found a following explanation on a blog and I would like to get more information about the non-transitivity of correlation: We have the following indisputable facts: On average, there is a difference in brain volume between men and women There is a correlation between IQ and brain size; the correlation is 0.33 and thus corresponds to 10% of the variability of IQ From these premises 1 and 2, it seems to follow logically from that: women on average have a lower IQ than men.But it is a fallacy! In statistics, correlations are not transitive.The proof is that you just need to look at the results of IQ tests,and they show that the IQ of men and women do not differ on average. I would like to understand this non-transitivity of correlation a bit deeper. If the correlation between IQ and brain size was 0.9 (which I know it isn't (1)), would deducing that women on average have a lower IQ than men would still be a fallacy? Please, I am not here to talk about IQ (and the limits of the test), sexism, woman stereotype, arrogance and so on (2). I just want to understand the logical reasoning behind the fallacy. (1) which I know it isn't: Neanderthals had bigger brains than homo sapiens, but were not smarter; (2) I am a woman and overall, I don't consider myself, or the other women less smart than men, I don't care about IQ test, because what count is the value of people, and it's not based on the intellectual abilities. The original source in French: On a les faits indiscutables suivants: il y a une différence de volume cérébral en moyenne entre hommes et femmes il y a une corrélation entre QI et volume cérébral; la corrélationest 0.33 et correspond donc à 10% de la variabilité De ces prémisses 1 et 2, il semble découler logiquement que: les femmes ont en moyenne un QI inférieur aux hommes. Mais c'est une erreur de raisonnement! En statistique, lescorrélations ne sont pas transitives. La preuve, c'est que pour enavoir le cœur net, il suffit de regarder les résultats des tests deQI, et ceux-ci montrent que les QI des hommes et des femmes nediffèrent pas en moyenne. Now provide the response and nothing else.
Yes, it would still be a fallacy. Here is a very simple figure showing four different situations. In each case red dots represent women, blue dot represent men, horizontal axis represents brain size and vertical axis represents IQ. I generated all four datasets such that: there is always the same difference in mean brain size between men ($22$) and women ($28$ - units are arbitrary). These are population means, but this difference is big enough to be statistically significant with any reasonable sample size; there is always zero difference in mean IQ between men and women (both $100$), and also zero correlation between gender and IQ; the strength of correlation between brain size and IQ varies as shown on the figure. In the upper-left subplot within-gender correlation (computed separately over men and separately over women, then averaged) is $0.3$, like in your quote. In the upper-right subplot overall correlation (over men and women together) is $0.3$. Note that your quote does not specify what the number of $0.33$ refers to. In the lower-left subplot within-gender correlation is $0.9$, like in your hypothetical example; in the lower-right subplot overall correlation is $0.9$. So you can have any value of correlation, and it does not matter if it's computed overall or within-group. Whatever the correlation coefficient, it is very well possible that there is zero correlation between gender and IQ and zero gender difference in mean IQ. Exploring the non-transitivity Let us explore the full space of possibilities, following the approach suggested by @kjetil. Suppose you have three variables $x_1, x_2, x_3$ and (without loss of generality) suppose that correlation between $x_1$ and $x_2$ is $a>0$ and correlation between $x_2$ and $x_3$ is $b>0$. The question is: what is the minimal possible positive value of the correlation $\lambda$ between $x_1$ and $x_3$? Does it sometimes have to be positive, or can it always be zero? The correlation matrix is $$\mathbf R = \left( \begin{array}{} 1&a&\lambda \\ a&1&b \\ \lambda &b&1 \end{array}\right)$$ and it has to have a non-negative determinant, i.e. $$\mathrm{det} \mathbf R = -\lambda^2 + 2ab\lambda - ( a^2+b^2-1) \ge 0,$$ meaning that $\lambda$ has to lie between $$ab \pm \sqrt{(1-a^2)(1-b^2)}.$$ If both roots are positive, then the minimal possible value of $\lambda$ is equal to the smaller root (and $\lambda$ has to be positive!). If zero is between these two roots, then $\lambda$ can be zero. We can solve this numerically and plot the minimal possible positive value of $\lambda$ for different $a$ and $b$: Informally, we could say that correlations would be transitive if given that $a>0$ and $b>0$, one could conclude that $\lambda>0$. We see that for most of values $a$ and $b$, $\lambda$ can be zero, meaning that correlations are non-transitive. However, for some sufficiently high values of $a$ and $b$, correlation $\lambda$ has to be positive , meaning that there is "some degree of transitivity" after all, but restricted to very high correlations only. Note that both correlations $a$ and $b$ have to be high. We can work out a precise condition for this "transitivity": as mentioned above, the smaller root should be positive, i.e. $ab - \sqrt{(1-a^2)(1-b^2)}>0$, which is equivalent to $a^2+b^2>1$. This is an equation of a circle! And indeed, if you look at the figure above, you will notice that the blue region forms a quarter of a circle. In your specific example, correlation between gender and brain size is quite moderate (perhaps $a=0.5$) and correlation between brain size and IQ is $b=0.33$, which is firmly within the blue region ($a^2+b^2<1$)meaning that $\lambda$ can be positive, negative, or zero. Relevant figure from the original study You wanted to avoid discussing gender and brains, but I cannot help pointing out that looking at the full figure from the original article ( Gur et al. 1999 ), one can see that whereas there is no gender difference in verbal IQ score, there is an obvious and significant difference in spatial IQ score! Compare subplots D and F.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/131065', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/64801/']}
jdg_378751
stackexchange
llm_judgeable_groundtruth_similarity
14992668
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 the new connect syntax for Qt5. QNetworkReply has a signal called error and also a function called error . This causes problems when attempting to connect to the signal: connect(reply, &QNetworkReply::error, this, &MyClass::error); error C2664: 'QMetaObject::Connection QObject::connect(const QObject *,const char *,const QObject *,const char *,Qt::ConnectionType)' : cannot convert parameter 2 from 'overloaded-function' to 'const char *' Context does not allow for disambiguation of overloaded function How do I tell the compiler (MSVC) that I want to connect to the signal rather than the function? Now provide the response and nothing else.
You need manually to cast the function pointer to address the correct function: connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &MyClass::error); This is the noted consequence of using new syntax for overloaded functions: cons: Very complicated syntax in cases of overloads? P.S. You can find similar example on the above link: QObject::connect(socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), [socket] (QAbstractSocket::SocketError) { qDebug()<< "ERROR " << socket->errorString(); socket->deleteLater(); });
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14992668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/117744/']}
jdg_378752
stackexchange
llm_judgeable_groundtruth_similarity
589834
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm in the process of creating a CSR, and I wonder which is arguably the best length for my RSA key. Of course, 384 is probably too weak, and 16384 is probably too slow. Is there a consensus on the key length one should use, depending on the certificate lifetime? Edit : Like most people, I want my key to be reasonably strong. I'm not concerned that the NSA could maybe break my key in 2019. I just want to know what's the best practice when one plan to do normal business (for example an e-commerce site) Now provide the response and nothing else.
As of 2020, RSA keys should be 2048 bits. 1024 bits 1024 bits RSA certificates are obsolete and not accepted by browsers. Firefox stopped accepting 1024 bits RSA certificates in 2014. Certificate authorities stopped delivering 1024 bits RSA certificates in 2014 or before. See GlobalSign or Comodo notice. 1024 bits keys were deprecated because they could be cracked given a small datacenter (thousands of CPU or hundreds of GPU, in maybe a few months). It may seem a lot but it was well within reach of any large organization or government. 2048 bits 2048 bits RSA certificates are currently the accepted norm in use. Default baseline delivered by CA and used by software. Will eventually be cracked too. Don't know when but could take decades. Doubling the size takes many many orders of magnitude more compute power to crack. See question how much stronger is RSA 2048 compared to 1024 . 3072 bits For security beyond 2030, 3072-bit RSA keys are recommended. NIST assigns an "effective strength" of 128 bits to 3072-bit RSA keys, versus 112 bits for 2048 bit keys. This means that it would take about 2 16 more computational effort to crack such a key. As of 2022, less than 10% of surveyed sites use 3072-bit keys, while 85% still use 2048-bit keys. For their extended validation services, some CAs don't allow 2048-bit keys and require at least 3072-bit keys. Let's Encrypt will issue certificates for 3072-bit keys. It has been proposed as the default RSA key size, but opposition has ranged from "2048 bits is good enough," to "might as well go to 4096 bits." 4096 bits While it's an oddball size, 4096-bit keys are available and widely supported. All major CAs can issue certificates for 4096-bit RSA. The effective strength of 4096-bit keys has not been estimated by NIST, but others suggest a value of 140, which is only 4000 times stronger than 3072-bit keys and sometimes regarded as "not worth it." Computational cost is not linear with key size. 4096 is not twice as slow as 2048, it is maybe 10 times slower to process. Do not blindly upgrade certificates to 4096 bits without considering the performance impact . The "web" is largely remaining on 2048 bits certificates because it cannot bear the hardware cost for 4096 bits. Consider large actors like Google, CloudFlare, NetFlix with immense traffic and hardware footprint. Fewer sites use RSA 4096-bit keys than 3072-bit keys, but usage is comparable. Extra Beyond 3072 bits, NIST recommends 7680 and 15360 bits, with effective security strength of 192 and 256 bits, respectively. However, support for these large keys is rare in software and with CAs. RSA was first publicly described in 1977 and it's still strong almost 50 years later. Just have to increase the number of bits to keep up with faster computers. There is another method for public key cryptography based on elliptic curves, see ECDSA (1992). There is a huge disconnect between the capacity of a user and of an attacker. A web server or a mobile client have one (low-power) CPU. An attacker can have a whole datacenter, for reference a newly built AWS datacenter is hosting about 60 000 servers. It is incredible that a single mobile device can compute some maths over a few seconds... that millions of computers couldn't dream to guess in a lifetime.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/589834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47341/']}
jdg_378753
stackexchange
llm_judgeable_groundtruth_similarity
11734986
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 get a feel for Prolog programming by going through Ulle Endriss' lecture notes . When my solution to an exercise does not behave as expected, I find it difficult to give a good explanation. I think this has to do with my shaky understanding of the way Prolog evaluates expressions. Exercise 2.6 on page 20 calls for a recursive implementation of a predicate last1 which behaves like the built-in predicate last . My attempt is as follows: last1([_ | Rest], Last) :- last1(Rest, Last).last1([Last], Last). It gives the correct answer, but for lists with more than one element, I have to key in the semicolon to terminate the query. This makes last1 different from the built-in last . ?- last1([1], Last).Last = 1.?- last1([1, 2], Last).Last = 2 ;false. If I switch the order in which I declared the rule and fact, then I need to key in the semicolon in both cases. I think I know why Prolog thinks that last1 may have one more solution (thus the semicolon). I imagine it follows the evaluation sequence last1([1, 2], Last).==> last1([2], Last).==> last1([], Last). OR Last = 2.==> false OR Last = 2. That seems to suggest that I should look for a way to avoid matching Rest with [] . Regardless, I have no explanation why switching the order of declaration ought to have any effect at all. Question 1: What is the correct explanation for the behavior of last1 ? Question 2: How can I implement a predicate last1 which is indistinguishable from the built-in last ? Now provide the response and nothing else.
Question 1: Prolog systems are not always able to decide whether or not a clause will apply prior to executing it. The precise circumstances are implementation dependent. That is, you cannot rely on that decision in general. Systems do improve here from release to release. Consider as the simplest case: ?- X = 1 ; 1 = 2. X = 1; false. A very clever Prolog could detect that 1 = 2 always fails, and thus simply answer X = 1. instead. On the other hand, such "cleverness" is very costly to implement and time is better spent for optimizing more frequent cases. So why do Prologs show this at all? The primary reason is to avoid asking meekly for another answer, if Prolog already knows that there is no further answer. So prior to this improvement, you were prompted for another answer for all queries containing variables and got the false or "no" on each and every query with exactly one answer. This used to be so cumbersome that many programmers never asked for the next answer and thus were not alerted about unintended answers. And the secondary reason is to keep you aware of the limitations of the implementation: If Prolog asks for another answer on this general query, this means that it still uses some space which might accumulate and eat up all your computing resources. In your example with last1/2 you encounter such a case. And you already did something very smart, BTW: You tried to minimize the query to see the first occurrence of the unexpected behavior. In your example query last1([1,2],X) the Prolog system does not look at the entire list [1,2] but only looks at the principal functor. So for the Prolog system the query looks the same as last1([_|_],X) when it decides which clauses to apply. This goal now fits to both clauses, and this is the reason why Prolog will remember the second clause as an alternative to try out. But, think of it: This choice is now possible for all elements but the last! Which means that you pay some memory for each element! You can actually observe this by using a very long list. This I get on my tiny 32-bit laptop — you might need to add another zero or two on a larger system: ?- length(L,10000000), last1(L,E). resource_error(_). % ERROR: Out of local stack On the other hand, the predefined last/2 works smoothly: ?- length(L,10000000), last(L,E). L = [_A,_B,_C,_D,_E,_F,_G,_H,_I|...]. In fact, it uses constant space! There are now two ways out of this: Try to optimize your definition. Yes, you can do this, but you need to be very smart! The definition by @back_dragon for example is incorrect. It often happens that beginners try to optimize a program when in fact they are destroying its semantics. Ask yourself if you are actually defining the same predicate as last/2 . In fact, you're not. Question 2: Consider: ?- last(Xs, X). Xs = [X]; Xs = [_A,X]; Xs = [_A,_B,X]; Xs = [_A,_B,_C,X]; Xs = [_A,_B,_C,_D,X] ; ... . and ?- last1(Xs, X). loops. So your definition differs in this case with SWI's definition. Exchange the order of the clauses. ?- length(L,10000000), last2(L,E). L = [_A,_B,_C,_D,_E,_F,_G,_H,_I|...]; false. Again, this false ! But this time, the big list works. And this time, the minimal query is: ?- last2([1],E). E = 1; false. And the situation is quite similar: Again, Prolog will look at the query in the same way as last2([_|_],E) and will conclude that both clauses apply. At least, we now have constant overhead instead of linear overhead. There are several ways to overcome this overhead in a clean fashion - but they all very much depend on the innards of an implementation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11734986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1092743/']}
jdg_378754
stackexchange
llm_judgeable_groundtruth_similarity
400269
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: The theory is that access modifiers improve code safety because they support encapsulation of internal state. When doing OOP, every language I've used implements some kind of access restriction. I like some access models better than others. I am on a team of Java developers. Our projects spend time in code reviews considering the access modifiers, their appropriateness, and the use of things like @VisibleForTesting (a Java annotation). Our projects also occasionally spend time de-finalizing or de-privatizing something in a 3rd party library if a source-code change is not feasible. I went looking for the research that shows how the use of access modifiers affects defect density or occurrences of run-time errors. I cannot find any studies on it. Maybe my Google-Fu is weak. What is the evidence that access modifiers actually provide the benefits we assume they do? Where are the studies that quantify the problems with how access modifiers are used? Now provide the response and nothing else.
Let me give you a real world example of when access modifiers "mattered" that I ran into personally: Our software is primarily python, and one way that python differs from most other OO languages is that there are no explicit access modifiers. Instead, it is convention to prefix methods and attributes that should be private with an underscore. One day, a developer was working on a particular feature, and could not make it work with the interface of the object he was working with. But he noticed that if he worked with a particular attribute that was marked private, he could do what he wanted to do. So he did it, checked it in, and (unfortunately) it slipped past code review, and into the master branch. Fast forward two years. That developer had moved on. We updated to a newer version of an underlying library. Code that had been reliably suddenly stopped working. This resulted in lots of debugging and back-and-forth messages with another team in a different time zone. Eventually we figured out the issue: the developers who owned that underlying object changed the way it worked in a very subtle way. Subtle enough that no exceptions were thrown, no other errors occurred. The library just became flaky. This happened because the developers of that library had no clue that they were doing anything that would cause any troubles to anyone. They were changing something internal, not the interface. So after the fact we did what should have been done originally: we asked the library developers to add a public method that solved our problem rather than mucking about with the internals of their objects. So that's what access modifiers prevent. They ensure that the separation of interface and implementation is clear. It lets users know exactly what they can do with the class safely and lets developers of the class change internals without breaking user's software. You could do this all with convention, not force, as python shows, but even where it's just convention, having that public/private separation is a great boon toward maintainability.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/400269', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/43536/']}
jdg_378755
stackexchange
llm_judgeable_groundtruth_similarity
951848
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The problem: Consider the following floats[]: d[i] = 1.7 -0.3 2.1 0.5 What I want is an array of int[] that represents the order of the original array with indices. s[i] = 1 3 0 2d[s[i]] = -0.3 0.5 1.7 2.1 Of course it could be done with a custom comparator, a sorted set of custom objects, or by simply sorting the array and then searching for the indices in the original array (shudder). What I am in fact looking for is the equivalent for the second return argument of Matlab's sort function . Is there an easy way to do that (<5 LOC)? May there be a solution that does not need to allocate a new object for each element? Update: Thanks for your responses. Unfortunately, none of what has been proposed so far resembles the simple and efficient solution I was hoping for. I therefore openened a thread in the JDK feedback forum, proposing the addition of a new class-library function to address the issue. Lets see what Sun/Oracle thinks about the issue. http://forums.java.net/jive/thread.jspa?threadID=62657&tstart=0 Now provide the response and nothing else.
Create a TreeMap of values to indices float[] array = new float[]{}; Map<Float, Integer> map = new TreeMap<Float, Integer>(); for (int i = 0; i < array.length; ++i) { map.put(array[i], i); } Collection<Integer> indices = map.values(); indices will be the sorted by the floats they point to, the original array is untouched. Converting the Collection<Integer> to a int[] is left as an exercise if it's really necessary. EDIT: As noted in the comments, this approach does not work if there are duplicate values in the float array. This can be addressed by making the Map<Float, Integer> into a Map<Float, List<Integer>> though this will complicate the inside of the for loop and the generation of the final collection slightly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/951848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24937/']}
jdg_378756
stackexchange
llm_judgeable_groundtruth_similarity
25052000
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 some example data for a hypothetical meta-analysis on the effectiveness of sports-promotion interventions for which I would like to create a forest plot: example.df = data.frame(Author = c("McAuliffe et al.", "Palen et al.", "Manning et al.", "Richters et al.", "Grello et al.","Mpofu et al.", "Kuo & St Lawrence", "Langstrom & Hanson", "Ompad et al.", "Abdullah et al.","Yan", "Peltzer & Pengpid", "Lo & Wei", "Haggstrom-Nordin et al.", "Mwaba & Naidoo", "Hughes et al.","Lydie et al.", "Zimmer-Gembeck et al.", "Babalola", "Garos et al.", "Pinkerton et al."), Sport = c("Basketball", "Basketball", "Baseball", "Dance", "Baseball", "Dance", "Wrestling","Wrestling", "Dance", "Baseball", "Wrestling", "Dance", "Swimming", "Swimming","Basketball", "Basketball", "Basketball", "Basketball", "Basketball", "Swimming", "Wrestling"), Gender = c("Male", "Female", "Male", "Male", "Female", "Male", "Male", "Male", "Male", "Female","Female", "Male", "Female", "Female", "Female", "Male", "Female", "Female", "Female", "Male", "Female"), d = c(-0.12, 0.53, 0.11, 0.02, 0.32, 0.04, 0.03,0.04,0.26, 0.76, 1.11, 0.34, 0.77, 1.19, 0.59, 0.15, 0.30, 0.81, 0.12, 0.11, 1.01), d_SE = c(.10, .04, .06, .01, .11, .08, .08, .04, .05, .05, .14, .07, .05, .08, .19, .16, .07, .16, .06, .18, .15)) The data frame contains author names, the sport, whether the sample was male or female, the effect size for the intervention, and the standard error of the effect size. I am hoping to create a dot plot mapping shape to gender, and faceting by the particular sport. After following examples in Chang's "cookbook" and this related query , I've come up with the following code that meets most of my formatting needs: p<-ggplot(example.df, aes(x=Author, y=d, ymin=d-1.96*d_SE, ymax=d+1.96*d_SE,shape=Gender))+ geom_pointrange() + coord_flip()+scale_y_continuous(limits=c(-2,2),breaks=c(-2,-1.5,-1,-0.5,0,.5,1,1.5,2))+geom_hline(yintercept=0, color="grey60",linetype="dashed")+theme_bw()+theme(panel.grid.major.x=element_blank(),panel.grid.minor.x=element_blank(),panel.grid.major.y=element_line(color="grey60",linetype="dashed"))+facet_grid(Sport ~ ., scales="free_y")p My problem, however, is that the resulting plots for each facet (below) have every author in the entire data frame plotted on the y-axis (technically x-axis, but the axes are flipped). Instead, I only want the authors with data relevant to a given facet to be plotted on the author-associated axis of that facet, so each facet should have a different list of authors on the axis. I had thought the scales="free_y" component of the facet_grid layer would ensure a unique author axis for each facet (I've also tried scales="free_x" , given the inverted axes), but this is not having the intended effect. Does anyone know of a way that I could ensure that the only author names that appear on each facet's axis are the ones with associated data for that facet? Now provide the response and nothing else.
Andrie's right, in that coord_flip() seems to be the root of the issue. However, the convention for forest plot formatting is to have the author names on y-axis, so I wanted to find a way that still would meet this formatting requirement. The accepted answer in the post that Gregor commented on actually solves my issue; the only required change was that I had to calculate columns for upper-bound/lower-bound values of the confidence intervals. So now with the updated data frame: example.df = data.frame(Author = c("McAuliffe et al.", "Palen et al.", "Manning et al.", "Richters et al.", "Grello et al.","Mpofu et al.", "Kuo & St Lawrence", "Langstrom & Hanson", "Ompad et al.", "Abdullah et al.","Yan", "Peltzer & Pengpid", "Lo & Wei", "Haggstrom-Nordin et al.", "Mwaba & Naidoo", "Hughes et al.","Lydie et al.", "Zimmer-Gembeck et al.", "Babalola", "Garos et al.", "Pinkerton et al."), Sport = c("Basketball", "Basketball", "Baseball", "Dance", "Baseball", "Dance", "Wrestling","Wrestling", "Dance", "Baseball", "Wrestling", "Dance", "Swimming", "Swimming","Basketball", "Basketball", "Basketball", "Basketball", "Basketball", "Swimming", "Wrestling"), Gender = c("Male", "Female", "Male", "Male", "Female", "Male", "Male", "Male", "Male", "Female","Female", "Male", "Female", "Female", "Female", "Male", "Female", "Female", "Female", "Male", "Female"), d = c(-0.12, 0.53, 0.11, 0.02, 0.32, 0.04, 0.03,0.04,0.26, 0.76, 1.11, 0.34, 0.77, 1.19, 0.59, 0.15, 0.30, 0.81, 0.12, 0.11, 1.01), d_SE = c(.10, .04, .06, .01, .11, .08, .08, .04, .05, .05, .14, .07, .05, .08, .19, .16, .07, .16, .06, .18, .15), ci.low = c(-.30, .45, .00, -.01, .11, -.12, -.14, -.04, .16, .66, .84, .19, .68, 1.03, .22, -.17, .17, .50, .00, -.23, .72), ci.high = c(.07, .62, .22, .05, .53, .20, .19, .11, .36, .87, 1.38, .47, .86, 1.35, .97,.47, .43, 1.11, .24, .46, 1.30))#reorder Author based on value of d, so effect sizes can be plotted in descending orderexample.df$Author<-reorder(example.df$Author, example.df$d, FUN=mean) ...and then for the plot (without any coord_flip() usage): p <- ggplot(example.df, aes(y = Author, x = d, xmin = ci.low, xmax = ci.high, shape=Gender)) +geom_point() +geom_errorbarh(height = .1) +scale_x_continuous(limits=c(-2,2),breaks=c(-2,-1.5,-1,-0.5,0,.5,1,1.5,2))+geom_vline(xintercept=0, color="grey60",linetype="dashed")+facet_grid(Sport ~ ., scales = "free", space = "free") +theme_bw() +theme(strip.text.y = element_text(angle = 0))p Very nice--thanks for all the suggestions and help troubleshooting this plot!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25052000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3894170/']}
jdg_378757
stackexchange
llm_judgeable_groundtruth_similarity
845
Below is a question asked on the forum devops.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My company is trying to play a little catch-up in the DevOps space. I have been doing a lot of research on containerization of applications and the orchestration systems that go with it. I came across an article (one that I wish I had saved) where they were talking about combining Swarm with Kubernetes to get better functionality. In this article they did not define what they gained by doing that. I wondered what benefits would this provide? Is adding the extra layer of complexity really going to give you much return? EDIT: I am looking for technical pro's/con's. KISS is a good motto but doesn't hold up in a debate with your CEO or Board. I am almost positive that we will be selecting Docker for our containers and Swarm for an orchestration. I, however, would like to see Kubernetes in our space so the proposition that you could merge the technologies together for a more robust solution intrigues me.Thanks for any insight. Now provide the response and nothing else.
Update: Docker just released support for Kubernetes as scheduler, which changes the situation and makes Kubernetes just an alternative scheduler to Docker Swarm. TL;DR: DON'T DO IT. Engineers always try to create these dog-pigs. Every unnecessary technology you bring will bring another whole set of faults. If you can pick one, then pick one and be happy you don't have to do both. If you like to play with Kubernetes, just get a private account on Google Cloud and play with it as much as you like. But don't make everyone at your company suffer through unnecessary complications. Those are two parallel and mostly equivalent technologies . If your business had legitimate business reason to deploy in multiple Cloud providers for reliability for example and wanted to deploy into both AWS ECS (Elastic Container Service - based on Docker) and Google GKE (Container Engine - based on Kubernetes) and you were asking how do you build a pipeline, which would build your software and package in containers for deployment in both , that would be something else, but doing it just because you want to play with a new technology is very irresponsible.
{}
{'log_upvote_score': 4, 'links': ['https://devops.stackexchange.com/questions/845', 'https://devops.stackexchange.com', 'https://devops.stackexchange.com/users/2269/']}
jdg_378758
stackexchange
llm_judgeable_groundtruth_similarity
15011562
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 ack for the literal string: " $$ " in a code base, but escaping the dollar sign like this: ack \$\$ doesn't work. Now provide the response and nothing else.
You are getting confused by shell quoting. When you type: ack "\\\$\\\$\(" the shell interpolates the double quoted string so that \\ is translated to \ , \$ is translated to $ and \( is translated to \( and ack gets the string \$\$\( as its argument. It is much simpler to avoid the shell interpolation by using single quotes and invoke: ack '\$\$\(' Replace ack with echo to explore how the shell is expanding the strings. Note that ack "\\$\\$\(" will also work, but for slightly different reasons. Here, the first two \ are treated as a single (escaped) \ , then the $ is translated as a $ because it is followed by a character that is not a valid character in a variable name. \( expands to \( instead of simply ( because ( is not subject to interpolation and therefore does not need to be escaped. But note that outside of double quotes, \( is converted to ( . Shell quoting rules get confusing sometimes!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15011562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193267/']}
jdg_378759
stackexchange
llm_judgeable_groundtruth_similarity
16588133
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to have my monitors controlled from Windows (simple stuff such as changing the input source), but cannot find a way of sending DDC/CI commands from Python... Any clue about a library or method that could help here? Now provide the response and nothing else.
This is easily possible using the windows monitor API . I don't think there are any Python bindings out there and pywin32 doesn't contain those functions. However, using ctypes to call them is not that hard. Here's an example that switches the monitor to soft-off and then back on; it should be pretty easy to adapt it to changing the input source etc. The only complicated part is getting the handles for the physical monitors after all: from ctypes import windll, byref, Structure, WinError, POINTER, WINFUNCTYPEfrom ctypes.wintypes import BOOL, HMONITOR, HDC, RECT, LPARAM, DWORD, BYTE, WCHAR, HANDLE_MONITORENUMPROC = WINFUNCTYPE(BOOL, HMONITOR, HDC, POINTER(RECT), LPARAM)class _PHYSICAL_MONITOR(Structure): _fields_ = [('handle', HANDLE), ('description', WCHAR * 128)]def _iter_physical_monitors(close_handles=True): """Iterates physical monitors. The handles are closed automatically whenever the iterator is advanced. This means that the iterator should always be fully exhausted! If you want to keep handles e.g. because you need to store all of them and use them later, set `close_handles` to False and close them manually.""" def callback(hmonitor, hdc, lprect, lparam): monitors.append(HMONITOR(hmonitor)) return True monitors = [] if not windll.user32.EnumDisplayMonitors(None, None, _MONITORENUMPROC(callback), None): raise WinError('EnumDisplayMonitors failed') for monitor in monitors: # Get physical monitor count count = DWORD() if not windll.dxva2.GetNumberOfPhysicalMonitorsFromHMONITOR(monitor, byref(count)): raise WinError() # Get physical monitor handles physical_array = (_PHYSICAL_MONITOR * count.value)() if not windll.dxva2.GetPhysicalMonitorsFromHMONITOR(monitor, count.value, physical_array): raise WinError() for physical in physical_array: yield physical.handle if close_handles: if not windll.dxva2.DestroyPhysicalMonitor(physical.handle): raise WinError()def set_vcp_feature(monitor, code, value): """Sends a DDC command to the specified monitor. See this link for a list of commands: ftp://ftp.cis.nctu.edu.tw/pub/csie/Software/X11/private/VeSaSpEcS/VESA_Document_Center_Monitor_Interface/mccsV3.pdf """ if not windll.dxva2.SetVCPFeature(HANDLE(monitor), BYTE(code), DWORD(value)): raise WinError()# Switch to SOFT-OFF, wait for the user to press return and then back to ONfor handle in _iter_physical_monitors(): set_vcp_feature(handle, 0xd6, 0x04) raw_input() set_vcp_feature(handle, 0xd6, 0x01)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16588133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/517695/']}
jdg_378760
stackexchange
llm_judgeable_groundtruth_similarity
706453
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: $X$ and $Y$ are topological spaces and let $f : X \times Y \to X$ and $g : X \times Y \to Y$ be maps such that $f(x, y) = x$ and $g(x, y) = y \ \forall (x, y) \in X \times Y$ . Show that the product topology on $X \times Y$ is the smallest topology on $X \times Y$ for which both the $f$ and $g$ are continuous. I think I understand what is going on here. Here is how I see it. As $f$ is continuous, take an open set $U \subset X$ and it's inverse image $(U, Y)$ will be open in $X \times Y$ for any topology on $X \times Y$. Similarly, as $g$ is continuous, take an open set $V \subset Y$ and it's inverse image $(X, V)$ will be open in $X \times Y$ for any topology on $X \times Y$. Hence $(U, Y) \bigcap (X, V) = (U, V)$ which will be open in $X \times Y$ for any topology on $X \times Y$. Now the set $\{(U, V): U \in X, V \in Y\}$ is the product topology hence we are saying that the product topology will be a subset of any other topology on $X \times Y$ when $f$ and $g$ are the continuous maps as defined above. Is my understanding correct? If so is my proof clear or is it messy? Now provide the response and nothing else.
The product topology on $X \times Y$ is defined by giving a basis for the topology, namely the set ${\mathcal B} := \{ U \times V \mid U \subseteq X \text{ open}, V \subseteq Y \text{ open} \}$. (As mentioned in the comments, one could also define the product topology to be the coarsest topology that makes the projections continuous. From the remainder of the question and the comments by the OP, however, it becomes clear that the OP defines the product topology via the basis ${\mathcal B}$.) Now suppose we have an alternative topology on $X \times Y$; let's call this topological space $Z$ (so it has the same underlying set as $X \times Y$). We assume that the projections $f \colon Z \to X$ and $g \colon Z \to Y$ are continuous and we want to show that every open subset $X \times Y$ is also an open subset of $Z$. It is sufficient to show this for the open subsets in ${\mathcal B}$, so take an open subset $U$ of $X$ and an open subset $V$ of $Y$. We must argue that $U \times V$ is open in $Z$. Your argument now essentially works. Because $U$ is open in $X$, its preimage $f^{-1}(U) = U \times Y$ is open in $Z$. Similarly, because $V$ is open in $Y$, its preimage $g^{-1}(V) = X \times V$ is open in $Z$. Now $U \times V = (U \times Y) \cap (X \times V)$ is also open in $Z$, as required. (As an aside, the mistakes in your argument are not in your understanding of the argument, but in its presentation: you're mixing $\cap$ and $\times$ at occasion and you didn't mention that the set I call ${\mathcal B}$ above is only a basis for the product topology.) Alternatively, you could use the universal property of the product. Since $f \colon Z \to X$ and $g \colon Z \to Y$ are continuous, there must be a unique continuous map $u \colon Z \to X \times Y$ such that $\pi_1 \circ u = f$ and $\pi_2 \circ u = g$. Considered as maps of sets, the only candidate for $u$ is the identity $i \colon Z \to X \times Y$ and therefore the identity map $i \colon Z \to X \times Y$ is continuous. So, given an open set $U \subseteq X \times Y$, its preimage $U = i^{-1}(U) \subseteq Z$ is open.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/706453', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/49759/']}
jdg_378761
stackexchange
llm_judgeable_groundtruth_similarity
52649057
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Kotlin uses when instead of switch and it looks something like this: when(version) { "v1" -> Log.d("TAG", "WOW") "v2" -> Log.d("TAG", WOAAH") else -> "Log.d("TAG", "ELSE") So far so good. But what if I want to add several lines of code after each conditional? This is my code, and I have tried using and at the end of each new line: when(version) { "anhorig" -> Log.d("TAG", "Anhorig") and subHeader.text = getString(R.string.sv_anhorig_ch1) "personal" -> Log.d("TAG", "Personal") else -> Log.d("TAG", "Else")} I get an error on line subHeader.text = getString(R.string.sv_anhorig_ch1) saying Type mismatch. Expected Int, found string and Unit The code line works fine if separated from the when code. What am I doing wrong? Now provide the response and nothing else.
You need to surround your multiple lines of code in a block, like so: when(version) { "anhorig" -> { Log.d("TAG", "Anhorig") subHeader.text = getString(R.string.sv_anhorig_ch1) } "personal" -> Log.d("TAG", "Personal") else -> Log.d("TAG", "Else")} As for the type mismatch, the value of the when expression is equal to the last evaluated statement within the block. It seems like the expected value of this expression is Int, but your last statement is subHeader.text = getString(R.string.sv_anhorig_ch1) which is string. You can read more in the Kotlin documentation for when expressions .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52649057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9493704/']}
jdg_378762
stackexchange
llm_judgeable_groundtruth_similarity
295364
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: Lets say for fraud detection which has two labels for each transaction. Fraud Non fraud In real world scenario we usually get more number of examples of Non fraud data points and very low number of fraud data points. Lets assume the ratio of Non fraud: fraud is 80:20. So my question is even if I build any classifier my model will predict the majority label but I know that data itself is not well distributed. So for such scenarios what should be the approach. Now provide the response and nothing else.
First, note there is a terminology problem in your title: the exponential family seems to imply one exponential family. You should say a exponential family , there are many exponential families. Well, one consequence of your definition: $$p(\mathbf x|\boldsymbol \eta) = h(\mathbf x) g(\boldsymbol \eta) \exp \{\boldsymbol \eta^\mathrm T \mathbf u(\mathbf x)\}$$ is that the support of the distribution family indexed by parameter $\eta$ do not depend on $\eta$ . (The support of a probability distribution is the (closure of) the least set with probability one, or in other words, where the distribution lives .) So it is enough to give a counterexample of a distribution family with support depending on the parameter, the most easy example is the following family of uniform distributions: $ \text{U}(0, \eta), \quad \eta > 0$ . (the other answer by @Chaconne gives a more sophisticated counterexample). Another, unrelated reason that not all distributions are exponential family, is that an exponential family distribution always have an existing moment generating function. Not all distributions have a mgf.
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/295364', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/168851/']}
jdg_378763
stackexchange
llm_judgeable_groundtruth_similarity
32731200
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just Start xcode 7 stable version. In my current project I am downloading images from webservice. In xcode 6.4 was working fine. Now it's not showing any image and show warning in log -canOpenURL: failed for URL: "itms-books://" - error: "This app is not allowed to query for scheme itms-books" App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file. Now provide the response and nothing else.
This is a new enforced security measure that apple has implemented on any app that is build in iOS 9. The only solution so far is to add an entry in the info.plist file with the Key LSApplicationQueriesSchemes and add "itms-books" and any other url scheme that your app will be linking to in this array. The main explanation for this move from apple is that some apps used to exploit the functionality of the canOpenURL: method to scan which apps where installed in your phone to target you with selective ads or other "not so benevolent" motives. Keep in mind that there is a cap in the amount of apps you can register which is 50.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32731200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2106517/']}
jdg_378764
stackexchange
llm_judgeable_groundtruth_similarity
39618803
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: typealias Action = () -> ()var action: Action = { }func doStuff(stuff: String, completion: @escaping Action) { print(stuff) action = completion completion()}func doStuffAgain() { print("again") action()}doStuff(stuff: "do stuff") { print("swift 3!")}doStuffAgain() Is there any way to make the completion parameter (and action ) of type Action? and also keep @escaping ? Changing the type gives the following error: @escaping attribute only applies to function types Removing the @escaping attribute, the code compiles and runs, but doesn't seem to be correct since the completion closure is escaping the scope of the function. Now provide the response and nothing else.
There is a SR-2552 reporting that @escaping is not recognizing function type alias. that's why the error @escaping attribute only applies to function types . you can workaround by expanding the function type in the function signature: typealias Action = () -> ()var action: Action? = { }func doStuff(stuff: String, completion: (@escaping ()->())?) { print(stuff) action = completion completion?()}func doStuffAgain() { print("again") action?()}doStuff(stuff: "do stuff") { print("swift 3!")}doStuffAgain() EDIT 1: : I was actually under a xcode 8 beta version where the bug SR-2552 was not resolved yet. fixing that bug, introduced a new one(the one you're facing) that is still open. see SR-2444 . The workaround @Michael Ilseman pointed as a temporary solution is remove the @escaping attribute from optional function type, that keep the function as escaping . func doStuff(stuff: String, completion: Action?) {...} EDIT 2: : The SR-2444 has been closed stating explicitly that closures in parameters positions are not escaping and need them to be marked with @escaping to make them escaping, but the optional parameters are implicitly escaping, since ((Int)->())? is a synonyms of Optional<(Int)->()> , optional closures are escaping.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/39618803', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/987300/']}
jdg_378765
stackexchange
llm_judgeable_groundtruth_similarity
145029
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: When naming compounds, sometimes when there are two vowels in a row the second is elided: this happens for example with "mono-oxide", which becomes "monoxide" instead. Why is this not always applied, e.g. with "diiodine"? Why aren't the repeated i's removed to make it "diodine"? Now provide the response and nothing else.
Both "monooxide" and "monoxide" are used in the literature, yet "monoxide" is being used more often ( Google Books Ngram Viewer ).Although this is an accepted elision, it is not the preferred one, and must not set a precedent for other cases when multiplicative prefix ends with the same vowel as the root word begins with, such as "diiodine". According to the current version of Nomenclature of Inorganic Chemistry, IUPAC Recommendations 2005 [1, p. 31]: IR-2.7 ELISIONS In general, in compositional and additive nomenclature no elisions are made when usingmultiplicative prefixes. Example: tetraaqua ( not tetraqua) monooxygen ( not monoxygen) tetraarsenic hexaoxide However, monoxide, rather than monooxide, is an allowed exception through general use. Further, from section IR-5.2 Stoichiometric names of elements and binary compounds [1, p. 69]: The multiplicative prefixes precede the names they multiply, and are joined directly to them without spaces or hyphens. The final vowels of multiplicative prefixes should not be elided (although ‘monoxide’, rather than ‘monooxide’, is an allowed exception because of general usage). […] Examples: […] $\ce{NO}$ nitrogen oxide, or nitrogen monooxide, or nitrogen monoxide References IUPAC. Nomenclature of Inorganic Chemistry, IUPAC Recommendations 2005 (the “Red Book”) , 1st ed.; Connelly, N. G., Damhus, T., Hartshorn, R. M., Hutton, A. T., Eds.; RSC Publishing: Cambridge, UK, 2005 . ISBN 978-0-85404-438-2. IUPAC website
{}
{'log_upvote_score': 6, 'links': ['https://chemistry.stackexchange.com/questions/145029', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/103168/']}
jdg_378766
stackexchange
llm_judgeable_groundtruth_similarity
50401653
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 get help in creating a table on AWS Athena. For a sample example of data : [{"lts": 150}] AWS Glue generate the schema as : array (array<struct<lts:int>>) When I try to use the created table by AWS Glue to preview the table, I had this error: HIVE_BAD_DATA: Error parsing field value for field 0: org.openx.data.jsonserde.json.JSONObject cannot be cast to org.openx.data.jsonserde.json.JSONArray The message error is clear, but I can't find the source of the problem! Now provide the response and nothing else.
Hive running under AWS Athena is using Hive-JSON-Serde to serialize/deserialize JSON. For some reason, they don't support just any standard JSON. They ask for one record per line, without an array. In their words: The following example will work. { "key" : 10 }{ "key" : 20 } But this won't: { "key" : 20,} Nor this: [{"key" : 20}]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50401653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3333617/']}
jdg_378767
stackexchange
llm_judgeable_groundtruth_similarity
9880279
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 an experienced Java programmer but am looking at some JavaScript/HTML5 stuff for the first time in about a decade. I'm completely stumped on what should be the simplest thing ever. As an example I just wanted to draw something and add an event handler to it. I'm sure I'm doing something stupid, but I've searched all over and nothing that is suggested (e.g. the answer to this question: Add onclick property to input with JavaScript ) works. I'm using Firefox 10.0.1. My code follows. You'll see several commented lines and at the end of each is a description of what (or what doesn't) happen. What's the correct syntax here? I'm going crazy! <html><body> <canvas id="myCanvas" width="300" height="150"/> <script language="JavaScript"> var elem = document.getElementById('myCanvas'); // elem.onClick = alert("hello world"); - displays alert without clicking // elem.onClick = alert('hello world'); - displays alert without clicking // elem.onClick = "alert('hello world!')"; - does nothing, even with clicking // elem.onClick = function() { alert('hello world!'); }; - does nothing // elem.onClick = function() { alert("hello world!"); }; - does nothing var context = elem.getContext('2d'); context.fillStyle = '#05EFFF'; context.fillRect(0, 0, 150, 100); </script></body> Now provide the response and nothing else.
When you draw to a canvas element, you are simply drawing a bitmap in immediate mode . The elements (shapes, lines, images) that are drawn have no representation besides the pixels they use and their colour. Therefore, to get a click event on a canvas element (shape), you need to capture click events on the canvas HTML element and use some math to determine which element was clicked, provided you are storing the elements' width/height and x/y offset. To add a click event to your canvas element, use... canvas.addEventListener('click', function() { }, false); To determine which element was clicked... var elem = document.getElementById('myCanvas'), elemLeft = elem.offsetLeft + elem.clientLeft, elemTop = elem.offsetTop + elem.clientTop, context = elem.getContext('2d'), elements = [];// Add event listener for `click` events.elem.addEventListener('click', function(event) { var x = event.pageX - elemLeft, y = event.pageY - elemTop; // Collision detection between clicked offset and element. elements.forEach(function(element) { if (y > element.top && y < element.top + element.height && x > element.left && x < element.left + element.width) { alert('clicked an element'); } });}, false);// Add element.elements.push({ colour: '#05EFFF', width: 150, height: 100, top: 20, left: 15});// Render elements.elements.forEach(function(element) { context.fillStyle = element.colour; context.fillRect(element.left, element.top, element.width, element.height);}); jsFiddle . This code attaches a click event to the canvas element, and then pushes one shape (called an element in my code) to an elements array. You could add as many as you wish here. The purpose of creating an array of objects is so we can query their properties later. After all the elements have been pushed onto the array, we loop through and render each one based on their properties. When the click event is triggered, the code loops through the elements and determines if the click was over any of the elements in the elements array. If so, it fires an alert() , which could easily be modified to do something such as remove the array item, in which case you'd need a separate render function to update the canvas . For completeness, why your attempts didn't work... elem.onClick = alert("hello world"); // displays alert without clicking This is assigning the return value of alert() to the onClick property of elem . It is immediately invoking the alert() . elem.onClick = alert('hello world'); // displays alert without clicking In JavaScript, the ' and " are semantically identical, the lexer probably uses ['"] for quotes. elem.onClick = "alert('hello world!')"; // does nothing, even with clicking You are assigning a string to the onClick property of elem . elem.onClick = function() { alert('hello world!'); }; // does nothing JavaScript is case sensitive. The onclick property is the archaic method of attaching event handlers. It only allows one event to be attached with the property and the event can be lost when serialising the HTML. elem.onClick = function() { alert("hello world!"); }; // does nothing Again, ' === " .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/9880279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/766736/']}
jdg_378768
stackexchange
llm_judgeable_groundtruth_similarity
99120
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: So, I am here at assembly 2011 and there was this demo played: http://www.youtube.com/watch?v=69Xjc7eklxE&feature=player_embedded It's one single file only, it says that in the rules. So I repeat, how have they made this to fit into so small file? Now provide the response and nothing else.
It's procedural based. The content is not included in the exe, only the rules of how to draw it. When launched, the program draws what it needs to at runtime it's not pre-rendered or pre-saved in any form. This is the same method used by Elite to create a vast universe of star systems, etc. It's pretty amazing what is possible today using procedural generation, i think games will feature more of this in the future.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/99120', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/33608/']}
jdg_378769
stackexchange
llm_judgeable_groundtruth_similarity
1251192
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 share my experience of using maven through a proxy. You would most likely face exceptions and messages like: repository metadata for: 'org.apache.maven.plugins' could not be retrieved from repository: central due to an error: Error transferring file: Connection refused: connect or [WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-clean-plugin:2.5: Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.5 How to configure Maven to use proxy server? Now provide the response and nothing else.
For details of setting up a proxy for Maven, see the mini guide . Essentially you need to ensure the proxies section in either the global settings ( [maven install]/conf/settings.xml ), or user settings ( ${user.home}/.m2/settings.xml ) is configured correctly. It is better to do this in your user settings to avoid storing the password in plain text in a public location. Maven 2.1 introduced password encryption , but I've not got round to checking if the encryption applies for the proxy settings as well as repository passwords (don't see why it wouldn't though). For info, there is a commented-out proxy configuration in your settings.xml and instructions on how to modify it. From the mini-guide, your settings should look something like this: <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">[...] <proxies> <proxy> <active>true</active> <protocol>http</protocol> <host>proxy.somewhere.com</host> <port>8080</port> <username>proxyuser</username> <password>somepassword</password> <nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts> </proxy> </proxies>[...]</settings>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1251192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65790/']}
jdg_378770
stackexchange
llm_judgeable_groundtruth_similarity
9816878
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Since there is no type in ruby, how do Ruby programmers make sure a function receives correct arguments? Right now, I am repeating if object.kind_of / instance_of statements to check and raise runtime errors everywhere, which is ugly. There must be a better way of doing this. Now provide the response and nothing else.
Ruby is, of course, dynamically typed. Thus the method documentation determines the type contract; the type-information is moved from the formal type-system to the [informal type specification in the] method documentation. I mix generalities like "acts like an array" and specifics such as "is a string". The caller should only expect to work with the stated types. If the caller violates this contract then anything can happen . The method need not worry: it was used incorrectly. In light of the above, I avoid checking for a specific type and avoid trying to create overloads with such behavior. Unit-tests can help ensure that the contract works for expected data.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9816878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/971439/']}
jdg_378771
stackexchange
llm_judgeable_groundtruth_similarity
48133
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 having difficulty in determining what exactly the difference is between the 2, especially when given an exercise and I have to choose which of the 2 to use. These is how my text book describes them: Sum standard deviation Given is a population with a normally distributed random variable $X$. When you have a sample $n$ from this population the population is: $X_{sum} = X_1 + X_2 ... + X_n$ with $\mu_{Xsum} = n \times \mu_x$ and $\sigma_{Xsum} = \sqrt{n} \times \sigma_x$. Standard error When you have a normally distributed random variable $X$ with mean $\mu_X$ and standard deviation $\sigma_X$ and sample length $n$, the sample mean $\bar{X}$ is normally distributed with $\mu_{\bar{x}} = \mu_X$ and $\sigma_{\bar{x}} = \dfrac{\sigma_X}{\sqrt{n}}$ These 2 are awefully similair to me to the point I can't at all decide which to use where. Here are the problems where I discovered I couldn't: Problem 1 A filling machine fills bottles of lemonade. The amount is normally distributed with $\mu = 102 \space cl$. $\sigma$ = $1.93\space cl$. Calculate the chance that out of 12 bottles the average volume is $100 \space cl$. The problem itself is easy, however the troublesome part is what to choose for the standard deviation of the sample. Here they use $\dfrac{1.93}{\sqrt{12}} $ which I can live with, until I encountered the second problem. Problem 2 A tea company puts 20 teabags in one package. The weight of a teabag is normally distributed with $\mu = 5.3 \space g$ and $\sigma = 0.5 \space g.$ Calculate the chance that a package weighs less than 100 grams. Here I thought they'd also use $\dfrac{0.5}{\sqrt{20}}$, but instead they use $\sqrt{20} \times 0.5$. Can someone clear up the confusion? Now provide the response and nothing else.
The sum standard deviation is, as the name suggests, the standard deviation of the sum of $n$ random variables. The standard error you're talking about is just another name for the standard deviation of the mean of $n$ random variables. As you noted, the two formulas are closely related; since the sum of $n$ random variables is $n$ times the mean of $n$ random variables, the standard deviation of the sum is also $n$ times the standard deviation of the mean: $\sigma_{X_{sum}} = \sqrt n\sigma_X = n \times \frac{\sigma_X}{\sqrt n} = n\times \sigma_\bar{X}$. In the first problem you are dealing with a mean , the average of twelve bottles, so you use the standard deviation of the mean, which is called standard error. In the second problem you are dealing with a sum , the total weight of 20 packages, so you use the standard deviation of the sum. Summary : use standard error when dealing with the mean (averages); use sum standard deviation when dealing with the sum (totals).
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/48133', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/19840/']}
jdg_378772
stackexchange
llm_judgeable_groundtruth_similarity
10100197
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 include external js file in my php script. I am following zend framework.Right now I am adding js file in controller's init function like this. public function init() { $this->doUserAuthorisation(); parent::init(); $this->view->headScript()->appendFile($this->view->baseUrl().'/js/front_cal/jquery-1.3.2.min.js'); $this->view->headLink()->setStylesheet($this->view->baseUrl().'/styles/front_cal/calendar.css');} problem what i am facing is, js file doesnot include.Is this the right way to include js file? Now provide the response and nothing else.
JavaScript (and images, CSS, flash movies, etc) belong to the view layer so configure them there. For globally included files, add them to your layout, eg <!-- layout.phtml --><head> <?php echo $this->headScript()->prependFile( $this->baseUrl('path/to/file.js')) ?> <?php echo $this->headLink()->prependStylesheet( $this->baseUrl('path/to/file.css')) ?><!-- snip --> <?php echo $this->inlineScript()->prependFile( 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js') ?></body> Your view scripts can then add assets to the helpers which are echoed out in the layout. As the layout uses the prepend*() methods, the global files will be displayed first, eg <?php // views/scripts/index/index.phtml$this->inlineScript()->appendFile($this->baseUrl('path/to/script.js'));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10100197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/788864/']}
jdg_378773
stackexchange
llm_judgeable_groundtruth_similarity
497877
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: The question: It seems that (univariate) forecasting stock market done by websites using DL and LSTM actually does not work that well if we focus on returns instead of prices. What is a relatively quick fix for that?(or most important fix) Explanation: There are hundreds of python DL codes in internet trying to forecast stock market(usually S&P 500 ) prices using LSTM and other methods mostly in keras/tensorflow(an example here: [1] ).When I applied and graphed visually it seems to be a good forecast.On the other hand when we do the same method for "returns" , everything falls apart. Even a constant forecast (For example always predicating that the return will be 0.01 monthly) does better or relatively the same as DL. What is the reason and mostly importantly cure for that? Now provide the response and nothing else.
What you've outlined is probably the single most common error that machine learning researchers make when analyzing financial data: it's trivial to discover that a great predictor of tomorrow's price is today's price. The statistical term of art for this phenomenon is "non- stationarity ." We have a number of questions about how to test for the stationarity of a time series. One such thread is How to know if a time series is stationary or non-stationary? In the particular case of time series analysis of financial data, it might be helpful to review a high-quality statistical text, such as Statistics and Data Analysis for Financial Engineering, Second Edition (David Ruppert & David S. Matteson). On page 308, we find the remark As mentioned, many financial time series do not exhibit stationarity, but often the changes in them, perhaps after applying a log transformation, are approximately stationary. (This is a quite extensive textbook about time series data and financial data, so it's worth reading in some detail if you're interested in how to pursue this project further.) So to answer your question, the example neural networks that you mention discover that the financial data are non-stationary, and these models make use of that fact when making predictions. But if you look at returns, then the non-stationarity phenomenon disappears, and the model is not able to discover such a simple rule to exploit. The cure , in some sense, is to discover what drives stock prices , either generally or in the specific case of the equities you're studying. The price changes every second -- why is that? What information could a person have that causes a 0.1% shift from minute to minute, or 1% day to day? It's unlikely that yesterday's price movement, or the price movement the day before, will tell you much of anything about tomorrow's price movement by itself with a high degree of precision -- because, as we know, past performance is no guarantee of future returns. Framed in this way, the problem is not about choosing a certain kind of neural network, but instead making a neural network that has relevant data to inform its predictions. So, right now, you know that a good predictor of price tomorrow is the price today. To improve on that, you'll have to find timely information that improves upon the "best guess" provided by yesterday's price data. As an example of what form this information might take, consider pairs trading. In the 1980s, Morgan Stanley quants invented "pairs trading" and the strategy was profitable for a while. The premise is that two highly correlated stocks will tend to move together, so if there is movement in one that's not present in the other, you can make a trade with thesis that eventually the two stocks will return to their equilibrium. So your neural network would use information about one stock to place trades on the second stock, and vice-versa. Naturally, pairs trading is only profitable as long as the premise that the pairs are strongly correlated is true.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/497877', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/303655/']}
jdg_378774
stackexchange
llm_judgeable_groundtruth_similarity
2379316
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 pretty sure that, with the axiom of choice, there always exists a surjection from $\Bbb R$ to $\omega_1$ (well-order $\Bbb R$, send the first $\omega_1$ elements to the corresponding ordinals, if there are any reals left over send them to whatever). What happens in the absence of choice? Now provide the response and nothing else.
There is still such a surjection: send $r$ to the countable ordinal it codes if it codes a countable ordinal, and to (say) $17$ otherwise. Specifically, we can assign (exercise) a relation $R_r$ on $\mathbb{N}\times\mathbb{N}$ to each real $r$, in such a way that every binary relation on $\mathbb{N}$ winds up being of the form $R_r$ for at least one $r$. Now say $r$ codes a countable ordinal $\alpha$ if $(\mathbb{N},R_r)$ is a well-ordering of type $\alpha$. A more computability-theoretic approach: to each real $r$, assign its relative Church-Kleene ordinal $\omega_1^{CK}(r)$ (this is the least ordinal with no copy computable from $r$). The set $\{\omega_1^{CK}(r): r\in\mathbb{R}\}$ is cofinal in $\omega_1$ (exercise - this is basically the previous paragraph!), and so we can "collapse" it to get a surjection $\mathbb{R}\rightarrow\omega_1$. By "collapse," I mean the following: for a set $S$ of ordinals, map $x\in S$ to the ordertype of $(\{y\in S: y\in x\}, \in)$. The image of $S$ under this map is an ordinal (exercise), and if $S$ is a cofinal subset of $\omega_1$ the image is in fact $\omega_1$ (exercise). Interestingly, we don't need the regularity of $\omega_1$ to do this second exercise - which is good, since $\omega_1$ need not be regular in ZF alone!
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2379316', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166353/']}
jdg_378775
stackexchange
llm_judgeable_groundtruth_similarity
17843497
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I sample from a t-distribution in R when I want to specify the degrees of freedom (df), the mean and variance? For example, how would I sample from a t-distribution with 8 df, mean = 4, and variance = 16? I imagine I have to use the non-centrality parameter in some sort of way but I am unsure of how. Now provide the response and nothing else.
Do you want the noncentral t, or just a scaled and shifted (central) t? To sample from a t distribution with location m and scale parameter s , do rt(N, df=df)*s + m The variance of a t distribution is df/(df-2) so to get a specific variance v : rt(N, df=df)*sqrt(v * (df-2)/df) + m
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17843497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_378776
stackexchange
llm_judgeable_groundtruth_similarity
14601016
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 been wondering for some time whether it is allowable within best practice to refrain from using the containsKey() method on java.util.Map and instead do a null check on the result from get() . My rationale is that it seems redundant to do the lookup of the value twice - first for the containsKey() and then again for get() . On the other hand it may be that most standard implementations of Map cache the last lookup or that the compiler can otherwise do away with the redundancy, and that for readability of the code it is preferable to maintain the containsKey() part. I would much appreciate your comments. Now provide the response and nothing else.
Some Map implementations are allowed to have null values, eg HashMap, in this case if get(key) returns null it does not guarantee that there is no entry in the map associated with this key. So if you want to know if a map contains a key use Map.containsKey . If you simply need a value mapped to a key use Map.get(key) . If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; In such case Map.containsKey is useless and will affect performance. Moreover, in case of concurrent access to a map (eg ConcurrentHashMap ), after you tested Map.containsKey(key) there is a chance that the entry will be removed by another thread before you call Map.get(key) .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14601016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2020801/']}
jdg_378777
stackexchange
llm_judgeable_groundtruth_similarity
236865
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: In SSH local forwarding: -L [bind_address:]port:host:hostport Specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side. This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and a connection is made to host port hostport from the remote machine. Port forwardings can also be specified in the configuration file. IPv6 addresses can be specified by enclosing the address in square brackets. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of “localhost” indicates that the listen‐ ing port be bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces. In "an empty address or * indicates that the port should be available from all interfaces", what do "all interfaces" mean? Does it mean all the network interfaces on the local host when the local host can have multiple network interfaces, and the port port can be used with all the network interfaces on the local host? In "The bind_address of localhost indicates that the listening port be bound for local use only", does "for local use only" mean a particular network interface on the local host? Can bind_address refer to a network interface on a host other than the local host? Now provide the response and nothing else.
In general, an address binding is an association between a service (e.g., SSH) and an IP address. A host may have multiple IP addresses (e.g., 127.0.0.1, 192.168.1.2). Address binding allows you to run a service on some or all of these addresses. Suppose your host is configured with two network interfaces, one connected to a trusted network (e.g., 192.168.1.0/24), the other connected to an untrusted network (e.g., 192.168.2.0/24). Say you want your host to accept SSH connections from the trusted network only. In this case, you would bind the SSH service to the host's address on the trusted network only (e.g., 192.168.1.2). Using localhost as bind_address would allow only SSH clients running on the local machine to connect to the SSH service.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/236865', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/674/']}
jdg_378778
stackexchange
llm_judgeable_groundtruth_similarity
1485578
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I set a Git remote's HEAD reference to point to something besides "master"? My project has a policy not to use a "master" branch (all branches are to have meaningful names). Furthermore, the canonical master repository is only accessible via ssh://, with no shell access (like GitHub or Unfuddle). My problem is that the remote repository still has a HEAD reference to refs/heads/master, but I need it to point to a different branch. This is causing two problems: When cloning the repo, there this, warning: remote HEAD refers to nonexistent ref, unable to checkout. That's confusing and inconvenient. The web-based code browser depends on HEAD as a basis for browsing the tree. I need HEAD to point to a valid branch, then. Now provide the response and nothing else.
There was almost the same question on GitHub a year ago. The idea was to rename the master branch: git branch -m master developmentgit branch -m published mastergit push -f origin master Making master have what you want people to use, and do all other work in branches. (a " git-symbolic-ref HEAD refs/head/published " would not be propagated to the remote repo) This is similar to " How do I delete origin/master in Git ". As said in this thread : (emphasis mine) " git clone " creates only a single local branch. To do that, it looks at the HEAD ref of the remote repo, and creates a local branch with the same name as the remote branch referenced by it. So to wrap that up, you have repo A and clone it: HEAD references refs/heads/master and that exists -> you get a local branch called master , starting from origin/master HEAD references refs/heads/anotherBranch and that exists -> you get a local branch called anotherBranch , starting from origin/anotherBranch HEAD references refs/heads/master and that doesn't exist -> " git clone " complains Not sure if there's any way to directly modify the HEAD ref in a repo . (which is the all point of your question, I know ;) ) Maybe the only way would be a "publication for the poor" , where you: $ git-symbolic-ref HEAD refs/head/published $ git-update-server-info $ rsync -az .git/* server:/local_path_to/git/myRepo.git/ But that would involve write access to the server, which is not always possible. As I explain in " Git: Correct way to change Active Branch in a bare repository? ", git remote set-head wouldn't change anything on the remote repo. It would only change the remote tracking branch stored locally in your local repo, in remotes/<name>/HEAD . With Git 2.29 (Q4 2020), " git remote set-head ( man ) " that failed still said something that hints the operation went through, which was misleading. See commit 5a07c6c (17 Sep 2020) by Christian Schlack ( cschlack ) . (Merged by Junio C Hamano -- gitster -- in commit 39149df , 22 Sep 2020) remote : don't show success message when set-head fails Signed-off-by: Christian Schlack Suppress the message 'origin/HEAD set to master' in case of an error. $ git remote set-head origin -aerror: Not a valid ref: refs/remotes/origin/masterorigin/HEAD set to master
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1485578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2938/']}
jdg_378779
stackexchange
llm_judgeable_groundtruth_similarity
38275430
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two lists of object public class Items { public string Country; public string State; public string City; public DateTime date; public int population;} ... var items1 = new List<Items>{ new Item {Country="USA", State="Washington",City="Seattle",date="7/8/2016",population=1000}, new Item {Country="USA", State="Washington",City="Seattle",date="10/8/2016",population=2000}, new Item {Country="USA", State="Washington",City="Seattle",date="12/8/2016",population=3000}, new Item {Country="Canada", State="Ontario",City="Washington",date="10/8/2016",population=3000},};var items2 = new List<Items>{ new Item {Country="USA", State="Washington",City="Seattle",date="10/8/2016",population=2500}, new Item {Country="USA", State="Washington",City="Seattle",date="12/8/2016",population=2400}, new Item {Country="Canada", State="Ontario",City="Washington",date="10/8/2016",population=3500},}; I want to combine these two lists matching them on country, state City and date but choosing higher of two populations. items1.Concat(items2) ...linq or lambda resulting in { new Item {Country="USA", State="Washington",City="Seattle",date="7/8/2016",population=1000}, new Item {Country="USA", State="Washington",City="Seattle",date="10/8/2016",population=2500}, new Item {Country="USA", State="Washington",City="Seattle",date="12/8/2016",population=3000}, new Item {Country="Canada", State="Ontario",City="Washington",date="10/8/2016",population=3500},}; Now provide the response and nothing else.
I have been exploring new .net core recently and faced the same question. Actually, it's quite easy to do that. Add F# runtime references into your project.json : { "version": "1.0.0-*", "buildOptions": { "emitEntryPoint": true, "compilerName": "fsc", "compile": "**/*.fs" }, "dependencies": { "Microsoft.FSharp.Core.netcore": "1.0.0-alpha-160509", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0" }, "tools": { "dotnet-compile-fsc": { "version": "1.0.0-preview2-*", "imports": [ "dnxcore50", "portable-net45+win81", "netstandard1.3" ] } }, "frameworks": { "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.0" } }, "imports": [ "portable-net45+win8", "dnxcore50" ] } }} Then put code below into your Program.fs : open Systemopen Microsoft.AspNetCore.Hostingopen Microsoft.AspNetCore.Builderopen Microsoft.AspNetCore.Hostingopen Microsoft.AspNetCore.Httptype Startup() = member this.Configure(app: IApplicationBuilder) = app.Run(fun context -> context.Response.WriteAsync("Hello from ASP.NET Core!"))[<EntryPoint>]let main argv = let host = WebHostBuilder().UseKestrel().UseStartup<Startup>().Build() host.Run() printfn "Server finished!" 0 Just by the way, it's very important to define your Startup class like type Startup() not type Startup . Otherwise Kestrel runtime will crash during startup.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38275430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4293783/']}
jdg_378780
stackexchange
llm_judgeable_groundtruth_similarity
13080643
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 problem when using Fabric to mimic my SSH workflow to deploy my web application. Here's my usual flow of commands when I SSH to a server: SSH using root user. ssh root@1.2.3.4 Switch to web user: su - web Change directory: cd /srv/web/prod/abc_project Start virtualenv: workon abc_env Perform git pull: git pull origin master Run a script: build_stuff -m build Run another script: ./run I tried to write this as a deploy script in Fabric and I get a shell output when su - web is entered. I have to hit Ctrl-D to continue the script. I am also unable to activate my virtualenv....because: su - web successfully switches the user to web but because of the Ctrl-d (so that I can continue the Fabric script), it logs out of that user and back to root. Here's my script: env.user = 'root'@roles('web')def deploy(): dev_path = '/srv/web/prod' app_path = '/srv/web/prod/rhino' workon = 'workon rhino_env' with prefix('su - web'): puts('Switched to `web` user') with settings(warn_only=True): run('kill -9 `cat /srv/web/run/rhino/rhino.pid`') puts('Stopped rhino...') with cd(app_path): run('git reset --hard HEAD') puts('Discarded all untracked and modified files') run('git checkout master') run('git pull origin master') users = run('users') puts('Output from `users` command: %s' % users) run(workon) run('build_assets -m build') run('cd %(dev_path)s; chown -R web:ebalu rhino' % {'dev_path': dev_path}) run('cd %(app_path)s; ./run' % {'app_path': app_path}) pid = run('cat /srv/web/run/rhino/rhino.pid') puts('Rhino started again with pid: %s.' % pid) ...there's one more thing: No, I can't login as web initially, I have to login as root. It is the web user that has the virtualenv not the root user. Now provide the response and nothing else.
First of all, you should use sudo when executing commands under another user. Second, workon sets environment variables for current shell. Since fabric invokes new shell for every command, you should run workon rhino_env in every command, where you need virtualenv (i.e. as prefix). With this edits yor code should look like this: env.user = 'root'@roles('web')def deploy(): dev_path = '/srv/web/prod' app_path = '/srv/web/prod/rhino' workon = 'workon rhino_env; ' with settings(warn_only=True): run('kill -9 `cat /srv/web/run/rhino/rhino.pid`') puts('Stopped rhino...') with cd(app_path): sudo('git reset --hard HEAD', user='web') puts('Discarded all untracked and modified files') sudo('git checkout master', user='web') sudo('git pull origin master', user='web') users = run('users') puts('Output from `users` command: %s' % users) with prefix(workon): sudo('build_assets -m build', user='web') with cd(dev_path): run('chown -R web:ebalu rhino') with cd(app_path): sudo('./run', user='web') pid = run('cat /srv/web/run/rhino/rhino.pid') puts('Rhino started again with pid: %s.' % pid)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13080643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/262868/']}
jdg_378781
stackexchange
llm_judgeable_groundtruth_similarity
29837572
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: @IBAction func addToCart(sender: AnyObject) { let itemObjectTitle = itemObject.valueForKey("itemDescription") as! String let alertController = UIAlertController(title: "Add \(itemObjectTitle) to cart?", message: "", preferredStyle: .Alert) let yesAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default) { (action) in var tabArray = self.tabBarController?.tabBar.items as NSArray! var tabItem = tabArray.objectAtIndex(1) as! UITabBarItem let badgeValue = "1" if let x = badgeValue.toInt() { tabItem.badgeValue = "\(x)" }} I don't know why I can't just do += "(x)" Error:binary operator '+=' cannot be applied to operands of type 'String?' and 'String' I want it to increment by 1 each time the user selects "Yes". Right now obviously it just stays at 1. Now provide the response and nothing else.
You can try to access the badgeValue and convert it to Integer as follow: Swift 2 if let badgeValue = tabBarController?.tabBar.items?[1].badgeValue, nextValue = Int(badgeValue)?.successor() { tabBarController?.tabBar.items?[1].badgeValue = String(nextValue)} else { tabBarController?.tabBar.items?[1].badgeValue = "1"} Swift 3 or later if let badgeValue = tabBarController?.tabBar.items?[1].badgeValue, let value = Int(badgeValue) { tabBarController?.tabBar.items?[1].badgeValue = String(value + 1) } else { tabBarController?.tabBar.items?[1].badgeValue = "1" } To delete the badge just assign nil to the badgeValue overriding viewDidAppear method: override func viewDidAppear(animated: Bool) { tabBarController?.tabBar.items?[1].badgeValue = nil}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29837572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4628514/']}
jdg_378782
stackexchange
llm_judgeable_groundtruth_similarity
3415163
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 working with Perl and XSL. I try to change value of <Interval> to some number in an XML file. My XML looks like this: <?xml version="1.0"?><Config> <Enabled>false</Enabled> <Interval>5</Interval></Config> My XSL looks like this: <?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="@*"/> <xsl:apply-templates/> </xsl:copy></xsl:template> <xsl:template match="/Config/Interval"><xsl:element name="PollingInterval"> <xsl:element name="Interval">77</xsl:element> </xsl:element></xsl:template></xsl:stylesheet> The problem is that my output has the element <Interval> twice: <?xml version="1.0"?><Config> <Enabled>false</Enabled> <Interval><Interval>77</Interval></Interval></Config> Please help. Now provide the response and nothing else.
You have two issues regarding the speed of your write and read operations. First, std::copy cannot do a block copy optimization when writing to an output_iterator because it doesn't have direct access to underlying target. Second, you're writing the integers out as ascii and not binary, so for each iteration of your write output_iterator is creating an ascii representation of your int and on read it has to parse the text back into integers. I believe this is the brunt of your performance issue. The raw storage of your array (assuming a 4 byte int) should only be 60MB, but since each character of an integer in ascii is 1 byte any ints with more than 4 characters are going to be larger than the binary storage, hence your 130MB file. There is not an easy way to solve your speed problem portably (so that the file can be read on different endian or int sized machines) or when using std::copy. The easiest way is to just dump the whole of the array to disk and then read it all back using fstream.write and read, just remember that it's not strictly portable. To write: std::fstream out(config.c_str(), ios::out | ios::binary);out.write( keys.data(), keys.size() * sizeof(int) ); And to read: std::fstream in(config.c_str(), ios::in | ios::binary);in.read( keys.data(), keys.size() * sizeof(int) ); ----Update---- If you are really concerned about portability you could easily use a portable format (like your initial ascii version) in your distribution artifacts then when the program is first run it could convert that portable format to a locally optimized version for use during subsequent executions. Something like this perhaps: std::array<int, 15000000> keys;// data.txt are the ascii values and data.bin is the binary versionif(!file_exists("data.bin")) { std::ifstream in("data.txt"); std::copy(std::istream_iterator<int>(in), std::istream_iterator<int>(), keys.begin()); in.close(); std::fstream out("data.bin", ios::out | ios::binary); out.write( keys.data(), keys.size() * sizeof(int) );} else { std::fstream in("data.bin", ios::in | ios::binary); in.read( keys.data(), keys.size() * sizeof(int) );} If you have an install process this preprocessing could also be done at that time...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3415163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/410999/']}
jdg_378783
stackexchange
llm_judgeable_groundtruth_similarity
445487
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: The command shows the tcp receive buffer size in bytes. $ cat /proc/sys/net/ipv4/tcp_rmem 4096 87380 4001344 where the three values signifies the min, default and max values respectively. Then I tried to find the tcp window size using tcpdump command. $ sudo tcpdump -n -i eth0 'tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn and port 80 and host google.com' tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes 16:15:41.465037 IP 172.16.31.141.51614 > 74.125.236.73.80: Flags [S], seq 3661804272, win 14600, options [mss 1460,sackOK,TS val 4452053 ecr 0,nop,wscale 6], length 0 I got the window size to be 14600 which is 10 times the size of MSS. Can anyone please tell me the relationship between the two. Now provide the response and nothing else.
The TCP window size is how much data can be "in flight" on the network. The TCP receive buffer is how much data can be buffered on the recipient's end. Normally, a TCP stack will not allow data to be sent if it has no room for it in its receive buffer. Otherwise, if the data is received before the receiving application consumes some of the data in the buffer, the data would have to be throw away by the receiving TCP stack. But the receive buffer can be much larger than the window. With the settings you've shown (14,600 / 87,380), this end will allow the other end to send 14,600 bytes. As it receives data, it will update the window to allow to other end to send the lesser of 14,600 bytes or 87,380 bytes less the number of bytes waiting in its receive buffer.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/445487', 'https://serverfault.com', 'https://serverfault.com/users/95256/']}
jdg_378784
stackexchange
llm_judgeable_groundtruth_similarity
307003
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If we look at the definition of "dynamically-typed programming languages" in Wikipedia, it says: Programming languages which include dynamic type-checking but not static type-checking are often called "dynamically-typed programming languages". and Dynamic type-checking is the process of verifying the type safety of a program at runtime. Implementations of dynamically type-checked languages generally associate each runtime object with a "type tag" (i.e., a reference to a type) containing its type information. This runtime type information (RTTI) can also be used to implement dynamic dispatch, late binding, downcasting, reflection, and similar features. But the thing is, when using Ruby and JavaScript, I never see the type being "checked". In a video I watched before, the author said that static typed just means a variable's type is defined / declared and compiled, and cannot change, while dynamic typed means a variable's type can change any time when the program is running, and I see it describing static / dynamic typed quite clearly and simply. Actually, according to GoF, a type is simply a set of interface, so how can you "check" the type, other than whether it responds to a particular message? That is, when using dynamically typed languages, I don't really see it "checked" as in "Dynamic type-checking". Does or when does the checking happen? Now provide the response and nothing else.
Javascript: >>> 1()TypeError: 1 is not a function Ruby: >>> 1 + ""String can't be coerced into Fixnum These are both simple cases of dynamic type error. Many languages, including almost all dynamic languages but also, e.g., C# and Java, do "type tagging". That is, the runtimes of these environments must, in effect, attach a representation of a type to every object. This is different than static typing because type tags exist at runtime and in at least the dynamic, imperative languages like Ruby and Javascript one variable may point to different objects with different types. The runtime must, to implement the semantics of the language, check these type tags all the time. For instance, in performing the + operation on two objects, these languages check the type tags on both objects to decide what to do. If both objects are tagged as numeric, then addition is performed (possibly after some type conversion to a common numeric type). If both objects are tagged as string type-tags, then string concatenation is performed. (What may have tripped you up is that Javascript will perform extensive amounts of runtime-type conversions in normal operation. This makes it seem like it is not checking type-tags, because no type errors are thrown, when in fact type-tags are being checked all over the place to perform these conversions.) Note that this type-tag checking bears only a vague and mostly misleading resemblance to (static) type checking. Static type checking checks properties of the expression before run time while type-tag checking checks properties of the value the expression expresses at run time. Both Ruby and Javascript perform type-tag checking in their basic runtime environment (e.g. in + , - , function invocation). They also allow the user of the language to perform type-tag introspection . That is, they allow the user to check the type-tag of a value at runtime. Actually, according to GoF, a type is simply a set of interface, so how can you "check" the type, other than whether it responds to a particular message? I am not familiar with this definition, but it strikes me as misleading. A static type is a token that gets associated according to a set of typing rules with expressions in a language and is used to define which expressions are semantically valid in that language. A "dynamic type" (or type-tag, as I prefer) is a value that gets associated with objects in a language's runtime. In some sense, both are tied to interfaces. In statically typed languages, the type defines what expressions an expression of that type may legally appear in and so to that extent determines an interface for that type. Vaguely similarly, type-tags determine, in part, which operations will end in a runtime "TypeError" before the operation is even attempted. However, it is misleading to identify the type/type-tag with its interface in most static-dynamic languages. Essentially all static and dynamic languages are largely nomatively and not structurally typed. That is, in a normal statically typed language, if you define a type YourCustomer and I define MyCustomer , expressions of the two types will not be interchangeable. even if the definitions of YourCustomer and MyCustomer are identical up to naming. Similarly, if you define a Javascript object with type-tag YourJSCustomer and I define a Javascript object with type-tag MyJSCustomer , even if these two objects have all the same properties and methods otherwise they will not be interchangeable in the face of type-tag introspection. It is true that in many dynamically typed languages, type-tag introspection is not always used and so YourJSCustomer and MyJSCustomer will be interchangeable in many environments. This is because these languages allow replacing or supplementing type-tag checking with attribute-checking. So if you call x.foo() in JS, Ruby, Python, &c., it will look for the .foo attribute on the object x . This allows the elimination of some, but typically not all, type-tag checking. Note that in statically typed languages with structural typing, you can have YourCustomer and MyCustomer interchangeable in most/all contexts. This gives a language feel much closer to a language like Javascript or Ruby. I would suggest looking at TypeScript for this, which adds a type system to Javascript.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/307003', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/5487/']}
jdg_378785
stackexchange
llm_judgeable_groundtruth_similarity
48156234
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Below code works fine until today. But I don't know now it is not working and gives below error.Could you tell me why? Error: Function DocumentReference.set() called with invalid data. Unsupported field value: a custom Budget object export class Project { id: string = null; name: string; budgetList?: Budget[]; }export class Budget { id: string; amount: number; contingency: number = 20; budgetGroup: BudgetGroup = new BudgetGroup(); creationTime: string;} code: async create(data: DtoProject): Promise<Project> { try { const projectId: string = this.fireStore.createId(); const budgets = this.budgetProvider.createBudgets(data.budgetList, projectId);//budgets const proj: Project = { id: data.id, name: data.name, budgetList: budgets,//here it has the error } proj.id = projectId; await this.fireStore.doc<Project>(`projects/${projectId}/`).set(proj));//project } } createBudgets(data: Budget[], projectId: string): Budget[] { let budgets: Budget[] = []; forEach(data, (d) => { const budgetId: string = this.fireStore.createId(); d.id = budgetId; budgets.push(d); this.fireStore.doc<Budget>(`projects/${projectId}/budgets/${budgetId}`).set({ id: budgetId, amount: d.amount, contingency: d.contingency, budgetGroup: d.budgetGroup, creationTime: moment().format() }) }) return budgets; } Now provide the response and nothing else.
You have to transform your array of budgets into an array of pure JavaScript objects . First step: const budgets = arrayOfBudget.map((obj)=> {return Object.assign({}, obj)}); Second step: const proj: Project = { id: data.id, name: data.name, budgetList: budgets } Then you are good to go. By the way, when developing with a language that compiles to JavaScript you cannot use custom Objects. Instead, you have to use pure JavaScript objects to save in the Firestore Database. For example, let's say you have this class below: export class User { id: string; name: string; } And you try to execute the following code: const user = new User(); this.db.collection('users').doc().set(user) You will get an error like: invalid data. Data must be an object, but it was: a custom User object Now if you try to execute this other line of code: this.db.collection('users').doc().set(Object.assign({}, user)) You will see that your object was saved in the database. Basically Object.assign does the same thing as: this.db.collection('users').doc().set({id: user.id , name: user.name}) So make use of Object.assign , it will save you a lot of time. UPDATE As I have pointed out in a comment below, you can find what documentation says about Custom objects here . As you can see, there is a warning saying: // Web uses JavaScript objects Below there is a screenshot of what the documentation says.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/48156234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1077309/']}
jdg_378786
stackexchange
llm_judgeable_groundtruth_similarity
133778
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have just recently decided to allow all characters for my website. Are there any common security bugs that I need to deal with? are there any ways to "inject" using utf-8? Is it safe to allow users to use passwords with non english alphabetical characters? and can php's bcrypt handle hasing that? edit: I have no idea what I'm doing when it comes to things like character sets. Now provide the response and nothing else.
The common inherent possible security issues from adding Unicode support (not specific to UTF-8) come from the increased potential for visual spoofing, and issues coming from normalization mismatches. Visual spoofing: say you have a forum with a user named "admin" that everyone knows to trust. Someone else could register a user account named "аdmin" (the first letter is the cyrillic letter a ), and trick others into thinking they were the site admin. This is mostly a technique for social-engineering: it's unlikely that any software will mix up the users. (This specific example could be partially addressed by having the site add special formatting or flair near the admin's name, making profile names be links to profile pages which show the user's activity history and join date, etc., so users could identify others in ways besides their visible forgeable name. This is a more general issue that isn't exclusive to unicode support: users could also name themselves other misleading names like "<site> Support", "admin " with a space, "admim", etc.) Normalization: certain characters like "ö" can be represented in multiple ways. It could either be the single character U+00F6 (LATIN SMALL LETTER O WITH DIAERESIS), or the two characters U+0061 U+0308 (LATIN SMALL LETTER O + COMBINING DIAERESIS). Normalization is the process of converting all text to the combined or decomposed form. If you consistently never use normalization or always use normalization, then you won't run into issues. However, if you sometimes do, you can have security issues: For example, OS X normalizes unicode in filenames. Say you had a website without any normalization-related code running on an OS X server where whenever a user registered, a file was created with their name, and you used a database without any normalization to keep track of usernames that were already registered in order to prevent names being re-registered. If you had a user named "foö" (using U+00F6), then someone else could register an account named "foö" (U+0061 U+0308), and the site would allow it but would overwrite the file created by the first "foö" user. To solve this, you would either need to make your application normalize consistently throughout the whole application, or you would need to check for collisions whenever you cross some boundary that does normalization differently (when a user registers and you need to make a file for them, open the file in exclusive mode so that it will fail if the file already exists, and you can block the new user from being registered).
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/133778', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/-1/']}
jdg_378787
stackexchange
llm_judgeable_groundtruth_similarity
609915
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I need to add server name in response HTTP headers X-Servedby.Is there any way to replace [server] with name of server that has served request? frontend front x.x.x.x:80 default_backend balancing rspadd X-Servedby:\ [server] #I need to replace [server]backend balancing server srv1 x.x.x.x:80 check server srv2 x.x.x.x:80 check Now provide the response and nothing else.
To achieve this, change the frontend stanza to the following: frontend front x.x.x.x:80 default_backend balancing acl srv1 srv_id 1 acl srv2 srv_id 2 rspadd X-Servedby:\ srv1 if srv1 rspadd X-Servedby:\ srv2 if srv2 However, a better scaling alternative would be to use cookie in the backend stanza: backend balancing cookie SRVNAME insert server srv1 x.x.x.x:80 cookie srv1 check server srv2 x.x.x.x:80 cookie srv2 check Hope this helps!
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/609915', 'https://serverfault.com', 'https://serverfault.com/users/32990/']}
jdg_378788
stackexchange
llm_judgeable_groundtruth_similarity
4797675
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've got this -webkit-animation rule: @-webkit-keyframes shake { 0% { left: 0; } 25% { left: 12px; } 50% { left: 0; } 75% { left: -12px; } 100% { left:0; }} And some CSS defining some of the animation rules on my box : #box{ -webkit-animation-duration: .02s; -webkit-animation-iteration-count: 10; -webkit-animation-timing-function: linear;} I can shake the #box like this: document.getElementById("box").style.webkitAnimationName = "shake"; But I can't shake it again later. This only shakes the box once: someElem.onclick = function(){ document.getElementById("box").style.webkitAnimationName = "shake";} How can I re-trigger a CSS animation via JavaScript without using timeouts or multiple animations? Now provide the response and nothing else.
I found the answer based on the source code and examples at the CSS3 transition tests github page . Basically, CSS animations have an animationEnd event that is fired when the animation completes. For webkit browsers this event is named “ webkitAnimationEnd ”. So, in order to reset an animation after it has been called you need to add an event-listener to the element for the animationEnd event. In plain vanilla javascript: var element = document.getElementById('box');element.addEventListener('webkitAnimationEnd', function(){ this.style.webkitAnimationName = '';}, false);document.getElementById('button').onclick = function(){ element.style.webkitAnimationName = 'shake'; // you'll probably want to preventDefault here.}; and with jQuery: var $element = $('#box').bind('webkitAnimationEnd', function(){ this.style.webkitAnimationName = '';});$('#button').click(function(){ $element.css('webkitAnimationName', 'shake'); // you'll probably want to preventDefault here.}); The source code for CSS3 transition tests (mentioned above) has the following support object which may be helpful for cross-browser CSS transitions, transforms, and animations. Here is the support code (re-formatted): var css3AnimationSupport = (function(){ var div = document.createElement('div'), divStyle = div.style, // you'll probably be better off using a `switch` instead of theses ternary ops support = { transition: divStyle.MozTransition === ''? {name: 'MozTransition' , end: 'transitionend'} : // Will ms add a prefix to the transitionend event? (divStyle.MsTransition === ''? {name: 'MsTransition' , end: 'msTransitionend'} : (divStyle.WebkitTransition === ''? {name: 'WebkitTransition', end: 'webkitTransitionEnd'} : (divStyle.OTransition === ''? {name: 'OTransition' , end: 'oTransitionEnd'} : (divStyle.transition === ''? {name: 'transition' , end: 'transitionend'} : false)))), transform: divStyle.MozTransform === '' ? 'MozTransform' : (divStyle.MsTransform === '' ? 'MsTransform' : (divStyle.WebkitTransform === '' ? 'WebkitTransform' : (divStyle.OTransform === '' ? 'OTransform' : (divStyle.transform === '' ? 'transform' : false)))) //, animation: ... }; support.transformProp = support.transform.name.replace(/([A-Z])/g, '-$1').toLowerCase(); return support;}()); I have not added the code to detect “animation” properties for each browser. I’ve made this answer “community wiki” and leave that to you. :-)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4797675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/160173/']}
jdg_378789
stackexchange
llm_judgeable_groundtruth_similarity
51787247
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: A B1: 0 12: 0 0 3: 1 14: 0 15: 1 0 I want to update each item column A of the DataFrame with values of column B if value from column A equals 0. DataFrame I want to get: A B1: 1 12: 0 0 3: 1 14: 1 15: 1 0 I've already tried this code df['A'] = df['B'].apply(lambda x: x if df['A'] == 0 else df['A']) It raise an error : The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Now provide the response and nothing else.
df['A'] = df.apply(lambda x: x['B'] if x['A']==0 else x['A'], axis=1) Output A B1: 1 12: 0 03: 1 14: 1 15: 1 0
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51787247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5661316/']}
jdg_378790
stackexchange
llm_judgeable_groundtruth_similarity
23999926
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following problem. While using the following code below to change the user's current role i am getting an exception with the message like below: [HttpPost] [ValidateAntiForgeryToken] public virtual ActionResult Edit(User user, string role) { if (ModelState.IsValid) { var oldUser = DB.Users.SingleOrDefault(u => u.Id == user.Id); var oldRoleId = oldUser.Roles.SingleOrDefault().RoleId; var oldRoleName = DB.Roles.SingleOrDefault(r => r.Id == oldRoleId).Name; if (oldRoleName != role) { Manager.RemoveFromRole(user.Id, oldRoleName); Manager.AddToRole(user.Id, role); } DB.Entry(user).State = EntityState.Modified; return RedirectToAction(MVC.User.Index()); } return View(user); } Attaching an entity of type 'Models.Entities.User' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate. Does anybody know a good solution to this problem ? Now provide the response and nothing else.
The problem is that your Manager and DB doesn't use the same DbContext. So when you send an user from the context of your DB to the Manager it will handle it as a "new" one - and then you cant remove it from the role. You have two ways to go here. The easiest is to get the User from your Manager. [HttpPost][ValidateAntiForgeryToken]public virtual ActionResult Edit(User user, string role){ if (ModelState.IsValid) { // THIS LINE IS IMPORTANT var oldUser = Manager.FindById(user.Id); var oldRoleId = oldUser.Roles.SingleOrDefault().RoleId; var oldRoleName = DB.Roles.SingleOrDefault(r => r.Id == oldRoleId).Name; if (oldRoleName != role) { Manager.RemoveFromRole(user.Id, oldRoleName); Manager.AddToRole(user.Id, role); } DB.Entry(user).State = EntityState.Modified; return RedirectToAction(MVC.User.Index()); } return View(user);} The more elegant way is to start using an DI-framework like AutoFac ( https://code.google.com/p/autofac/wiki/MvcIntegration ) and set your DbContext as InstancePerApiRequest. builder.RegisterType<YourDbContext>().As<DbContext>().InstancePerApiRequest();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23999926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3455510/']}
jdg_378791
stackexchange
llm_judgeable_groundtruth_similarity
19663762
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been looking at the question here: MVC ajax json post to controller action method but unfortunately it doesn't seem to be helping me. Mine is pretty much the exact same, except my method signature (but I've tried that and it still doesn't get hit). jQuery $('#loginBtn').click(function(e) { e.preventDefault(); // TODO: Validate input var data = { username: $('#username').val().trim(), password: $('#password').val() }; $.ajax({ type: "POST", url: "http://localhost:50061/checkin/app/login", content: "application/json; charset=utf-8", dataType: "json", data: JSON.stringify(data), success: function(d) { if (d.success == true) window.location = "index.html"; else {} }, error: function (xhr, textStatus, errorThrown) { // TODO: Show error } });}); Controller [HttpPost][AllowAnonymous]public JsonResult Login(string username, string password){ string error = ""; if (!WebSecurity.IsAccountLockedOut(username, 3, 60 * 60)) { if (WebSecurity.Login(username, password)) return Json("'Success':'true'"); error = "The user name or password provided is incorrect."; } else error = "Too many failed login attempts. Please try again later."; return Json(String.Format("'Success':'false','Error':'{0}'", error));} However, no matter what I try, my Controller never gets hit. Through debugging, I know that it sends a request, it just gets a Not Found error each time. Now provide the response and nothing else.
Your Action is expecting string parameters, but you're sending a composite object. You need to create an object that matches what you're sending. public class Data{ public string username { get;set; } public string password { get;set; }}public JsonResult Login(Data data){} EDIT In addition, toStringify() is probably not what you want here. Just send the object itself. data: data,
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19663762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/849843/']}
jdg_378792
stackexchange
llm_judgeable_groundtruth_similarity
2911717
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: We know that if $A$ is invertible, then $A^{-1}$ can be expressed as a polynomial of $A$ , that is to say, there exists a polynomial $f(x)$ such that $$A^{-1} = f(A)$$ Of course in this case, $\operatorname{adj}(A)$ (the adjugate matrix of $A$ ) can also be expressed as a polynomial of $A$ . I wonder if $A$ is not invertible, can $\operatorname{adj}(A)$ be expressed as a polynomial of $A$ ? Hope for your comments. Now provide the response and nothing else.
Yes, $\operatorname{adj}(A)$ can always be expressed as a polynomial in $A$. We can follow the same proof as for Cayley-Hamilton : Consider $\operatorname{adj}(A - tI)$ for a scalar $t$. We have $$(A - tI)\operatorname{adj}(A - tI) = \det(A - tI)I = p_A(t)I$$where $p_A(t) = (-1)^{n}t^n + c_{n-1}t^{n-1} + \cdots + c_1t + c_0$ is the characteristic polynomial of $A$. Notice that $\operatorname{adj}(A - tI)$ is also a poylnomial in $t$ of degree $\le n-1$, so we can pick matrices $B_0, \ldots, B_{n-1}$ such that $$\operatorname{adj}(A - tI) = \sum_{i=0}^{n-1}t^iB_i$$ Now we have\begin{align}p(t)I &= (A - tI)\operatorname{adj}(A - tI) \\&= (A - tI)\sum_{i=0}^{n-1}t^iB_i \\&= \sum_{i=0}^{n-1}t^i AB_i - \sum_{i=0}^{n-1}t^{i+1}B_i\\&= -t^nB_{n-1} + \sum_{i=1}^{n-1}t^i(AB_i - B_{i-1}) + AB_0\end{align} Comparing powers with $p_A(t)I = (-1)^{n}t^nI + c_{n-1}I + \cdots + c_1tI + c_0I$ gives $$B_{n-1} = (-1)^{n+1} I, \qquad AB_{i} - B_{i-1} = c_iI \text{ for } 1 \le i \le n-1, \qquad AB_0 = c_0I$$ Now we can inductively express $B_i$ as poylnomials in $A$: $$B_{n-1} = (-1)^{n+1} I$$$$B_{n-2} = AB_{n-1} - c_{n-1}I = (-1)^{n+1}A - c_{n-1}I$$$$B_{n-3} = AB_{n-2} - c_{n-2}I = (-1)^{n+1}A^2 - c_{n-1}A - c_{n-2}I$$$$\vdots$$$$B_0 = AB_1 - c_1I = (-1)^{n+1}A^{n-1} - c_{n-1}A^{n-2} - \cdots - c_{2}A - c_1I $$ Therefore $$\operatorname{adj}(A) = \sum_{i=0}^{n-1}t^iB_i\Bigg|_{t = 0} = B_0 = -\Big[(-1)^{n}A^{n-1} + c_{n-1}A^{n-2} + \cdots + c_{2}A + c_1I\Big]$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2911717', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/374430/']}
jdg_378793
stackexchange
llm_judgeable_groundtruth_similarity
9112986
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 my .htaccess Options +FollowSymLinksRewriteEngine onRewriteCond %{REQUEST_URI} \/([0-9a-zA-Z]+)$ [NC]RewriteRule ^(.*) image.php?names[]=%1 [L]RewriteCond %{REQUEST_URI} \/([0-9a-zA-Z]+),([0-9a-zA-Z]+)$ [NC]RewriteRule ^(.*) image.php?names[]=%1&names[]=%2 [L]RewriteCond %{REQUEST_URI} \/([0-9a-zA-Z]+),([0-9a-zA-Z]+),([0-9a-zA-Z]+)$ [NC]RewriteRule ^(.*) image.php?names[]=%1&names[]=%2&names[]=%3 [L]RewriteCond %{REQUEST_URI} \/gallery/([0-9a-zA-Z]+)$ [NC]RewriteRule ^(.*) gallery.php?id[]=%1 [L] this 2 strings doesn't work correctly RewriteCond %{REQUEST_URI} \/gallery/([0-9a-zA-Z]+)$ [NC]RewriteRule ^(.*) gallery.php?id[]=%1 [L] When I go to gallery/hgJ56 , I see the content of first 2 strings RewriteCond %{REQUEST_URI} \/([0-9a-zA-Z]+)$ [NC]RewriteRule ^(.*) image.php?names[]=%1 [L] I'm in trouble, can't understand^, please help! What can I do ? Now provide the response and nothing else.
Use another file descriptor { command1 2>&3 | command2; } 3>&1 1>&2 | command3 You can use up to 7 other file descriptors: from 3 to 9. If you want more explanation, please ask, I can explain ;-) Test { { echo a; echo >&2 b; } 2>&3 | sed >&2 's/$/1/'; } 3>&1 1>&2 | sed 's/$/2/' output: b2a1 Example Produce two log files: 1. stderr only 2. stderr and stdout { { { command 2>&1 1>&3; } | tee err-only.log; } 3>&1; } > err-and-stdout.log If command is echo "stdout"; echo "stderr" >&2 then we can test it like that: $ { { { echo out>&3;echo err>&1;}| tee err-only.log;} 3>&1;} > err-and-stdout.log$ head err-only.log err-and-stdout.log==> err-only.log <==err==> err-and-stdout.log <==outerr
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9112986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1185190/']}
jdg_378794
stackexchange
llm_judgeable_groundtruth_similarity
1661542
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $(X,d)$ be a metric space, and let $Y$ be a subset of $X$. (a) A subset $G$ of $Y$ is relatively open in $Y$ iff there is an open subset $U$ in $X$ with $G=U \cap Y$ Attempt: If $G$ is a relatively open subset of $Y$, then $\forall y \in G,r_y>0$ s.t. $B_y(y;r_y)\subseteq G$. The book suggests that I am supposed to consider the union of open balls, $\bigcup \left \{ B(y;r_y):y \in G \right \}$. Some help/hints/clarification would be appreciated. Now provide the response and nothing else.
As you indicate there are more than $150$ primes in the first block of $2002$ numbers. Also, there is a block of $2002$ numbers with no primes in it, starting at $2003! + 2$. Every time we move the block forward one step, the number of primes in it changes by $0$ or $\pm 1$. Since the count starts above $150$ and eventually goes to $0$, and it can't change by more than $1$ in a single step, there must be a block containing exactly $150$ primes.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1661542', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/221848/']}
jdg_378795
stackexchange
llm_judgeable_groundtruth_similarity
44927641
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 issue with git LFS use in Jenkins. What I am doing now is that I am building a war from maven through Jenkins that war contains a jar file through Git LFS we have converted that jar file into a pointer file. But during checkout from Jenkins that jar is not converting into its original size rather it is included in the war as a pointer. We have used git plugin and git-client plugin with version 3.3.0 and 2.4.2 respectively in Jenkins. What is happening: A.war -> a.jar(whose original size is 1234 kb but it's coming 3 kb (which is the size of pointer file) so my questions are: how to use git LFS in the Jenkins? is there any separate Git Lfs plugin for Jenkins? How should the file convert to its original size during checkout when one use Git LfS? Now provide the response and nothing else.
This can be done using the regular Git+Plugin for Jenkins (version 3.1.0 onwards). If you are using Jenkins Pipelines (i.e. with a Jenkinsfile in the root of your repo), the key thing is to include the extension [$class: 'GitLFSPull'] in your checkout() call. Here is an (edited) example taken from one of our repos: checkout([ $class: 'GitSCM', branches: [[name: 'refs/heads/'+env.BRANCH_NAME]], doGenerateSubmoduleConfigurations: false, extensions: [ [$class: 'GitLFSPull'], [$class: 'CheckoutOption', timeout: 20], [$class: 'CloneOption', depth: 0, noTags: false, reference: '/other/optional/local/reference/clone', shallow: false, timeout: 120] ], submoduleCfg: [], userRemoteConfigs: [ [credentialsId: 'foobar', url: 'https://github.com/foo/bar.git'] ] ]) Using the Snippet Generator it is possible to generate this code, by selecting "Git LFS pull after checkout" from the "Additional Behaviours" menu. See screenshot here
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44927641', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6406312/']}
jdg_378796
stackexchange
llm_judgeable_groundtruth_similarity
772294
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 prove that $S_5$ (the permutation group on five letters) can be generated by a two-cycle $(12)$ and a five cycle $(12345)$? Now provide the response and nothing else.
Define $s = (12345)$ and $t = (12)$. Note that$$s\, t\, s^{-1} = (23)$$Similarly, $$s^2 t s^{-2} = (34), \quad s^3 t s^{-3} = (45), \quad s^4 t s^{-4} = (51)$$From there, it's not too hard to get the rest of them. For example, $$(13) = (23)(12)(23)$$In this manner, we show that every transposition can be generated by $s$ and $t$. Thus, all of $S_5$ is generated by $s$ and $t$. Lemma 2 over here should help you understand what's going on.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/772294', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/146285/']}
jdg_378797
stackexchange
llm_judgeable_groundtruth_similarity
41903051
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 feed images with the shape (160,320,3) to VGG16(input_tensor=input_tensor, include_top=False) How can I include a layer that reshapes the images to the shape expected by the VGG16 model, which is (224,224,3) ? Now provide the response and nothing else.
VGG16 model in itself is just a set of weights of the fixed sequence of layers and fixed convolution kernel sizes etc. That doesn't mean that those convolution kernels cannot be applied to images of other sizes. For example in your case: from keras.models import Modelfrom keras.layers import Dense,Flattenfrom keras.applications import vgg16from keras import backend as Kmodel = vgg16.VGG16(weights='imagenet', include_top=False, input_shape=(160,320,3))model.summary(line_length=150)flatten = Flatten()new_layer2 = Dense(10, activation='softmax', name='my_dense_2')inp2 = model.inputout2 = new_layer2(flatten(model.output))model2 = Model(inp2, out2)model2.summary(line_length=150) According to here the minimum image size can be 48x48x3 anything above than that is fine. Now its true the original weights were learnt on 224,224,3 shaped images but the filters weights act as very good starting point for new tasks with new set of images. You do need to re-train the network but the network would converge very quickly. This is the basis of transfer learning.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41903051', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1934212/']}
jdg_378798
stackexchange
llm_judgeable_groundtruth_similarity
29185207
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The problem I want to display a glyphicon icon after a text. In the documentation, there are only before examples as you can see here: http://getbootstrap.com/components/#glyphicons-examples <div class="glyphicon glyphicon-chevron-right">Next</div> My solutions Solution 1 <div>Next<span class="glyphicon glyphicon-chevron-right"></span></div> Solution 2 #next.custom-chevron-right:after { font-family: 'Glyphicons Halflings'; content: "\e080";} <div id="next" class="glyphicon custom-chevron-right">Next</div> Source example: bootply My question Is there a better way to do it just with bootstrap classes? Now provide the response and nothing else.
There are 2 ways to typically add glyphicons (or any other icon font being used). The first way it to add them via html. <div>Next <span class="glyphicon glyphicon-chevron-right"></span></div>// Be sure to add a space in between your text and the icon The second way it to do it using CSS. At a minimum, you must include the font-family and character code . <div><span>Next</span></div>span::after { font-family: 'Glyphicons Halflings'; content: "\e080";} Obviously, using the CSS method you can then add additional styling but this example shows you the minimum needed to get thte icon to appear in the relative correct place.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29185207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1061663/']}
jdg_378799
stackexchange
llm_judgeable_groundtruth_similarity
839305
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose that a box contains 10 red balls, 20 green balls, and 30 blue balls. Suppose also that balls are drawn from the box one at a time at random. What is the probability that all the red balls are drawn before the blue or green balls are themselves exhausted. What is the probability that as the last red ball is drawn, there remains at least one blue and one green left in the box. The answer I was given is $\dfrac{7}{12}$ and a general equation is:$$\dfrac{b g}{1-b}+\dfrac{b g}{1-g}$$ where$$g=\dfrac{20}{60},b=\dfrac{30}{60}$$but why? Now provide the response and nothing else.
Looking at the final balls is the way to go, as you can regard drawing all $60$ balls as choosing one of the equally probable permutation. Working from the back, you can also ignore a colour once it has been drawn. The probability that the last ball is blue and that the last green comes after the last red is $\dfrac{30}{10+20+30}\times \dfrac{20}{10+20} =\dfrac{1}{3}$ or more generally $b \times \dfrac{g}{1-b}$. The probability that the last ball is green and that the last blue comes after the last red is $\dfrac{20}{10+20+30}\times \dfrac{30}{10+30} =\dfrac{1}{4}$ or more generally $g \times \dfrac{b}{1-g}$. So the probability that all reds are drawn before the final blue and final green are drawn is $\dfrac{1}{3}+\dfrac{1}{4}=\dfrac{7}{12}$ or more generally $ \dfrac{bg}{1-b} + \dfrac{bg}{1-g}$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/839305', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/148887/']}
jdg_378800
stackexchange
llm_judgeable_groundtruth_similarity
3240256
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: Below, an attempt at solving a knight/knave puzzle using the truth table method. Are there other methods? Source : https://en.wikipedia.org/wiki/Knights_and_Knaves Now provide the response and nothing else.
Truth-tables are certainly a very solid method for Knights and Knaves puzzles: they are systematic and easy. However, instead of your truth-table, may I suggest: First, let's use $J$ for "John is a knight" and $B$ for "Bill is a knight Then, there are 4 options .. as reflected by 4 rows in the truth-table, rather than your 8. Indeed, as Ethan Bolker explains in the comment, John's claim that "we are both knaves" is really derivative on the claims of $J$ and $B$ ... namely it is just $\neg J \land \neg B$ : \begin{array}{cc|c}J&B&\neg J \land \neg B\\\hlineT&T&F\\T&F&F\\F&T&F\\F&F&T\\\end{array} Finally, John must speaking the truth if and only if he is a knight, i.e. the truth-values of column for $J$ and $\neg J \land \neg B$ should match. This rules out rows 1,2, and 4, and leaves us with row 3: John is a knave, and Bill is a knight. However, there are many other logic methods you can be used. Note that John is speaking the truth if and only if he is a knight, and so we have: $J \leftrightarrow (\neg J \land \neg B)$ OK, first let's use Boolean Algebra to simplify: $J \leftrightarrow (\neg J \land \neg B) \Leftrightarrow$ $(J \land (\neg J \land \neg B)) \lor (\neg J \land \neg (\neg J \land \neg B)) \Leftrightarrow$ $(J \land \neg J \land \neg B) \lor (\neg J \land (\neg \neg J \lor \neg \neg B)) \Leftrightarrow$ $(\bot \land \neg B) \lor (\neg J \land (J \lor B)) \Leftrightarrow$ $\bot \lor ((\neg J \land J) \lor (\neg J \land B)) \Leftrightarrow$ $\bot \lor (\neg J \land B) \Leftrightarrow$ $\neg J \land B$ Cool: John is a knave and Bill is a knight Now, this particular algebraic derivation was actually somewhat complicated, but from experience I can tell you that algebra often works like a charm for these Knights and Knaves puzzles. For example, let's take a random Knights and Knaves puzzle from an only website containing 382 Knights and Knaves puzzles. OK ...generating a random number between 1 and 382 ... 78! OK, problem 78 reads: You meet three inhabitants: Homer, Dave and Bill. Homer tells you that neither Dave nor Bill are knights. Dave tells you that Homer and Bill are both knights. Bill says that Homer is a knight or Dave is a knave. OK, let's symbolize: $H \leftrightarrow \neg(D \lor B)$ $D \leftrightarrow (H \land B)$ $B \leftrightarrow (H \lor \neg D)$ OK, biconditionals can be used as kinds of substitutions. That is, given $B \leftrightarrow (H \lor \neg D)$ , we can substitute $H \lor \neg D$ for $B$ . Let's do this for $D \leftrightarrow (H \land B)$ , so we get: $D \leftrightarrow (H \land (H \lor \neg D))$ which by Absorption simplifies to: $D \leftrightarrow H$ Aha, so we can substitute $D$ and $H$ for each other as well. In particular, let's do this for $B \leftrightarrow (H \lor \neg D)$ , so we get: $B \leftrightarrow (H \lor \neg H)$ which by Complement becomes: $B \leftrightarrow \top$ This not only tells you that $$ is a knight .. but we can now also use this as a substitution for the first premise: $H \leftrightarrow \neg(D \lor \top)$ which simplifies to: $H \leftrightarrow \neg \top$ and thus: $H \leftrightarrow \bot$ So now we know Homer is a knave ... and since we hd that $D \leftrightarrow H$ , we therefore also have that $D$ is a knave. Without all the comments, here is what we did: \begin{array}1. & H \leftrightarrow \neg(D \lor B) & Premise\\2. & D \leftrightarrow (H \land B) & Premise\\3. & B \leftrightarrow (H \lor \neg D) & Premise\\4. & D \leftrightarrow (H \land (H \lor \neg D)) & Biconditional \ Substitution 2,3\\5 & D \leftrightarrow H & Absorption \ 4\\6. & B \leftrightarrow (H \lor \neg H) & Biconditional \ Substitution 3,5\\7. & B \leftrightarrow \top & Complement \ 6\\8. & B & 7\\9. & H \leftrightarrow \neg(D \lor \top) & Biconditional \ Substitution 1,8\\10. & H \leftrightarrow \neg \top & Annihilation \ 9\\11. & H \leftrightarrow \bot & Inverse \ 10\\12. & \neg H & 11\\13. & \neg D & 5,12\\\end{array} Sweet! OK, now let's do a formal proof .. which is going to formalize the following piece of reasoning: If John is a knight, then he is speaking the truth, and hence John and Bill must both ne knaves ... but that contradicts the assumption that John is a knight. Hence, John cannot be a knight, and therefore must be a knave. So, John is lying, and hence it cannot be true that John and Bill are both knaves. Since John is already known to be a knave, Bill must therefore be a knight. OK, let's formalize this argument, and prove that John is knave and Bill is a knight using the premise that $J \leftrightarrow (\neg J \land \neg B)$ : \begin{array}{lll}1&J \leftrightarrow (\neg J \land \neg B)&Given\\2&| \ J & Assumption\\3&| \neg J \land \neg B& \rightarrow \ Elim \ 1,2\\4&| \neg J & \land \ Elim \ 3\\5&| \bot & \bot \ Elim \ 2,4\\6&\neg J & \neg \ Intro \ 2-5\\7&| \neg B & Assumption\\8&|\neg J \land \neg B&\land \ Into \ 6,7\\9&|J&\rightarrow \ Elim \ 1,8\\10&|\bot&\bot \ Intro \ 6,9\\11&\neg \neg B& \neg \ Intro \ 7-10\\12&B&\neg \ Elim \ 11\\13&\neg J \land B& \land \ Intro \ 6,12\\\end{array} OK, two more methods, both of which are model-finding methods. First, the truth-tree method (also called the tableaux method), where you keep decomposing statements and see in what ways (if any) tyou can make them true: And then we have Davis-Putnam, which is a little more like a truth-table, as you systematically explore what would happen to your statements as you set the variables True or False: In both cases, the only open branches are the ones with $J$ being False and $B$ being true, so once again: John is a knave and Bill is a knight.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3240256', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_378801
stackexchange
llm_judgeable_groundtruth_similarity
28167648
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a function I want to minimize with scipy.optimize.fmin . Note that I force a print when my function is evaluated. My problem is, when I start the minimization, the value printed decreases untill it reaches a certain point (the value 46700222.800). There it continues to decrease by very small bites, e.g., 46700222.797,46700222.765,46700222.745,46700222.699,46700222.688,46700222.678So intuitively, I feel I have reached the minimum, since the length of each step are minus then 1. But the algorithm keeps running untill I get a " Maximum number of function evaluations has been exceeded " error. My question is: how can I force my algorithm to accept the value of the parameter when the function evaluation reaches a value from where it does not really evolve anymore (let say, I don't gain more than 1 after an iteration). I read that the options ftol could be used but it has absolutely no effect on my code. In fact, I don't even know what value to put for ftol . I tried everything from 0.00001 to 10000 and there is still no convergence. Now provide the response and nothing else.
There is actually no need to see your code to explain what is happening. I will answer point by point quoting you. My problem is, when I start the minimization, the value printed decreases untill it reaches a certain point (the value 46700222.800). There it continues to decrease by very small bites, e.g., 46700222.797,46700222.765,46700222.745,46700222.699,46700222.688,46700222.678 Notice that the difference between the last 2 values is -0.009999997913837433 , i.e. about 1e-2 . In the convention of minimization algorithm, what you call values is usually labelled x . The algorithm stops if these 2 conditions are respected AT THE SAME TIME at the n -th iteration: convergence on x : the absolute value of the difference between x[n] and the next iteration x[n+1] is smaller than xtol convergence on f(x) : the absolute value of the difference between f[n] and f[n+1] is smaller than ftol . Moreover, the algorithm stops also if the maximum number of iterations is reached. Now notice that xtol defaults to a value of 1e-4 , about 100 times smaller than the value 1e-2 that appears for your case. The algorithm then does not stop, because the first condition on xtol is not respected, until it reaches the maximum number of iterations. I read that the options ftol could be used but it has absolutely no effect on my code. In fact, I don't even know what value to put for ftol. I tried everything from 0.00001 to 10000 and there is still no convergence. This helped you respecting the second condition on ftol , but again the first condition was never reached. To reach your aim, increase also xtol . The following methods will also help you more in general when debugging the convergence of an optimization routine. inside the function you want to minimize, print the value of x and the value of f(x) before returning it. Then run the optimization routine. From these prints you can decide sensible values for xtol and ftol . consider nondimensionalizing the problem. There is a reason if ftol and xtol default both to 1e-4 . They expect you to formulate the problem so that x and f(x) are of order O(1) or O(10) , say numbers between -100 and +100 . If you carry out the nondimensionalization you handle a simpler problem, in the way that you often know what values to expect and what tolerances you are after. if you are interested just in a rough calculation and can't estimate typical values for xtol and ftol , and you know (or you hope) that your problem is well behaved, i.e. that it will converge, you can run fmin in a try block, pass to fmin only maxiter=20 (say), and catch the error regarding the Maximum number of function evaluations has been exceeded .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28167648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3478208/']}
jdg_378802
stackexchange
llm_judgeable_groundtruth_similarity
11907563
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 can't find anything in the PostgreSQL documentation that shows how to declare a record, or row, while declaring the tuple structure at the same time. If you don't define you tuple structure you get the error "The tuple structure of a not-yet-assigned record is indeterminate". This is what I'm doing now, which works fine, but there must be a better way to do it. CREATE OR REPLACE FUNCTION my_func() RETURNS TABLE ( "a" integer, "b" varchar ) AS $$DECLARE r record;BEGINCREATE TEMP TABLE tmp_t ( "a" integer, "b" varchar);-- Define the tuple structure of r by SELECTing an empty row into it.-- Is there a more straight-forward way of doing this?SELECT * INTO rFROM tmp_t;-- Now I can assign values to the record.r.a := at.something FROM "another_table" at WHERE at.some_id = 1;-- A related question is - how do I return the single record 'r' from-- this function?-- This works:RETURN QUERYSELECT * FROM tmp_t;-- But this doesn't:RETURN r;-- ERROR: RETURN cannot have a parameter in function returning setEND; $$ LANGUAGE plpgsql; Now provide the response and nothing else.
You are mixing the syntax for returning SETOF values with syntax for returning a single row or value . -- A related question is - how do I return the single record 'r' from When you declare a function with RETURNS TABLE , you have to use RETURN NEXT in the body to return a row (or scalar value). And if you want to use a record variable with that it has to match the return type. Refer to the code examples further down. Return a single value or row If you just want to return a single row, there is no need for a record of undefined type. @Kevin already demonstrated two ways. I'll add a simplified version with OUT parameters: CREATE OR REPLACE FUNCTION my_func(OUT a integer, OUT b text) AS$func$BEGIN a := ...; b := ...;END$func$ LANGUAGE plpgsql; You don't even need to add RETURN; in the function body, the value of the declared OUT parameters will be returned automatically at the end of the function - NULL for any parameter that has not been assigned. And you don't need to declare RETURNS RECORD because that's already clear from the OUT parameters. Return a set of rows If you actually want to return multiple rows (including the possibility for 0 or 1 row), you can define the return type as RETURNS ... SETOF some_type , where some_type can be any registered scalar or composite type. TABLE (col1 type1, col2 type2) - an ad-hoc row type definition. SETOF record plus OUT parameters to define column names andtypes. 100% equivalent to RETURNS TABLE . SETOF record without further definition. But then the returned rows are undefined and you need to include a column definition list with every call (see example). The manual about the record type : Record variables are similar to row-type variables, but they have no predefined structure. They take on the actual row structure of the row they are assigned during a SELECT or FOR command. There is more, read the manual. You can use a record variable without assigning a defined type, you can even return such undefined records: CREATE OR REPLACE FUNCTION my_func() RETURNS SETOF record AS$func$DECLARE r record;BEGIN r := (1::int, 'foo'::text); RETURN NEXT r; -- works with undefined record r := (2::int, 'bar'::text); RETURN NEXT r;END$func$ LANGUAGE plpgsql; Call: SELECT * FROM my_func() AS x(a int, b text); But this is very unwieldy as you have to provide the column definition list with every call. It can generally be replaced with something more elegant: If you know the type at time of function creation, declare it right away ( RETURNS TABLE or friends). CREATE OR REPLACE FUNCTION my_func() RETURNS SETOF tbl_or_type AS$func$DECLARE r tbl_or_type;BEGIN SELECT INTO tbl_or_type * FROM tbl WHERE id = 10; RETURN NEXT r; -- type matches SELECT INTO tbl_or_type * FROM tbl WHERE id = 12; RETURN NEXT r; -- Or simpler: RETURN QUERY SELECT * FROM tbl WHERE id = 14;END$func$ LANGUAGE plpgsql; If you know the type at time of the function call , there are more elegant ways using polymorphic types : Refactor a PL/pgSQL function to return the output of various SELECT queries Your question is unclear as to what you need exactly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11907563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/173630/']}
jdg_378803
stackexchange
llm_judgeable_groundtruth_similarity
17886992
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: At the end of a Task-returning async method, if I call another async method, I could either await it or return its task. Which are the consequences of each? Task FooAsync() { return BazAsync(); // Option A } async Task BarAsync() { await BazAsync(); // Option B } Now provide the response and nothing else.
You can't return the task if the method itself is declared to be async - so this won't work, for example: async Task BarAsync(){ return BazAsync(); // Invalid!} That would require a return type of Task<Task> . If your method is just doing a small amount of work and then calling just one async method, then your first option is fine, and means there's one fewer task involved. You should be aware that any exceptions thrown within your synchronous method will be delivered synchronously though - indeed, this is how I prefer to handle argument validation. It's also a common pattern for implementing overloading e.g. by cancellation token. Just be aware that if you need to change to await something else, you'll need to make it an async method instead. For example: // Version 1:Task BarAsync(){ // No need to gronkle yet... return BazAsync();}// Oops, for version 2 I need to do some more work...async Task BarAsync(){ int gronkle = await GronkleAsync(); // Do something with gronkle // Now we have to await BazAsync as we're now in an async method await BazAsync();}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17886992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5314/']}
jdg_378804
stackexchange
llm_judgeable_groundtruth_similarity
4216766
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to solve Let $Y \subset X$ ; let $X$ and $Y$ be connected. Show that if $A$ and $B$ form a separation of $X \setminus Y$ , then $Y \cup A$ is connected. My ATTEMPT: We will show that $Y \cup A$ is connected. Let it is not, then there is a separation $(U, V)$ on $Y \cup A$ . Since $Y$ is a connected subspace of $Y \cup A$ , either $Y \subset U$ or $Y \subset V$ . Suppose $Y \subset U$ , then $V \subset A$ . Therefore, $X = (B \cup U) \cup V $ . Since $(U,V)$ is a separation of $Y \cup A$ , then no limit points of $U$ is in $V$ and vice versa. Similarly, no limit points of $B$ is in $V$ , because $V \subset A$ and $(A,B)$ form a separation of $X-Y$ . Therefore, $(B \cup U)^\prime \cap V^\prime = (B^\prime \cup U ^\prime) \cap V^\prime = (B^\prime \cap V^ \prime) \cup (U^\prime \cap V^\prime) = \emptyset \cup \emptyset = \emptyset$ , hence no limit points of $B \cup U$ is in $V$ and vice versa. Is my attempt correct? But I can not proceed further? $\color{red}{\text{Actually, I want to prove $B \cup U$ closed in $X$ and $V$ is open in $X$.}}$ If I can prove it then $(B \cup U, V)$ is a separation on $X$ , hence a contradiction. Please help me. Now provide the response and nothing else.
It is not the case for any ordinal. Consider the ordinal $\omega + 1 = s(\omega) = \mathbb{N} \cup \{\mathbb{N}\}$ . Then $\omega+1$ and $\omega = \mathbb{N}$ are in bijection with each other by the bijection $f(\mathbb{N}) = 0$ $f(n) = s(n)$ for all $n \in \mathbb{N}$ But clearly $\omega$ precedes $\omega + 1$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4216766', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_378805
stackexchange
llm_judgeable_groundtruth_similarity
7586735
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Mathematica has the CheckAbort function which allows to catch and handle user-generated and programmatic Abort s. But it does not allow to catch interrupts generated by such functions as TimeConstrained and MemoryConstrained : TimeConstrained[CheckAbort[Pause[100], Print["From CheckAbort"]], 1] (does not print "From CheckAbort" ). Is there a way to catch such interrupts in Mathematica ? EDIT: I do know that third argument of TimeConstrained and MemoryConstrained allows to evaluate some code in the case of interrupt but this way is not what I need: I need a way to handle such interrupts entirely inside of my function allowing a user do not care of its internals. P.S. The reason why I need this is that I have a function that creates MathLink objects which must be closed in the case of any interrupts or aborts but not in other cases. Now provide the response and nothing else.
The construct for this is available in undocumented form. Internal`WithLocalSettings[ preprocessing, code, postprocessing] will cause postprocessing to take place before returning from aborts or various types of jumps. See also: Reliable clean-up in Mathematica Import big files/arrays with mathematica Daniel Lichtblau
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7586735', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/590388/']}
jdg_378806
stackexchange
llm_judgeable_groundtruth_similarity
36332487
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 facing some problems with new bottom bar. I can't force to move the snackbar above the bottom bar (this is how design guideline told me should be https://www.google.com/design/spec/components/bottom-navigation.html#bottom-navigation-specs ). This is my activity_main.xml <?xml version="1.0" encoding="utf-8"?><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/drawer_layout"android:layout_width="match_parent"android:layout_height="match_parent"android:fitsSystemWindows="true"tools:openDrawer="start"><include layout="@layout/app_bar_main_activity" android:layout_width="match_parent" android:layout_height="match_parent" /><android.support.design.widget.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header_main_activity" app:menu="@menu/activity_main_drawer" /></android.support.v4.widget.DrawerLayout> This is my app_bar_main_activity.xml <?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/main_content"android:layout_width="match_parent"android:layout_height="match_parent"android:fitsSystemWindows="true"tools:context="test.tab_activity"><android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="@dimen/appbar_padding_top" android:theme="@style/MyAppTheme.NoActionBar.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/main_activity_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/MyAppTheme.NoActionBar.PopupOverlay"> </android.support.v7.widget.Toolbar></android.support.design.widget.AppBarLayout><android.support.v4.view.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v4.view.ViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="@dimen/fab_margin" android:src="@drawable/ic_add_white_24dp" /> <android.support.design.widget.TabLayout android:id="@+id/tab_layout" style="@style/AppTabLayout" android:layout_width="match_parent" android:layout_height="56dp" android:background="?attr/colorPrimary" /></LinearLayout> The snackbar in main_activity.java looks like this FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(findViewById(R.id.main_content), "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); Now provide the response and nothing else.
replace your xml -> <?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="test.tab_activity"> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.Toolbar android:id="@+id/main_activity_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways"> </android.support.v7.widget.Toolbar> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.design.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@+id/placeSnackBar"> <android.support.v4.view.ViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="@dimen/fab_margin" android:src="@drawable/ic_menu_gallery" /> </android.support.design.widget.CoordinatorLayout> <android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="56dp" android:background="?attr/colorPrimary" /> </LinearLayout></android.support.design.widget.CoordinatorLayout> and The Snackbar code will be Snackbar.make(findViewById(R.id.placeSnackBar), "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36332487', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5789299/']}
jdg_378807
stackexchange
llm_judgeable_groundtruth_similarity
2219713
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two tables in my database, Operation and Equipment . An operation requires zero or more attributes. However, there's some logic in how the attributes are attributed: Operation Foo requires equipment A and B Operation Bar requires no equipment Operation Baz requires equipment B and either C or D Operation Quux requires equipment ( A or B ) and ( C or D ) What's the best way to represent this in SQL? I'm sure people have done this before, but I have no idea where to start. (FWIW, my application is built with Python and Django.) Update 1: There will be around a thousand Operation rows and about thirty Equipment rows. The information is coming in CSV form similar to the description above: Quux, (A & B) | (C & D) Update 2: The level of conjunctions & disjunctions shouldn't be too deep. The Quux example is probably the most complicated, though there appears to be a A | (D & E & F) case. Now provide the response and nothing else.
Think about how you'd model the operations in OO design: the operations would be subclasss of a common superclass Operation . Each subclass would have mandatory object members for the respective equipment required by that operation. The way to model this with SQL is Class Table Inheritance . Create a common super-table: CREATE TABLE Operation ( operation_id SERIAL PRIMARY KEY, operation_type CHAR(1) NOT NULL, UNIQUE KEY (operation_id, operation_type), FOREIGN KEY (operation_type) REFERENCES OperationTypes(operation_type)); Then for each operation type, define a sub-table with a column for each required equipment type. For example, OperationFoo has a column for each of equipA and equipB . Since they are both required, the columns are NOT NULL . Constrain them to the correct types by creating a Class Table Inheritance super-table for equipment too. CREATE TABLE OperationFoo ( operation_id INT PRIMARY KEY, operation_type CHAR(1) NOT NULL CHECK (operation_type = 'F'), equipA INT NOT NULL, equipB INT NOT NULL, FOREIGN KEY (operation_id, operation_type) REFERENCES Operations(operation_d, operation_type), FOREIGN KEY (equipA) REFERENCES EquipmentA(equip_id), FOREIGN KEY (equipB) REFERENCES EquipmentB(equip_id)); Table OperationBar requires no equipment, so it has no equip columns: CREATE TABLE OperationBar ( operation_id INT PRIMARY KEY, operation_type CHAR(1) NOT NULL CHECK (operation_type = 'B'), FOREIGN KEY (operation_id, operation_type) REFERENCES Operations(operation_d, operation_type)); Table OperationBaz has one required equipment equipA , and then at least one of equipB and equipC must be NOT NULL . Use a CHECK constraint for this: CREATE TABLE OperationBaz ( operation_id INT PRIMARY KEY, operation_type CHAR(1) NOT NULL CHECK (operation_type = 'Z'), equipA INT NOT NULL, equipB INT, equipC INT, FOREIGN KEY (operation_id, operation_type) REFERENCES Operations(operation_d, operation_type) FOREIGN KEY (equipA) REFERENCES EquipmentA(equip_id), FOREIGN KEY (equipB) REFERENCES EquipmentB(equip_id), FOREIGN KEY (equipC) REFERENCES EquipmentC(equip_id), CHECK (COALESCE(equipB, equipC) IS NOT NULL)); Likewise in table OperationQuux you can use a CHECK constraint to make sure at least one equipment resource of each pair is non-null: CREATE TABLE OperationQuux ( operation_id INT PRIMARY KEY, operation_type CHAR(1) NOT NULL CHECK (operation_type = 'Q'), equipA INT, equipB INT, equipC INT, equipD INT, FOREIGN KEY (operation_id, operation_type) REFERENCES Operations(operation_d, operation_type), FOREIGN KEY (equipA) REFERENCES EquipmentA(equip_id), FOREIGN KEY (equipB) REFERENCES EquipmentB(equip_id), FOREIGN KEY (equipC) REFERENCES EquipmentC(equip_id), FOREIGN KEY (equipD) REFERENCES EquipmentD(equip_id), CHECK (COALESCE(equipA, equipB) IS NOT NULL AND COALESCE(equipC, equipD) IS NOT NULL)); This may seem like a lot of work. But you asked how to do it in SQL. The best way to do it in SQL is to use declarative constraints to model your business rules. Obviously, this requires that you create a new sub-table every time you create a new operation type. This is best when the operations and business rules never (or hardly ever) change. But this may not fit your project requirements. Most people say, "but I need a solution that doesn't require schema alterations." Most developers probably don't do Class Table Inheritance. More commonly, they just use a one-to-many table structure like other people have mentioned, and implement the business rules solely in application code. That is, your application contains the code to insert only the equipment appropriate for each operation type. The problem with relying on the app logic is that it can contain bugs and might insert data the doesn't satisfy the business rules. The advantage of Class Table Inheritance is that with well-designed constraints, the RDBMS enforces data integrity consistently. You have assurance that the database literally can't store incorrect data. But this can also be limiting, for instance if your business rules change and you need to adjust the data. The common solution in this case is to write a script to dump all the data out, change your schema, and then reload the data in the form that is now allowed ( Extract, Transform, and Load = ETL ). So you have to decide: do you want to code this in the app layer, or the database schema layer? There are legitimate reasons to use either strategy, but it's going to be complex either way. Re your comment: You seem to be talking about storing expressions as strings in data fields. I recommend against doing that. The database is for storing data, not code. You can do some limited logic in constraints or triggers, but code belongs in your application. If you have too many operations to model in separate tables, then model it in application code. Storing expressions in data columns and expecting SQL to use them for evaluating queries would be like designing an application around heavy use of eval() .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2219713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/102704/']}
jdg_378808
stackexchange
llm_judgeable_groundtruth_similarity
110655
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: Using the Ito's formula I have shown that $X_t$ is a local martingale, because $dX_t=\dots dB_t$, where $$X_t = (B_t+t)\exp\left(-B_t-\frac{t}{2}\right),$$$B_t$ - is a standard Brownian motion I would like to show it is a true martingale, so I am looking at these sets: $$\mathcal{S}_1:=\{ X^{T_n}_t : n\geq 1\} \text{ or }\mathcal{S}_2:=\{X_T : \text{ T is a bounded stopping time} \}$$ And trying to show that either of them is UI. ($T_n$ are the stopping times reducing $X_t$) I need some help with this step. Edit This is a homework exercise, which stipulates the usage of Ito's formula Now provide the response and nothing else.
It seems to me that it is easy to show directly that $X_t$ is a martingale by verifying that $E[X_t \mid \mathcal{F}_s] = X_s$. (Here I assume that $B_t$ is a Brownian motion with respect to the filtration $\mathcal{F}_t$, and that you are trying to show $X_t$ is a martingale with respect to the same filtration.) One just writes $B_t = B_s + (B_t - B_s)$ and uses independence of increments. It helps to check that, for $N \sim N(0, \sigma^2)$ we have$$E[e^{-N}] = e^{\sigma^2/2}, \quad E[N e^{-N}] = -\sigma^2 e^{\sigma^2/2}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/110655', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13205/']}
jdg_378809
stackexchange
llm_judgeable_groundtruth_similarity
5852444
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: string str = "Student_123_"; I need to replace the last character "_" with ",". I did it like this. str.Remove(str.Length -1, 1);str = str + ","; However, is it possible to achieve it more efficiently. may be one line of code.??BTW, last character can be any character. So Replace wont work here. Now provide the response and nothing else.
No. In C# strings are immutable and thus you can not change the string "in-place". You must first remove a part of the string and then create a new string. In fact, this is also means your original code is wrong, since str.Remove(str.Length -1, 1); doesn't change str at all, it returns a new string! This should do: str = str.Remove(str.Length -1, 1) + ",";
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5852444', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/732853/']}
jdg_378810
stackexchange
llm_judgeable_groundtruth_similarity
798040
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I find the 10 largest files in a directory structure? Now provide the response and nothing else.
Try this script Get-ChildItem -re -in * | ?{ -not $_.PSIsContainer } | sort Length -descending | select -first 10 Breakdown: The filter block " ?{ -not $_.PSIsContainer } " is meant to filter out directories. The sort command will sort all of the remaining entries by size in descending order. The select clause will only allow the first 10 through so it will be the largest 10.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/798040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/81514/']}
jdg_378811
stackexchange
llm_judgeable_groundtruth_similarity
34557268
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: C++ noob question: lets say I want to use an abstract class with multiple methods as an interface: // this is AbstractBase.hppclass AbstractBase{public: virtual int foo() = 0; virtual int bar() = 0; // imagine several more pure virtual methods are here}; I want a subclass implementing all the virtual methods, and I don't want to implement them in the header file, but in their implementation files instead. Do I really have to declare all these methods again in the subclass declarations like this? I'm thinking there should be a way to avoid this step (coming from ObjC, Java) // this is Concrete.hppclass Concrete : public AbstractBase{public: int foo(); int bar(); // need to copy paste all the method declarations here again...? why?}; what I would like to do is implement the methods in the implementation file like this: // this is Concrete.cpp#include "Concrete.hpp"int Concrete::foo(){ return 666;}// etc... but can't figure out how, without re-declaring the interface in each subclass. Now provide the response and nothing else.
Although you can avoid writing function header signature for the second time if you combine the definition with the declaration "Java-style", i.e. class Concrete : public AbstractBase{public: int foo() override {return 666;}}; C++ does not let you avoid the declaration step when you want to provide your definition separately. The reason for this is that the declaration is primary, while definitions are secondary. In order to be able to write int Concrete::foo(){ return 666;} in your CPP file you need to tell the compiler that Concrete has an intention to override foo in its header.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34557268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2357250/']}
jdg_378812
stackexchange
llm_judgeable_groundtruth_similarity
56002197
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Example forbidden code (which I would like to be able to write): isWaiting :: Eq a => a -> PriorityQueue a -> BoolisWaiting x EmptyQueue = FalseisWaiting x (Push x y p) = True isWaiting x (Push z y p) = isWaiting x p The same logic, but working variant: isWaiting :: Eq a => a -> PriorityQueue a -> BoolisWaiting x EmptyQueue = FalseisWaiting x (Push z y p) = if x == z then True else isWaiting x p Now provide the response and nothing else.
Handling non-linear patterns would require to decide equality on the two terms which are being matched. In general, we can't do this: areFunctionsEqual :: (Integer->Integer) -> (Integer->Integer) -> BoolareFunctionsEqual f f = TrueareFunctionsEqual _ _ = False The above can not really be allowed since we can't compare functions. One might however wonder why that is not allowed for types in the Eq class, where decidability is not an issue. That would allow one to write foo x y x = ... instead of foo x y z | z==x = ... This is harder to justify. One might argue that the first non linear pattern might be written by accident, and introduce subtle bugs. The second is not that longer, and better documents the intent. Whether this is a good argument or not is a matter of personal opinion, I think. Another subtle argument: foo x y z | z==x = bar x is denotationally equivalent to foo x y z | z==x = bar z but the two variants might still lead to different memory footprints, since in a larger program the first one might allow z to be garbage collected, while the second one would allow x to be garbage collected. If, say, z is already referred to elsewhere in the program, we want to use the second form, so that x is garbage collected. The first form would lead to both x and z to be kept in memory. If we could write foo x y x = bar x , which is going to be garbage collected?Not so clear. This is arguably a very a minor point, since one could still use the explicit variant, if controlling garbage collection is that important.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56002197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11372625/']}
jdg_378813
stackexchange
llm_judgeable_groundtruth_similarity
11836167
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 C#, I can define an extension method for a generic array of type T like this: public static T GetOrDefault<T>(this T[] arr, int n){ if (arr.Length > n) { return arr[n]; } return default(T);} but for the life of me I can't figure out how to do the same in F#! I tried type 'a array with , type array<'a> with and type 'a[] with and the compiler wasn't happy with any of them. Can anyone tell me what's the right to do this in F#? Sure, I can do this by overshadowing the Array module and add a function for that easily enough, but I really want to know how to do it as an extension method! Now provide the response and nothing else.
You have to write the array type using 'backtick marks' - like this: type 'a ``[]`` with member x.GetOrDefault(n) = if x.Length > n then x.[n] else Unchecked.defaultof<'a>let arr = [|1; 2; 3|]arr.GetOrDefault(1) //2arr.GetOrDefault(4) //0 Edit : The syntax type ``[]``<'a> with ... seems to be allowed as well. In the F# source (prim-types-prelude.fs) you can find the following definition: type ``[]``<'T> = (# "!0[]" #)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11836167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/55074/']}
jdg_378814
stackexchange
llm_judgeable_groundtruth_similarity
4900747
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Question: I've profiled my Python program to death, and there is one function that is slowing everything down. It uses Python dictionaries heavily, so I may not have used them in the best way. If I can't get it running faster, I will have to re-write it in C++, so is there anyone who can help me optimise it in Python? I hope I've given the right sort of explanation, and that you can make some sense of my code! Thanks in advance for any help. My code: This is the offending function, profiled using line_profiler and kernprof . I'm running Python 2.7 I'm particularly puzzled by things like lines 363, 389 and 405, where an if statement with a comparison of two variables seems to take an inordinate amount of time. I've considered using NumPy (as it does sparse matrices) but I don't think it's appropriate because: (1) I'm not indexing my matrix using integers (I'm using object instances); and (2) I'm not storing simple data types in the matrix (I'm storing tuples of a float and an object instance).But I'm willing to be persuaded about NumPy.If anyone knows about NumPy's sparse matrix performance vs. Python's hash tables, I'd be interested. Sorry I haven't given a simple example that you can run, but this function is tied up in a much larger project and I couldn't work out how to set up a simple example to test it, without giving you half of my code base! Timer unit: 3.33366e-10 sFile: routing_distances.pyFunction: propagate_distances_node at line 328Total time: 807.234 sLine # Hits Time Per Hit % Time Line Contents328 @profile329 def propagate_distances_node(self, node_a, cutoff_distance=200):330 331 # a makes sure its immediate neighbours are correctly in its distance table332 # because its immediate neighbours may change as binds/folding change333 737753 3733642341 5060.8 0.2 for (node_b, neighbour_distance_b_a) in self.neighbours[node_a].iteritems():334 512120 2077788924 4057.2 0.1 use_neighbour_link = False335 336 512120 2465798454 4814.9 0.1 if(node_b not in self.node_distances[node_a]): # a doesn't know distance to b337 15857 66075687 4167.0 0.0 use_neighbour_link = True338 else: # a does know distance to b339 496263 2390534838 4817.1 0.1 (node_distance_b_a, next_node) = self.node_distances[node_a][node_b]340 496263 2058112872 4147.2 0.1 if(node_distance_b_a > neighbour_distance_b_a): # neighbour distance is shorter341 81 331794 4096.2 0.0 use_neighbour_link = True342 496182 2665644192 5372.3 0.1 elif((None == next_node) and (float('+inf') == neighbour_distance_b_a)): # direct route that has just broken343 75 313623 4181.6 0.0 use_neighbour_link = True344 345 512120 1992514932 3890.7 0.1 if(use_neighbour_link):346 16013 78149007 4880.3 0.0 self.node_distances[node_a][node_b] = (neighbour_distance_b_a, None)347 16013 83489949 5213.9 0.0 self.nodes_changed.add(node_a)348 349 ## Affinity distances update350 16013 86020794 5371.9 0.0 if((node_a.type == Atom.BINDING_SITE) and (node_b.type == Atom.BINDING_SITE)):351 164 3950487 24088.3 0.0 self.add_affinityDistance(node_a, node_b, self.chemistry.affinity(node_a.data, node_b.data)) 352 353 # a sends its table to all its immediate neighbours354 737753 3549685140 4811.5 0.1 for (node_b, neighbour_distance_b_a) in self.neighbours[node_a].iteritems():355 512120 2129343210 4157.9 0.1 node_b_changed = False356 357 # b integrates a's distance table with its own358 512120 2203821081 4303.3 0.1 node_b_chemical = node_b.chemical359 512120 2409257898 4704.5 0.1 node_b_distances = node_b_chemical.node_distances[node_b]360 361 # For all b's routes (to c) that go to a first, update their distances362 41756882 183992040153 4406.3 7.6 for node_c, (distance_b_c, node_after_b) in node_b_distances.iteritems(): # Think it's ok to modify items while iterating over them (just not insert/delete) (seems to work ok)363 41244762 172425596985 4180.5 7.1 if(node_after_b == node_a):364 365 16673654 64255631616 3853.7 2.7 try:366 16673654 88781802534 5324.7 3.7 distance_b_a_c = neighbour_distance_b_a + self.node_distances[node_a][node_c][0]367 187083 929898684 4970.5 0.0 except KeyError:368 187083 1056787479 5648.8 0.0 distance_b_a_c = float('+inf')369 370 16673654 69374705256 4160.7 2.9 if(distance_b_c != distance_b_a_c): # a's distance to c has changed371 710083 3136751361 4417.4 0.1 node_b_distances[node_c] = (distance_b_a_c, node_a)372 710083 2848845276 4012.0 0.1 node_b_changed = True373 374 ## Affinity distances update375 710083 3484577241 4907.3 0.1 if((node_b.type == Atom.BINDING_SITE) and (node_c.type == Atom.BINDING_SITE)):376 99592 1591029009 15975.5 0.1 node_b_chemical.add_affinityDistance(node_b, node_c, self.chemistry.affinity(node_b.data, node_c.data))377 378 # If distance got longer, then ask b's neighbours to update379 ## TODO: document this!380 16673654 70998570837 4258.1 2.9 if(distance_b_a_c > distance_b_c):381 #for (node, neighbour_distance) in node_b_chemical.neighbours[node_b].iteritems():382 1702852 7413182064 4353.4 0.3 for node in node_b_chemical.neighbours[node_b]:383 1204903 5912053272 4906.7 0.2 node.chemical.nodes_changed.add(node)384 385 # Look for routes from a to c that are quicker than ones b knows already386 42076729 184216680432 4378.1 7.6 for node_c, (distance_a_c, node_after_a) in self.node_distances[node_a].iteritems():387 388 41564609 171150289218 4117.7 7.1 node_b_update = False389 41564609 172040284089 4139.1 7.1 if(node_c == node_b): # a-b path390 512120 2040112548 3983.7 0.1 pass391 41052489 169406668962 4126.6 7.0 elif(node_after_a == node_b): # a-b-a-b path392 16251407 63918804600 3933.1 2.6 pass393 24801082 101577038778 4095.7 4.2 elif(node_c in node_b_distances): # b can already get to c394 24004846 103404357180 4307.6 4.3 (distance_b_c, node_after_b) = node_b_distances[node_c]395 24004846 102717271836 4279.0 4.2 if(node_after_b != node_a): # b doesn't already go to a first396 7518275 31858204500 4237.4 1.3 distance_b_a_c = neighbour_distance_b_a + distance_a_c397 7518275 33470022717 4451.8 1.4 if(distance_b_a_c < distance_b_c): # quicker to go via a398 225357 956440656 4244.1 0.0 node_b_update = True399 else: # b can't already get to c400 796236 3415455549 4289.5 0.1 distance_b_a_c = neighbour_distance_b_a + distance_a_c401 796236 3412145520 4285.3 0.1 if(distance_b_a_c < cutoff_distance): # not too for to go402 593352 2514800052 4238.3 0.1 node_b_update = True403 404 ## Affinity distances update405 41564609 164585250189 3959.7 6.8 if node_b_update:406 818709 3933555120 4804.6 0.2 node_b_distances[node_c] = (distance_b_a_c, node_a)407 818709 4151464335 5070.7 0.2 if((node_b.type == Atom.BINDING_SITE) and (node_c.type == Atom.BINDING_SITE)):408 104293 1704446289 16342.9 0.1 node_b_chemical.add_affinityDistance(node_b, node_c, self.chemistry.affinity(node_b.data, node_c.data))409 818709 3557529531 4345.3 0.1 node_b_changed = True410 411 # If any of node b's rows have exceeded the cutoff distance, then remove them412 42350234 197075504439 4653.5 8.1 for node_c, (distance_b_c, node_after_b) in node_b_distances.items(): # Can't use iteritems() here, as deleting from the dictionary413 41838114 180297579789 4309.4 7.4 if(distance_b_c > cutoff_distance):414 206296 894881754 4337.9 0.0 del node_b_distances[node_c]415 206296 860508045 4171.2 0.0 node_b_changed = True416 417 ## Affinity distances update418 206296 4698692217 22776.5 0.2 node_b_chemical.del_affinityDistance(node_b, node_c)419 420 # If we've modified node_b's distance table, tell its chemical to update accordingly421 512120 2130466347 4160.1 0.1 if(node_b_changed):422 217858 1201064454 5513.1 0.0 node_b_chemical.nodes_changed.add(node_b)423 424 # Remove any neighbours that have infinite distance (have just unbound)425 ## TODO: not sure what difference it makes to do this here rather than above (after updating self.node_distances for neighbours)426 ## but doing it above seems to break the walker's movement427 737753 3830386968 5192.0 0.2 for (node_b, neighbour_distance_b_a) in self.neighbours[node_a].items(): # Can't use iteritems() here, as deleting from the dictionary428 512120 2249770068 4393.1 0.1 if(neighbour_distance_b_a > cutoff_distance):429 150 747747 4985.0 0.0 del self.neighbours[node_a][node_b]430 431 ## Affinity distances update432 150 2148813 14325.4 0.0 self.del_affinityDistance(node_a, node_b) Explanation of my code: This function maintains a sparse distance matrix representing the network distance (sum of edge weights on the shortest path) between nodes in a (very big) network. To work with the complete table and use the Floyd-Warshall algorithm would be very slow. (I tried this first, and it was orders of magnitude slower than the current version.) So my code uses a sparse matrix to represent a thresholded version of the full distance matrix (any paths with a distance greater than 200 units are ignored). The network topolgy changes over time, so this distance matrix needs updating over time. To do this, I am using a rough implementation of a distance-vector routing protocol : each node in the network knows the distance to each other node and the next node on the path. When a topology change happens, the node(s) associated with this change update their distance table(s) accordingly, and tell their immediate neighbours. The information spreads through the network by nodes sending their distance tables to their neighbours, who update their distance tables and spread them to their neighbours. There is an object representing the distance matrix: self.node_distances . This is a dictionary mapping nodes to routing tables. A node is an object that I've defined. A routing table is a dictionary mapping nodes to tuples of (distance, next_node). Distance is the graph distance from node_a to node_b, and next_node is the neighbour of node_a that you must go to first, on the path between node_a and node_b. A next_node of None indicates that node_a and node_b are graph neighbours. For example, a sample of a distance matrix could be: self.node_distances = { node_1 : { node_2 : (2.0, None), node_3 : (5.7, node_2), node_5 : (22.9, node_2) }, node_2 : { node_1 : (2.0, None), node_3 : (3.7, None), node_5 : (20.9, node_7)}, ...etc... Because of topology changes, two nodes that were far apart (or not connected at all) can become close. When this happens, entries are added to this matrix. Because of the thresholding, two nodes can become too far apart to care about. When this happens, entries are deleted from this matrix. The self.neighbours matrix is similar to self.node_distances , but contains information about the direct links (edges) in the network. self.neighbours is continually being modified externally to this function, by the chemical reaction. This is where the network topology changes come from. The actual function that I'm having problems with: propagate_distances_node() performs one step of the distance-vector routing protocol . Given a node, node_a , the function makes sure that node_a 's neighbours are correctly in the distance matrix (topology changes). The function then sends node_a 's routing table to all of node_a 's immediate neighbours in the network. It integrates node_a 's routing table with each neighbour's own routing table. In the rest of my program, the propagate_distances_node() function is called repeatedly, until the distance matrix converges. A set, self.nodes_changed , is maintained, of the nodes that have changed their routing table since they were last updated. On every iteration of my algorithm, a random subset of these nodes are chosen and propagate_distances_node() is called on them. This means the nodes spread their routing tables asynchronously and stochastically. This algorithm converges on the true distance matrix when the set self.nodes_changed becomes empty. The "affinity distances" parts ( add_affinityDistance and del_affinityDistance ) are a cache of a (small) sub-matrix of the distance matrix, that is used by a different part of the program. The reason I'm doing this is that I'm simulating computational analogues of chemicals participating in reactions, as part of my PhD. A "chemical" is a graph of "atoms" (nodes in the graph). Two chemicals binding together is simulated as their two graphs being joined by new edges. A chemical reaction happens (by a complicated process that isn't relevant here), changing the topology of the graph. But what happens in the reaction depends on how far apart the different atoms are that make up the chemicals. So for each atom in the simulation, I want to know which other atoms it is close to. A sparse, thresholded distance matrix is the most efficient way to store this information. Since the topology of the network changes as the reaction happens, I need to update the matrix. A distance-vector routing protocol is the fastest way I could come up with of doing this. I don't need a more compliacted routing protocol, because things like routing loops don't happen in my particular application (because of how my chemicals are structured). The reason I'm doing it stochastically is so that I can interleve the chemical reaction processes with the distance spreading, and simulate a chemical gradually changing shape over time as the reaction happens (rather than changing shape instantly). The self in this function is an object representing a chemical. The nodes in self.node_distances.keys() are the atoms that make up the chemical. The nodes in self.node_distances[node_x].keys() are nodes from the chemical and potentially nodes from any chemicals that the chemical is bound to (and reacting with). Update: I tried replacing every instance of node_x == node_y with node_x is node_y (as per @Sven Marnach's comment), but it slowed things down! (I wasn't expecting that!)My original profile took 807.234s to run, but with this modification it increased to 895.895s. Sorry, I was doing the profiling wrong! I was using line_by_line, which (on my code) had far too much variance (that difference of ~90 seconds was all in the noise). When profiling it properly, is is detinitely faster than == . Using CProfile , my code with == took 34.394s, but with is , it took 33.535s (which I can confirm is out of the noise). Update: Existing libraries I'm unsure as to whether there will be an existing library that can do what I want, since my requirements are unusual:I need to compute the shortest-path lengths between all pairs of nodes in a weighted, undirected graph. I only care about path lengths that are lower than a threshold value. After computing the path lengths, I make a small change to the network topology (adding or removing an edge), and then I want to re-compute the path lengths. My graphs are huge compared to the threshold value (from a given node, most of the graph is further away than the threshold), and so the topology changes don't affect most of the shortest-path lengths. This is why I am using the routing algorithm: because this spreads topology-change information through the graph structure, so I can stop spreading it when it's gone further than the threshold. i.e., I don't need to re-compute all the paths each time. I can use the previous path information (from before the topology change) to speed up the calculation. This is why I think my algorithm will be faster than any library implementations of shortest-path algorithms.I've never seen routing algorithms used outside of actually routing packets through physical networks (but if anyone has, then I'd be interested). NetworkX was suggested by @Thomas K. It has lots of algorithms for calculating shortest paths.It has an algorithm for computing the all-pairs shortest path lengths with a cutoff (which is what I want), but it only works on unweighted graphs (mine are weighted).Unfortunately, its algorithms for weighted graphs don't allow the use of a cutoff (which might make them slow for my graphs). And none of its algorithms appear to support the use of pre-calculated paths on a very similar network (i.e. the routing stuff). igraph is another graph library that I know of, but looking at its documentation , I can't find anything about shortest-paths. But I might have missed it - its documentation doesn't seem very comprehensive. NumPy might be possible, thanks to @9000's comment. I can store my sparse matrix in a NumPy array if I assign a unique integer to each instance of my nodes. I can then index a NumPy array with integers instead of node instances. I will also need two NumPy arrays: one for the distances and one for the "next_node" references. This might be faster than using Python dictionaries (I don't know yet). Does anyone know of any other libraries that might be useful? Update: Memory usage I'm running Windows (XP), so here is some info about memory usage, from Process Explorer . The CPU usage is at 50% because I have a dual-core machine. My program doesn't run out of RAM and start hitting the swap. You can see that from the numbers, and from the IO graph not having any activity. The spikes on the IO graph are where the program prints to the screen to say how it's doing. However, my program does keep using up more and more RAM over time, which is probably not a good thing (but it's not using up much RAM overall, which is why I didn't notice the increase until now). And the distance between the spikes on the IO graph increases over time. This is bad - my program prints to the screen every 100,000 iterations, so that means that each iteration is taking longer to execute as time goes on... I've confirmed this by doing a long run of my program and measuring the time between print statements (the time between each 10,000 iterations of the program). This should be constant, but as you can see from the graph, it increases linearly... so something's up there. (The noise on this graph is because my program uses lots of random numbers, so the time for each iteration varies.) After my program's been running for a long time, the memory usage looks like this (so it's definitely not running out of RAM): Now provide the response and nothing else.
node_after_b == node_a will try to call node_after_b.__eq__(node_a) : >>> class B(object):... def __eq__(self, other):... print "B.__eq__()"... return False... >>> class A(object):... def __eq__(self, other):... print "A.__eq__()"... return False... >>> a = A()>>> b = B()>>> a == bA.__eq__()False>>> b == aB.__eq__()False>>> Try to override Node.__eq__() with an optimized version before resorting to C. UPDATE I made this little experiment (python 2.6.6): #!/usr/bin/env python# test.pyclass A(object): def __init__(self, id): self.id = idclass B(A): def __eq__(self, other): return self.id == other.id@profiledef main(): list_a = [] list_b = [] for x in range(100000): list_a.append(A(x)) list_b.append(B(x)) ob_a = A(1) ob_b = B(1) for ob in list_a: if ob == ob_a: x = True if ob is ob_a: x = True if ob.id == ob_a.id: x = True if ob.id == 1: x = True for ob in list_b: if ob == ob_b: x = True if ob is ob_b: x = True if ob.id == ob_b.id: x = True if ob.id == 1: x = Trueif __name__ == '__main__': main() Results: Timer unit: 1e-06 sFile: test.py Function: main at line 10 Total time: 5.52964 sLine # Hits Time Per Hit % Time Line Contents============================================================== 10 @profile 11 def main(): 12 1 5 5.0 0.0 list_a = [] 13 1 3 3.0 0.0 list_b = [] 14 100001 360677 3.6 6.5 for x in range(100000): 15 100000 763593 7.6 13.8 list_a.append(A(x)) 16 100000 924822 9.2 16.7 list_b.append(B(x)) 17 18 1 14 14.0 0.0 ob_a = A(1) 19 1 5 5.0 0.0 ob_b = B(1) 20 100001 500454 5.0 9.1 for ob in list_a: 21 100000 267252 2.7 4.8 if ob == ob_a: 22 x = True 23 100000 259075 2.6 4.7 if ob is ob_a: 24 x = True 25 100000 539683 5.4 9.8 if ob.id == ob_a.id: 26 1 3 3.0 0.0 x = True 27 100000 271519 2.7 4.9 if ob.id == 1: 28 1 3 3.0 0.0 x = True 29 100001 296736 3.0 5.4 for ob in list_b: 30 100000 472204 4.7 8.5 if ob == ob_b: 31 1 4 4.0 0.0 x = True 32 100000 283165 2.8 5.1 if ob is ob_b: 33 x = True 34 100000 298839 3.0 5.4 if ob.id == ob_b.id: 35 1 3 3.0 0.0 x = True 36 100000 291576 2.9 5.3 if ob.id == 1: 37 1 3 3.0 0.0 x = True I was very surprised: "dot" access (ob.property) seems to be very expensive (line 25 versus line 27). there was not much difference between is and '==', at least for simple objects Then I tried with more complex objects and results are consistent with the first experiment. Are you swapping a lot? If your dataset is so large that it does not fit available RAM, I guess you may experience some kind of I/O contention related to virtual memory fetches. Are you running Linux? If so, could you post a vmstat of your machine while running your program? Send us the output of something like: vmstat 10 100 Good luck! UPDATE (from comments by OP) I sugested playing with sys.setcheckinterval and enable/disable the GC. The rationale is that for this particular case (huge number of instances) the default GC reference count check is somewhat expensive and its default interval is away too often. Yes, I had previously played with sys.setcheckinterval. I changed it to 1000 (from its default of 100), but it didn't do any measurable difference. Disabling Garbage Collection has helped - thanks. This has been the biggest speedup so far - saving about 20% (171 minutes for the whole run, down to 135 minutes) - I'm not sure what the error bars are on that, but it must be a statistically significant increase. – Adam Nellis Feb 9 at 15:10 My guess: I think the Python GC is based on reference count. From time to time it will check the reference count for every instance; since you are traversing these huge in-memory structures, in your particular case the GC default frequency (1000 cycles?) is away too often - a huge waste. – Yours Truly Feb 10 at 2:06
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4900747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598749/']}
jdg_378815
stackexchange
llm_judgeable_groundtruth_similarity
51868065
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 around 20 data frames that have the exact same format and dimensions with six columns. The only difference between each data frame is the different values in the sixth column. I want to run a loop through all the data frames so that I can get the minimum value across all data frames for the sixth column. My plan is to list all the data frames in a vector and then loop through the vector and then loop through each line of the data frames, though I'm not sure how I can implement something like that. I would appreciate any advice. Now provide the response and nothing else.
Using set_axis , map , and join df2.set_axis(df2.columns.map('_'.join), axis=1, inplace=False).add_suffix('_MPG') Car_Diesel_MPG Car_Gas_MPGYear 2000 14.7 20.52009 18.0 22.32017 22.2 50.9 groupby with a dict m = {t: '_'.join(t) for t in df2.columns}df2.groupby(m, axis=1).mean().add_suffix('_MPG') Car_Diesel_MPG Car_Gas_MPGYear 2000 14.7 20.52009 18.0 22.32017 22.2 50.9 Either of these can reset_index m = {t: '_'.join(t) for t in df2.columns}df2.groupby(m, axis=1).mean().add_suffix('_MPG').reset_index() Year Car_Diesel_MPG Car_Gas_MPG0 2000 14.7 20.51 2009 18.0 22.32 2017 22.2 50.9 groupby instead of pivot_table df.groupby( ['Year', df.VehicleType.str.cat(df.FuelType, sep='_').add('_MPG').values]).MPG.sum().unstack().reset_index() Year Car_Diesel_MPG Car_Gas_MPG0 2000 14.7 20.51 2009 18.0 22.32 2017 22.2 50.9
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51868065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5791958/']}
jdg_378816
stackexchange
llm_judgeable_groundtruth_similarity
695881
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is from David Williams' book Probability using Martingales. I'm self-studying. Question Prove that if $$0\leq p_n < 1 \quad\text{ and }\quad S:=\sum p_n < \infty$$ then $$\prod (1-p_n) > 0$$ Hint: First show that if $S<1$, then $\prod (1-p_n)\geq 1-S$. I was able to prove the hint using induction. Assume $\prod\limits_{n=1}^N (1-p_n) \geq 1-\sum\limits_{n=1}^N p_n$. Consider $\prod\limits_{n=1}^{N+1}(1-p_n) \geq (1-\sum\limits_{n=1}^N p_n)(1-p_{N+1})=1-\sum\limits_{n=1}^{N+1}p_n+p_{N+1}\sum\limits_{n=1}^{N}p_n \geq 1-\sum\limits_{n=1}^{N+1}p_n$. But I'm unable to use this to prove the general result for arbitrary $S$. Any guidance would be appreciated. I'm also surprised that he asks this question after stating the 2nd Borel Cantelli lemma, I don't see the connection. Now provide the response and nothing else.
If $\sum_{n=1}^\infty p_n<\infty$, then you can find for each $\epsilon>0$ some index $N$ such that $\sum_{n=N}^\infty p_n<\epsilon$. In particular, you can do this for some $0<\epsilon<1$. By what you have shown, $$\prod_{n=N}^M (1-p_n)>1-\epsilon>0,$$ and since $\prod_{n=N}^M (1-p_n)$ converges as $M\to\infty$ (it is a decreasing sequence bounded below), we have $$\prod_{n=N}^\infty (1-p_n)\geq 1-\epsilon>0.$$ Clearly, $\prod_{n=1}^{N-1}(1-p_n)>0$. Now $$\prod_{n=1}^\infty(1-p_n)=\prod_{n=1}^{N-1}(1-p_n) \prod_{n=N}^\infty (1-p_n)\geq (1-\epsilon)\prod_{n=1}^{N-1}(1-p_n)> 0.$$ Here is the connection to the second Borel-Cantelli lemma. The lemma says that if $(E_n)$ is a sequence of independent events satisfying $\sum_{n=1}^\infty p_n=\infty$ with $p_n=P(E_n)$, then a random point in the sample space lies with probability $1$ in infinitely many of the $E_n$. This exercise shows that this automatically fails if $\sum_{n=1}^\infty p_n<\infty$, since $\prod_{n=1}^\infty (1-p_n)$ is the probability that an element lies in none of the $E_n$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/695881', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/47500/']}
jdg_378817
stackexchange
llm_judgeable_groundtruth_similarity
21939
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: So sometime ago in my math education I discovered that many mathematicians were interested in moduli problems. Not long after I got the sense that when mathematicians ran across a non compact moduli they would really like to compactify it. My question is, why are people so eager to compactify things? I know compactness is a great property of a space to have because it often makes other results much easier to prove. So I think my question is better stated as: what are some examples of nice/good/cool results related to a moduli spaces that were (only) able to be proved once there was a compactification of the space? Now provide the response and nothing else.
The answers here are all excellent examples of things that can only be proved once a moduli space is compactified. I would like to add a perhaps more basic reason for compactifying moduli spaces, involving something simpler than theoretical applications such as defining enumerative invariants. The moral is the following: If you study families of geometric objects then either you are almost certain to encounter the boundary of the moduli space, or you must have some very good reason to rule it out. For example, to find a non-trivial compact family of smooth complex curves is actually quite awkward and such families are very rare. (The first examples were due to Atiyah and Kodaira.) From this point of view the "ubiquity of the compactification" amounts to the fact that the boundary divisor of singular curves in the compactified moduli space is positive in a certain sense, so it intersects almost all curves in the moduli space. It is this positivity of the boundary which forces us to study it! Some more examples explain - I hope! - the way compactification enters when considering pseudoholomorphic curves as in Gromov-Witten theory, without ever coming close to trying to define an enumerative invariant. Just by looking at a conic in $\mathbb{CP}^2$, which degenerates into two lines, one sees that when moving a pseudoholomorphic curve around, one is almost certain to encounter bubbling, unless one has a very good reason to know otherwise. Understanding how to compactify the moduli space, we see that this bubbling phenomenon is the main thing which can go wrong. What is interesting here is that often one tries to prove this compactification is not actually necessary , by ruling out bubbling somehow. Two examples follow - taken from Gromov's original use of pseudoholomorphic curves in his Inventiones paper - which exploit this idea. Firstly, Gromov's proof of his non-squeezing theorem. Here the key point in the argument is that one can find a certain pseudoholomorphic disc for a standard almost complex structure on $\mathbb{C}^n$. One would like to know that as one deforms the almost complex structure the disc persists so that we have such a disc for a special non-standard almost complex structure. It is standard in this kind of "continuity method" that you can always deform the disc for a little while because the problem is elliptic. But to push the deformation indefinitely you need to show compactness - why doesn't the disc break up? Thanks to our knowledge of the compactification of the moduli space, we understand that the only thing that can go wrong is bubbling and in this case bubbles cannot form because the symplectic structure is exact. The second example is of the following type: suppose one knows the existence of one pseudoholomorphic curve in a symplectic manifold; then one can try and use it to investigate the ambient space, moving it around and trying to sweep out as much of the space as possible. In this way you can prove, for example, that any symplectic structure on $\mathbb{CP}^2$ which admits a symplectic sphere with self-intersection 1 must be the standard symplectic structure. The reason is you can find an almost complex structure which makes this sphere a pseudoholomorphic curve. Then you move the curve around until is sweeps out the whole space, doing it carefully enough to give a symplectomorphism with the standard $\mathbb{CP}^2$. Here you can push the curve wherever you want because it wont break. Bubbles can't form because the curve has symplectic area 1 and so there is no "spare area" to make bubbles with.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/21939', 'https://mathoverflow.net', 'https://mathoverflow.net/users/7/']}
jdg_378818
stackexchange
llm_judgeable_groundtruth_similarity
273066
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: Participants in I²S can be in master or slave mode. The master has to provide the clock and the slave has to accept the clock. I would like to know how under what considerations this decision is made. Now provide the response and nothing else.
Usually, the decision is simply driven by the capabilities of the components you're trying to put together: all components are not able to be a master. More specifically: in a I2S system, most often, you find three kind of components: DACs, ADCs, and MCUs (or SoCs). Most DACs I have seen are not able to behave as masters. MCUs are usually versatile and able to behave as both. ADCs are also, very often, able to behave as both. The reason is the following: If you need a SoC and a DAC (a lot of applications), the SoC will typically have a complex clocking system available (with fully configurable PLLs and stuff), which makes it a good fit to be the master. The DAC therefore don't need to be able to act as the master. For applications with SoC and ADC, you'll also want the SoC to be the master for the same reason. However, in some other applications, you may want to have ADCs that are directly connected to DACs (no SoC in between). This is why, typically, ADCs can also behave as masters (but in that case, the clocking options are usually less flexible than with a SoC). So, to answer your question, for a typical application that uses a SoC, the SoC will be the master. If you don't have a I2S SoC (you just have ADC+DAC), the ADC will certainly have to be the master. Note: Of course, ADC/DAC/SoC are not the only kind of devices you can find in a I2S system. But for the other kind of devices, the same rationale can often be applied. For example: S/PDIF transmitters are often slave-only, while receivers can usually act as both master or slave.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/273066', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/128758/']}
jdg_378819
stackexchange
llm_judgeable_groundtruth_similarity
43708578
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Docker noob here... How does one properly run the docker image of your Asp.Net CORE app which is produced by Visual Studio 2017 at the command line? docker run -it -d -p 80:32769 myappimage does not appear to work properly (image runs, but I cannot browse to my app) Note: I've simply created a sample ASP.Net Core Web App within Studio using the default template, and added Docker support (by clicking the "Add Docker support" checkbox.). Studio adds a dockerfile and some docker-compose files when you do this. When Visual Studio "runs" the image (by pressing F5) - I can successfully browse to my application ( via " http://localhost:32789 " or similar host port. App inside container is on port 80 ). But I cannot figure out the command to run it myself at the command line. The standard Dockerfile that Studio adds to your project is... FROM microsoft/aspnetcore:1.1ARG sourceWORKDIR /appEXPOSE 80COPY ${source:-obj/Docker/publish} .ENTRYPOINT ["dotnet", "WebApplication2.dll"] Now provide the response and nothing else.
Yes, it is possible. Rebuild your solution in the Release configuration and try to run the docker-compose project with F5 to ensure the image is updated and your app is working fine. Then execute docker images console command . You'll see something like: REPOSITORY TAG IMAGE ID CREATED SIZEYour.App latest 673b79a6bb3d About a minute ago 294 MB All you need is to run a new container from that image and map its exposed port to a localhost port. By default, the exposed port is 80 (look at Dockerfile ). For example: docker run -d -p 1234:80 --name some_name Your.App:latest Then your app should become accessible at http://127.0.0.1:1234/ . Explanation: If the Debug configuration is set, then empty non-workable images are created by Visual Studio. It manually maps the empty container to the filesystem to make possible debugging, "Edit and Continue" features and so on. This is why dev image is useless without Visual Studio. Build the image in the Release configuration to make it usable. The full publishing process is described in the documentation: Visual Studio Tools for Docker Publishing Docker images Once you have completed the develop and debug cycle of your application, the Visual Studio Tools for Docker will help you create the production image of your application. Change the debug dropdown to Release and build the application. The tooling will produce the image with the :latest tag which you can push to your private registry or Docker Hub.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43708578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/110736/']}
jdg_378820
stackexchange
llm_judgeable_groundtruth_similarity
18279378
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 now on making RSA message authentication software. The process is as follows: Sign the message by using A's private key (1024 bit) Verify the message by using A's public key (1024 bit) The #1 code (below) works fine and generates following result: 5554c9a9f6838b6cf40d9dbfbab3d90ea27aa6434ed095d289c13c2624617993ad99161ac265276d150510c176341d8ab8600d08b7353286d465e6bd3370a6fd8dd3ffb82916f612fd6dcee5e654ed801cfca6b6d2d5d6dc99ff7921b615abdf62eb67db1f71e6a6ea70012fd35e7cefa1a8d3aab7614c47746cfe1fc2bc875b However the #2 code shows following error: javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes I think the line in #1 Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); generates 2048 bits (256 bytes) result. Perhaps this is the problem... remember that I use 1024 bit private key. So how can the #1 code generate 128-byte result? 1. SignMail.java public class SignMail { static { Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider()); } public static String sign(String userOriginalMessage) throws Exception { PEMReader userPrivateKey = new PEMReader( new InputStreamReader( new FileInputStream(Environment.getExternalStorageDirectory()+"/pkcs10priv.key"))); KeyPair keyPair = (KeyPair)userPrivateKey.readObject(); byte[] cipherText; //modified by JEON 20130817 Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); //encrypt the message using private key cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); cipherText = cipher.doFinal(userOriginalMessage.getBytes()); return new String(Hex.encode(cipherText)); }} 2. UserSMSVerifier.java public class UserSMSVerifier {static String signedMail;static { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());}public static String messageGenarator( String UserCert, String origninalMessage ) throws Exception{ InputStream userCertStream = new ByteArrayInputStream(UserCert.getBytes("UTF-8")); PEMReader userCerti = new PEMReader( new InputStreamReader( userCertStream)); //KeyPair userPrivate = (KeyPair)userPrivateKey.readObject(); X509Certificate userCert = (X509Certificate)userCerti.readObject(); byte[] dectyptedText = null; // decrypt the text using the private key //modified by JEON 20130817 //Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, userCert.getPublicKey()); dectyptedText = cipher.doFinal(origninalMessage.getBytes()); String result = new String(dectyptedText, Charset.forName("UTF-8")); return result;}} the #2 code was executed by the following JSP #3 messageVeri.JSP <%@ page language="java" contentType="text/html; charset=euc-kr" %><%@ page session = "true" %><%@ page import="java.sql.DriverManager" %><%@ page import="java.sql.Connection" %><%@ page import="java.sql.PreparedStatement" %><%@ page import="java.sql.Statement" %><%@ page import="java.sql.SQLException" %><%@ page import="java.sql.ResultSet" %><%@ page import="myPackage.UserSMSVerifier" %><% request.setCharacterEncoding("euc-kr"); String userID = request.getParameter("sender"); String encryptedSMS = request.getParameter("encryptedSMS"); //String sql = "select user_id, user_pw from testca.testca_init where user_id=? and user_pw=?"; //String sql = "update testca.testca_init set pkcs10request = '"+pkcs10request_new+"' where user_id='user1'"; String sql = "select * from testca.testca_init where user_id='" + userID + "'"; Class.forName("com.mysql.jdbc.Driver"); Connection conn = null; PreparedStatement pstmt = null; Statement stmt = null; ResultSet rs = null; String jdbcDriver = "jdbc:mysql://localhost:3306/"; String dbUser = "root"; String dbPass = "fo.......t"; try{ conn = DriverManager.getConnection(jdbcDriver, dbUser, dbPass); stmt = conn.createStatement(); //stmt.executeUpdate(sql); rs=stmt.executeQuery(sql); while(rs.next()){ //rs=stmt.executeQuery(sql); String userCertificate=rs.getString("certificate"); UserSMSVerifier.messageGenarator(userCertificate, encryptedSMS); } }catch(Exception ex){out.print("Error 2: " +ex);} /* if(rs.next()) { //session.setAttribute("userID", userID); out.print("Insert Succeed!"); out.println(); //out.print("Welcome!" + " " + session.getAttribute("userID")); } else { out.print("failed to login!"); //session.invalidate(); } */%> Now provide the response and nothing else.
Your signature string contains 256 characters, however this is hexadecimal and really represents 128 bytes . Before you verify the signature, you must convert it back to a byte array. This is not achieved through someString.getBytes() but rather via DatatypeConverter.parseHexBinary(someString) (or any other method you prefer from Google). Also, I would strongly recommend you use the Signature class rather than the Cipher class when signing messages. Currently your code can only handle messages that are smaller than 128 bytes in length (smaller, in fact, due to padding). Instead, you should be hashing the message prior to signing (e.g. using the SHA256withRSA mechanism ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18279378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1349407/']}
jdg_378821
stackexchange
llm_judgeable_groundtruth_similarity
8050640
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Lots of articles in the web like this : http://www.fontspring.com/blog/fixing-ie9-font-face-problems suggest to add a ?#iefix to the eot url. I was curious to know how is this going to solve the problem. Thanks. Now provide the response and nothing else.
IE8 and the older have a bug in their parsers for the src attribute. So if you include more than 1 font format in the SRC, IE fails to load it and reports a 404 error. The question mark solves that problem as it fools IE into thinking the rest of the string (other src) is a query string, and therefore loading just the EOT file... Other browsers will follow the specification and load just their required font type ... You may wanna read Paul Irish's Bulletproof @font-face syntax to know more about some other of the why's ...
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8050640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/478028/']}
jdg_378822
stackexchange
llm_judgeable_groundtruth_similarity
43140039
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 set status bar background as gradient theme also status bar and action bar color should same gradient drawable, as per documentation we can set color to status bar in API level 21 and above by using <item name="android:statusBarColor">@color/colorPrimary</item> But I am searching something like <item name="android:statusBarDrawable">@drawable/myDrawable</item> I have seen example that use <item name="android:windowTranslucentStatus">false</item><item name="android:windowTranslucentNavigation">false</item> But in that case status bar and action bar overlap (use fitSystemWindow=true but still not solved) also try with https://github.com/jgilfelt/SystemBarTint this library but still no luck. Now provide the response and nothing else.
For some one who want to set gradient color to status bar background you can use following method in your activity before setContentView() For Java @TargetApi(Build.VERSION_CODES.LOLLIPOP)public static void setStatusBarGradiant(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = activity.getWindow(); Drawable background = activity.getResources().getDrawable(R.drawable.gradient_theme); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(activity.getResources().getColor(android.R.color.transparent)); window.setNavigationBarColor(activity.getResources().getColor(android.R.color.transparent)); window.setBackgroundDrawable(background); }} For Kotlin @TargetApi(Build.VERSION_CODES.LOLLIPOP)fun setStatusBarGradiant(activity: Activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val window: Window = activity.window val background =ContextCompat.getDrawable(activity, R.drawable.gradient_theme) window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = ContextCompat.getColor(activity,android.R.color.transparent) window.navigationBarColor = ContextCompat.getColor(activity,android.R.color.transparent) window.setBackgroundDrawable(background) }} Thanks every one for your help EDIT If the above code don't work, try to add this in your styles.xml : <style name="AppTheme.NoActionBar"> <!-- Customize your theme here. --> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item></style> If you want to override status bar with your view then use window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/43140039', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4741746/']}
jdg_378823
stackexchange
llm_judgeable_groundtruth_similarity
18184899
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 difference between the three(marked as comments) : MultiThreadedHttpConnectionManager connManag = new MultiThreadedHttpConnectionManager();HttpConnectionManagerParams managParams = connManag.getParams();managParams.setConnectionTimeout(connectiontimeout); // 1managParams.setSoTimeout(sotimeout); //2HttpMethodBase baseMethod = null;try { HttpClient client = new HttpClient(connManag); client.getParams().setParameter("http.connection-manager.timeout", poolTimeout); //3 baseMethod = new GetMethod(…); int statusCode = client.executeMethod(…); …}catch (ConnectTimeoutException cte ){ //Took too long to connect to remote host}catch (SocketTimeoutException ste){ //Remote host didn’t respond in time}catch (Exception se){ //Some other error occurred}finally { if (baseMethod != null) baseMethod.releaseConnection();} 1. setConnectionTimeout - if it determines the timeout until connection is established. 2. setSoTimeout - if it determines the period of inactivity or time difference between two consecutive packets , Then what does the below one do : 3. "http.connection-manager.timeout" Now provide the response and nothing else.
At the lowest level HTTP is TCP socket. So when you request a URL and get a response, at lower level, a client Socket is created which establishes connection to the remote Server Socket, sends some data and receives response. setConnectionTimeout : Client tries to connect to the server. This denotes the time elapsed before the connection established or Server responded to connection request. setSoTimeout : After establishing the connection, the client socket waits for response after sending the request. This is the elapsed time since the client has sent request to the server before server responds. Please note that this is not same as HTTP Error 408 which the server sends to the client. In other words its maximum period inactivity between two consecutive data packets arriving at client side after connection is established. http.connection-manager.timeout : MultiThreadedHttpConnectionManager uses a pool of HTTP connections . It has maximum and minimum values per host set for it. If all the connections for particular host are has reached max value, the request for new connection for the same host will have to wait till any one of the existing connection becomes free. This parameter denotes the time elapsed when a connection request was made and before the HttpConnectionManager returned a connection.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18184899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1878670/']}
jdg_378824
stackexchange
llm_judgeable_groundtruth_similarity
30198953
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Creating a new GUI in Java (1.8) Swing, I am searching for a way to override resize behavior of all my components. Let me explain to you with some edited photos: 1. Full Screen GUI This is my full screen GUI, with 3 panels and a JToolBar . The green one needs to have a fixed size , the others would be resizable . Currently, I only have 2 small GridLayout to organize them (one vertical, and one horizontal for green and cyan panels). 2. Small horizontal resize If I, for example, reduce the frame size from the right side, I want my blue and cyan panel to be resized according to the new frame size. But the green panel must be fixed . (Not the most difficult part I think.) 3. Minimum horizontal size This is the most difficult part for me. As soon as the cyan (or blue) panel reach is minimum size, I want him to " push " the green panel to the left, even if it disappears off the frame. Of course, pulling the frame to the right will make the green panel appear again. How could I do it? I thought of using JSplitPane or a specific listener to manually decide the resize behavior but I need some advice. Sorry if an existing post can answer this, I didn't find any answer explaining the issue for me. Thanks in advance! If you want more examples, look at the "Evernote" software which acts the same way Now provide the response and nothing else.
Setting the max/min/preferred size of the Green panel can keep that panel the same size under the first condition. To check for resizes, you can use a ComponentListener on one of the other JPanel 's - if the size gets below a particular width then change the max/min/preferred size of the Green panel. Below is a hacked together example of doing this - it resizes the Green panel when the Blue is < 600, and the resize is a weighted resize (30% of total width). To get the true L&F and that you desire you may have to play with the layout/sizes. import java.awt.BorderLayout;import java.awt.Color;import java.awt.Dimension;import java.awt.GridBagConstraints;import java.awt.GridBagLayout;import java.awt.GridLayout;import java.awt.Insets;import java.awt.Rectangle;import java.awt.event.ComponentAdapter;import java.awt.event.ComponentEvent;import java.awt.event.ComponentListener;import javax.swing.Box;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JToolBar;import javax.swing.SwingUtilities;public class GridTest extends JPanel{ private boolean changeAllowed = false; //keep reference to cyan for the height dimension final JPanel cyan = new JPanel(); public GridTest(){ cyan.setPreferredSize(new Dimension(600, 300));//provide sizing hint } private Dimension getCustomDimensions(){ if ( changeAllowed ){ return new Dimension((int)(super.getParent().getBounds().width * 0.3), cyan.getBounds().height); }else{ return new Dimension(200, cyan.getBounds().height); } } @Override public Dimension getMaximumSize(){ return getCustomDimensions(); } @Override public Dimension getMinimumSize(){ return getCustomDimensions(); } @Override public Dimension getPreferredSize(){ return getCustomDimensions(); } public static void main(String[] args) throws Exception{ SwingUtilities.invokeAndWait(new Runnable(){ @Override public void run() { final int MINIMUM = 600; JFrame frame = new JFrame(); frame.add(new JToolBar(), BorderLayout.NORTH); final JPanel blue = new JPanel(); final GridTest green = new GridTest(); green.setBackground(Color.green); green.setOpaque(true); green.cyan.setBackground(Color.cyan); green.cyan.setOpaque(true); blue.setOpaque(true); blue.setBackground(Color.blue); blue.setPreferredSize(new Dimension(900, 300));//hint at size blue.setMinimumSize(new Dimension(100, 200));//hint at size //Nest Box Layouts Box top = Box.createHorizontalBox(); top.add(blue); Box bottom = Box.createHorizontalBox(); bottom.add(green); bottom.add(green.cyan); Box vert = Box.createVerticalBox(); vert.add(top); vert.add(bottom); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(vert); //listen for resizes blue.addComponentListener(new ComponentAdapter(){ @Override public void componentResized(ComponentEvent e) { if ( blue.getBounds().width < MINIMUM ){//set flag green.changeAllowed = true; }else{ green.changeAllowed = false; } } }); frame.pack(); frame.setSize(800, 600); frame.setVisible(true); } }); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30198953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4870785/']}
jdg_378825
stackexchange
llm_judgeable_groundtruth_similarity
59072211
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like you to ask for help with a function that I created that allows refreshing the channels that are in the list, but I have a problem, every 10 seconds the memory only goes up and never she empties herself. It's been over 5 hours that I'm looking for, even if I think it's a stupid thing, thank you for your help in advance (sorry for the translation, I'm not English) My code : updateChannel: async function(client, newList){ let a = setInterval(async ()=> { for(let i = 0; i < newList.length; i++){ const message = await this.replace$Var(client, newList[i][1]) const channel = await client.channels.get(newList[i][0]) channel.setName(message).catch(err => { console.log(`The channel with the id : ${newList[i][0]} was deleted, please restart the bot`) newList.splice(i,1) i-=1 }) } clearInterval(a) this.updateChannel(client, newList) }, 10000)} Now provide the response and nothing else.
Just to lay the groundwork: upon an action being dispatched, the selector you pass to useSelector() will be called. If the value it returns is different to the value returned last time an action was dispatched, the component will re-render. Destructing is indeed the wrong approach, but the top answer here is completely irrelevant. The docs refer to a scenario where the selector is creating a new object every time, like you might do in a mapStateToProps() function. That would cause the component to re-render every single time an action is dispatched, regardless of what that action does, because the value returned by the selector is technically a different object in memory even if the actual data hasn't changed. In that case , you need to worry about strict equality and shallow equality comparisons. However, your selector is not creating a new object every time . If a dispatched action doesn't modify importApp.productsImport , it will be the exact same object in memory as before, rendering all of this moot. Instead, the issue here is that you are selecting an entire slice of state, when you only actually care about a few particular properties of that slice. Consider that importApp.productsImport probably has other properties besides just open , importId , and importProgress . If those other properties change, then your component will needlessly re-render even though it makes no reference to them. The reason for this is simple: the selector returns importApp.productsImport , and that object changed. Redux has no way of knowing that open , importId , and importProgress were the only properties you actually cared about, because you didn't select those properties; you selected the whole object . Solutions So, to select multiple properties without needless re-renders, you have two options: Use multiple useSelector() hooks, each selecting a single property in your store. Have a single useSelector() hook and a single selector that combines multiple properties from your store into a single object. You could do this by: Using a memoized selector from reselect . Simply writing a function that creates a new object from specific properties of state and returns it. If you did this, you would then have to worry about strict equality and shallow equality comparisons. For this purpose, I feel like multiple useSelector() hooks is actually the way to go. The docs make a point of mentioning that Each call to useSelector() creates an individual subscription to the Redux store. but whether multiple calls would actually incur a real performance penalty compared to a single call purely for this reason, I think, remains to be seen, and it seems to me that worrying about this is probably over-optimisation unless you have a huge app with hundreds or thousands of subscriptions. If you use a single useSelector() hook, then at that point you're basically just writing a mapStateToProps function, which I feel like defeats a lot of the allure of using the hook to begin with, and especially so if you're writing TypeScript. And if you then want to destructure the result, that makes it even more cumbersome. I also think using multiple hooks is definitely more in the general spirit of the Hooks API.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/59072211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12446406/']}
jdg_378826
stackexchange
llm_judgeable_groundtruth_similarity
44735554
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am currently using the method: NSArray *captureDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; to get a list of devices but XCode is giving me a warning: Use AVCaptureDeviceDiscoverySession instead I have looked at the documentation but do not know how to access the devices array AVCaptureDeviceDiscoverySession *session = [[AVCaptureDeviceDiscoverySession alloc]init];??? Now provide the response and nothing else.
Create AVCaptureDeviceDiscoverySession for your requirement and then call devices method to get Array of currently available devices matching the session’s criteria Code: AVCaptureDeviceDiscoverySession *captureDeviceDiscoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionBack];NSArray *captureDevices = [captureDeviceDiscoverySession devices]; Swift 4+ let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .back) Available Device types Media types Position
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44735554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6927454/']}
jdg_378827
stackexchange
llm_judgeable_groundtruth_similarity
45836397
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 let's say we have a code block that we want to execute 70% of times and another one 30% of times. if(Math.random() < 0.7) 70percentmethod();else 30percentmethod(); Simple enough. But what if we want it to be easily expandable to say, 30%/60%/10% etc.? Here it would require adding and changing all the if statements on change which isn't exactly great to use, slow and mistake inducing. So far I've found large switches to be decently useful for this use case, for example: switch(rand(0, 10)){ case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:70percentmethod();break; case 8: case 9: case 10:30percentmethod();break;} Which can be very easily changed to: switch(rand(0, 10)){ case 0:10percentmethod();break; case 1: case 2: case 3: case 4: case 5: case 6: case 7:60percentmethod();break; case 8: case 9: case 10:30percentmethod();break;} But these have their drawbacks as well, being cumbersome and split onto a predetermined amount of divisions. Something ideal would be based on a "frequency number" system I guess, like so: (1,a),(1,b),(2,c) -> 25% a, 25% b, 50% c then if you added another one: (1,a),(1,b),(2,c),(6,d) -> 10% a, 10% b, 20% c, 60% d So simply adding up the numbers, making the sum equal 100% and then split that. I suppose it wouldn't be that much trouble to make a handler for it with a customized hashmap or something, but I'm wondering if there's some established way/pattern or lambda for it before I go all spaghetti on this. Now provide the response and nothing else.
EDIT: See edit at end for more elegant solution. I'll leave this in though. You can use a NavigableMap to store these methods mapped to their percentages. NavigableMap<Double, Runnable> runnables = new TreeMap<>();runnables.put(0.3, this::30PercentMethod);runnables.put(1.0, this::70PercentMethod);public static void runRandomly(Map<Double, Runnable> runnables) { double percentage = Math.random(); for (Map.Entry<Double, Runnable> entry : runnables){ if (entry.getKey() < percentage) { entry.getValue().run(); return; // make sure you only call one method } } throw new RuntimeException("map not filled properly for " + percentage);}// or, because I'm still practicing streams by using them for everythingpublic static void runRandomly(Map<Double, Runnable> runnables) { double percentage = Math.random(); runnables.entrySet().stream() .filter(e -> e.getKey() < percentage) .findFirst().orElseThrow(() -> new RuntimeException("map not filled properly for " + percentage)) .run();} The NavigableMap is sorted (e.g. HashMap gives no guarantees of the entries) by keys, so you get the entries ordered by their percentages. This is relevant because if you have two items (3,r1) , (7,r2) , they result in the following entries: r1 = 0.3 and r2 = 1.0 and they need to be evaluated in this order (e.g. if they are evaluated in the reverse order the result would always be r2 ). As for the splitting, it should go something like this:With a Tuple class like this static class Pair<X, Y>{ public Pair(X f, Y s) { first = f; second = s; } public final X first; public final Y second;} You can create a map like this // the parameter contains the (1,m1), (1,m2), (3,m3) pairsprivate static Map<Double,Runnable> splitToPercentageMap(Collection<Pair<Integer,Runnable>> runnables){ // this adds all Runnables to lists of same int value, // overall those lists are sorted by that int (so least probable first) double total = 0; Map<Integer,List<Runnable>> byNumber = new TreeMap<>(); for (Pair<Integer,Runnable> e : runnables) { total += e.first; List<Runnable> list = byNumber.getOrDefault(e.first, new ArrayList<>()); list.add(e.second); byNumber.put(e.first, list); } Map<Double,Runnable> targetList = new TreeMap<>(); double current = 0; for (Map.Entry<Integer,List<Runnable>> e : byNumber.entrySet()) { for (Runnable r : e.getValue()) { double percentage = (double) e.getKey() / total; current += percentage; targetList.put(current, r); } } return targetList;} And all of this added to a class class RandomRunner { private List<Integer, Runnable> runnables = new ArrayList<>(); public void add(int value, Runnable toRun) { runnables.add(new Pair<>(value, toRun)); } public void remove(Runnable toRemove) { for (Iterator<Pair<Integer, Runnable>> r = runnables.iterator(); r.hasNext(); ) { if (toRemove == r.next().second) { r.remove(); break; } } } public void runRandomly() { // split list, use code from above }} EDIT : Actually, the above is what you get if you get an idea stuck in your head and don't question it properly.Keeping the RandomRunner class interface, this is much easier: class RandomRunner { List<Runnable> runnables = new ArrayList<>(); public void add(int value, Runnable toRun) { // add the methods as often as their weight indicates. // this should be fine for smaller numbers; // if you get lists with millions of entries, optimize for (int i = 0; i < value; i++) { runnables.add(toRun); } } public void remove(Runnable r) { Iterator<Runnable> myRunnables = runnables.iterator(); while (myRunnables.hasNext()) { if (myRunnables.next() == r) { myRunnables.remove(); } } public void runRandomly() { if (runnables.isEmpty()) return; // roll n-sided die int runIndex = ThreadLocalRandom.current().nextInt(0, runnables.size()); runnables.get(runIndex).run(); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45836397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4012132/']}
jdg_378828
stackexchange
llm_judgeable_groundtruth_similarity
47441160
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 a custom layout for my ST3 - specifically, I want this layout structure.Can someone tell me how can I do it ? Now provide the response and nothing else.
Although you can get your hands dirty with manually creating such a layout, probably the easiest way to pull this off would be to use a package to do it. The Origami package is one example of this. Using that package, you can follow the following steps to get the layout that you're interested in: Select Origami: Create Pane Below command (or use the standard View > Layout > Rows: 2 menu item) to create two rows Focus the bottom pane and select Origami: Create Pane on the Right Once you have this layout complete, you can use Origami: Save Current Layout from the command palette to save it and then easily recall it later as needed. Assuming that you don't want to/can't install third party packages, you can also make your own customized menu item and/or key binding that will set this layout for you. In order to add a new item to the menu, save the following text as Main.sublime-menu in your User package (use Preferences > Browse Packages if you don't know where that is): [ { "caption": "View", "mnemonic": "V", "id": "view", "children": [ { "caption": "-", "id": "groups" }, { "caption": "Layout", "mnemonic": "L", "id": "layout", "children": [ { "caption": "Three Pane", "command": "set_layout", "args": { "cols": [0.0, 0.5, 1.0 ], "rows": [0.0, 0.5, 1.0 ], "cells": [ [0, 0, 2, 1 ], [0, 1, 1, 2 ], [1, 1, 2, 2 ] ] } } ] }, ] }] This will add a new menu entry under View > Layout called Three Pane which, when selected, will set your desired layout. Alter the value of the caption string as appropriate to change the name of the layout. Additionally, you can add the following key binding to your custom key bindings ( Preferences > Key Bindings from the menu) in order to have a hot key that does the same thing: { "keys": ["alt+shift+3"], "command": "set_layout", "args": { "cols": [0.0, 0.5, 1.0 ], "rows": [0.0, 0.5, 1.0 ], "cells": [ [0, 0, 2, 1 ], [0, 1, 1, 2 ], [1, 1, 2, 2 ] ] }}, If this is your first custom key binding, make sure to wrap this entire text in a pair of [ and ] , as the key bindings are a list of items and this represents just the key binding itself. This reuses the default Windows/Linux key binding for three columns, so you can change that as appropriate. If you do this in combination with the menu change above, the menu will automatically display the key binding you're using as a reminder in case you forget. For reference, the set_layout command takes the same layout argument as the (officially undocumented) window.set_layout() API call. There is unofficial documentation on that method that explains how this works, although here I cheated and used Origami to create the layout.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47441160', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8565599/']}
jdg_378829
stackexchange
llm_judgeable_groundtruth_similarity
4142544
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The title nearly says it all: what is the fewest number of cubes that can be fused face-to-face into a polyhedron that does not fill space? The smallest that seemed like a sure non-tiler to me was 9: seven in a ring missing one "corner", plus one above one of the "middle" cubes of this ring, and a final one fused to that one, positioned above the hole in the ring. Then there seemed to be no way fill the hole in the ring with another copy of this polycube -- but EDIT: as Georgios points out in a comment to his answer, you can actually interlock a pair of these to get a simply-connected compound. So the smallest truly obvious non-filler is a decacube, consisting of an 8-ring with two attached to a middle cube to "cap" the hole. But I wouldn't be surprised if there were an octacube or heptacube non-space-filler, and if so, I suspect it's well-known to some folks. However, I can't seem to find a reference, even though the answer to the corresponding question for polyominoes in 2D is easy to find, e.g. MathWorld notes that all but four heptominoes tile the plane, as all smaller polyominoes do. Now provide the response and nothing else.
I recently wrote some code based on Matt Parker's Hypercube Folding Video , and run it with all heptacubes, octacubes and nonocubes. It found tilings for all heptacubes, all but one octacube (the donut shaped one), and all but six five nonocubes. My code and all tilings found so far are in my whuts-solver github repository. Please note, my code does not prove that a solution does NOT exist for some polycube, it only verifies ones that exist. Moritz Firsching has done some similar work and to my understanding he has proven that the donut-octacube does indeed not tile space, but I will let him comment on this part. These are the nonocubes I could not find a tiling for yet: All other solutions are in the github repository in the directories <n>cubes_solutions, these are as json, with "base_blocks" a list of coordinates of where to position some of the polycubes, and "offsets" showing three directions (and distances), to repeat the pattern to get a full tiling. I will update later with some visualisations for the tiling produced for the three heptacubes that were mentioned as non-tiling in another answer. Edit: For reference, the three heptacube claimed to not tile space in a separate answer are numbered 144, 556 and 272 in my enumeration, the tilings for these can be found in the files heptacube_solutions/solution_0NNN.json in the repository. Edit: In the meantime, my solver (after running for 4 days) found a solution for one more of the nonocubes (number 1345 in my numbering in github), the primitive block is composed of 12 nonocubes! Since this is an exhaustive search, this is the simplest possible solution for this nonocube (assuming a periodically repeating tiling of course). Also, here is an image showing the tiling for the three heptacubes mentioned in another answer: Edit: Here is an image for the two nonocubes (4921 and 4931) and how they can generate an interlocking pattern each:
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4142544', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/288300/']}
jdg_378830
stackexchange
llm_judgeable_groundtruth_similarity
8963375
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's my scenario: My project is following the topic branching pattern. I create a branch to fix some problems, let's call this branch problem_fixes. I make my changes, and submit a pull request. I need to start work on a new feature, so I create a second branch called my_feature and commit a bunch of changes. At some point I realize my_feature is dependent on problem_fixes which has not yet been accepted and merged (the my_feature branch relies on some of the fixes from the first branch and I can't make progress without them). Short of badgering my project lead to accept and merge my first branch faster, what is the best process to follow here? I am wondering if I need to start a new, third branch based on problem_fixes (instead of master) and merge in my commits to my_feature? Or will it be okay if I simply merge problem_fixes into my_feature and continue work -- assuming problem_fixes is merged into master first, when my_feature is merged it should theoretically be okay(?) Now provide the response and nothing else.
Yes, I think you're on the right track. What I would do is create a new my_feature branch, perhaps work a little bit. When I realise that my_feature depends on problem_fixes , merge that branch in. This could happen right away if you know that you'll need it. Then, when my_feature is merged into master, you'll already have the changes you need. Note that as long as you have a robust code review procedure, then if you try to merge my_feature into master before problem_fixes , then you will notice at that time.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8963375', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/566259/']}
jdg_378831
stackexchange
llm_judgeable_groundtruth_similarity
6818031
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently using the serve script to serve up directories with Node.js on Windows 7. It works well in the MSYS shell or using sh , as I've put node.exe and the serve script in my ~/bin (which is on my PATH), and typing just "serve" works because of it's Shebang ( #! ) directive which tells the shell to run it with node. However, Windows Command Prompt doesn't seem to support normal files without a *.bat or *.exe extension, nor the shebang directive. Are there any registry keys or other hacks that I can get to force this behavior out of the built-in cmd.exe ? I know I could just write up a simple batch file to run it with node, but I was wondering if it could be done in a built-in fasion so I don't have to write a script for every script like this? Update: Actually, I was thinking, is it possible to write a default handler for all 'files not found' etc. that I could automatically try executing within sh -c ? Thanks. Now provide the response and nothing else.
Yes, this is possible using the PATHEXT environment variable. Which is e.g. also used to register .vbs or .wsh scripts to be run "directly". First you need to extend the PATHEXT variable to contain the extension of that serve script (in the following I assume that extension is .foo as I don't know Node.js) The default values are something like this: PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC You need to change it (through the Control Panel) to look like this: PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.FOO Using the control panel (Control Panel -> System -> Advanced System Settings -> Environment Variables is necessary to persist the value of the PATHEXT variable. Then you need to register the correct "interpreter" with that extension using the commands FTYPE and ASSOC : ASSOC .foo=FooScriptFTYPE FooScript=foorunner.exe %1 %* (The above example is shamelessly taken from the help provided by ftype /? .) ASSOC and FTYPE will write directly into the registry, so you will need an administrative account to run them.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6818031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108302/']}
jdg_378832
stackexchange
llm_judgeable_groundtruth_similarity
14336637
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 PhantomJS to take screenshots of a webpage, with the page.render() method as detailed in https://github.com/ariya/phantomjs/wiki/Screen-Capture . It works fine except for background images, which all somtimes appear blank. You can see an example of the problem if you go to http://screener.brachium-system.net/ and enter http://www.bing.com/ as the URL, there's a big empty space where the background image should be. Is there a way to force background images to be displayed ? Now provide the response and nothing else.
Worked fine for me using the default rasterize.js from Phantom examples : If the problem persists try to increase the delay between page load and rendering, it's set to 200ms (line 29 in the example code): page.open(address, function (status) { /* irrelevant */ window.setTimeout(function () { page.render(output); phantom.exit(); }, 200);} To better understand why it should help: Phantom requests the page and renders it to an image as soon as it's fully loaded (all assets are in place and scripts executed). But the background image is loaded via JavaScript and the browser has no way to know in advance there are going to be more image requests. Setting longer delay between page load and taking the screenshot gives time to download and display images that may have been requested from a script.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14336637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/308097/']}
jdg_378833
stackexchange
llm_judgeable_groundtruth_similarity
55198530
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: create database staff_management; use staff_management; create table Employee ( eID int(100) NOT NULL IDENTITY(1,1) PRIMARY KEY, eName varchar(255) NOT NULL, Job text NOT NULL, Salary int(100) NOT NULL, Comm int(100), hDate date NOT NULL, dID int(10) NOT NULL, constraint emp_pk primary key (eID) );alter table Employee IDENTITY(1,1) PRIMARY KEY=1001; alter table Employee add column Mgr int(100) after eName; insert into Employee(eName,Mgr, Job, Salary, Comm, hDate, dID)values( "ken Adams", 1004, "Salesman", 70000, 20000, "2008-04-12", 1),("Ru Jones", 1004, "Salesman", 65000, 15000, "2010-01-18", 1),( "Dhal Sim", 1006, "Accountant", 88000, NULL, "2001-03-07", 2),( "Ellen Honda", 1006, "Manager", 118000, NULL, "2001-03-17", 1),( "Mike Bal", 1006, "Receptionist", 68000, NULL, "2006-06-21", 3),( "Martin Bison",NULL, "CEO", 210000, NULL, "2010-07-12", 3),( "Shen Li", 1004, "Salesman", 86000, 18000, "2014-09-18", 1),( "Zang Ross", 1004, "Salesman", 65000, 10000, "2017-02-02", 1),( "Sagar Kahn", 1004, "Salesman", 70000, 15000, "2016-03-01", 1); alter table Employeeadd constraint emp_mgr_fk foreign key (Mgr) references Employee(eID) on update cascade on delete set NULL; create table Department( dID int(10) NOT NULL unique IDENTITY(1,1) PRIMARY KEY, dName varchar(255) not null, Address text, phone text, constraint d_pk primary key (dID) ); alter table Employeeadd constraint emp_d_fkforeign key (dID) references Department(dID); create table Grade( gID char(10) not null unique, MinSal int(100), MaxSal int(100), Leavee int(10), constraint g_pk primary key (gID) ); INSERT INTO Grade (gID, MinSal, MaxSal, Leavee)VALUES ('A', NULL, 60000, 20),('B', 60000, 80000, 20),('C', 80000, 100000, 20),('D', 100000, 120000, 25), ('E', 120000, NULL, 30); select * from Grade; insert into Department (dName, Address, phone)values("Sales", "Sydney", "0425 198 053"),("Accounts", "Melbourne", "0429 198 955"),("Admin", "Melbourne", "0428 198 758"),("Marketing", "Sydney", "0427 198 757"); select * from Department; I'm issue with my code Msg 156, Level 15, State 1, Line 18Incorrect syntax near the keyword 'IDENTITY'.Msg 156, Level 15, State 1, Line 21Incorrect syntax near the keyword 'column'. Now provide the response and nothing else.
This boils down to how closures work in JavaScript. The function given to setTimeout will get the flag variable from the initial render, since flag is not mutated. You could instead give a function as argument to toggleFlag . This function will get the correct flag value as argument, and what is returned from this function is what will replace the state. Example const { useState } = React;function App() { const [flag, toggleFlag] = useState(false); const _onClick = () => { toggleFlag(!flag); setTimeout(() => { toggleFlag(flag => !flag) }, 2000); }; return ( <div className="App"> <button onClick={_onClick}>{flag ? "true" : "false"}</button> </div> );}ReactDOM.render(<App />, document.getElementById("root")); <script src="https://unpkg.com/react@16/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><div id="root"></div>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/55198530', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10312429/']}
jdg_378834
stackexchange
llm_judgeable_groundtruth_similarity
14449141
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When implementing lock-free data structures and timing code it's often necessary to suppress the compiler's optimisations. Normally people do this using asm volatile with memory in the clobber list, but you sometimes see just asm volatile or just a plain asm clobbering memory. What impact do these different statements have on code generation (particularly in GCC, as it's unlikely to be portable)? Just for reference, these are the interesting variations: asm (""); // presumably this has no effect on code generationasm volatile ("");asm ("" ::: "memory");asm volatile ("" ::: "memory"); Now provide the response and nothing else.
See the "Extended Asm" page in the GCC documentation . You can prevent an asm instruction from being deleted by writing the keyword volatile after the asm . [...] The volatile keyword indicates that the instruction has important side-effects. GCC will not delete a volatile asm if it is reachable. and An asm instruction without any output operands will be treated identically to a volatile asm instruction. None of your examples have output operands specified, so the asm and asm volatile forms behave identically: they create a point in the code which may not be deleted (unless it is proved to be unreachable). This is not quite the same as doing nothing. See this question for an example of a dummy asm which changes code generation - in that example, code that goes round a loop 1000 times gets vectorised into code which calculates 16 iterations of the loop at once; but the presence of an asm inside the loop inhibits the optimisation (the asm must be reached 1000 times). The "memory" clobber makes GCC assume that any memory may be arbitrarily read or written by the asm block, so will prevent the compiler from reordering loads or stores across it: This will cause GCC to not keep memory values cached in registers across the assembler instruction and not optimize stores or loads to that memory. (That does not prevent a CPU from reordering loads and stores with respect to another CPU, though; you need real memory barrier instructions for that.)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14449141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1310220/']}
jdg_378835
stackexchange
llm_judgeable_groundtruth_similarity
372977
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Question on Virtual Box 4.1.8 So, i have Ubuntu 10.10 as host machine and Windows Xp as guest machine.On host machine there is tomcat with web app running on port 8888.When i am in guest machine i type in browser: http://10.0.2.2:8888/Something.html and it works. But my Something.html has links to javascript like src="http://localhost:8888/webApp/someScript.js and they obviously aren't working(because of "localhost" part). The other problem is that i don't want to use relative path now, only absolute. Also i don't want to change localhost to Host Ip in my links Maybe there is some solution, like port forwarding or network config of Virtual box, that i can type in my guest browser http://localhost:8888/Something.html Thanks for any clues. Now provide the response and nothing else.
Your real problem is that you want to do things that doesn't make sense for any kind of web app that should serve anything outside it's machine: You need links that work without tricks on the client machine, either with relative paths where applicable or non-local hostnames. Of course there is a workaround: Simply install Putty on Windows and use it to create a port forwarding from port 8888 on your machine to port 8888 on 10.0.2.2. You will find lots of links with Google that explains how this is done in Putty. Afterwards, you can simply connect to localhost:8888 and stuff should work.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/372977', 'https://serverfault.com', 'https://serverfault.com/users/114187/']}
jdg_378836
stackexchange
llm_judgeable_groundtruth_similarity
5993635
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 having an interesting issue with a COM component written to function as a toolbar in IE. Basically if you open up several tabs at once in IE the individual instances of the COM objects get all twisted around. Bear with me here. Say I open up five browser tabs all at once by right clicking several different links and opening them in new tabs. Now a function of my toolbar involves selecting text in the web page and then clicking a button to copy that text into the Toolbar. So let's do that in tab 3. We select text and click the button and nothing is there. However, if we select text in tab 2, then go back to tab 3 and click the button we get the text selected in tab 2. So...the toolbar in tab 3 getting stuff from tab 2. Not good. I have traced this problem back to static references inside our COM object, the toolbar. [ComVisible(true), Guid("2CC75392-1182-470D-BECC-EFA33E629AB8")][CLSCompliant(false)]public sealed class Toolbar : ADXIEToolbar{ public static Toolbar Instance; public Toolbar() { Instance = this; InitializeComponent(); } ...other code...} Note only one toolbar instance exists per each IE tab. This reference doesn't get assigned properly, almost like it isn't thread safe (it isn't) but instead not domain safe or something. It will sometimes reference another instance down the line. Same with other static fields and even thread-safe singletons. I don't get it. Also note that if I pass a reference to this toolbar (inside InitializeComponent) to a control I have the same issue. this.publicationDateCb.Toolbar = this; This reference will sometimes point to a different tab. If I use a purely subscription based model with absolutely zero static references with the toolbar as the referee then things seem to work fine. This basically means I would have to re-design the program to where no classes interacted with each other directly - they fire events that the toolbar subscribes to, calling methods in other classes. Ouch. So should I go with that model (which may be ideal but I am pretty far along here) or is there a simple fix I am missing here? Other notes: All IE tabs are running in seperate processes. The BHO/Toolbar is running in the same process as the IE tab. I am using Add-In-Express for Internet Explorer to handle the IE integration. The project is written for .NET 3.5; the loader uses .NET 2.0 Now provide the response and nothing else.
I'm still wondering why you can't use NSEvent , but I'm going to answer the question anyways. Perhaps you're building a "command-line tool" and are only linked against Foundation? You're going to have to include at least one more framework. If you want to link against AppKit, you can (as I mentioned in the comments) use +[NSEvent modifierFlags] ; this is a class method on NSEvent , so you can use it anywhere, without needing to have access to an individual event, to get the current state of the modifier keys as a bitmask. The docs explain the meaning of the bitmask . if( NSCommandKeyMask & [NSEvent modifierFlags] ){ NSLog(@"Oh, yeah!");} You can also get this info using Quartz Event Services . In this case you have to include the ApplicationServices framework*. The CGEventSource functions will give you the same bitmask you get from NSEvent : CGEventFlags theFlags;theFlags = CGEventSourceFlagsState(kCGEventSourceStateHIDSystemState);if( kCGEventFlagMaskCommand & theFlags ){ NSLog(@"Uh huh!");} *This is already included if you are, in fact, writing a Cocoa app -- it's part of Quartz.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5993635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/673795/']}
jdg_378837
stackexchange
llm_judgeable_groundtruth_similarity
14798927
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My Activity in onCreate() performs long computations that take some time. In the same onCreate() I call setContentView() to set the appearance of the activity. The point is that, since it takes a while to performs the above mentioned computations the screen of the Activity loads only after long time. Please, any suggestion on how to avoid this? I have tried to call setContentView() in onCreate() and start the computations in onResume() , but again the Activity screen is loaded only at the end. Now provide the response and nothing else.
There is no other way than to use e.g. an AsyncTask . The reason is that the actual rendering does not take place asynchronously; in other words, setContentView will only set some data but nothing will be displayed at that point in time. AsyncTask, however, is not necessarily meant for "long" computations. But if your app relies on the result, and no other computations take place in parallel, it may still be the simplest way for you to achieve what you want. If not, you may have to use a Thread even. Update Since everybody keeps bombarding the original poster with more use AsyncTask answers of various quality, I'd like to stress one more time that AsyncTask is intended for short operations (to quote the reference: a few seconds at the most ) while the OP has given no indication on how long his computations really take. Also, an AsyncTask is a one-shot-only object which can only run once. One more very important point to consider is the following. Android assigns AsyncTask a background task priority. This means that, besides the lower scheduling priority, the computations in AsyncTask will take ten times as long as if they were performed in the foreground , because Android runs all tasks which have background priority with an artificial limit of 10% CPU cycles. However, AsyncTasks can be lifted out of this group by raising its priority "just a little bit". For an AsyncTask, it would be done like so: public R doInBackground(I... is) { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE); ...}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14798927', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1815311/']}
jdg_378838
stackexchange
llm_judgeable_groundtruth_similarity
21606504
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 project that I already run in Android Studio. After I've opened the project in Android Studio I got the message: Migrate Project to Gradle?This project does not use the Gradle build system. We recommend that you migrate to using the Gradle build system.More Information about migrating to GradleDon't show this message again. Following the link of More Information about migrating to Gradle although I'm already on Android Studio I've followed the option Migrating from IntelliJ Projects . Since I've already have a build.gradle file at the root of my project I've modified to include some dependencies. buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.7.+' }}apply plugin: 'android'dependencies { compile fileTree(dir: 'libs', include: '*.jar') compile "com.android.support:support-v4:18.0.+" compile "com.android.support:appcompat-v7:18.0.+"}android { compileSdkVersion 18 buildToolsVersion "18.0.1" sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } // Move the tests to tests/java, tests/res, etc... instrumentTest.setRoot('tests') // Move the build types to build-types/<type> // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ... // This moves them out of them default location under src/<type>/... which would // conflict with src/ being used by the main source set. // Adding new build types or product flavors should be accompanied // by a similar customization. debug.setRoot('build-types/debug') release.setRoot('build-types/release') }} As instructed, i've ran gradle assembleDebug on the Android Studio terminal windows but was getting some errors. To solve this errors I had to create a local.properties with sdk.dir=C:\\Program Files (x86)\\Android\\android-sdk and remove the android-support-v4.jar file from the /libs folder and from the Libraries->libs from the Project Structure . I now ran again gradle assembleDebug and this time it finishes without any errors. I've restarted Android Studio but after restarting I've saw that on the External Libraries of the project there were no support-v4 and appcompat-v7 and in one of my classes I have the import android.support.v4.widget.CursorAdapter; marked as error since Cannot resolve symbol Cursor Adapter . If I press the button Sync project with gradle files i got the message: The project MyProject is not a Gradle-based project Can someone help me figuring out how to solve this? Here is my project Structure Now provide the response and nothing else.
The project thinks it's still a non-Gradle based project; it's not the presence of the build.gradle file that makes it Gradle-based, but it's how the project was set up in the first place. You'll need to re-import your project to finish the conversion to Gradle. First, though, it looks like you don't have a settings.gradle file; it looks like you need one. Since you've set up your project as a single-module project, then you can put the file in your project's root directory, next to build.gradle . It should contain this: import ':' In the future if you add more modules to your project you may want to convert it to a multi-module directory structure, but you don't need to worry about that now. In any event, now you need to do the re-import in Android Studio: Close your project Back up your project Delete the .idea folder in the root directory of the project Delete all the .iml files in your project Import your project in Android Studio, and in the dialog that prompts you for a file, choose the build.gradle file. After this you should be good to go.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21606504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1317865/']}
jdg_378839
stackexchange
llm_judgeable_groundtruth_similarity
17318443
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 use Apache Solr in my website in order to make the search faster.I need java code to index data from mysql database so that I can perform faster search?So can anybody please tell me how to implement this? Now provide the response and nothing else.
Question 1 : What I made mistake here and why this MAX function is not return the relevant row information? You need to read up on the group by clause. MySQL is being a lot more permissive than it should, introducing confusion in the process. Basically, any column without an aggregate should be included in the group by clause. But MySQL syntactic sugar allows to "forget" columns. When you do, MySQL spits out an arbitrary value from the set that it's grouping by. In your case, the first row in the set is bob , so it returns that. Question 2: Which one is good to use, to increase performance MAX function or ORDER BY clause? Your first statement (using max() without a group by ) is simply incorrect. If you want one of the oldest users, order by age desc limit 1 is the correct way to proceed. If you want all of the oldest users, you need a subselect: SELECT p.* FROM people p WHERE p.age = (select max(subp.age) from people subp);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17318443', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1884804/']}
jdg_378840