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
13391544
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 this page: https://developers.google.com/java-dev-tools/download-wbpro , there is no option to install WindowBuilder Pro to Eclipse Juno (4.2). Is WindowBuilder Pro already installed with Eclipse Juno? Also, is there a better free alternative to WindowBuilder Pro? Now provide the response and nothing else.
UPDATE 2019 Again WindowBuilder Pro is no longer included in any of the latest Eclipse versions. So you need to add it as was shown in the initial answer below. It is also strange, that WindowBuilder Pro is not available when searching Eclipse Market place (checked with the latest as of now version of Eclipse For Enterprise Java Developers version 2019-09 ) despite the fact that the product's website is available. But at least the related repository URL for the latest version of WindowBuilder Pro is now much compact and intuitive: http://download.eclipse.org/windowbuilder/latest/ UPDATE 2014 As Sean Lynch noted in his answer WindowBuilder is included in Eclipse IDE for Java . Actually, it was already included there since version 3.7 ( Eclipse Indigo ), which was released in year 2011. Note that currently, it is included by default only in the version for Java Developers , NOT in the version for Java EE Developers , which is the most downloaded and wanted version. So for the Eclipse IDE for Java EE Developers you still need to install it yourself. Old answer It is not installed by default in Eclipse. The new WindowBuilder Pro home page is here: http://www.eclipse.org/windowbuilder/ On that page, in the "Current Status" section on the right, it says (emphasis mine): "Welcome to the new WindowBuilder homepage!" How to install WindowBuilder in Eclipse. 1) Copy the correct link for your version of Eclipse from the Update Site column ( Release Version ) on the download page : 2) In the Eclipse main menu choose Help > Install new Software... 3) In the appeared window click Add... button: 4) In the appeared dialog box, in the Name field write some descriptive name (like "WindowBuilder Pro") and paste the correct link (see step 1) in the Location field. After that click the OK button: 5) Select all the checkboxes that are going to appear, then click Next button and install WindowBuilder: Another way to add a link to the list of available Software Sites: in the Eclipse main menu choose Window > Preferences , in the preferences window choose Install/Update > Available Software Sites , click Add... button and go on as described above. As for the better alternative, well, seems like WindowBuilder Pro is the most preferred: Best GUI designer for Eclipse? Hope this helps.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13391544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1748450/']}
jdg_72741
stackexchange
llm_judgeable_groundtruth_similarity
49718855
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 creating an single page app in vanilla JavaScript. I want to organize my code in different files to make it modular, which means I should be able to access functions defined in one file in another file. I am using ES6 native import export for this: file-1.js: export function func1() {}export function func2() {} file-2.js: import { func1, func2 } from './file-1'; index.html: <script src="file-1.js"></script> When I run index.html in Chrome (version 65), I get the following error: Uncaught SyntaxError: Unexpected token { . What's wrong in my code? Chrome 65 fully supports ES6 module system. Now provide the response and nothing else.
Here is a working example file1.mjs function log1() { console.log('log1');}function log2() { console.log('log2');}export { log1, log2 }; file2.mjs you must explicitly write .mjs extension import { log1, log2 } from './file1.mjs';log1();log2(); index.html Notice attribute type="module" <body> <script type="module" src="file2.mjs"></script></body> Then you need a static server to get rid of CORS block. $ yarn global add serve$ serve ./ Finally go to http://localhost:5000 and it will work Update: It is recommended to use .mjs file extension for modules instead of .js
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49718855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3706051/']}
jdg_72742
stackexchange
llm_judgeable_groundtruth_similarity
49553
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been playing with two dimensional machine learning using pandas (trying to do something like this ), and I would like to combine Lat/Long into a single numerical feature -- ideally in a linear fashion. Is there a "best practice" to do this? Now provide the response and nothing else.
A note: for those who've ended here looking for a hashing technique, geohash is likely your best choice . Representing latitude and longitude in a single linear scale is not possible due to the fact that their domain is inherently a 3D space. Reducing that as per your needs would require a spatial flattening technique that's unheard of to me. Reasoning As far as lat/long merging goes, the best of best practices would be to resort to the Haversine formula, which calculates the distance between two points over a spherical surface, and receives those points' coordinates as input. One way to incorporate that in your use case - where each point should probably have an independent lat/long combination - would be to assume the distance's origin point coordinates to be $(\varphi_1, \lambda_1) = (0, 0)$ , which would render $$d =2r \arcsin\left(\sqrt{\sin^2\left(\frac{\varphi_2 - 0}{2}\right) + \cos(0) \cos(\varphi_2)\sin^2\left(\frac{\lambda_2 - 0}{2}\right)}\right)$$ $$= 2r \arcsin\left(\sqrt{\sin^2\left(\frac{\varphi_2}{2}\right) + \cos(\varphi_2)\sin^2\left(\frac{\lambda_2}{2}\right)}\right)$$ With $r$ being Earth's radius (~6371km) and $(\varphi_2, \lambda_2)$ your point's latitude and longitude, respectively. However, as stated before, that couldn't possibly give you a linear relation, as you can see by 3d plotting the function : Implementation The circumstances imply you're likely to be using pandas , or at least should be. Here's an example implementation of this relativized Haversine formula: from math import radians, cos, sin, asin, sqrtdef single_pt_haversine(lat, lng, degrees=True): """ 'Single-point' Haversine: Calculates the great circle distance between a point on Earth and the (0, 0) lat-long coordinate """ r = 6371 # Earth's radius (km). Have r = 3956 if you want miles # Convert decimal degrees to radians if degrees: lat, lng = map(radians, [lat, lng]) # 'Single-point' Haversine formula a = sin(lat/2)**2 + cos(lat) * sin(lng/2)**2 d = 2 * r * asin(sqrt(a)) return d Which could be used as in the below minimal example: >>> import pandas as pd>>> df = pd.DataFrame([[45.0, 120.0], [60.0, 30.0]], columns=['x', 'y'])>>> df x y0 45.0 120.01 60.0 30.0>>> df['harvesine_distance'] = [single_pt_haversine(x, y) for x, y in zip(df.x, df.y)]>>> df x y harvesine_distance0 45.0 120.0 12309.8133441 60.0 30.0 7154.403197
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/49553', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/71765/']}
jdg_72743
stackexchange
llm_judgeable_groundtruth_similarity
974
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: An article from the Los Angeles Times regarding the concerns of individuals who live near the Fukushima I Nuclear Plant that appeared in my local newspaper this morning contained this interesting tidbit: For Japanese, the desperation has an added dimension: Already the name "Fukushima" is laden with something beyond the fear of damaged health. The Japanese survivors of the 1945 atomic bombings of Hiroshima and Nagasaki lived the rest of their lives with the stigma of having been exposed to radiation, a stain that the years never erased. Known as Hibakushas, they are formally recognized by the government if they lived within proximity of the blasts and receive a special medical allowance. But the designation also led them to become ostracized by other Japanese, who feared wrongly that the contamination was contagious or could be hereditary. The result was that many survivors of the bombings, and even their children, lived ghettoized lives because of their exposure to radiation. Is there any merit to their concerns? Now provide the response and nothing else.
As others have stated, the radiation itself doesn't "stay" with a person. External exposure to radiation often takes the form of burns. Just as you wouldn't be concerned with "catching" sunburn by being close to someone who lingered at the beach too long, you also don't need to worry about "catching" radiation burns. Transference of radioactive particles, which can linger on skin, hair, and clothing, is the only transmission risk. I think the one of the MAIN stigmas in Japanese culture after the atomic bombings stemmed from the belief that the children of those exposed to radiation would be born disfigured by horrifying birth defects. This is especially important in a society where family honor and kinship are so important. Many would argue that the "Godzilla" fear, of monsters born from radiation, is a manifestation of this concern. Fortunately for the Japanese, their fears about the post-bombing effects of radiation being passed on to their kin went mainly unrealized. As this study shows: The incidence of major birth defects (594 cases or 0.91%) among the 65,431 [births to parents exposed to radiation from the bombings]...accords well with a large series of contemporary Japanese births...where radiation exposure was not involved and overall malformation frequency was 0.92%. No untoward outcome showed any relation to parental radiation dose or exposure. Hopefully the lessons of Hiroshima and Nagasaki, and the swift moves by the Japanese government to evacuate the areas around the troubled nuclear facilities, will prevent further generations from suffering under the unnecessary stigmas associated with radiation exposure.
{}
{'log_upvote_score': 5, 'links': ['https://skeptics.stackexchange.com/questions/974', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/334/']}
jdg_72744
stackexchange
llm_judgeable_groundtruth_similarity
31324739
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to find the gradient with regards to the input layer for a single convolutional filter in a convolutional neural network (CNN) as a way to visualize the filters . Given a trained network in the Python interface of Caffe such as the one in this example , how can I then find the gradient of a conv-filter with respect to the data in the input layer? Edit: Based on the answer by cesans , I added the code below. The dimensions of my input layer is [8, 8, 7, 96] . My first conv-layer, conv1 , has 11 filters with a size of 1x5 , resulting in the dimensions [8, 11, 7, 92] . net = solver.netdiffs = net.backward(diffs=['data', 'conv1'])print diffs.keys() # >> ['conv1', 'data']print diffs['data'].shape # >> (8, 8, 7, 96)print diffs['conv1'].shape # >> (8, 11, 7, 92) As you can see from the output, the dimensions of the arrays returned by net.backward() are equal to the dimensions of my layers in Caffe. After some testing I've found that this output is the gradients of the loss with regards to respectively the data layer and the conv1 layer. However, my question was how to find the gradient of a single conv-filter with respect to the data in the input layer, which is something else. How can I achieve this? Now provide the response and nothing else.
Caffe net juggles two "streams" of numbers. The first is the data "stream": images and labels pushed through the net. As these inputs progress through the net they are converted into high-level representation and eventually into class probabilities vectors (in classification tasks). The second "stream" holds the parameters of the different layers, the weights of the convolutions, the biases etc. These numbers/weights are changed and learned during the train phase of the net. Despite the fundamentally different role these two "streams" play, caffe nonetheless use the same data structure, blob , to store and manage them. However, for each layer there are two different blobs vectors one for each stream. Here's an example that I hope would clarify: import caffesolver = caffe.SGDSolver( PATH_TO_SOLVER_PROTOTXT )net = solver.net If you now look at net.blobs You will see a dictionary storing a "caffe blob" object for each layer in the net. Each blob has storing room for both data and gradient net.blobs['data'].data.shape # >> (32, 3, 224, 224)net.blobs['data'].diff.shape # >> (32, 3, 224, 224) And for a convolutional layer: net.blobs['conv1/7x7_s2'].data.shape # >> (32, 64, 112, 112)net.blobs['conv1/7x7_s2'].diff.shape # >> (32, 64, 112, 112) net.blobs holds the first data stream, it's shape matches that of the input images up to the resulting class probability vector. On the other hand, you can see another member of net net.layers This is a caffe vector storing the parameters of the different layers. Looking at the first layer ( 'data' layer): len(net.layers[0].blobs) # >> 0 There are no parameters to store for an input layer. On the other hand, for the first convolutional layer len(net.layers[1].blobs) # >> 2 The net stores one blob for the filter weights and another for the constant bias. Here they are net.layers[1].blobs[0].data.shape # >> (64, 3, 7, 7)net.layers[1].blobs[1].data.shape # >> (64,) As you can see, this layer performs 7x7 convolutions on 3-channel input image and has 64 such filters. Now, how to get the gradients? well, as you noted diffs = net.backward(diffs=['data','conv1/7x7_s2']) Returns the gradients of the data stream. We can verify this by np.all( diffs['data'] == net.blobs['data'].diff ) # >> Truenp.all( diffs['conv1/7x7_s2'] == net.blobs['conv1/7x7_s2'].diff ) # >> True ( TL;DR ) You want the gradients of the parameters, these are stored in the net.layers with the parameters: net.layers[1].blobs[0].diff.shape # >> (64, 3, 7, 7)net.layers[1].blobs[1].diff.shape # >> (64,) To help you map between the names of the layers and their indices into net.layers vector, you can use net._layer_names . Update regarding the use of gradients to visualize filter responses: A gradient is normally defined for a scalar function. The loss is a scalar, and therefore you can speak of a gradient of pixel/filter weight with respect to the scalar loss. This gradient is a single number per pixel/filter weight. If you want to get the input that results with maximal activation of a specific internal hidden node, you need an "auxiliary" net which loss is exactly a measure of the activation to the specific hidden node you want to visualize. Once you have this auxiliary net, you can start from an arbitrary input and change this input based on the gradients of the auxilary loss to the input layer: update = prev_in + lr * net.blobs['data'].diff
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31324739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1452257/']}
jdg_72745
stackexchange
llm_judgeable_groundtruth_similarity
14965238
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to assert the equality of two System.Drawing.Size structures, and I'm getting a format exception instead of the expected assert failure. [TestMethod]public void AssertStructs(){ var struct1 = new Size(0, 0); var struct2 = new Size(1, 1); //This throws a format exception, "System.FormatException: Input string was not in a correct format." Assert.AreEqual(struct1, struct2, "Failed. Expected {0}, actually it is {1}", struct1, struct2); //This assert fails properly, "Failed. Expected {Width=0, Height=0}, actually it is {Width=1, Height=1}". Assert.AreEqual(struct1, struct2, "Failed. Expected " + struct1 + ", actually it is " + struct2); } Is this intended behavior? Am I doing something wrong here? Now provide the response and nothing else.
I've got it. And yes, it's a bug. The problem is that there are two levels of string.Format going on here. The first level of formatting is something like: string template = string.Format("Expected: {0}; Actual: {1}; Message: {2}", expected, actual, message); Then we use string.Format with the parameters you've supplied: string finalMessage = string.Format(template, parameters); (Obviously there's cultures being provided, and some sort of sanitization... but not enough.) That looks fine - unless the expected and actual values themselves end up with braces in, after being converted to a string - which they do for Size . For example, your first size ends up being converted to: {Width=0, Height=0} So the second level of formatting is something like: string.Format("Expected: {Width=0, Height=0}; Actual: {Width=1, Height=1 }; " + "Message = Failed expected {0} actually is {1}", struct1, struct2); ... and that's what's failing. Ouch. Indeed, we can prove this really easily by fooling the formatting to use our parameters for the expected and actual parts: var x = "{0}";var y = "{1}";Assert.AreEqual<object>(x, y, "What a surprise!", "foo", "bar"); The result is: Assert.AreEqual failed. Expected:<foo>. Actual:<bar>. What a surprise! Clearly broken, as we weren't expecting foo nor was the actual value bar ! Basically this is like a SQL injection attack, but in the rather less scary context of string.Format . As a workaround, you can use string.Format as StriplingWarrior suggests. That avoids the second level of formatting being performed on the result of formatting with the actual/expected values.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14965238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/199647/']}
jdg_72746
stackexchange
llm_judgeable_groundtruth_similarity
172772
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to model the following system of $n$ nonlinear differential equations: $$\dot{P}_i(t) = \sum_{1 \, \leq \, j \, < \, i} R(p_{ji}) - A(p_{ji}) + \sum_{i \, < \, j \, \leq \, N} A(p_{ij}) - R(p_{ij}) \quad \text{for} \quad i = 1, \ldots, N$$ where $p_{ij} = P_j - P_i$, $A(p_{ij}) = \dfrac{ap_{ij}}{e^{bp_{ij}}}$ and $R(p_{ij}) = \dfrac{c}{p_{ij}}$. The following code solves this system of $n$ nonlinear differential equations in one dimension (for arbitrary $n \in \mathbb{N}_{\, \geq \, 2}$): p[i_, j_] = P[j][t] - P[i][t];A@p[j, i] = (a*p[j, i])/Exp[b*p[j, i]];R@p[j, i] = c/p[j, i];summand1 = R@p[j, i] - A@p[j, i];A@p[i, j] = (a*p[i, j])/Exp[b*p[i, j]];R@p[i, j] = c/p[i, j];summand2 = A@p[i, j] - R@p[i, j];n = 12;sys = Table[P[i]'[t] == Sum[If[j < i, summand1, 0], {j, 1, n}] + Sum[If[i < j, summand2, 0], {j, 1, n}], {i, 1, n}];sol = ParametricNDSolveValue[{sys, P[1][0] == 1, P[2][0] == 1.01, P[3][0] == 1.02, P[4][0] == 5, P[5][0] == 6.8, P[6][0] == 6.9, P[7][0] == 7, P[8][0] == 7.2, P[9][0] == 8.9, P[10][0] == 10, P[11][0] == 10.25, P[12][0] == 11}, P /@ Range[12], {t, 0, 100}, {a, b, c}];Manipulate[Plot[sol[a, b, c][t] // Through // Evaluate, {t, 0, T}, PlotRange -> Automatic, ImageSize -> Large, AspectRatio -> 1], {{a, 1}, .1, 10}, {{b, 1}, .1, 10}, {{c, .1}, .1, 100}, {{T, 1}, .1, 100}] Edit: After taking out the errors I got the following in two dimensions : ClearAll["Global`*"]n = 5;P[i_][t_] = {X[i][t], Y[i][t]};p[j_, i_] = Norm[P[i][t] - P[j][t]];A@p[j, i] = (a*(P[i][t] - P[j][t]))/Exp[b*p[j, i]];R@p[j, i] = (c*(P[i][t] - P[j][t]))/p[j, i]^2;summand1 = R@p[j, i] - A@p[j, i];A@p[i, j] = (a*(P[j][t] - P[i][t]))/Exp[b*p[i, j]];R@p[i, j] = (c*(P[j][t] - P[i][t]))/p[i, j]^2;summand2 = A@p[i, j] - R@p[i, j];sys = Table[ D[P[i][t], t] == Sum[If[j < i, summand1, 0], {j, 1, n}] + Sum[If[i < j, summand2, 0], {j, 1, n}], {i, 1, n}];sol = ParametricNDSolveValue[{sys, P[1][0] == {1, 1}, P[2][0] == {1, 6}, P[3][0] == {1, -1}, P[4][0] == {5, 3}, P[5][0] == {6, 2}}, Table[P[i][t], {i, 1, n}], {t, 0, 5}, {a, b, c}];Manipulate[ ParametricPlot[sol[a, b, c][t] // Through // Evaluate, {t, 0, T}, PlotRange -> Automatic, ImageSize -> Large, AspectRatio -> 1], {{a, 1}, .1, 5}, {{b, 1}, .1, 5}, {{c, .1}, .1, 5}, {{T, 1}, 0, 5}] The only thing is that there's no output. Now provide the response and nothing else.
Mathematica is flexible, but you can not write code in such wild way. You'd better spend some time learning the basic of the core language first. The following is a working example, which is just a simple use case of Table : p[i_, j_] = P[j][t] - P[i][t]A@p[i, j] = (a p[i, j])/Exp[b p[j, i]]R@p[i, j] = c/p[i, j]summand = R@p[i, j] - A@p[i, j]Ν = 3; sys = Table[ P[i]'[t] == Sum[If[i == j, 0, summand], {j, 1, Ν}], {i, 1, Ν}]sol = ParametricNDSolveValue[{sys, P[1][0] == 0, P[2][0] == 0.5, P[3][0] == 1}, P /@ Range[3], {t, 0, 10}, {a, b, c}]lst = sol[-1/10, -1/10, -1/10]ParametricPlot3D[lst[t] // Through // Evaluate, {t, 0, 10}]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/172772', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/57591/']}
jdg_72747
stackexchange
llm_judgeable_groundtruth_similarity
3424474
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 writing a fastcgi application for my site in C. Don't ask why, leave all that part. Just help me with this problem- I want to replace spaces in the query string with %20.Here's the code I'm using, but I don't see 20 in the output, only %. Where's the problem? Code: unsigned int i = 0;/* * Replace spaces with its hex %20 * It will be converted back to space in the actual processing * They make the application segfault in strtok_r() */char *qstr = NULL;for(i = 0; i <= strlen(qry); i++) { void *_tmp; if(qry[i] == ' ') { _tmp = realloc(qstr, (i + 2) * sizeof(char)); if(!_tmp) error("realloc() failed while allocting string memory (space)\n"); qstr = (char *) _tmp; qstr[i] = '%'; qstr[i + 1] = '2'; qstr[i + 2] = '0'; } else { _tmp = realloc(qstr, (i + 1) * sizeof(char)); if(!_tmp) error("realloc() failed while allocating string memory (not space)\n"); qstr = (char *) _tmp; qstr[i] = qry[i]; }} In the code, qry is char *, comes as a actual parameter to the function.I tried with i + 3, 4, 5 in realloc() in the space replacer block, no success. Now provide the response and nothing else.
String-handling in C can be tricky. I'd suggest going through the string first, counting the spaces, and then allocating a new string of the appropriate size (original string size + (number of spaces * 2)). Then, loop through the original string, maintaining a pointer (or index) to the position in both the new string and the original one. (Why two pointers? Because every time you encounter a space, the pointer into the new string will get two characters ahead of the pointer into the old one.) Here's some code that should do the trick: int new_string_length = 0;for (char *c = qry; *c != '\0'; c++) { if (*c == ' ') new_string_length += 2; new_string_length++;}char *qstr = malloc((new_string_length + 1) * sizeof qstr[0]);char *c1, *c2;for (c1 = qry, c2 = qstr; *c1 != '\0'; c1++) { if (*c1 == ' ') { c2[0] = '%'; c2[1] = '2'; c2[2] = '0'; c2 += 3; }else{ *c2 = *c1; c2++; }}*c2 = '\0';
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3424474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/328993/']}
jdg_72748
stackexchange
llm_judgeable_groundtruth_similarity
24046586
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is that really true that i can use $_ as a dummy variable in foreach loop if there is no need for $value in foreach($array as $key => $value) ? I could not find any useful information that proves this except PHP syntax formatting . There's a special case for foreach loops when the value is not used inside the loop. In this case the dummy variable $_ (underscore) is used: foreach ($GLOBALS['TCA'] as $table => $_) { // Do something with $table } This is done for performance reasons, as it is faster than calling array_keys() and looping on its result. Now provide the response and nothing else.
"_" is a valid variable name character , so you can use it as you would any other variable and has no special significance; this isn't Perl. <?php $_ = "Hello"; $__ = "World"; $___ = "foo"; print "{$_}, {$__}, {$___}\n";?> will output "Hello, World, foo" as expected. Also, foreach ( [ 'a' => 'Alpha', 'b' => 'Beta', 'c' => 'Gamma' ] as $letter => $_ ) { print $letter;}print $_; will output "abcGamma", showing that the $_ variable remains defined after being used in the foreach ; it's not some weird kind of "local" variable. As for the performances, I don't think it makes much difference, but that's your call. Rather, I'd try and not use global variables, to avoid polluting the global scope. Tests and rants more or less at random n.b. a recent PHP required, I think feel free to correct/add/suggest improvements define('INNER_LOOP', 10000);define('OUTER_LOOP', 10);$TCA = [ 'customers' => '', 'relations' => '', 'invoices' => '', 'books' => '', 'parts' => '', 'records' => '', 'calories' => '', 'bounties' => '', 'cats' => '', 'cowabunga' => '', 'amenities' => '',];$tests = [ "foreach access to global" => function() { global $TCA; for ($i = 0; $i < INNER_LOOP; $i++) { foreach ($TCA as $table => $_) { $t = $table . 'x'; } } }, "foreach access to GLOBALS" => function() { for ($i = 0; $i < INNER_LOOP; $i++) { foreach ($GLOBALS['TCA'] AS $table => $_) { $t = $table . 'x'; } } }, "passing parameter" => function($TCA) { for ($i = 0; $i < INNER_LOOP; $i++) { foreach ($TCA AS $table => $_) { $t = $table . 'x'; } } }, "passing parameter and array_keys" => function($TCA) { $keys = array_keys($TCA); for ($i = 0; $i < INNER_LOOP; $i++) { foreach ($keys AS $table) { $t = $table . 'x'; } } }, "walking passed parameter w/lambda" => function($TCA) { for ($i = 0; $i < INNER_LOOP; $i++) { array_map( function($table) { $t = $table . 'x'; }, array_keys($TCA) ); } }, "walking passed parameter w/ anon func" => function($TCA) { $handler = function($table) { $t = $table . 'x'; }; $keys = array_keys($TCA); for ($i = 0; $i < INNER_LOOP; $i++) { array_map($handler, $keys); } },];function timeFunc($function, $obj) { $time = microtime(true); for ($i = 0; $i < OUTER_LOOP; $i++) { $function($obj); } return (microtime(true) - $time);}foreach ($tests as $name => $test) { print "$name: " . timeFunc($test, $TCA) . "\n"; flush();} These are my results, formatted and sorted: - passing parameter and array_keys: 0.04573917388916- foreach access to global: 0.067629098892212- passing parameter: 0.08098292350769- foreach access to GLOBALS: 0.082289934158325- walking passed parameter w/ anon func: 1.6233508586884- walking passed parameter w/lambda: 1.6796138286591 Two things need noting: between the fastest and slowest I have a difference of about forty times . But the difference over one hundred thousand calls is 1.63 seconds, which means 16.3 microseconds for a single call between the faster and the slower versions. So if one of these versions show promise of saving you, say, five minutes a year of head-scratching, bug-hunting or customer support, it's likely that going for that version will prove a worthwhile investment. If, on the other hand, you really need something called several billion times, so that those paltry microseconds add up to something worth tackling, then probably you'd be better off investing some time in porting (or having ported) that section of code to a language which is either inherently faster or can be made to massively parallelize - maybe C, or Erlang; or re-thinking the architecture (e.g. daemonize a process to save on the overhead, use stored procedures to offload the hassle to the RDBMS, cache results, ...). UPDATE FOR PHP 7.2 These are the results for PHP 7.2.19 on a newer 64bit machine: passing parameter and array_keys 0.57718586921692foreach access to global 0.65028595924377passing parameter 0.65098810195923foreach access to GLOBALS 0.69678092002869walking passed parameter w/ anon func 0.84391593933105walking passed parameter w/lambda 1.0423438549042 Note that the difference between fastest and slowest is now less than a factor of 2; therefore, the argument for "go with the clearest, easiest to understand code" is now even stronger.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24046586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1525573/']}
jdg_72749
stackexchange
llm_judgeable_groundtruth_similarity
338155
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've problem with this surface integral:$$\iint\limits_S {\sqrt{ \left(\frac{x^2}{a^4}+\frac{y^2}{b^4}+\frac{z^2}{c^4}\right)}}{dS}$$, where$$S = \{(x,y,z)\in\mathbb{R}^3: \frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2}= 1\}$$ Now provide the response and nothing else.
Note that the outward unit normal ${\bf n}$ to the ellipsoid is given by ${\displaystyle {({x \over a^2}, {y \over b^2}, {z \over c^2}) \over \sqrt{ \left(\frac{x^2}{a^4}+\frac{y^2}{b^4}+\frac{z^2}{c^4}\right)}}}$. So if ${\bf F} = ({x \over a^2}, {y \over b^2}, {z \over c^2})$, your integral is $\int_S {\bf F} \cdot {\bf n}\,dS$. By the divergence theorem, this is equal to $\int_E div\,\mathbf{F}$, where$E$ is the ellipsoid's interior. But $ div \,\mathbf{F}$ is the constant ${1 \over a^2} + {1 \over b^2} + {1 \over c^2}$ and the ellipsoid has volume ${4\pi \over 3}abc$, so the integral will evaluate to $${4\pi \over 3}abc \times \bigg({1 \over a^2} + {1 \over b^2} + {1 \over c^2}\bigg)$$$$= {4\pi \over 3} \bigg({bc \over a} + {ac \over b} + {ab \over c}\bigg)$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/338155', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/68046/']}
jdg_72750
stackexchange
llm_judgeable_groundtruth_similarity
4178798
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 somewhat confused about how the group by command works in mysql. Suppose I have a table: mysql> select recordID, IPAddress, date, httpMethod from Log_Analysis_Records_dalhousieShort; +----------+-----------------+---------------------+-------------------------------------------------+| recordID | IPAddress | date | httpMethod |+----------+-----------------+---------------------+-------------------------------------------------+| 1 | 64.68.88.22 | 2003-07-09 00:00:21 | GET /news/science/cancer.shtml HTTP/1.0 | | 2 | 64.68.88.166 | 2003-07-09 00:00:55 | GET /news/internet/xml.shtml HTTP/1.0 | | 3 | 129.173.177.214 | 2003-07-09 00:01:23 | GET / HTTP/1.1 | | 4 | 129.173.177.214 | 2003-07-09 00:01:23 | GET /include/fcs_style.css HTTP/1.1 | | 5 | 129.173.177.214 | 2003-07-09 00:01:23 | GET /include/main_page.css HTTP/1.1 | | 6 | 129.173.177.214 | 2003-07-09 00:01:23 | GET /images/bigportaltopbanner.gif HTTP/1.1 | | 7 | 129.173.177.214 | 2003-07-09 00:01:23 | GET /images/right_1.jpg HTTP/1.1 | | 8 | 64.68.88.165 | 2003-07-09 00:02:43 | GET /studentservices/responsible.shtml HTTP/1.0 | | 9 | 64.68.88.165 | 2003-07-09 00:02:44 | GET /news/sports/basketball.shtml HTTP/1.0 | | 10 | 64.68.88.34 | 2003-07-09 00:02:46 | GET /news/science/space.shtml HTTP/1.0 | | 11 | 129.173.159.98 | 2003-07-09 00:03:46 | GET / HTTP/1.1 | | 12 | 129.173.159.98 | 2003-07-09 00:03:46 | GET /include/fcs_style.css HTTP/1.1 | | 13 | 129.173.159.98 | 2003-07-09 00:03:46 | GET /include/main_page.css HTTP/1.1 | | 14 | 129.173.159.98 | 2003-07-09 00:03:48 | GET /images/bigportaltopbanner.gif HTTP/1.1 | | 15 | 129.173.159.98 | 2003-07-09 00:03:48 | GET /images/left_1g.jpg HTTP/1.1 | | 16 | 129.173.159.98 | 2003-07-09 00:03:48 | GET /images/webcam.gif HTTP/1.1 | +----------+-----------------+---------------------+-------------------------------------------------+ When I am execute this statement how does it choose which recordID to include since there are a range of recordID s that would be correct? Does it just choose the first one that matches? mysql> select recordID, IPAddress, date, httpMethod from Log_Analysis_Records_dalhousieShort GROUP BY IPADDRESS;+----------+-----------------+---------------------+-------------------------------------------------+| recordID | IPAddress | date | httpMethod |+----------+-----------------+---------------------+-------------------------------------------------+| 11 | 129.173.159.98 | 2003-07-09 00:03:46 | GET / HTTP/1.1 | | 3 | 129.173.177.214 | 2003-07-09 00:01:23 | GET / HTTP/1.1 | | 8 | 64.68.88.165 | 2003-07-09 00:02:43 | GET /studentservices/responsible.shtml HTTP/1.0 | | 2 | 64.68.88.166 | 2003-07-09 00:00:55 | GET /news/internet/xml.shtml HTTP/1.0 | | 1 | 64.68.88.22 | 2003-07-09 00:00:21 | GET /news/science/cancer.shtml HTTP/1.0 | | 10 | 64.68.88.34 | 2003-07-09 00:02:46 | GET /news/science/space.shtml HTTP/1.0 | +----------+-----------------+---------------------+-------------------------------------------------+6 rows in set (0.00 sec) For this table the max(date) and min(date) values seem logical to me but I am confused about how the recordID and httpMethod where chosen. Is it safe use two aggregate functions in one command? mysql> select recordID, IPAddress, min(date), max(date), httpMethod from Log_Analysis_Records_dalhousieShort GROUP BY IPADDRESS;+----------+-----------------+---------------------+---------------------+-------------------------------------------------+| recordID | IPAddress | min(date) | max(date) | httpMethod |+----------+-----------------+---------------------+---------------------+-------------------------------------------------+| 11 | 129.173.159.98 | 2003-07-09 00:03:46 | 2003-07-09 00:03:48 | GET / HTTP/1.1 | | 3 | 129.173.177.214 | 2003-07-09 00:01:23 | 2003-07-09 00:01:23 | GET / HTTP/1.1 | | 8 | 64.68.88.165 | 2003-07-09 00:02:43 | 2003-07-09 00:02:44 | GET /studentservices/responsible.shtml HTTP/1.0 | | 2 | 64.68.88.166 | 2003-07-09 00:00:55 | 2003-07-09 00:00:55 | GET /news/internet/xml.shtml HTTP/1.0 | | 1 | 64.68.88.22 | 2003-07-09 00:00:21 | 2003-07-09 00:00:21 | GET /news/science/cancer.shtml HTTP/1.0 | | 10 | 64.68.88.34 | 2003-07-09 00:02:46 | 2003-07-09 00:02:46 | GET /news/science/space.shtml HTTP/1.0 | +----------+-----------------+---------------------+---------------------+-------------------------------------------------+6 rows in set (0.00 sec) Now provide the response and nothing else.
Usually use of GROUP BY while listing a field in the select expression without an aggregate function is invalid SQL and should throw an error. MySQL, however, allows this and simply chooses one value randomly. Try to avoid it, because it is confusing. To disallow this, you can say at runtime: SET sql_mode := CONCAT('ONLY_FULL_GROUP_BY,',@@sql_mode); or use the configuration value and/or command line option sql-mode . Yes, listing two aggregate functions is completely valid.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4178798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/251589/']}
jdg_72751
stackexchange
llm_judgeable_groundtruth_similarity
15028159
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 understand the difference between "Flush Magento Cache" and "Flush Cache Storage" in Magento ( example ). I'm trying to work on a cron job that will flush the cache storage from time to time. I'm assuming that this button doesn't just remove the contents of var/cache/, but I can't find a solid resource that says what it does. I am using APC as well as all the inbuilt Magento cache features. Is it possible to run the equivalent of the "Fluch Cache Storage" button from a script? Now provide the response and nothing else.
In the app/code/core/Mage/Adminhtml/controllers/CacheController.php , you can see that flushAllAction() (the action that is called when you click Flush Cache Storage ) is called. This function contains the following: /** * Flush cache storage */public function flushAllAction(){ Mage::dispatchEvent('adminhtml_cache_flush_all'); Mage::app()->getCacheInstance()->flush(); $this->_getSession()->addSuccess(Mage::helper('adminhtml')->__("The cache storage has been flushed.")); $this->_redirect('*/*');} To call this in your own file, you can do the following. require_once('app/Mage.php');Mage::app()->getCacheInstance()->flush(); Now, you can run your php file using a cronjob.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15028159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2036972/']}
jdg_72752
stackexchange
llm_judgeable_groundtruth_similarity
45518413
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 a C++ project, I'm trying to call this function, which is defined in C: int CyBtldr_RunAction(CyBtldr_Action action, const char* file, const uint8_t* securityKey, uint8_t appId, CyBtldr_CommunicationsData* comm, CyBtldr_ProgressUpdate* update); CyBtldr_ProgressUpdate is also defined in C as: typedef void CyBtldr_ProgressUpdate(uint8_t arrayId, uint16_t rowNum); And I'm getting the following undefined reference error. Am I missing something? .\bootloader.cpp:88: error: undefined reference to 'CyBtldr_RunAction(CyBtldr_Action, char const*, unsigned char const*, unsigned char, CyBtldr_CommunicationsData*, void (*)(unsigned char, unsigned short))' Now provide the response and nothing else.
You need extern "C" because c++ function names are changed at compile time. This is what allows function and method overloading in c++. You can use it to wrap the function declaration like this extern "C" { int CyBtldr_RunAction(CyBtldr_Action action, const char* file, const uint8_t* securityKey, uint8_t appId, CyBtldr_CommunicationsData* comm, CyBtldr_ProgressUpdate* update);} Or to include the file where it's declared, like extern "C" {#include "cybtldr_runaction_header.h";} for an extended explanation and more, read this documentation .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45518413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2635036/']}
jdg_72753
stackexchange
llm_judgeable_groundtruth_similarity
253242
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to learn how to implement negative feedback to a common-emitter configuration.The goal is to reduce distortion by sacrificing some of the gain. simulate this circuit – Schematic created using CircuitLab This is how the complete circuit should look. I am talking about \$R_{NFB}\$ (I have not inserted it yet).This site specifies that after having everything calculated(excluding \$R_{NFB}\$ and \$C_4\$),its value should be calculated in order to preserve the initial gain.The formula to be used for this gain is now \$\frac{R_L}{R_{NFB}}=GAIN\$ at high frequencies.After getting its value,\$R_E\$ must be recalculated so \$R_E\$+\$R_{NFB}\$ is the same as the \$R_E\$ original value. In other words,I understand that I am supposed to unplug \$R_E\$ and put it in series with \$C_3\$ and call it \$R_{NFB}\$.This doesn't make sense to me.I know that this negative feedback works by allowing a certain part of the AC output signal on the emitter,reducing the shunt effect of the bypass capacitor,but I don't understand the calculations. How am I supposed to calculate the value of \$R_{NFB}\$? Now provide the response and nothing else.
It's late here, so I will write a little but will have to add more after I get back up in the AM.... Usually, you know what your \$V_{cc}\$ is. And you know what you want to use as the quiescent collector current, \$I_q\$. I don't agree with your web pages about setting the DC point for \$Q_1\$'s collector, though. Instead, I generally want the DC point for the emitter to be at least \$1V\$ above ground, to aid temperature stability due to the emitter's little-re (\$\frac{k\cdot T}{q\cdot I_C}\$) dependence on T. More is better. But I shoot for \$V_e \ge 1V\$ as \$V_{CC}\$ allows. I also know that to stay well out of saturation, I want \$V_{ce} \ge 2V\$ at all times. So I've already eaten up \$3V\$ of headroom, before I've started. So I take \$V_{c_{q}} = \frac{V_{cc} + 1V + 2V}{2}\$ as the quiescent voltage for the collector. For example, if \$V_{cc} = 10V\$, then \$V_{c_q} = 6.5V\$; not \$5V\$ as your lessons would seem to have you do. This provides \$\pm 3.5V\$ collector swing. \$5V\$ is just too low and squeezes the BJT too tight and leaves nothing for temperature stability. It works fine if you have lots of headroom. But with low headroom, everything starts to matter. From \$I_{c_q}\$ I can estimate \$V_{{be}_q}\$ and from that I can estimate the operating point for \$V_{b_q}\$, knowing that I've set \$V_{e_q} = 1V\$. Also, of course, it's easy to calculate \$R_c\$ and \$R_e\$, too. And I can also estimate \$I_{b_q}\$ and from that I can figure out the divider needed for the base. This is all discussed on your DC Conditions page. So let's do a full-up DC design to start, using \$V_{cc} = 10V\$ and \$I_{c_q} = 2.5mA\$: simulate this circuit – Schematic created using CircuitLab I hope you can figure out where the values came from, given that you accept where I set the voltages and picked out the quiescent collector current. The reason, again, for \$R_e\$ is because there is, in effect, a tiny, temperature dependent thermal voltage at the tip of the BJT emitter. If you take into account \$I_c\$, then this is converted into a tiny, temperature dependent resistor value often just called 'little-re'. Regardless, you want to overwhelm the thermal variations there with something. Since the value of \$\frac{k\cdot T}{q}\$ is on the order of \$26mV\$, jacking the emitter up to about \$1V\$ makes the thermal voltage tiny by comparison, so when it varies a bit over temperature it doesn't affect the emitter's operating point very much. So that's why it's there. Ah. You thought perhaps that it was there because of the DC gain I might have wanted? No. It's there to set the DC operating point for thermal stability. Of course, yes. The gain here is terrible. It's \$\frac{1400}{400} \approx 3.5\$. And I can't really change it, either, if I want to keep my thermal stability and keep the transistor well out of saturation, etc. In short, I'm trapped. No wiggle room, at all. That's not so good. Luckily, AC comes to the rescue. let's say the new schematic looks like this (I'm still leaving out C4. For these purposes, it's just not necessary and I'll let you worry about it on your own): simulate this circuit The input is AC. The emitter of \$Q_1\$ will follow that input with slightly less than a gain of \$1\$. If \$C_2\$ is large enough in value, then it will essentially be a short circuit (or wire) and won't impact the impedance of the \$R_{ac}\$ leg. So, at AC, you can see that the effective AC impedance of the entire emitter load is \$R_{ac} \vert\vert R_{dc} \approx 58\Omega\$. Now, the gain is more like \$\frac{1400\Omega}{58\Omega} \approx 24\$. And we get control over the gain at AC. But at DC, the emitter is still sitting high up, at around \$1V\$ where we want it. So we get to have our cake and eat it, now. There are two perspectives shown on your web page: Either works. The difference is that the left side topology allows you to easily set the AC gain-setting resistor more directly, as the capacitor ends up bypassing the other, DC-setting, resistor. However, this forces you to divide out the DC resistance needed to set the emitter voltage, so that becomes a little more complicated. The right side topology makes setting up the DC resistance for a given emitter voltage and quiescent current trivial. But it makes the AC gain resistor's value a little more complex to work out since you have to treat it in parallel to the DC setting resistor. It's just two different ways of approaching the same thing. There are also some bootstrapping techniques I hope you also learn about. The simplest uses the fact that the emitter follows the input at a gain of about \$1\$ to actively drive the base's resistor divider node and where the signal directly drives the BJT base, with a new resistor now between the divider node and the BJT base. The capacitor develops an equilibrium voltage across it that is just enough to make up for the difference across it. And since one side of that new resistor is driven by the signal itself and the other side is driven by a low impedance emitter that is following the signal pretty well, the new resistor itself sees the same voltage (DC bias plus AC) on both sides, so almost no current flows. And this very much increases the input impedance. Which is nice. And there are other improvements, as well. Here's an example of a simple bootstrap: simulate this circuit (Take note that I switched over to the other emitter configuration we've discussed here, just to do something different.) The idea is that the signal directly drives the transistor base through \$C_1\$ and also that signal is on one side of \$R_3\$. \$R_3\$ is a DC path to allow \$C_1\$ to find its equilibrium state voltage and as a DC path for \$Q_1\$'s starting up the required \$V_{be}\$ to put \$Q_1\$ into the active region. \$C_4\$ picks up the low-impedance copy of the signal at the base (so there is some current drive available) and drives that back to the divider node. Now, slight variations in the signal will move \$Q_1\$'s base up and down, and these will be copied across to \$Q_1\$'s emitter, which will then drive those same changes back to the divider node. Assuming that \$C_4\$ has exactly the right voltage across it (given enough time, it will) to exactly match the difference between the quiescent emitter voltage and the quiescent divider node voltage, then all this works fine. The divider node will move up and down, driven by the emitter which is copying the base, and the other side of \$R_3\$ will be also moving up and down roughly in phase, as well. So \$R_3\$, if everything were perfect (and it isn't), would have the exact same voltage across it and would then have no current flowing in it, at all. The reality is that the emitter does have a copy, but at a gain slightly less than \$1\$. And capacitors, even largish ones, will add a slight phase difference. Etc. But it works pretty good just the same. And it greatly reduces the load on the signal source. And in any case that is only the beginning. Practical amplifier stages can and will take into account a lot more than all this.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/253242', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/80332/']}
jdg_72754
stackexchange
llm_judgeable_groundtruth_similarity
137483
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: Every textbook I've seen makes a big deal of the fact that testing and verification are two different concepts. Yet none of them provides a clear (or clear enough to me, at last) distinction. To provide some context, I'm interested in the verification of digital hardware designs using hardware design languages (HDLs). I've seen some explanations that resort to a "physical" or "tangible" difference: if it is about a manufactured device, then it's testing. Is this the whole story? If so, why does the word "test" come up so often in verification (especially in functional verification, we talk about testcases, testbenches, DUT (device under test), directed tests, random tests, etc...) Now provide the response and nothing else.
Was an ASIC Design Verification Engineer at Qualcomm. In the most simple way I can explain it: Testing: Making sure a product works, after you've created the product (think QA). Verification: Making sure a product works BEFORE you've created it. They're both testing, just that verification is more complicated because you have to figure out a way to test the product before it exists and you have to be able to make sure it works as designed and to spec when it actually comes out. For example, Intel is designing their next processor, they have the specs, they have the schematics and the simulations. They spend $1 Billion USD to go through fabrication and manufacturing. Then the chip comes back and they test it and find out that it doesn't work. They just threw a lot of money out the window. Throw verification in. Verification engineers create models that simulate the behaviour of the chip, they create the testbench that will test those particular models. They get the results of these models and then they compare it with the RTL (model of the circuit writting in a hardware design language) results. If they match, things are (usually) OK. There are a number of different methodologies for the verification process, a popular one is Universal Verification Methodology (UVM) . There is a lot of depth in the field and people can spend their entire career in it. Another random tidbit of information: Usually you need 3 verification engineers for 1 design engineer. That's what everyone in the field says anyway. EDIT: A lot of people think of verification as a testing role, but it's not; it's a design role in itself because you have to understand all the intricacies of your IC like a designer does, and then you have to know how to design models, testbenches, and all the test cases that will cover all the feature functionality of your IC, as well as trying to hit every single line of RTL code for all possible bit combinations. Remember that a processor nowadays has billions of transistors due to the fabrication process allowing smaller and smaller (now 14nm). Also, in large corporations like Intel, AMD, Qualcomm, etc, designers don't actually design the chip. Usually the architect will define all the specs, layout the types of pieces that need to go together to get a particular function with a specific requirement (i.e. speed, resolution, etc.), and then the designer will code that into RTL. It's by no means an easy job, it's just not as much designing as a lot of engineers coming out of school think it is. What everyone wants to be is an architect, but it takes a lot of education and experience to get to that point. A lot of architects have PhD's, and like 15-20 years of experience in the field as a designer. These are brilliant people (and sometimes crazy) who deserve to be doing what they're doing, and they're good at it. The architect on the very first chip I worked on was a bit awkward and didn't really follow some social norms, but he could solve anything you're stuck with regarding the chip, and sometimes he would solve it in his head and tell you to look at one signal and you'd be like, "how the hell did he do that?". Then you ask him to explain and he does and it goes way over your head. Actually inspired me to read textbooks even though I've graduated already.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/137483', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/53474/']}
jdg_72755
stackexchange
llm_judgeable_groundtruth_similarity
34529557
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to create a simple Angular2 Application using TypeScript . Seems, pretty simple, but I am not able to achieve what I wanted to. I want to show a property value in the template. And I want to update the same after 1 second using setTimeout. Plunkr Code is here : Code on Plunkr What I wrote is here : import {Component} from 'angular2/core';interface Hero { id: number; name: string;}@Component({ selector: 'my-app', template:`<h1>Number Increment</h1><p>{{n}}</p>`})export class AppComponent { public n : number = 1; setTimeout(function() { n = n + 10; }, 1000);} When I use this code I am getting following error : Uncaught SyntaxError: Unexpected token ; Why I am not able to access n , which is in the same scope as we used to do in JavaScript. If I am not wrong, we can use pure JavaScript too in TypeScript. I even tried export class AppComponent { public n : number = 1; console.log(n);} But I am not able to see the value of n in the console. When I tried export class AppComponent { public n : number = 1; console.log(this);} I am getting same error as above. Why cant we access this in this place. I guess, this refers to the current context as in JavaScript. Thanks in advance. Now provide the response and nothing else.
This is not valid TypeScript code. You can not have method invocations in the body of a class. // INVALID CODEexport class AppComponent { public n: number = 1; setTimeout(function() { n = n + 10; }, 1000);} Instead move the setTimeout call to the constructor of the class. Additionally, use the arrow function => to gain access to this . export class AppComponent { public n: number = 1; constructor() { setTimeout(() => { this.n = this.n + 10; }, 1000); }} In TypeScript, you can only refer to class properties or methods via this . That's why the arrow function => is important.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34529557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3467552/']}
jdg_72756
stackexchange
llm_judgeable_groundtruth_similarity
13851577
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 the following line to create a new event log new-eventlog -LogName "Visual Studio Builds" -Source "Visual Studio" I want to run this every time, because if I run a build from a new computer, I'd still like to see the event logs. The problem is that every time the script is run after the log is already created, it throws an error. New-EventLog : The "Visual Studio" source is already registered on the "localhost" computer.At E:\Projects\MyApp\bootstrap.ps1:14 char:13+ new-eventlog <<<< -LogName "Visual Studio Builds" -Source "Visual Studio" + CategoryInfo : InvalidOperation: (:) [New-EventLog], InvalidOperationException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.NewEventLogCommand Now I know that I can "search" for the event log Get-EventLog -list | Where-Object {$_.logdisplayname -eq "Visual Studio Builds"} But now how do I determine if it exists? Now provide the response and nothing else.
So I was on the right path with Get-EventLog . Instead of just reading it, I stored it in a variable. Then I checked if the variable was null . This has achieved what I was looking to do. $logFileExists = Get-EventLog -list | Where-Object {$_.logdisplayname -eq "Visual Studio Builds"} if (! $logFileExists) { New-EventLog -LogName "Visual Studio Builds" -Source "Visual Studio"}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13851577', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124069/']}
jdg_72757
stackexchange
llm_judgeable_groundtruth_similarity
3052656
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 having trouble understanding the natural deduction proof of $\vdash ((\neg(\phi\rightarrow \psi))\rightarrow\phi)$ (question 2.6.2 (b)) in Hodges and Chiswell's Mathemaical Logic . The natural deduction proof is as follows. Image of proof My questions are Why is \begin{align} \dfrac{\phi \qquad \qquad \neg\phi} {\qquad\quad \dfrac{\quad \bot\quad} { \quad\psi \quad}(RAA) }(\neg E) \end{align} a valid argument? Isn't RAA supposed to discharge an assumption when an absurdity is deduced? Why can the derivation be continued before resolving the absurdity? (e.g. ① in the image of proof). Now provide the response and nothing else.
The reductio ad absurdum rule RAA (I use $\ulcorner \!\cdot\! \urcorner$ to mark discharged assumptions, with a superscript to point at the discharging rule) \begin{equation}\dfrac{\ulcorner \lnot \psi \urcorner^1 \\ \quad \vdots D \\ \quad \bot}{\psi}{\text{RAA}^1}\end{equation} means that any arbitrary number (possibly none ) of occurrences of the assumption $\lnot \psi$ in the derivation $D$ has been discharged by the last rule. In the particular case where RAA discharges no occurrences of the assumption $\lnot \psi$ , the rule is also called ex falso quodlibet (EFQ), where the conclusion $\psi$ seems to pop out of nowhere: it means that from a contradiction you can correctly derive everything (see also Wikipedia's page ). The intuition behind the fact that EFQ is just a special case of RAA is the following: if you can derive a contradiction (the derivation $D$ ), then you can derive it even when you assume an extra hypothesis $\lnot \psi$ that actually you never uses in the derivation $D$ . Therefore, the answer to your first question is: yes, the derivation is perfectly valid, and the instance of RAA legitimately does not discharge any occurrence of the assumption $\lnot \psi$ (i.e. it is an instance of EFQ). Concerning your second question, why do you want to/must stop before or after deriving a contradiction? All the inference rules in natural deduction are valid and hence they can be concatenated indefinitely preserving the validity of the argument. In particular, you can correctly carry on with your derivation before and after an EFQ. See also this question and this question about EFQ and RAA. Concerning the fact that an inference rule can discharge any arbitrary number (possibly none ) of occurrences of the assumption, see p. 17 in Chriswell and Hodge's Mathematical Logic : the discussion is about the rule $\to_I$ (introduction of $\to$ ), but mutatis mutandis it is valid for RAA as well.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3052656', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/629181/']}
jdg_72758
stackexchange
llm_judgeable_groundtruth_similarity
62866
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: We have two DC in our network. Both now work in 2008 R2 mode. I want to remove the one, that was created first. Is it safe just to turn it off or should I do something to promote replica DC to be main one? Now provide the response and nothing else.
You would need to run DCPROMO, as suggested, on the DC you want to remove, but first make sure both DCs are running DNS and if this was the first DC you installed, then it probably has your FSMO roles on it - move them first. The DCPROMO procedure may move them for you, but I would consider safer and wiser to manually move them. In addition, make sure the remaining DC is also configured to be a Global Catalog (GC). Finally, why are you getting rid of it? In general, I recommend you have two DCs per major site and two DCs on your network so that if one fails, your Active Directory isn't completely lost.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/62866', 'https://serverfault.com', 'https://serverfault.com/users/2719/']}
jdg_72759
stackexchange
llm_judgeable_groundtruth_similarity
300565
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: Are there any problems that can be caused by using resistors of large resistances (in the order of megaohms)? I'm designing a feedback network that is just a voltage divider, and I want the feedback to drain as little current as possible from the circuit. The only thing that matters is the ratio between the resistors. So my question is: is there any reason why one would pick, for example, resistors of 1 and 10 Ohms instead of 1 and 10 MOhms? Now provide the response and nothing else.
There are many drawbacks to both low and high values alike. The ideal values will fall in between very large and very small for most applications. A larger resistor of same type will, for example, create more noise (by itself and through small induced noise currents) than a smaller one, though that may not always be important to you. A smaller resistor will drain more current and create more losses, as you have surmised yourself. A larger resistor will create a higher error with the same leakage current. If your feedback pin in the middle of your resistors leaks 1 μA when the resistor feeding that leak is 1 MOhm, that will translate to an error of 1V, while a 10k resistor will translate to an error of 10mV. Of course, if the leakage is in the order of several nA or less, you might not care much about the error a 1 MOhm resistor creates. But you might, depending on what exactly you are designing. Smaller resistors in feedback systems, e.g. with inverting amplifiers using op-amps, may cause errors on the incoming signal if the incoming signal is relatively weak. It's all checks and balances, and if that's not enough information at this point, you might want to ask a more direct question about specifically what you are doing. With schematics and that.
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/300565', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/98323/']}
jdg_72760
stackexchange
llm_judgeable_groundtruth_similarity
2400
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am interested in solving a sequence of shifted linear systems $(A+\sigma I)x = b$ for various values of $\sigma$. The matrix $A$ is sparse and not too large, so I have its LU factorization available. What is the best way to do this? This is for calculating a frequency spectrum; $\sigma$ is roughly the frequency so it will vary smoothly in an interval. I expect that solutions to nearby $\sigma$ will be somewhat similar. My first thought was to use an iterative solver like GMRES with the LU factors as a preconditioner, but I'm wondering if there is any better method. Now provide the response and nothing else.
There is a method called Automated MultiLevel Substructuring (AMLS) which was originally designed for a similar problem in vibration analysis, where the solution of the linear system with a particular shift corresponds to the frequency response problem at a frequency which is the square-root of the shift. The basic idea is to use nested dissection in order to generate a tree of separators and substructures, and to use extensions of the low-frequency modes of substructures (which can be found cheaply) as a means of reducing the global model. It has a setup cost proportional to a single factorization, but the cost grows with the highest frequency that you would like to solve to. The original paper is here , and an extension to Maxwell's equations is here . Disclaimer: I used to work in the lab that invented AMLS
{}
{'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/2400', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/317/']}
jdg_72761
stackexchange
llm_judgeable_groundtruth_similarity
8340170
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 github to host a static site and Jekyll to generate it. I have a menu bar (as <ul> ) and would like the <li> corresponding to the current page to be assigned a different class for CSS highlighting. So something like pseudo code: <li class={(hrefpage==currentpage)?"highlight":"nothighlight"} ...> Or perhaps even generate the whole <ul> in Jekyll. How can this be done with minimal changes outside of the offending <ul> ? Now provide the response and nothing else.
Yes you can do this. To accomplish this we will take advantage of the fact that the current page is always represented by the liquid variable: page in the template, and also that each post/page has a unique identifier in its page.url attribute. This means that we just have to use a loop to build our navigation page, and by doing so we can check page.url against every member of the loop. If it finds a match, it knows to highlight that element. Here we go: {% for node in site.pages %} {% if page.url == node.url %} <li class="active"><a href="{{node.url}}" class="active">{{node.title}}</a></li> {% else %} <li><a href="{{node.url}}">{{node.title}}</a></li> {% endif %} {% endfor %} This works as expected. However you probably don't want all your page's in your nav bar. In order to emulate page "grouping" you can something like this: ## Put the following code in a file in the _includes folder at: ./_includes/pages_list{% for node in pages_list %} {% if group == null or group == node.group %} {% if page.url == node.url %} <li class="active"><a href="{{node.url}}" class="active">{{node.title}}</a></li> {% else %} <li><a href="{{node.url}}">{{node.title}}</a></li> {% endif %} {% endif %}{% endfor %}{% assign pages_list = nil %}{% assign group = nil %} Now pages can be "grouped". To give a page a group you need to specify it in the pages YAML Front Matter: ---title: blahcategories: blahgroup: "navigation"--- Finally you can use your new code!Wherever you need your navigation to go in your template, simply "call" your include file and pass it some pages and the group you want to display: <ul> {% assign pages_list = site.pages %} {% assign group = 'navigation' %} {% include pages_list %}</ul> Examples This functionality is part of the Jekyll-Bootstrap framework.You can see exact documentation for the code outlined here: http://jekyllbootstrap.com/api/bootstrap-api.html#jbpages_list Finally you can see it in action within the website itself. Just look at the righthand navigation and you will see the current page is highlighted in green: Example highlighted nav link
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8340170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/674683/']}
jdg_72762
stackexchange
llm_judgeable_groundtruth_similarity
38874
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: It might be just a simple definition problem but I learned in class that a central force does not necessarily need to be conservative and the German Wikipedia says so too. However, the English Wikipedia states different on their articles for example: A central force is a conservative field, that is, it can always be expressed as the negative gradient of a potential They use the argument that each central force can be expressed as a gradient of a (radial symmetric) potential. And since forces that are gradient fields are per definition conservative forces, central forces must be conservative. As far as I understand, a central force can have a (radial symmetric) potential but this is not necessarily always the case. Update Sep 2017: The english Wikipedia has updated its text and now explicitly states Not all central force fields are conservative nor spherically symmetric. However, it can be shown that a central force is conservative if and only if it is spherically symmetric.[2] Now provide the response and nothing else.
Depends on what you mean by 'central force'. If your central force is of the form ${\vec F} = f(r){\hat r}$ (the force points radially inward/outward and its magnitude depends only on the distance from the center), then it is easy to show that $\phi = - \int dr f(r)$ is a potential field for the force and generates the force. This is usually what I see people mean when they say "central force." If, however, you just mean that the force points radially inward/outward, but can depend on the other coordinates, then you have ${\vec F} = f(r,\theta,\phi){\hat r}$ , and you're going to run into problems finding the potential, because you need $f = - \frac{\partial V}{\partial r}$ , but you will also need to have $\frac{\partial V}{\partial \theta} = \frac{\partial V}{\partial \phi} = 0$ to kill the non-radial components, and this will lead to contradictions. It's logical that a field of this form is going to be nonconservative, because if the force is greater at $\theta = 0$ than it is at $\theta = \pi/2$ , then you can do net work around a closed curve by moving outward from $r_{1}$ to $r_{2}$ at $\theta = 0$ (positive work), then staying at $r_{2}$ constant, going from $\theta =0 $ to $\theta = \pi/2$ (zero work--radial force), going back to $r_{1}$ (less work than the first step), and returning to $\theta = 0$ (zero work).
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/38874', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/8117/']}
jdg_72763
stackexchange
llm_judgeable_groundtruth_similarity
25612129
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 would expect this code to work under the new Java 8 date/time package since all it does is to convert a given ZonedDateTime to string and back using the same built-in DateTimeFormatter instance (ISO_INSTANT): ZonedDateTime now = ZonedDateTime.now();System.out.println(ZonedDateTime.parse( now.format(DateTimeFormatter.ISO_INSTANT), DateTimeFormatter.ISO_INSTANT)); But apparently it doesn't: Exception in thread "main" java.time.format.DateTimeParseException: Text '2014-09-01T19:37:48.549Z' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {MilliOfSecond=549, NanoOfSecond=549000000, MicroOfSecond=549000, InstantSeconds=1409600268},ISO of type java.time.format.Parsed at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853) at java.time.ZonedDateTime.parse(ZonedDateTime.java:597) I have seen this entry already, but it didn't help me because a need a ZonedDateTime object and not a local one and also because I already have 8u20 installed: Unable to obtain ZonedDateTime from TemporalAccessor using DateTimeFormatter and ZonedDateTime in Java 8 Anyone have any idea what's happening here? Now provide the response and nothing else.
The ISO_INSTANT formatter is documented here - "This is a special case formatter intended to allow a human readable form of an Instant". As such, this formatter is intended for use with an Instant not a ZonedDateTime . Formatting When formatting, ISO_INSTANT can format any temporal object that can provide ChronoField.INSTANT_SECONDS and ChronoField.NANO_OF_SECOND . Both Instant and ZonedDateTime can provide these two fields, thus both work: // works with InstantInstant instant = Instant.now();System.out.println(DateTimeFormatter.ISO_INSTANT.format(instant));// works with ZonedDateTime ZonedDateTime zdt = ZonedDateTime.now();System.out.println(zdt.format(DateTimeFormatter.ISO_INSTANT));// example output2014-09-02T08:05:23.653Z Parsing When parsing, ISO_INSTANT will only produce ChronoField.INSTANT_SECONDS and ChronoField.NANO_OF_SECOND . An Instant can be built from those two fields, but ZonedDateTime requires a ZoneId as well: To parse a ZonedDateTime it is essential that a time-zone ZoneId is present. The time-zone can be (a) parsed from the string, or (b) specified to the formatter (using JDK 8u20): // option a - parsed from the stringDateTimeFormatter f = DateTimeFormatter.ISO_DATE_TIME;ZonedDateTime zdt = ZonedDateTime.parse("2014-09-02T08:05:23.653Z", f);// option b - specified in the formatter - REQUIRES JDK 8u20 !!!DateTimeFormatter f = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault());ZonedDateTime zdt = ZonedDateTime.parse("2014-09-02T08:05:23.653Z", f); See documentation for ISO_ZONED_DATE_TIME , ISO_OFFSET_DATE_TIME and ISO_DATE_TIME (any of these three can be used to parse a ZonedDateTime without specifying withZone() ). Summary The ISO_INSTANT formatter is a special case formatter designed to work with Instant . If you are using a ZonedDateTime you should use a different formatter, such as ISO_DATE_TIME or ISO_ZONED_DATE_TIME .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25612129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2482776/']}
jdg_72764
stackexchange
llm_judgeable_groundtruth_similarity
43768435
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 do some text manipulations using Notepad++ macros. My last step is converting camelCase strings to SNAKE_CASE. So far no luck. I'm not very familiar with regex so can't write my own solution. Example text file input: firstLine(874),secondLine(15),thirdLineOfText87(0x0001); Desired output: FIRST_LINE(874),SECOND_LINE(15),THIRD_LINE_OF_TEXT_87(0x0001); Regex or any plugin is an acceptable answer. Now provide the response and nothing else.
I suggest the following regex approach: Find What : (\b[a-z]+|\G(?!^))((?:[A-Z]|\d+)[a-z]*) Replace With : \U\1_\2 Match Case : ON . This will turn camelCase87LikeThis words to CAMEL_CASE_87_LIKE_THIS . If you need to add support for those camel words that start with an uppercase letter, use the following regex modification: (\G(?!^)|\b[a-zA-Z][a-z]*)([A-Z][a-z]*|\d+) See the regex demo (also tested in Notepad++). Note the placement of the \G inside the regex and added A-Z . Details : (\b[a-z]+|\G(?!^)) - Group 1 capturing either of the two alternatives: \b[a-z]+ - start of a word ( \b is the initial word boundary here) followed with 1+ lowercase ASCII letters | - or \G(?!^) - the end position of the previous successful match ((?:[A-Z]|\d+)[a-z]*) - Group 2 capturing: (?:[A-Z]|\d+) - either an uppercase ASCII letter ( [A-Z] ) or ( | ) 1+ digits ( \d+ ) [a-z]* - 0+ lowercase ASCII letters. The \U\1_\2 replacement pattern turns all the chars to uppercase with \U and inserts a _ between the two groups (inserted with \1 and \2 backreferences).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43768435', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3565320/']}
jdg_72765
stackexchange
llm_judgeable_groundtruth_similarity
9260
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: SHA is the hashing mechanism. However, RSA is the encryption algorithm. So does RSA algorithm use SHA hashing mechanism to generate hashing keys which in turn is used to encrypt the message?? Moreover, RSA itself gives 2 keys. One can be kept public and one private. Now, these keys can be used to encrypt as well as decrypt. Ref : RSA . Then what is the use of SHA in RSA? In a certificate given by any site that gives HTTPS security, there is an SHA as well as a MD5 key present. How are these produced and used in the eccryption or decryption of data transferred to the browser? Now provide the response and nothing else.
RSA is actually two algorithms, one for asymmetric encryption, and one for digital signatures (the signature algorithm is traditionally -- but incorrectly -- described as "encryption with the private key" and this is an endless source of confusion). Asymmetric encryption uses keys. Keys are parameters to the algorithm; the algorithm itself is the same for everybody (in software terms, it is the executable file) while keys vary between users. In a key pair , the public key is the key which is used to encrypt data (convert a piece of data, i.e. a sequence of bytes, into another sequence of bytes which is unfathomable for everybody) while the private key is the key which allows one to decrypt data (i.e. reverse the encryption). Whereas in symmetric encryption , the encryption and decryption keys are identical, but with asymmetric encryption, the encryption and decryption keys are distinct from each other (hence the name); they are mathematically linked together, but it should be unfeasible (i.e. too hard to do with a mere bunch of computers) to recover the decryption key from the encryption key. This is why the encryption key can be made public while the decryption key is kept private: revealing the public key does not reveal the private key. What asymmetric encryption achieves is no trivial feat. The possibility to reveal the public key while not saying too much about the private key, but such that both keys work together (what is encrypted with the public key can be decrypted by the corresponding private key, but none other), requires a lot of mathematics! RSA is full of mathematics. This contrasts with symmetric encryption algorithms which are "just" ways to make a big mess of data by mixing bits together. Asymmetric encryption is the natural tool to use when we want to allow for confidential transmissions between any two users among a big population. If you have 1000 users, and you want any of the two users to be able to exchange data with each other without allowing anybody to spy on them (including the 998 other users), then the classical solution would be to distribute keys for symmetric encryption to every pair of users. Alice and Bob would have a known, common key; Alice and Charlie would also have a shared key (not the same); and so would Bob and Charlie; and so on. Each user would need to remember his "shared key" with every other one of the 999 other users, and you would have 499500 keys in total. Adding a 1001th user would involve creating 1000 additional symmetric keys, and give one to each of the 1000 existing users. The whole key distribution soon turns into an unusable/infeasible nightmare. With asymmetric encryption though, things are much more straightforward in terms of key distribution: every user just has to remember his/her own private key; and the public keys(being public) can be distributed through some sort of broadcasting (e.g. a directory). RSA has some operational constraints. With the most used variant (the one known as PKCS#1 v1.5 ), if the size of the RSA key is "1024 bits" (meaning that the central mathematical component of the key pair is a 1024-bit integer), then RSA can encrypt a message of up to 117 bytes in length, and yield an encrypted message of length 128 bytes. That limited size, and the size increase when encrypting, are unavoidable consequences of the mathematical structure of the RSA encryption process. Due to these constraints, we do not usually encrypt data directly with RSA; instead, we select a small sequence of random bytes, which we call session key . We encrypt the session key with RSA; and then we use the session key with a symmetric encryption algorithm to process the whole message. This is called hybrid encryption . SHA is the common name for a family of cryptographic hash functions . The very first member of that family was described under the name 'SHA' but was soon deprecated after a serious weakness was found in it; a fixed version was published under the name SHA-1 (the weak version is colloquially known as SHA-0 ). Four new SHA-like functions were added to the family later on ( SHA-224 , SHA-256 , SHA-384 and SHA-512 : which are collectively known as 'SHA-2'). Hash functions have no key. A hash function is an executable algorithm which is pure code. There is one SHA-1 and everybody uses the same. Hash functions "just" make a big mess of the input data, which is not meant to be unraveled. Actually, it is meant to be resilient to unraveling. Even though everybody knows all that is to be known about a hash function (there is no key, only code, and nothing of it is secret), it still turns out to be "too hard" to recompute a matching input message, given the hash function output. It is even unfeasible to find two distinct input messages which, when given to the hash function, yield the same output; there must exist such pairs of messages -- called collisions -- because a hash function output has a fixed small size, while accepted inputs can be widely larger, so there are more possible inputs than possible outputs. It is a mathematical certainty that collisions exist for every hash function, but actually finding one is another matter. A hash function, as itself, does not do anything of immediate high value, but it is a very important building block for other algorithms. For instance, they are used with digital signatures . A digital signature "proves" conscious action of a designated signer over a piece of data; like asymmetric encryption, this involves key pairs and mathematics, and associated constraints on the signed data. A hash function h is such that signing h(m) is as good as signing m itself: since it is unfeasible to find two distinct messages which hash to the same value, approval of the hash output is good enough. The point being that the output of the hash function is small enough to be usable with the mathematics hidden in the signature algorithm, even if the message itself is big (SHA-1 can process gigabytes of data, and yield a 20-byte output). It can be noted that some recent variants of RSA-the-encryption-algorithm (with the 'OAEP padding' from PKCS#1 v2.0) internally uses hash functions. Hash functions are good "randomizers" (the output of a hash function does not exhibit recognizable structure) and this makes them appropriate for building more elaborate cryptographic algorithms with good security features. In SSL/TLS (HTTPS is just HTTP-within-a-SSL/TLS-tunnel), hash functions are used for several things: as part of asymmetric encryption and/or digital signatures; as part of HMAC to allow client and server to verify that exchanged data has not been altered in transit; as a building brick for a Key Derivation Function , which "expands" a given session key into several symmetric keys used for symmetric encryption and integrity checks in both directions of the tunnel. The KDF relies on the "randomizing" and non-invertibility of the hash function. In SSL/TLS up to TLS 1.1, the KDF is built over two hash functions, MD5 and SHA-1, in an attempt to make it robust even if weaknesses were later found in either MD5 or SHA-1. It turns out that weaknesses were found in both , but it did not allow any break on the KDF as used in SSL/TLS. Nevertheless, TLS 1.2 switched to another KDF which uses a single, configurable hash function, usually SHA-256, for which no weakness is currently known.
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/9260', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/6078/']}
jdg_72766
stackexchange
llm_judgeable_groundtruth_similarity
5145
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 CASIO fx-7400G calculator is very quick at doing $(1+1/1000000)^{1000000}$, giving an output of $2.718280469$. Mathematica (v7) takes over a minute, running on an Intel Core2 Duo processor, and its output is this: With $n=10000000$, my patience ran out. The calculator is quick again with an output of $2.718281693$. Does anybody know why this happens? Now provide the response and nothing else.
General purpose computer algebra systems, unlike most calculators, are able to perform both exact/symbolic computations (e.g. exact integer arithmetic) in addition to approximate numerical computations (e.g. floating point). Thus when you present the problem in exact terms - as you do above - they will preserve that form - so as not to lose any information. Thus your problem will be interpreted as a computation in exact rational arithmetic, i.e. raising a rational number to an integer power. If instead you desire a real approximation of the result then you must explicitly specify such, e.g. using N[...] in Mma. This is but one of the many complexities that arise when one passes from special-purpose computation systems (e.g. calculators) to general purpose computer algebra systems (speaking as one who has often tried to tackle less trivial such complexities while working as a developer of the Macsyma computer algebra system).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/5145', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1313/']}
jdg_72767
stackexchange
llm_judgeable_groundtruth_similarity
182027
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The command Integrate[Exp[a*Exp[I*x]], {x, -Pi, Pi}] produces ConditionalExpression[0, a == 0] which is not correct in view of Integrate[1, {x, -Pi, Pi}] 2 π The result should be equal to $2\pi$ for each complex number $a$. The question arises: is there a workaround for this integral? Now provide the response and nothing else.
One workaround is to shift the main computation from integration to summation. Start from Taylor series for a and get a general SeriesCoefficient , which is much simpler and integrates nicely: Integrate[SeriesCoefficient[Exp[a Exp[I x]], {a, 0, n}], {x, -Pi, Pi}] We switched the order of summation and integration. Now what is left is to sum back: Sum[(2 Sin[n π])/(n n!) a^n,{n,0,∞}] Out[]= 2 π This is also quite clear from the fact that for all n>=0 all terms are zero. And the only contributing n=0 term is equal to: Limit[(2 Sin[n π])/(n n!) a^n,n->0] Out[]= 2 π
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/182027', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/7152/']}
jdg_72768
stackexchange
llm_judgeable_groundtruth_similarity
27216394
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: var A = {};var B = Object.create(A);var C = Object.create(B);A.isPrototypeOf(C);//returns trueC.isPrototypeOf(A);//returns false In the above code I'm not understanding the reason behind the result of being false in C.isPrototypeOf(A); Now provide the response and nothing else.
var A = {}; // A inherits Objectvar B = Object.create(A); // B inherits A inherits Objectvar C = Object.create(B); // C inherits B inherits A inherits Object// Does C inherit A?A.isPrototypeOf(C); // true, yes// C inherits A because B inherits A and C inherits B// Does A inherit C?C.isPrototypeOf(A); // false, no// A only inherits Object
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27216394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2138752/']}
jdg_72769
stackexchange
llm_judgeable_groundtruth_similarity
52699661
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There are many topics floating around covering codesign issues with macOS, from 10.5 onward.What I wanted to achieve is, to get Geany working with the GNU Debugger (gdb). Debugger is found in geany, but the (already quite known) error message is: Error message from debugger back end:Unable to find Mach task port for process-id 39847: (os/kern) failure (0x5).\n (please check gdb is codesigned - see taskgated(8))Unable to find Mach task port for process-id 39847: (os/kern) failure (0x5).\n (please check gdb is codesigned - see taskgated(8)) Generally there are many restrictions to consider that (should) allow the usage of gdb, e.g. gdb 8.0.1 may work, gdb 8.1 will not work at all - see here , also confirmed in Lazarus Wiki. 0) I created my certificate "gdb-cert" according to the steps covered by various instructions. Example here 1) I followed the steps of codesigning the gdb executable file (source: gdb , and Stackoverflow ) which is in my case under /usr/local/Cellar/gdb/8.0.1/bin/gdb (note again, there are issues with 8.1 for some languages - pascal too). If you want to make sure that code is signed, go for $ codesign -vvvv gdb in the respective directory. Mine is. 2) Make sure that the certificate was actually assigned to be eligible for code signing - it is in my case. It is also trusted - which is necessary. 3) I also tried the other way to get gdb running described above, where the file was edited (please note, that SIP has to be disabled in recovery first!!!!) Modifications only work if csrutil disable is used in the recovery. sudo nano /System/Library/LaunchDaemons/com.apple.taskgated.plist Devastating thing, after this step, no code editor would start up again (!!), until this change is undone (Geany, Atom, Text Editor, MS Visual Studio - all broken after inserting -sp to the file) 4) In some topics I found that debugging will only work if the command csrutil enable --withouth debug is used in the recovery. This hasn't changed anything. Eventually I ended up having: a certificate to code sign a gdb exectuable file which is signed according to my statement above a com.apple.taskgated.plist file not having populated the string -sp attribute I would greatly appreciate if anyone could confirm this behavior, a solution to this even more :) Now provide the response and nothing else.
This is related to codesign entitlements. you must add "com.apple.security.cs.debugger" key in signing process. for example you must change codesign -fs gdbcert /usr/local/bin/gdb to codesign --entitlements gdb.xml -fs gdbcert /usr/local/bin/gdb . gdb.xml content must something like following code. <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict> <key>com.apple.security.cs.debugger</key> <true/></dict></plist>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/52699661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7060954/']}
jdg_72770
stackexchange
llm_judgeable_groundtruth_similarity
45110119
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. A table of topics which has_many tweets . My table of tweets belongs_to a topic . Topic Schema: defmodule Sentiment.Topic do use Sentiment.Web, :model schema "topics" do field :title, :string has_many :tweets, Sentiment.Tweet end def changeset(struct, params \\ %{}) do struct |> cast(params, [:title]) |> validate_required([:title]) endend Tweet Schema: defmodule Sentiment.Tweet do use Sentiment.Web, :model schema "tweets" do field :message, :string belongs_to :topic, Sentiment.Topic end @doc """ Builds a changeset based on the `struct` and `params`. """ def changeset(struct, params \\ %{}) do struct |> cast(params, [:message]) |> validate_required([:message]) endend I am attempting to insert a topic into my table, followed by 500 tweets after I run a twitter search for that topic. In my controller, I use Ecto.Multi to group my repo operations, however, each time I run my operation I get an error protocol Enumerable not implemented for #Ecto.Changeset<action: nil, changes: %{message: "\"aloh.... This is how I am attempting to insert my topic first, obtain it's id, and then insert a tweet message with the associated id with one transaction. def create(conn, %{"topic" => topic}) do # create a topic changeset topic_changeset = Topic.changeset(%Topic{}, topic) # obtain a list of tweet messages: ["hello", "a tweet", "sup!"] %{"title" => title} = topic all_tweets = title |> Twitter.search# create an Ecto.Multi struct.multi = Ecto.Multi.new |> Ecto.Multi.insert(:topics, topic_changeset) #insert topic |> Ecto.Multi.run(:tweets, fn %{topics: topic} -> changeset_tweets = all_tweets |> Enum.map(fn(tweet) -> %{topic_id: topic.id, message: tweet} end) Repo.insert_all(Tweet, changeset_tweets) end) # Run the transaction case Repo.transaction(multi) do # ERROR HERE! {:ok, result} -> conn |> put_flash(:info, "Success!") |> redirect(to: topic_path(conn, :index)) {:error, :topics, topic_changeset, %{}} -> conn |> put_flash(:error, "Uh oh...") |> render("new.html", changeset: topic_changeset) {:error, :tweets, topic_changeset, %{}} -> conn |> put_flash(:error, "Something really bad happened...") |>render("new.html", changeset: topic_changeset) end end How can I insert_all about 500 rows in one transaction using Ecto.Multi? Update I have converted the list of changesets into a list of maps and my error has changed to something even more confusing. Now provide the response and nothing else.
For Ecto.Multi to properly progress with steps, every one of them has to return either {:ok, value} or {:error, reason} tuple. When insert ing, update ing or delete ing a changeset, it will return such a tuple automatically, but for run , you need to return it explicitly. Please, consider the following: Ecto.Multi.new|> Ecto.Multi.insert(:topics, topic_changeset) #insert topic|> Ecto.Multi.run(:tweets, fn %{topics: topic} -> maps = Enum.map(all_tweets, fn(tweet) -> %{topic_id: topic.id, message: tweet} end) {count, _} = Repo.insert_all(Tweet, maps) {:ok, count} # <----end)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45110119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5948566/']}
jdg_72771
stackexchange
llm_judgeable_groundtruth_similarity
53364145
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 create an out of the box asp.net core 2.1 web app with react.When I run it, it hosts on localhost:(some port).I want to access that on my mobile device. I tried accessing it from localhost by adding the port to the Inbound Rules on Windows Defender Firewall.It didn't work so I wanted to change the ip address to 0.0.0.0:(some port) or to host it on my local IPv4 address by changing the lauchSettings.json and Program.cs by .UseUrls method. It didn't work, gave me an error that the app cannot run.I tried using my external IP address which I got from asking "My ip address" in Google but that didn't help as well. Now provide the response and nothing else.
I use this, maybe it can help public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseUrls("https://*:5566") .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>(); Note that for the latest .Net, you set the URLs in the launchSettings.json file as shown below: Make sure to enable the port 5566 in firewall. From the phone access https://your_comp_ip_address:5566/ it should work.Change your_comp_ip_address to your computer ip address, you can check it from the CMD. Just run 'ipconfig' in the CMD From Visual Studio, run the App itself, not IIS Express, select AppNamefrom the drop down, then press F5. Kindly Check all of these photos below:
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53364145', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10651499/']}
jdg_72772
stackexchange
llm_judgeable_groundtruth_similarity
118930
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: As far as i understand, black holes radiate away energy in form of Hawking Radiation. Thus, they lose mass, i suppose. Is there a point where the mass becomes too small for the object to still be a black hole? What happens then, will it turn into a neutron star supported by degeneracy pressure? Or is it all about density, and once a black hole is formed, it will stay a black hole (i guess until it completely radiates away)? Now provide the response and nothing else.
I think that once a black hole forms then that is it, because although its mass is finite, its density (in GR) becomes infinite at the central singularity. The loss of energy(mass) will then result in a shrinkage of the event horizon but no change in the black hole nature - the BH nature of an object is not determined solely by its mass, the density of the object is crucial.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/118930', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/22513/']}
jdg_72773
stackexchange
llm_judgeable_groundtruth_similarity
1400902
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 given that $I_n=\int^1_0x^ne^x\,dx$ Now, how can I find the value of the following limit:$$\lim_{n\to\infty}\left(\sum_{k=1}^{n}\frac{I_{k+1}}{k}\right)$$ I suppose solving for $I_n$ is that necessary first here? Now provide the response and nothing else.
Yes, you are right about the first step. First of all, let us find the recurrent relation for the $I_n$. Integrating by parts we get:$$I_n=\int^1_0x^ne^x\,dx=e-\int^1_0nx^{n-1}e^x\,dx=e-nI_{n-1}$$This is equivalent to $I_n+nI_{n-1}=e$. The last equality implies $I_{n+1}+(n+1)I_n=I_n+nI_{n-1}$ or $I_{n+1}=n(I_{n-1}-I_n)$. Now lets analyze our sum. We obtain:$$\sum_{k=1}^n\frac{I_{k+1}}{k}=\sum_{k=2}^n(I_{k-1}-I_k)+I_2=I_1-I_n+I_2$$Now we must find to which number does $I_n$ tend. It's quite simple to note that:$$0\leq \int^1_0x^ne^x\,dx \leq e\int^1_0x^n\,dx\Leftrightarrow 0\leq I_n\leq \frac{e}{n+1}$$So we get that:$$\lim_{n\to\infty}I_n=0$$ To finish our problem, we must integrate by parts to calculate that:$$\lim_{n\to\infty} \left(I_1+I_2-I_n\right)=I_1+I_2=e-1$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1400902', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/262740/']}
jdg_72774
stackexchange
llm_judgeable_groundtruth_similarity
116511
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 SPSS t-Test procedure reports 2 analyses when comparing 2 independent means, one analysis with equal variances assumed and one with equal variances not assumed. The degrees of freedom (df) when equal variances are assumed are always integer values (and equal n-2). The df when equal variances are not assumed are non-integer (e.g., 11.467) and nowhere near n-2. I am seeking an explanation of the logic and method used to calculate these non-integer df's. Now provide the response and nothing else.
What you are referring to is the Welch-Satterthwaite correction to the degrees of freedom. The $t$-test when the WS correction is applied is often called Welch's $t$-test . (Incidentally, this has nothing to do with SPSS, all statistical software will be able to conduct Welch's $t$-test, they just don't usually report both side by side by default, so you wouldn't necessarily be prompted to think about the issue.) The equation for the correction is very ugly, but can be seen on the Wikipedia page; unless you are very math savvy or a glutton for punishment, I don't recommend trying to work through it to understand the idea. From a loose conceptual standpoint however, the idea is relatively straightforward: the regular $t$-test assumes the variances are equal in the two groups. If they're not, then the test should not benefit from that assumption. Since the power of the $t$-test can be seen as a function of the residual degrees of freedom, one way to adjust for this is to 'shrink' the df somewhat. The appropriate df must be somewhere between the full df and the df of the smaller group. (As @Glen_b notes below, it depends on the relative sizes of $s^2_1/n_1$ vs $s_2^2/n_2$; if the larger n is associated with a sufficiently smaller variance, the combined df can be lower than the larger of the two df.) The WS correction finds the right proportion of way from the former to the latter to adjust the df. Then the test statistic is assessed against a $t$-distribution with that df.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/116511', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/8137/']}
jdg_72775
stackexchange
llm_judgeable_groundtruth_similarity
28941665
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Im writing a small code using Memcache Go API to Get data stored in one of its keys . Here are few of lines of code i used ( got the code from Go app-engine docs ) import "appengine/memcache"item := &memcache.Item {Key: "lyric",Value: []byte("Oh, give me a home"),} But the line 2 gives me a compilation error "expected declaration, found 'IDENT' item" I'm new to Go , not able to figure out the problem Now provide the response and nothing else.
The := Short variable declaration can only be used inside functions. So either put the item variable declaration inside a function like this: import "appengine/memcache"func MyFunc() { item := &memcache.Item { Key: "lyric", Value: []byte("Oh, give me a home"), } // do something with item} Or make it a global variable and use the var keyword: import "appengine/memcache"var item = &memcache.Item { Key: "lyric", Value: []byte("Oh, give me a home"),}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28941665', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2067919/']}
jdg_72776
stackexchange
llm_judgeable_groundtruth_similarity
2236661
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: Show that $$\prod\limits_{k=1}^n\left(1-\frac1{2k}\right)<\frac1{\sqrt{2n+1}}$$ for every $n\ge 1$, essentially without induction My attempt: Let say $n$ is odd integer. $$\displaystyle\prod_{k=1}^n\left(1-\frac1{2k}\right)=\dfrac1{2^n}\displaystyle\prod_{k=1}^n\left(\dfrac{2k-1}{k}\right)=\dfrac1{2^n}\left(\dfrac{1.3.5.7.9...(2n-1)}{1.2.3.4...(n-1).n}\right)=U$$ Hence: $$U=\dfrac1{2^n}\left(\dfrac{\overbrace{(n+2)(n+4)...(2n-1)}^{Y}}{\underbrace{1.2.4.6...(n-3)(n-1)}_T}\right)$$ Let analyse $T$ ; $$T=1.2.4.6...(n-3)(n-1)=2^{\frac{n-1}{2}}\left(1.2.3...\left(\frac{n-3}2\right)\left(\frac{n-1}2\right)\right)=2^{\frac{n-1}{2}}\left(\frac{n-1}{2}\right)!$$ and; $$U=\dfrac1{2^n.2^{\frac{n-1}{2}}}\dfrac{Y}{\left(\frac{n-1}{2}\right)!}<\dfrac{(2n-1)^{\frac{n-1}2}}{2^{\frac{3n-1}{2}}\left(\frac{n-1}{2}\right)!}<\dfrac1{\sqrt{8^n-1}}$$ I think, It's not enough. How should we approach this inequality? Now provide the response and nothing else.
You want an overkill? You will get one. For first, we may notice that by integration by parts$$ \prod_{k=1}^{n}\left(1-\frac{1}{2k}\right) = \frac{2}{\pi}\int_{0}^{\pi/2}\cos(x)^{2n}\,dx.\tag{1}$$Then we may notice that over the interval $\left(0,\frac{\pi}{2}\right)$ we have $\cos(x)\leq e^{-x^2/2}$: it is enough to integrate, then exponentiating, both sides of the convexity inequality $-\tan(x)\leq -x$. It follows that: $$ \prod_{k=1}^{n}\left(1-\frac{1}{2k}\right)\leq \frac{2}{\pi}\int_{0}^{+\infty}e^{-nx^2}\,dx=\frac{1}{\sqrt{\pi n}}\tag{2} $$that is stronger than the wanted inequality.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2236661', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/324389/']}
jdg_72777
stackexchange
llm_judgeable_groundtruth_similarity
43989931
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 cam across this in a pattern match | {call_name = #bundle_source; _ } source Earlier in the code, bundle_source is defined as a type ( type bundle_source = ... ). So what does the hash sign mean? Does {call_name = #bundle_source } in the pattern match mean that the value of call_name is expected to have type bundle_source ? I searched the manual for "hash sign" and "pound sign" but found nothing. Now provide the response and nothing else.
This is a shorthand for constructing patterns that match a collection of polymorphic variant values. The documentation is in Section 6.6 of the OCaml manual: If the type [('a,'b,…)] typeconstr = [ ` tag-name1 typexpr1 | … | ` tag-namen typexprn] is defined, then the pattern #typeconstr is a shorthand for the following or-pattern: ( `tag-name1(_ : typexpr1) | … | ` tag-namen(_ : typexprn)) . It matches all values of type [< typeconstr ] . # type b = [`A | `B];;type b = [ `A | `B ]# let f x = match x with | #b -> "yes" | _ -> "no";;val f : [> b ] -> string = <fun># f `A;;- : string = "yes"# f `Z;;- : string = "no" (I was not familiar with this notation either.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43989931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2482570/']}
jdg_72778
stackexchange
llm_judgeable_groundtruth_similarity
32752747
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 text in the following form: "\x91It will have to be paid for,\x92 they said. \x91It isn\x92t natural, and\ntrouble will come of it!" I want to convert it to: "'It will have to be paid for,' they said. 'It isn't natural, and\ntrouble will come of it!" Now provide the response and nothing else.
No, sorted function (or list.sort ) internally does not need to check if the object it received is a function or a class . All it cares about is that the object it received in key argument should be callable and should return a value that can be compared to other values when called. Classes are also callable , when you call a class , you receive the instance of that class back. To answer your question, first we need to understand (atleast at a basic level) how key argument works - The key callable is called for each element and it receives back the object with which it should sort. After receiving the new object, it compares this to other objects (again received by calling the key callable with the othe element). Now the important thing to note here is that the new object received is compared against other same objects. Now onto your equivalent code, when you create an instance of that class, it can be compared to other instances of the same class using your mycmp function. And sort when sorting the values compares these objects (in-effect) calling your mycmp() function to determine whether the value is less than or greater than the other object. Example with print statements - >>> def cmp_to_key(mycmp):... 'Convert a cmp= function into a key= function'... class K(object):... def __init__(self, obj, *args):... print('obj created with ',obj)... self.obj = obj... def __lt__(self, other):... print('comparing less than ',self.obj)... return mycmp(self.obj, other.obj) < 0... def __gt__(self, other):... print('comparing greter than ',self.obj)... return mycmp(self.obj, other.obj) > 0... def __eq__(self, other):... print('comparing equal to ',self.obj)... return mycmp(self.obj, other.obj) == 0... def __le__(self, other):... print('comparing less than equal ',self.obj)... return mycmp(self.obj, other.obj) <= 0... def __ge__(self, other):... print('comparing greater than equal',self.obj)... return mycmp(self.obj, other.obj) >= 0... def __ne__(self, other):... print('comparing not equal ',self.obj)... return mycmp(self.obj, other.obj) != 0... return K...>>> def mycmp(a, b):... print("In Mycmp for", a, ' ', b)... if a < b:... return -1... elif a > b:... return 1... return 0...>>> print(sorted([3,4,2,5],key=cmp_to_key(mycmp)))obj created with 3obj created with 4obj created with 2obj created with 5comparing less than 4In Mycmp for 4 3comparing less than 2In Mycmp for 2 4comparing less than 2In Mycmp for 2 4comparing less than 2In Mycmp for 2 3comparing less than 5In Mycmp for 5 3comparing less than 5In Mycmp for 5 4[2, 3, 4, 5]
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32752747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4005399/']}
jdg_72779
stackexchange
llm_judgeable_groundtruth_similarity
14740199
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 have a binary operator cross (cross-product/cartesian product) that operates with traversables in Scala: val x = Seq(1, 2)val y = List('hello', 'world', 'bye')val z = x cross y # i can chain as many traversables e.g. x cross y cross w etcassert z == ((1, 'hello'), (1, 'world'), (1, 'bye'), (2, 'hello'), (2, 'world'), (2, 'bye')) What is the best way to do this in Scala only (i.e. not using something like scalaz)? Now provide the response and nothing else.
You can do this pretty straightforwardly with an implicit class and a for -comprehension in Scala 2.10: implicit class Crossable[X](xs: Traversable[X]) { def cross[Y](ys: Traversable[Y]) = for { x <- xs; y <- ys } yield (x, y)}val xs = Seq(1, 2)val ys = List("hello", "world", "bye") And now: scala> xs cross ysres0: Traversable[(Int, String)] = List((1,hello), (1,world), ... This is possible before 2.10—just not quite as concise, since you'd need to define both the class and an implicit conversion method. You can also write this: scala> xs cross ys cross List('a, 'b)res2: Traversable[((Int, String), Symbol)] = List(((1,hello),'a), ... If you want xs cross ys cross zs to return a Tuple3 , however, you'll need either a lot of boilerplate or a library like Shapeless .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14740199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/471136/']}
jdg_72780
stackexchange
llm_judgeable_groundtruth_similarity
18401213
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 Three.js, I would like to have the camera looking at an object in the scene, and when I click on another object, to have the camera rotate smoothly to look at the new object. (i.e animate the rotation of the camera). I´ve checked in SO and this is the most similar question : Three.js How to use quaternion to rotate camera I've also tried modifying the code in this website and I manage to get something like this http://jsfiddle.net/F7Bh3/ var quat0 = mesh2.quaternion; var eye = mesh2.position; var center = mesh.position; var mat = new THREE.Matrix4(); mat.lookAt(center, eye, new THREE.Vector3(0,1,0)); var quat1 = new THREE.Quaternion(); quat1.setFromRotationMatrix( mat ); var qm = new THREE.Quaternion(); deltaTheta = angleBetweenQuats(quat0,quat1); var frac = 0.2/deltaTheta; if (frac>1) frac=1; mesh2.quaternion.slerp(quat1,frac); mesh2.quaternion.normalize(); But when I try to rotate the camera instead of the object all I get is: http://jsfiddle.net/5Peq9/1/ What am I missing? Thanks in advance Now provide the response and nothing else.
I managed to animate a camera smoothly in three.js using quaternions. It took me a while to figure it out, but once it is done it is beautiful to watch how nicely quaternions work. The method is: store the initial quaternion define a target quaternion tween something from 0 to 1 interpolate quaternions on every frame during the tween apply interpolated quaternion back to camera on every frame And a quick example with the key parts of the code: var camera // cameravar cameraPos0 // initial camera positionvar cameraUp0 // initial camera upvar cameraZoom // camera zoomvar iniQ // initial quaternionvar endQ // target quaternionvar curQ // temp quaternion during slerpvar vec3 // generic vector objectvar tweenValue // tweenable value // init camerafunction setup(){ camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 2000) camera.position = new THREE.Vector3(0, 0, 80) cameraPos0 = camera.position.clone() cameraUp0 = camera.up.clone() cameraZoom = camera.position.z}// set a new target for the camerafunction moveCamera(euler, zoom){ // reset everything endQ = new THREE.Quaternion() iniQ = new THREE.Quaternion().copy(camera.quaternion) curQ = new THREE.Quaternion() vec3 = new THREE.Vector3() tweenValue = 0 endQ.setFromEuler(euler) TweenLite.to(this, 5, { tweenValue:1, cameraZoom:zoom, onUpdate:onSlerpUpdate })}// on every update of the tweenfunction onSlerpUpdate(){ // interpolate quaternions with the current tween value THREE.Quaternion.slerp(iniQ, endQ, curQ, tweenObj.value) // apply new quaternion to camera position vec3.x = cameraPos0.x vec3.y = cameraPos0.y vec3.z = cameraZoom vec3.applyQuaternion(curQ) camera.position.copy(vec3) // apply new quaternion to camera up vec3 = cameraUp0.clone() vec3.applyQuaternion(curQ) camera.up.copy(vec3)} The last step is to find the target Euler rotation to pass to moveCamera . In my case I was using TrackballControls to find some interesting camera positions/rotations, then retrieving them with euler = camera.rotation.clone() and passing that as a target. For example: moveCamera(new THREE.Euler(2.20, -0.15, 0.55), 120) An application of this method can be seen here: http://brunoimbrizi.com/experiments/#/08
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18401213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2294885/']}
jdg_72781
stackexchange
llm_judgeable_groundtruth_similarity
4470370
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: Section 4, page 10 of The geometry of G-structures by S. S. Chern, Bull. Amer. Math. Soc. 72(2): 167-219 (March 1966), the definition of G-structure is somewhat vague, and I have have the impression that it is wrong. Let $T$ be an $n$ -dimensional real vector space and let $T^*$ be its dual space. Denote their pairing by $\langle y, \xi \rangle \in R$ , $y \in T$ , $\xi \in T^*$ . We let $GL(n,R)$ act on $T$ on the left and on $T^*$ on the right, so that the following relation holds: $$\langle gy, \xi \rangle = \langle y, \xi g \rangle, \quad \quad g \in GL(n,R).$$ The tangent bundle over $M$ has the local charts $(x,y_U)$ , $x \in U$ , $y_U \in T$ , which are the local coordinates of the tangent vectors relative to $U$ . The local coordinates $(x, y_U)$ and $(x, y_V)$ in $U \cap V$ define the same tangent vector if and only if $y_U = g_{UV}(x)y_V$ , where $g_{UV} : U \cap V \to GL(n,R)$ . Consider a subgroup $G$ of $GL(n,R)$ ; we say that the structural gropu of the tangent bundle is reduced to $G$ , if all $g_{UV}(x) \in G$ . Such a reduction will simply be called a $G$ -structure. I cannot relate this definition to other ones found elsewhere (using the notion of principal G-bundles). Is it complete? Correct? What am I missing? The article by Chern is in the reference list of Wikipedia's article G-Structures on a manifold Now provide the response and nothing else.
Chern's definition is a little sloppy. His phrasing here gives the impression that reduction of the structure group is a property of $M$ , which it's not; reductions need not be unique if they exist. You can see that reflected implicitly here by the fact that local coordinates and hence transition functions are highly non-unique. It's also a bit confusing that even if reductions exist in some coordinates they may not be witnessed by a generic choice of coordinates. To fix it one can say that a choice of reduction of the structure group is a choice of local coordinates such that the transition functions lie in $G$ ; up to isomorphism this agrees with the usual definition in terms of $G$ -bundles, although the $G$ -bundle definition is more general because the map $G \to GL_n(\mathbb{R})$ need not be injective (e.g. $G$ might be the spin group $\text{Spin}(n)$ ).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4470370', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/122865/']}
jdg_72782
stackexchange
llm_judgeable_groundtruth_similarity
29376581
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 really new to jackson , I am trying to retrieve values from json response. This is my json response : - {total: "1",count: "1",params: {res: "all",detail: "summary",smartCardId: "S1234567890",receiverId: "r1234567890",format: "all",lang: "en",storefrontType: "EN",tcsMasterId: "41S7V"},baseUrl: {asset: "http://10.84.90.186/content/video/",poster: "http://10.84.90.186/content"},items: [{contentType: "ASSET",endPointUrl: "/assets/41S7V",showType: "MOVIE",tcsMasterId: "41S7V",title: "300: Rise of an Empire",titleBrief: "300: Rise of an Empire",summaryShort: "l ",summaryMedium: "l ",summaryLong: "l ",year: "2014",rating: "G",runtime: "00:14:59",displayRuntime: "14",suggestedPrice: "5.99",providerId: "www.mongrelmedia.com",maximumViewingLength: "2880",audioType: ["Dolby Digital 5.1"],licensingWindowStart: "2015-01-01T00:00:00",licensingWindowEnd: "2015-12-31T12:00:00",genres: ["Movies/Action and Adventure"],actors: [" d"],actorsDisplay: "d",reviewRating: {type: "ROTTEN_TOMATOES",criticSummaryCount: "55",criticSummaryValue: "71",criticSummaryRating: "3.0",fanSummaryCount: "47103",fanSummaryValue: "88",fanSummaryRating: "4.0",fanSummaryPreRelease: false,reviews: [{reviewId: "1727471",publicationId: "0",publication: "Newsweek",date: "2008-05-12",freshnessScore: "null",freshness: "rotten",criticId: "0",criticName: "David Ansen",quote: "For all its ambition, the movie ends up using great historical events in the service of a dubious sentimentality."},{reviewId: "1710100",publicationId: "0",publication: "Film4",date: "2008-02-20",freshnessScore: "4/5",freshness: "fresh",criticId: "0",quote: "Unashamedly sentimental, this is a technically triumphant tear-jerker."}]},rightsIconDisplay: "IPT=1,DTH=0,WEB=0,NSC=1,MOB=0",wishList: false,preview: {assetId: "41S8V21",type: "PREVIEW",contentPath: "www.mongrelmedia.com/41S8V21_a4289887-5f7c-47a4-afad-842c934025e1/MPL_41S8V21_a4289887-5f7c-47a4-afad-842c934025e1.m3u8",masterPlaylist: "MPL_41S8V21_a4289887-5f7c-47a4-afad-842c934025e1.m3u8",runtime: "00:14:59"}}]} I am trying to retrieve values from : - items: [] such as displayRuntime: "14", and genre but not able reach to it - here is the main pojo class : - public class AssetGen{ private BaseUrl baseUrl; private String count; private List items; private Params params; private String total; public BaseUrl getBaseUrl(){ return this.baseUrl; } public void setBaseUrl(BaseUrl baseUrl){ this.baseUrl = baseUrl; } public String getCount(){ return this.count; } public void setCount(String count){ this.count = count; } public List getItems(){ return this.items; } public void setItems(List items){ this.items = items; } public Params getParams(){ return this.params; } public void setParams(Params params){ this.params = params; } public String getTotal(){ return this.total; } public void setTotal(String total){ this.total = total; } } here is the item pojo :- public class Items{ private List actors; private String actorsDisplay; private List audioType; private String contentType; private String displayRuntime; private String endPointUrl; private List genres; private String licensingWindowEnd; private String licensingWindowStart; private String maximumViewingLength; private Preview preview; private String providerId; private String rating; private ReviewRating reviewRating; private String rightsIconDisplay; private String runtime; private String showType; private String suggestedPrice; private String summaryLong; private String summaryMedium; private String summaryShort; private String tcsMasterId; private String title; private String titleBrief; private boolean wishList; private String year; public List getActors(){ return this.actors; } public void setActors(List actors){ this.actors = actors; } public String getActorsDisplay(){ return this.actorsDisplay; } public void setActorsDisplay(String actorsDisplay){ this.actorsDisplay = actorsDisplay; } public List getAudioType(){ return this.audioType; } public void setAudioType(List audioType){ this.audioType = audioType; } public String getContentType(){ return this.contentType; } public void setContentType(String contentType){ this.contentType = contentType; } public String getDisplayRuntime(){ return this.displayRuntime; } public void setDisplayRuntime(String displayRuntime){ this.displayRuntime = displayRuntime; } public String getEndPointUrl(){ return this.endPointUrl; } public void setEndPointUrl(String endPointUrl){ this.endPointUrl = endPointUrl; } public List getGenres(){ return this.genres; } public void setGenres(List genres){ this.genres = genres; } public String getLicensingWindowEnd(){ return this.licensingWindowEnd; } public void setLicensingWindowEnd(String licensingWindowEnd){ this.licensingWindowEnd = licensingWindowEnd; } public String getLicensingWindowStart(){ return this.licensingWindowStart; } public void setLicensingWindowStart(String licensingWindowStart){ this.licensingWindowStart = licensingWindowStart; } public String getMaximumViewingLength(){ return this.maximumViewingLength; } public void setMaximumViewingLength(String maximumViewingLength){ this.maximumViewingLength = maximumViewingLength; } public Preview getPreview(){ return this.preview; } public void setPreview(Preview preview){ this.preview = preview; } public String getProviderId(){ return this.providerId; } public void setProviderId(String providerId){ this.providerId = providerId; } public String getRating(){ return this.rating; } public void setRating(String rating){ this.rating = rating; } public ReviewRating getReviewRating(){ return this.reviewRating; } public void setReviewRating(ReviewRating reviewRating){ this.reviewRating = reviewRating; } public String getRightsIconDisplay(){ return this.rightsIconDisplay; } public void setRightsIconDisplay(String rightsIconDisplay){ this.rightsIconDisplay = rightsIconDisplay; } public String getRuntime(){ return this.runtime; } public void setRuntime(String runtime){ this.runtime = runtime; } public String getShowType(){ return this.showType; } public void setShowType(String showType){ this.showType = showType; } public String getSuggestedPrice(){ return this.suggestedPrice; } public void setSuggestedPrice(String suggestedPrice){ this.suggestedPrice = suggestedPrice; } public String getSummaryLong(){ return this.summaryLong; } public void setSummaryLong(String summaryLong){ this.summaryLong = summaryLong; } public String getSummaryMedium(){ return this.summaryMedium; } public void setSummaryMedium(String summaryMedium){ this.summaryMedium = summaryMedium; } public String getSummaryShort(){ return this.summaryShort; } public void setSummaryShort(String summaryShort){ this.summaryShort = summaryShort; } public String getTcsMasterId(){ return this.tcsMasterId; } public void setTcsMasterId(String tcsMasterId){ this.tcsMasterId = tcsMasterId; } public String getTitle(){ return this.title; } public void setTitle(String title){ this.title = title; } public String getTitleBrief(){ return this.titleBrief; } public void setTitleBrief(String titleBrief){ this.titleBrief = titleBrief; } public boolean getWishList(){ return this.wishList; } public void setWishList(boolean wishList){ this.wishList = wishList; } public String getYear(){ return this.year; } public void setYear(String year){ this.year = year; }} here is the jackson code I am trying to use : - @SuppressWarnings("rawtypes") public String[] getShowNWdetailsGopherParser (String url) throws JsonParseException, JsonMappingException, IOException{ System.err.println("STAGE 1"); URL jsonUrl = new URL(url); ObjectMapper objmapper = new ObjectMapper(); objmapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); List<AssetGen> jsongenShow_1 = objmapper.readValue(jsonUrl, new TypeReference <List<AssetGen>>() {}); List [] shows = new List [jsongenShow_1.size()]; String[] showsArr = new String[jsongenShow_1.size()]; int i = 0; for(AssetGen element : jsongenShow_1){ shows[i]=element.getItems(). showsArr[i]=shows[i].toString(); i++; } return showsArr; } Need clear solution , really new to jackson. Now provide the response and nothing else.
I finally fixed this after hours of work! I found out that you can pass the path to the paginator. As you can see this can be done by passing an array as the 5th argument when building an paginator object. This array will overwrite any options you pass it. We need to overwrite the path option. I'm getting the current path using Paginator::resolveCurrentPath() . So my code now looks like: // Create a paginator instance.$profiles = new Paginator($collection->all(), $total, $perPage, Paginator::resolveCurrentPage(), [ 'path' => Paginator::resolveCurrentPath()]); For people that are interested, the paginator constructor looks like: __construct($items, $total, $perPage, $currentPage = null, array $options = []) It is weird that you need to pass this manually and i would consider this a bug.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29376581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3837982/']}
jdg_72783
stackexchange
llm_judgeable_groundtruth_similarity
3083781
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need the start date and the end date of the current month in Java. When the JSP page is loaded with the current month it should automatically calculate the start and end date of that month. It should be irrespective of the year and month. That is some month has 31 days or 30 days or 28 days. This should satisfy for a leap year too. Can you help me out with that? For example if I select month May in a list box I need starting date that is 1 and end date that is 31. Now provide the response and nothing else.
There you go: public Pair<Date, Date> getDateRange() { Date begining, end; { Calendar calendar = getCalendarForNow(); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); setTimeToBeginningOfDay(calendar); begining = calendar.getTime(); } { Calendar calendar = getCalendarForNow(); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); setTimeToEndofDay(calendar); end = calendar.getTime(); } return Pair.of(begining, end);}private static Calendar getCalendarForNow() { Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(new Date()); return calendar;}private static void setTimeToBeginningOfDay(Calendar calendar) { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0);}private static void setTimeToEndofDay(Calendar calendar) { calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); calendar.set(Calendar.MILLISECOND, 999);} PS: Pair class is simply a pair of two values.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3083781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/358471/']}
jdg_72784
stackexchange
llm_judgeable_groundtruth_similarity
40164660
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm running the following RUN command in my Dockerfile, expecting a "logs" directory to be created under each of the listed subdirectories: RUN mkdir -p /opt/seagull/{diameter-env,h248-env,http-env,msrp-env,octcap-env,radius-env,sip-env,synchro-env,xcap-env}/logs But when I check the image, I see a directory literally called "{diameter-env,h248-env,http-env,msrp-env,octcap-env,radius-env,sip-env,synchro-env,xcap-env}" created under /opt/seagull, instead of brace expansion taking place. What could I be doing wrong? Now provide the response and nothing else.
You're not using brace expansion, because you're not using Bash. If you look at the documentation for the RUN command : RUN (shell form, the command is run in a shell, which by default is /bin/sh -c on Linux or cmd /S /C on Windows) And also: Note: To use a different shell, other than ‘/bin/sh’, use the exec form passing in the desired shell. For example, RUN ["/bin/bash", "-c", "echo hello"] So, just change the command to use the exec form and explicitly use a Bash shell: RUN [ "/bin/bash", "-c", "mkdir -p /opt/seagull/{diameter-env,h248-env,http-env,msrp-env,octcap-env,radius-env,sip-env,synchro-env,xcap-env}/logs" ]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40164660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23501/']}
jdg_72785
stackexchange
llm_judgeable_groundtruth_similarity
991142
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to Wikipedia, the following is a very elegant bash fork bomb: :(){ :|:& };: How does it work? Now provide the response and nothing else.
Breaking it down, there are three big pieces: :() # Defines a function, ":". It takes no arguments.{ ... }; # The body of the function.: # Invoke the function ":" that was just defined. Inside the body, the function is invoked twice and the pipeline is backgrounded; each successive invocation on the processes spawns even more calls to ":". This leads rapidly to an explosive consumption in system resources, grinding things to a halt. Note that invoking it once, infinitely recursing, wouldn't be good enough, since that would just lead to a stack overflow on the original process, which is messy but can be dealt with. A more human-friendly version looks like this: kablammo() { # Declaration kablammo | kablammo& # The problematic body.}; kablammo # End function definition; invoke function. Edit: William's comment below was a better wording of what I said above, so I've edited to incorporate that suggestion.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/991142', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107245/']}
jdg_72786
stackexchange
llm_judgeable_groundtruth_similarity
485448
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a Windows standard way to do things such as "start fan", "decrease speed" or the like, from C/C++? I have a suspicion it might be ACPI, but I am a frail mortal and cannot read that kind of documentation. Edit: e.g. Windows 7 lets you select in your power plan options such as "passive cooling" (only when things get hot?) vs. "active cooling" (keep the CPU proactively cool?). It seems the OS does have a way to control the fan generically. Now provide the response and nothing else.
I am at the moment working on a project that, among other things, controls the computer fans. Basically, the fans are controlled by the superIO chip of your computer. We access the chip directly using port-mapped IO, and from there we can get to the logical fan device. Using port-mapped IO requires the code to run in kernel mode, but windows does not supply any drivers for generic port IO (with good reason, since it is a very powerful tool), so we wrote our own driver, and used that. If you want to go down this route, you basically need knowledge in two areas: driver development and how to access and interpret superIO chip information. When we started the project, we didn't know anything in either of these areas, so it has been learning by browsing, reading and finally doing. To gain the knowledge, we have been especially helped by looking at these links: The WDK , which is the Windows Driver Kit. You need this to compile any driver you write for windows, With it comes a whole lot of source code for example drivers, including a driver for general port-mapped IO, called portio. WinIO has source code for a driver in C, a dll in C that programmatically installs and loads that driver, and some C# code for a GUI, that loads the dll and reads/writes to the ports. The driver is very similar to the one in portio. lm-sensors is a linux project, that, among other things, detects your superIO chip. /prog/detect/sensors-detect is the perl program, that does the detecting, and we have spent some time going through the code to see how to interface with a superIO chip. When we were going through the lm-sensors code, it was very nice to have tools like RapidDriver and RW-everything , since they allowed us to simulate a run of sensors-detect. The latter is the more powerful, and is very helpful in visualising the IO space, while the former provides easier access to some operations which map better to the ones in sensors-detect (read/write byte to port) Finally, you need to find the datasheet of your superIO chip. From the examples, that I have seen, the environment controllers of each chip provide similar functionality (r/w fan speed, read temperature, read chip voltage), but vary in what registers you have to write to in order to get to this functionality. This place has had all the datasheets, we have needed so far.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/485448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9665/']}
jdg_72787
stackexchange
llm_judgeable_groundtruth_similarity
7799153
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 an F# type: type Foo() = member this.Prop with get() = () interface IDisposable with member this.Dispose() = () In C#, I create the object, but I can't call Dispose() : var x = new Foo();x.Dispose(); // compile error, x does not contain a definition of Dispose However, I can write: ((IDisposable)x).Dispose(); // works, but I don't like the cast Is there any way to avoid the cast in C#? Is this related to the way F# doesn't automatically let you call .Dispose() on the Foo type from within F#? Now provide the response and nothing else.
Interface implementations in F# are explicit by default. Hence the methods are not visible unless seen from the type converted to the interface (some form of casting). To work around this expose an instance method which has the same signature as the interface version. Then have the interface on forward to the instance function. For example type Foo() = member this.Prop with get() = () member this.Dispose() = () interface IDisposable with member this.Dispose() = this.Dispose()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7799153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/160673/']}
jdg_72788
stackexchange
llm_judgeable_groundtruth_similarity
50729625
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 some problems related with this code. The parameter of printf is of type const char* and ... (variable argument list). 1) Why the output of the program is d and not 127 ? 2) Is it that the +1 would get converted into string and passed to parameter variable of type const char* ? #include<stdio.h>int main(){ printf("%d"+1 , 127); //how this will get executed? return 0;} Output: d Now provide the response and nothing else.
First parameter is a pointer to char . The literal "%d" would be a pointer to the '%' , which is implicitly followed by 'd' and '\0' . It is a pointer to char , because that is the C representation of string literals: sequences of characters with a '\0' at the end; represented for use as parameters etc. as a pointer to char . But "%d"+1 , according to pointer arithmetic, is a pointer to 'd' , followed by '\0' . Both are zero-terminated, as fitting for a parameter to printf. So the output is the same as printf("d", ignored); 127 turns into "ignored", i.e. it is ignored, because the "d" tells printf not to expect anything, because it does not have any of the special character sequences, e.g. "%someletter". So it will not expect, not look for anything and will not do any printing beyond the perfectly normal string it thinks to have been given. Note however that the additional parameters, those not covered by anything in the format string, do get evaluated and then ignored. This is relevant, because any side effects (e.g. function calls) of that evaluation do in fact occur. See e.g. here for details: http://en.cppreference.com/w/c/io/fprintf
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50729625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9905549/']}
jdg_72789
stackexchange
llm_judgeable_groundtruth_similarity
151297
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 would like to allow users of my web application to have long passwords, if they so wish. Today I became aware of bcrypt's password length limitation (72 characters, the rest truncated). Would it be secure for me to do the following? I am using PHP. Current Implementation: password_hash($password, PASSWORD_BCRYPT, $options); Implementation in question: password_hash(hash('sha256', $password), PASSWORD_BCRYPT, $option); What are the drawbacks of the implementation in question? I am not a crypto expert, please advise. Will the implementation in question limit the password length that a user can use? If so, what will the limit be? Now provide the response and nothing else.
In general, this will be fine. It's even a fairly well recommended method to allow arbitrary length passwords in bcrypt. Mathematically, you are now using bcrypt on a 64 character string, where there are 2^256 possible values (SHA-256 gives 256 bit output, which is commonly represented as a 64 character hexadecimal string). Even if someone pre-calculated common passwords in SHA-256, they'd need to run those through bcrypt to find what the actual input for a given hash was. The main potential drawback is implementation flaws: if you ever store the SHA-256 values, they're relatively fast to break, so an attacker wouldn't need to expend the effort to break the bcrypt values. It would still be recommended to keep a high enough iteration count for the bcrypt step - this shouldn't have any particularly detrimental effect on your processing time, but makes brute force attacks much harder. See Pre-hash password before applying bcrypt to avoid restricting password length for the general case.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/151297', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/92420/']}
jdg_72790
stackexchange
llm_judgeable_groundtruth_similarity
19025075
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to render a partial inside ActiveAdmin page. I am trying something like: form(:html => { :multipart => true }) do |f| f.inputs "Описание товара #{f.object.name if f.object.name}" do f.input :name, :required => true f.input :brand f.input :category f.input :created_at, :wrapper_html => { :class => 'inline-list' } f.input :updated_at, :wrapper_html => { :class => 'inline-list' } f.actions end content do render partial: 'fancybox' end end But it doesn't work. My partial contents replace the form contents. I guess I need a right wrapper element for render but using panel was no success. Any thoughts? Now provide the response and nothing else.
Try to use render with f.template : form(:html => { :multipart => true }) do |f| f.inputs "Описание товара #{f.object.name if f.object.name}" do f.input :name, :required => true f.input :brand f.input :category f.input :created_at, :wrapper_html => { :class => 'inline-list' } f.input :updated_at, :wrapper_html => { :class => 'inline-list' } f.actions end f.inputs "Fancybox" do f.template.render partial: 'fancybox' endend
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19025075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/801058/']}
jdg_72791
stackexchange
llm_judgeable_groundtruth_similarity
349566
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Every time Windows Server 2008 R2 asks me to change the admin password all the backup related scheduled task stop working, is there any way to avoid this? Backup is a serious thing an have to work forever. We have 3 server machines in a company.local domain each one with its scheduled windows server backup. Now provide the response and nothing else.
Ideally, you shouldn't be running scheduled tasks using the built in administrator accounts My advice would be to create a service account and use that for your scheduled tasks. A service account is just a normal AD user, but usually has: 1) A VERY strong password (The kind you can't remember) 2) A meaningful name (E.g. svc_backup) 3) Password set to never expire 4) Configured so 'user' can't change password The bottom two are just configured in the users AD properties. You then give this account the relevant rights and privileges- ideally without making it a Domain Administrator.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/349566', 'https://serverfault.com', 'https://serverfault.com/users/38557/']}
jdg_72792
stackexchange
llm_judgeable_groundtruth_similarity
29808573
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 ViewModel that has a complex object as one of its members. The complex object has 4 properties (all strings). I'm trying to create a re-usable partial view where I can pass in the complex object and have it generate the html with html helpers for its properties. That's all working great. However, when I submit the form, the model binder isn't mapping the values back to the ViewModel's member so I don't get anything back on the server side. How can I read the values a user types into the html helpers for the complex object. ViewModel public class MyViewModel{ public string SomeProperty { get; set; } public MyComplexModel ComplexModel { get; set; }} MyComplexModel public class MyComplexModel{ public int id { get; set; } public string Name { get; set; } public string Address { get; set; } ....} Controller public class MyController : Controller{ public ActionResult Index() { MyViewModel model = new MyViewModel(); model.ComplexModel = new MyComplexModel(); model.ComplexModel.id = 15; return View(model); } [HttpPost] public ActionResult Index(MyViewModel model) { // model here never has my nested model populated in the partial view return View(model); }} View @using(Html.BeginForm("Index", "MyController", FormMethod.Post)){ .... @Html.Partial("MyPartialView", Model.ComplexModel)} Partial View @model [email protected](m => m.Name)... how can I bind this data on form submission so that the parent model contains the data entered on the web form from the partial view? thanks EDIT: I've figured out that I need to prepend "ComplexModel." to all of my control's names in the partial view (textboxes) so that it maps to the nested object, but I can't pass the ViewModel type to the partial view to get that extra layer because it needs to be generic to accept several ViewModel types. I could just rewrite the name attribute with javascript, but that seems overly ghetto to me. How else can I do this? EDIT 2: I can statically set the name attribute with new { Name="ComplexModel.Name" } so I think I'm in business unless someone has a better method? Now provide the response and nothing else.
You can pass the prefix to the partial using @Html.Partial("MyPartialView", Model.ComplexModel, new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "ComplexModel" }}) which will perpend the prefix to you controls name attribute so that <input name="Name" ../> will become <input name="ComplexModel.Name" ../> and correctly bind to typeof MyViewModel on post back Edit To make it a little easier, you can encapsulate this in a html helper public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string partialViewName){ string name = ExpressionHelper.GetExpressionText(expression); object model = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model; var viewData = new ViewDataDictionary(helper.ViewData) { TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = string.IsNullOrEmpty(helper.ViewData.TemplateInfo.HtmlFieldPrefix) ? name : $"{helper.ViewData.TemplateInfo.HtmlFieldPrefix}.{name}" } }; return helper.Partial(partialViewName, model, viewData);} and use it as @Html.PartialFor(m => m.ComplexModel, "MyPartialView")
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29808573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4451095/']}
jdg_72793
stackexchange
llm_judgeable_groundtruth_similarity
41880
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm curious whether I can find the overlap $\langle q | p \rangle$ knowing only the following: $|q\rangle$ is an eigenvector of an operator $Q$ with eigenvalue $q$ . $|p\rangle$ is an eigenvector of an operator $P$ with eigenvalue $p$ . $Q$ and $P$ are Hermitian. $[Q,P] = i \hbar$ . I'm asking because books and references I've looked in tend to assume that $Q$ is a differential operator when viewed in the $P$ -basis, then show that it satisfies the commutation relation. (I haven't read one yet that proves that the form given for $Q$ is the only possible one.) I've heard, though, that we can work purely from the hypothesis of the commutation relation and prove the properties of $Q$ and $P$ from it. Now provide the response and nothing else.
Those things are surely not enough to find the inner product $\langle q|p\rangle$ uniquely. For example, starting with the conventional $Q,P$, you may redefine them by a canonical transformation, for example by $$ Q\to Q'=Q, \quad P\to P'= P + Q^3 $$Then $P', Q'$ obey all the four conditions in the same way as $P,Q$. They also have eigenstates and $|p'\rangle$ states are something else than $|p\rangle$. In fact, eigenstates with a large eigenvalue $P'$ are close to $Q$ eigenstates because $Q^3$ easily dominates. The inner product – which is nothing else than the wave function of the $P'$ eigenstate written in the $Q$ representation – will end up being different. It will be a complicated solution of the equation for $\psi$ saying that it's a $P+Q^3$ eigenstate. The conditions you wrote can only tell you that $$\langle q | PQ | p \rangle = \langle q | QP | p \rangle - i\hbar \langle q | p \rangle = (qp - i\hbar )\langle q | p \rangle $$so they're only enough to say how $Q$ acts on the $p$ eigenstates and vice versa, in this combination. But the inner product itself isn't related to itself in any sense, so it can't be determined. Let me mention that even if you imposed additional conditions that would say that $P$ and $Q$ are physically what they should be – e.g. that they scale properly under the scaling of $Q,P$ – the inner product would still be undetermined because at least the phase of the $|p\rangle$ and $|q\rangle$ eigenstates is arbitrary. In fact, even the "absolute value part of the" normalization is a matter of conventions that could be modified. More generally, and I would say that this point is often overlooked, many properties of "wave functions" similar to your inner products are intermediate, convention- and representation-dependent quantities that don't have a direct physical impact (i.e. direct link with observable quantities). It's really the properties of observables such as the four conditions that you described that may be considered objective facts.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/41880', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/74/']}
jdg_72794
stackexchange
llm_judgeable_groundtruth_similarity
227929
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: If I do this 10 times a month, how much would that cost me? Now provide the response and nothing else.
Very close to nothing. There is no cost to make an AMI itself, but if you're making it from a running instance you will pay the fees for running a micro instance (which is about $0.02/hr, depending on availability region - see the pricing details ) and also fees for using the EBS root for however long you use it. When storing the AMI, you only pay for the S3 storage taken from the snapshot. The root FS must be an EBS volume (for all micro instances), but this is stored as an EBS snapshot (which are stored in S3, rather than EBS) so you pay S3 fees to store it. Note that EBS charges per allocated GB , while S3 charges per used GB ; with the way they do things, a 10G EBS volume that only has 500MB on it will only take up approx. 500MB of S3 storage. Further to that, Micro instances are included in Amazon's free tier at the moment, so all of the above will cost you nothing (with limits - see the pricing link above).
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/227929', 'https://serverfault.com', 'https://serverfault.com/users/81082/']}
jdg_72795
stackexchange
llm_judgeable_groundtruth_similarity
14366390
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was wondering if there is an efficient way to check if an element is present within an array in Bash? I am looking for something similar to what I can do in Python, like: arr = ['a','b','c','d']if 'd' in arr: do your thingelse: do something I've seen solutions using associative array for bash for Bash 4+, but I am wondering if there is another solution out there. Please understand that I know the trivial solution is to iterate in the array, but I don't want that. Now provide the response and nothing else.
You could do: if [[ " ${arr[*]} " == *" d "* ]]; then echo "arr contains d"fi This will give false positives for example if you look for "a b" -- that substring is in the joined string but not as an array element. This dilemma will occur for whatever delimiter you choose. The safest way is to loop over the array until you find the element: array_contains () { local seeking=$1; shift local in=1 for element; do if [[ $element == "$seeking" ]]; then in=0 break fi done return $in}arr=(a b c "d e" f g)array_contains "a b" "${arr[@]}" && echo yes || echo no # noarray_contains "d e" "${arr[@]}" && echo yes || echo no # yes Here's a "cleaner" version where you just pass the array name, not all its elements array_contains2 () { local array="$1[@]" local seeking=$2 local in=1 for element in "${!array}"; do if [[ $element == "$seeking" ]]; then in=0 break fi done return $in}array_contains2 arr "a b" && echo yes || echo no # noarray_contains2 arr "d e" && echo yes || echo no # yes For associative arrays , there's a very tidy way to test if the array contains a given key : The -v operator $ declare -A arr=( [foo]=bar [baz]=qux )$ [[ -v arr[foo] ]] && echo yes || echo noyes$ [[ -v arr[bar] ]] && echo yes || echo nono See 6.4 Bash Conditional Expressions in the manual.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14366390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1818327/']}
jdg_72796
stackexchange
llm_judgeable_groundtruth_similarity
71870
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm wondering if there is an easy way to get the plot below exported in a small PDF file? The plot below is made in the following steps: Create a StreamPlot Create a DensityPlot , where the DensityPlot has to have a lot of sampling points in some cases !! Put the two of them together. Now whenever I save this as a PDF-file it becomes huge due to the large amount of sampling points. Now I was wondering if it was possible to get this in a single (small !!) PDF-file? As far as I understand I need to rasterize the density plot and put the axes separately. Now I've seen some answers regarding this for a ListDensityPlot , but it doesn't seem to work for a DensityPlot . Whenever I try to put the PlotRangePadding to 0 weird things happen. Next to that I've also not been able to put the legend next to the plot after rasterization. Are there any hints on this ? Code to reproduce the above example: vx[x_, y_, d_] := -y*(1/((x - d)^2 + y^2) - 1/((x - 1/d)^2 + y^2)) + y*(1/((x + d)^2 + y^2) - 1/((x + 1/d)^2 + y^2))vy[x_, y_,d_] := (x - d)/((x - d)^2 + y^2) - (x - 1/d)/((x - 1/d)^2 + y^2) - (x + d)/((x + d)^2 + y^2) + (x + 1/d)/((x + 1/d)^2 + y^2)v[x_, y_, d_] := Sqrt[( 4 d^2 (-1 + d^2)^2 ((1 + x^2)^2 + 2 (-1 + x^2) y^2 + y^4))/(((d - x)^2 + y^2) ((d + x)^2 + y^2) ((-1 + d x)^2 + d^2 y^2) ((1 + d x)^2 + d^2 y^2))]part1 = StreamPlot[{vx[x, y, 0.6], vy[x, y, 0.6]}, {x, -2, 2}, {y, -1.4, 1.4}, ImageSize -> 650, PlotRangePadding -> None, FrameStyle -> Black, BaseStyle -> FontSize -> 22, PerformanceGoal -> "Quality", StreamStyle -> "PinDart", StreamPoints -> Fine, StreamScale -> .15, AspectRatio -> ((1.4 - (-1.4))/(2 - (-2)))]legend = BarLegend[{"SunsetColors", {0, 15}}, LegendFunction -> "Panel", LegendLabel -> "|\!\(\*OverscriptBox[\(v\), \(\[RightVector]\)]\)|/(\[Kappa]/2\\[Pi]R)", LabelStyle -> Directive[Bold, Black, 14], LegendMargins -> 0, LegendMarkerSize -> 400]part2 = DensityPlot[{v[x, y, 0.6]}, {x, -2, 2}, {y, -1.4, 1.4}, ImageSize -> 650, ColorFunction -> "SunsetColors", PlotRangePadding -> None, FrameStyle -> Black, BaseStyle -> FontSize -> 22, PerformanceGoal -> "Quality", AspectRatio -> ((1.4 - (-1.4))/(2 - (-2))), FrameLabel -> {"x/R", "y/R"}, PlotLabel -> Style["The vortex-antivortex velocity field", Black, 30] , PlotRange -> {0, 15}, PlotPoints -> 200, Epilog -> Style[Circle[{0, 0}, 1], {Thick, Dashed, White}], PlotLegends -> Placed[legend, Right]]plot = Show[part2, part1] Now provide the response and nothing else.
The rasterizeBackground function originally written by Szabolcs and then improved by Lukas Lang requires further minor update and improvement in order to get it working for your case in recent versions of Mathematica . Here is a substantially more reliable version of that function which doesn't depend on the buggy AbsoluteOptions (I use here the workaround suggested by Carl Woll in this answer): ClearAll[rasterizeBackground]Options[rasterizeBackground] = {"TransparentBackground" -> False, Antialiasing -> False};rasterizeBackground[g_Graphics, rs_Integer: 3000, OptionsPattern[]] := Module[{raster, plotrange, rect}, {raster, plotrange} = Reap[First@Rasterize[ Show[g, Epilog -> {}, Prolog -> {}, PlotRangePadding -> 0, ImagePadding -> 0, ImageMargins -> 0, PlotLabel -> None, FrameTicks -> None, Frame -> None, Axes -> None, Ticks -> None, PlotRangeClipping -> False, Antialiasing -> OptionValue[Antialiasing], GridLines -> {Function[Sow[{##}, "X"]; None], Function[Sow[{##}, "Y"]; None]}], "Graphics", ImageSize -> rs, Background -> Replace[OptionValue["TransparentBackground"], {True -> None, False -> Automatic}]], _, #1 -> #2[[1]] &]; rect = Transpose[{"X", "Y"} /. plotrange]; Graphics[raster /. Raster[data_, _, rest__] :> Raster[data, rect, rest], Options[g]]]rasterizeBackground[g_, rs_Integer: 3000, OptionsPattern[]] := g /. gr_Graphics :> rasterizeBackground[gr, rs] With this version rasterization of your DensityPlot can be made as easy as follows: plot = Show[rasterizeBackground[part2, 1000], part1] The size of exported PDF file is reasonable and easily controllable by setting the raster size of the embedded image via the second argument of rasterizeBackground : Export["plot.pdf", plot] // FileByteCount 490504 Additional example of use: Adding the option ChartElementFunction -> "GlassBoxWhisker" to BoxWhiskerChart increases file size enormously
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/71870', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/8195/']}
jdg_72797
stackexchange
llm_judgeable_groundtruth_similarity
22692286
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 tried using various iterations of skew to get outline of an angle like this with pure CSS: It never seems to come out right. I can easily make a 90 degree angle with rotation and a border, but getting a greater than 90 degree angle has escaped me. I'm actually using less, but this more of a css question. Solid shapes I understand how do to, it is achieving the border with a transparent background that I can't figure out. Now provide the response and nothing else.
Data Annotations The easiest approach is probably adorning the property itself with a Data Annotation , although I'm not myself a huge fan of this: public class MyDataClass{ [Range(1, 60)] public decimal Diameter { get; set; }} AutoFixture will respect the [Range] attribute's values. Convention-based A better approach is, in my opinion, a convention-based approach that doesn't rely on non-enforceable attributes: public class DiameterBuilder : ISpecimenBuilder{ public object Create(object request, ISpecimenContext context) { var pi = request as PropertyInfo; if (pi == null || pi.Name != "Diameter" || pi.PropertyType != typeof(decimal)) return new NoSpecimen(request); return context.Resolve( new RangedNumberRequest(typeof(decimal), 1.0m, 60.0m)); }} This passing test demonstrates how to use it: [Fact]public void ResolveRangeLimitedType(){ var fixture = new Fixture(); fixture.Customizations.Add(new DiameterBuilder()); var actual = fixture.Create<Generator<MyDataClass>>().Take(100); Assert.True(actual.All(x => 1 <= x.Diameter && x.Diameter <= 60));} For more details, please refer to this other, very closely related SO Q&A . Overcoming Primitive Obsession Perhaps an even better approach is to listen to your tests, combat Primitive Obsession , and introduce a custom type - in this case, a Diameter Value Object. This is often my preferred approach.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22692286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/66475/']}
jdg_72798
stackexchange
llm_judgeable_groundtruth_similarity
7260134
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 recently started learning ExtJS, and have trouble understanding how to handle Events. I have no experience of any previous versions of ExtJS. From reading various manuals, guides and documentation pages, I've figured out how to use it, but I'm not clear on how it works. I've found several tutorials for older versions of ExtJS, but I'm not sure how applicable they are in ExtJS 4. I'm specifically looking on the "final word" on things like what arguments does an event handling function get passed? Is there a standard set of args that always get passed? how to define custom events for custom components we write? how can we fire these custom event? does the return value (true/false) affect how the event bubbles? If not, how can we control event bubbling from within, or outside of the event handler? is there a standard way to register event listeners? (I've come across two different ways til now, and I'm not sure why each method was used). For example, this question leads me to believe that an event handler can receive quite a few arguments. I've seen other tutorials where there are just two arguments to the handler. What changes? Now provide the response and nothing else.
Let's start by describing DOM elements' event handling. DOM node event handling First of all you wouldn't want to work with DOM node directly. Instead you probably would want to utilize Ext.Element interface. For the purpose of assigning event handlers, Element.addListener and Element.on (these are equivalent) were created. So, for example, if we have html: <div id="test_node"></div> and we want add click event handler. Let's retrieve Element : var el = Ext.get('test_node'); Now let's check docs for click event. It's handler may have three parameters: click( Ext.EventObject e, HTMLElement t, Object eOpts ) Knowing all this stuff we can assign handler: // event name event handlerel.on( 'click' , function(e, t, eOpts){ // handling event here}); Widgets event handling Widgets event handling is pretty much similar to DOM nodes event handling. First of all, widgets event handling is realized by utilizing Ext.util.Observable mixin. In order to handle events properly your widget must containg Ext.util.Observable as a mixin. All built-in widgets (like Panel, Form, Tree, Grid, ...) has Ext.util.Observable as a mixin by default. For widgets there are two ways of assigning handlers. The first one - is to use on method (or addListener ). Let's for example create Button widget and assign click event to it. First of all you should check event's docs for handler's arguments: click( Ext.button.Button this, Event e, Object eOpts ) Now let's use on : var myButton = Ext.create('Ext.button.Button', { text: 'Test button'});myButton.on('click', function(btn, e, eOpts) { // event handling here console.log(btn, e, eOpts);}); The second way is to use widget's listeners config: var myButton = Ext.create('Ext.button.Button', { text: 'Test button', listeners : { click: function(btn, e, eOpts) { // event handling here console.log(btn, e, eOpts); } }}); Notice that Button widget is a special kind of widgets. Click event can be assigned to this widget by using handler config: var myButton = Ext.create('Ext.button.Button', { text: 'Test button', handler : function(btn, e, eOpts) { // event handling here console.log(btn, e, eOpts); }}); Custom events firing First of all you need to register an event using addEvents method: myButton.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */); Using the addEvents method is optional. As comments to this method say there is no need to use this method but it provides place for events documentation. To fire your event use fireEvent method: myButton.fireEvent('myspecialevent1', arg1, arg2, arg3, /* ... */); arg1, arg2, arg3, /* ... */ will be passed into handler. Now we can handle your event: myButton.on('myspecialevent1', function(arg1, arg2, arg3, /* ... */) { // event handling here console.log(arg1, arg2, arg3, /* ... */);}); It's worth mentioning that the best place for inserting addEvents method call is widget's initComponent method when you are defining new widget: Ext.define('MyCustomButton', { extend: 'Ext.button.Button', // ... other configs, initComponent: function(){ this.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */); // ... this.callParent(arguments); }});var myButton = Ext.create('MyCustomButton', { /* configs */ }); Preventing event bubbling To prevent bubbling you can return false or use Ext.EventObject.preventDefault() . In order to prevent browser's default action use Ext.EventObject.stopPropagation() . For example let's assign click event handler to our button. And if not left button was clicked prevent default browser action: myButton.on('click', function(btn, e){ if (e.button !== 0) e.preventDefault();});
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7260134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2119053/']}
jdg_72799
stackexchange
llm_judgeable_groundtruth_similarity
877723
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 make an entire inline formset within an admin change form compulsory. So in my current scenario when I hit save on an Invoice form (in Admin) the inline Order form is blank. I'd like to stop people creating invoices with no orders associated. Anyone know an easy way to do that? Normal validation like ( required=True ) on the model field doesn't appear to work in this instance. Now provide the response and nothing else.
The best way to do this is to define a custom formset, with a clean method that validates that at least one invoice order exists. class InvoiceOrderInlineFormset(forms.models.BaseInlineFormSet): def clean(self): # get forms that actually have valid data count = 0 for form in self.forms: try: if form.cleaned_data: count += 1 except AttributeError: # annoyingly, if a subform is invalid Django explicity raises # an AttributeError for cleaned_data pass if count < 1: raise forms.ValidationError('You must have at least one order')class InvoiceOrderInline(admin.StackedInline): formset = InvoiceOrderInlineFormsetclass InvoiceAdmin(admin.ModelAdmin): inlines = [InvoiceOrderInline]
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/877723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108791/']}
jdg_72800
stackexchange
llm_judgeable_groundtruth_similarity
9059631
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to use the autoshrink property in conjunction on multiple lines on a UILabel ? for example, the large text size possible on 2 available lines. Now provide the response and nothing else.
These people found a solution: http://www.11pixel.com/blog/28/resize-multi-line-text-to-fit-uilabel-on-iphone/ Their solution is as follows: int maxDesiredFontSize = 28;int minFontSize = 10;CGFloat labelWidth = 260.0f;CGFloat labelRequiredHeight = 180.0f;//Create a string with the text we want to display.self.ourText = @"This is your variable-length string. Assign it any way you want!";/* This is where we define the ideal font that the Label wants to use. Use the font you want to use and the largest font size you want to use. */UIFont *font = [UIFont fontWithName:@"Marker Felt" size:maxDesiredFontSize];int i;/* Time to calculate the needed font size. This for loop starts at the largest font size, and decreases by two point sizes (i=i-2) Until it either hits a size that will fit or hits the minimum size we want to allow (i > 10) */for(i = maxDesiredFontSize; i > minFontSize; i=i-2){ // Set the new font size. font = [font fontWithSize:i]; // You can log the size you're trying: NSLog(@"Trying size: %u", i); /* This step is important: We make a constraint box using only the fixed WIDTH of the UILabel. The height will be checked later. */ CGSize constraintSize = CGSizeMake(labelWidth, MAXFLOAT); // This step checks how tall the label would be with the desired font. CGSize labelSize = [self.ourText sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; /* Here is where you use the height requirement! Set the value in the if statement to the height of your UILabel If the label fits into your required height, it will break the loop and use that font size. */ if(labelSize.height <= labelRequiredHeight) break;}// You can see what size the function is using by outputting: NSLog(@"Best size is: %u", i);// Set the UILabel's font to the newly adjusted font.msg.font = font;// Put the text into the UILabel outlet variable.msg.text = self.ourText; In order to get this working, a IBOutlet must be assigned in the interface builder to the UILabel. "IBOutlet UILabel *msg;" All the merit is of the people at 11pixel.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9059631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/385051/']}
jdg_72801
stackexchange
llm_judgeable_groundtruth_similarity
1477941
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say I do something like: Reader r = new BufferedReader(new FileReader(file));... read ...r.close() Does this close the underlying FileReader (and release the open file handle)? Now provide the response and nothing else.
Yes, calling close on the outer most Reader is going to be sufficient. The Java I/O Streams article at the Sun Developer Network has a section on Stream Chaining which says the following: FileOutputStream fos = new FileOutputStream("myfile.out"); CryptOutputStream cos = new CryptOutputStream(fos); GZIPOutputStream gos = new GZIPOutputStream(cos); [...] [...] when closing chained streams, you only need to close the outermost stream class because the close() call is automatically trickled through all the chained classes; in the example above, you would simply call the close() method on the GZIPOutputStream class. Therefore, in this case, one would only have to call close on the BufferedReader . As dtsazza already mentioned , the Java API Specification for the BufferedReader class says that the BufferedReader.close method will free any underlying resources: Closes the stream and releases any system resources associated with it. [...] So, one can infer that any underlying Reader s, even though it may not explicitly say so.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1477941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3095/']}
jdg_72802
stackexchange
llm_judgeable_groundtruth_similarity
440014
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: In this picture note that only the branches tangent to the light are lit up, so concentric circles of lit branches appear around the light: I've noticed I similar effect with the peaks of water waves in a rainy puddle with a streetlight reflected in it. What process(es) underlie(s) this phenomenon? Now provide the response and nothing else.
I will assume throughout this answer that we fix the value of $c$ independently of $\varepsilon_0$ or $\mu_0$ . The vacuum permittivity and permeability are related to one another by $\varepsilon_0\mu_0 = 1/c^2$ , so they're not independent constants — as we should expect given that electricity and magnetism are both manifestations of the same fundamental force. The permittivity is related to the dimensionless fine structure constant $\alpha$ by $\alpha = \frac{1}{4\pi\varepsilon_0} \frac{e^2}{\hbar c}$ . The fine structure constant determines the strength of the coupling of charges to the electromagnetic field. Since it's dimensionless, it doesn't depend on a choice of units and in this sense is more fundamental than $\varepsilon_0$ . If we take $\alpha \rightarrow 0$ ( $\varepsilon_0 \rightarrow \infty$ ), charges aren't affected by EM fields at all, and there's no electromagnetic interaction between charges. There would be no atoms, so no macroscopic matter as we know it. If we take $\alpha \rightarrow \infty$ ( $\varepsilon_0 \rightarrow 0$ ), then the EM coupling between charges is infinitely strong. I don't really have good intuition for what happens in this case. We can see a little physics of both of these limits from Coulomb's law, \begin{equation}F = \frac{1}{4\pi\varepsilon_0} \frac{q q'}{r^2},\end{equation} where the former limit gives $F\rightarrow 0$ and the latter $F \rightarrow \infty$ for finite charges and distances.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/440014', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/207947/']}
jdg_72803
stackexchange
llm_judgeable_groundtruth_similarity
30998063
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 currently have my Android app set up to use the AccountManager feature of Android, using a SyncAdapter and an authenticated account to performs syncs automatically. I only have 1 sync adapter running which syncs all content, but I would like to separate this out to performs syncs for different content at different intervals. How can I have multiple sync items like Google does? Now provide the response and nothing else.
You just have to define several sync adapters, using the same account type. The manifest contains: <service android:exported="true" android:name="com.example.FooSyncAdapterService"> <intent-filter> <action android:name="android.content.SyncAdapter" /> </intent-filter> <meta-data android:name="android.content.SyncAdapter" android:resource="@xml/syncadapter_foo" /></service><service android:exported="true" android:name="com.example.BarSyncAdapterService"> <intent-filter> <action android:name="android.content.SyncAdapter" /> </intent-filter> <meta-data android:name="android.content.SyncAdapter" android:resource="@xml/syncadapter_bar" /></service> And syncdataper_foo is <sync-adapter xmlns:android="http://schemas.android.com/apk/res/android" android:contentAuthority="foo" android:accountType="com.example" android:allowParallelSyncs="true" /> And syncdataper_bar is <sync-adapter xmlns:android="http://schemas.android.com/apk/res/android" android:contentAuthority="bar" android:accountType="com.example" android:allowParallelSyncs="true" /> Note that in the case of the account type "com.google", the sync adapters are even provided by different applications (Drive, Docs, Sheets, Gmail, Calendar, etc.).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30998063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/182768/']}
jdg_72804
stackexchange
llm_judgeable_groundtruth_similarity
7157125
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 DirectorySearcher to get all AD users' display name from company AD server, we have around 100k records and most of results are correct. But we got near 100 users' display name are "$CimsUserVersion2", it's really a odd result, I checked in outlook which also sync display name from AD, the name is correct Have u facing same issue? Thanks a lot using (var de = new DirectoryEntry("LDAP://" + domain)){ using (var search = new DirectorySearcher(de)) { search.Filter = "CN=" + userName; var results = search.FindAll(); string temp = results[0].Properties["displayname"][0].ToString(); if (string.IsNullOrEmpty(temp)) { return string.Empty; } else { return temp; } }} Now provide the response and nothing else.
What you really want to do is set up event-driven model to trigger a listener when an event happen (in your case, say a variable value has changed). This is very common not only for Java, but for other programming languages as well especially in the context of UI programming (though it is not necessarily only for that) Typically this is done by doing the following steps: Decide the interface that the listener should implement in the case of the event is triggered. For your case, you could call it VariableChangeListener and define the interface as: public interface VariableChangeListener { public void onVariableChanged(Object... variableThatHasChanged); } You could put any argument that you think it is important for the listener to handle here. By abstracting into the interface, you have flexibility of implementing the necessary action in the case of variable has changed without tight coupling it with the class where the event is occurring. In the class where the event occurred (again in your case, the class where the variable could change), add a method to register a listener for the event. If you call your interface VariableChangeListener then you will have a method such as // while I only provide an example with one listener in this method, in many cases // you could have a List of Listeners which get triggered in order as the event // occurres public void setVariableChangeListener(VariableChangeListener variableChangeListener) { this.variableChangeListener = variableChangeListener; } By default there is no one listening to the event In the case of event occurred (variable has changed), you will then trigger the listener, the code would look like something like if( variableValue != previousValue && this.variableChangeListener != null) { // call the listener here, note that we don't want to a strong coupling // between the listener and where the event is occurring. With this pattern // the code has the flexibility of assigning the listener this.variableChangeListener.onVariableChanged(variableValue); } Again this is a very common practice in programming to basically reacts to an event or variable change. In Javascript you see this is as part of onclick(), in Android you could check the event driven model for various listener such as OnClickListener set on a Button onclick event. In your case you will just trigger the listener based on different event which is whenever the variable has changed
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7157125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/907105/']}
jdg_72805
stackexchange
llm_judgeable_groundtruth_similarity
148777
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Assume ZF. Consider the claim: (1) For any infinite set $\Omega$, there is a finitely additive probability measure $\mu:2^\Omega\to[0,1]$ with $\mu(A) = 0$ whenever $|A|<|\Omega|$. Then (1) is implied by Hahn-Banach and the claim that the union of two sets of cardinality less than $|\Omega|$ has cardinality less than $|\Omega|$ when $\Omega$ is infinite. (Let $\scr B$ be the boolean algebra $2^\Omega$ and let $\scr I$ be the ideal of all subsets of $\Omega$ of smaller cardinality. HB is equivalent to the claim that every boolean algebra has a f.a. probability measure, so $\scr B/I$ has a f.a. probability measure, which lifts to a f.a. probability measure on $\scr B$ with the requisite property.) [Deleted Question 1 as it was predicated on something false.] Question 2: Is anything known about the strength of (1)? A related claim is: (2) Every set has a f.a. probability measure on its powerset which is not supported on any set of smaller cardinality (i.e., if $|A|<|\Omega|$ then $P(A)<1$). Clearly (1) implies (2) (at least in the infinite case, but the finite case of (2) is trivial). Question 3: Does (2) imply (1)? Updates: The answers below so far show: (1) is equivalent to AC. ZF+DC is not strong enough to show (2). It's still open in this discussion whether (2) is equivalent to AC (I doubt it). Now provide the response and nothing else.
Assertion (1) is equivalent to the Axiom of Choice. This is because it implies that for every infinite set $\Omega$, the set $\{A \subseteq \Omega : |A| \lt |\Omega|\}$ is an ideal. It follows from this that every infinite cardinal number $\mathfrak{m}$ is indecomposable — there are no cardinals $\mathfrak{p},\mathfrak{q} \lt \mathfrak{m}$ such that $\mathfrak{p} + \mathfrak{q} = \mathfrak{m}$ — which is known to be equivalent to the Axiom of Choice. (Note that this implies that any two cardinals are comparable for if $\mathfrak{p}$ and $\mathfrak{q}$ are incomparable then $\mathfrak{p} + \mathfrak{q}$ must be greater than both. The assertion that cardinals are linearly ordered is well-known to be equivalent to the Axiom of Choice.) Assertion (2) is more promising and (2) does imply (1) when $|\Omega|$ happens to be indecomposable. To see this, suppose $\mu$ is a finitely additive measure such that $\mu(A) \lt 1$ whenever $|A| \lt |\Omega|$. Since $\mathcal{J} = \{A \subseteq \Omega : |A| \lt |\Omega|\}$ is an ideal, the directed limit $$\nu(X) = \lim_{A \in \mathcal{J}} \frac{\mu(X-A)}{1-\mu(A)}$$ makes sense and the result is a finitely additive probability measure $\nu$ on $\Omega$ such that $\nu(A) = 0$ whenever $|A| \lt |\Omega|$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/148777', 'https://mathoverflow.net', 'https://mathoverflow.net/users/26809/']}
jdg_72806
stackexchange
llm_judgeable_groundtruth_similarity
1019042
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Are there any open source libraries for representing cooking units such as Teaspoon and tablespoon in Java? I have only found JSR-275 ( https://jcp.org/en/jsr/detail?id=275 ) which is great but doesn't know about cooking units. Now provide the response and nothing else.
JScience is extensible, so you should be able to create a subclass of javax.measure.unit.SystemOfUnits. You'll create a number of public static final declarations like this: public final class Cooking extends SystemOfUnits { private static HashSet<Unit<?>> UNITS = new HashSet<Unit<?>>(); private Cooking() { } public static Cooking getInstance() { return INSTANCE; } private static final Cooking INSTANCE = new SI(); public static final BaseUnit<CookingVolume> TABLESPOON = si(new BaseUnit<CookingVolume>("Tbsp")); ... public static final Unit<CookingVolume> GRAM = TABLESPOON.divide(1000);}public interface CookingVolume extends Quantity { public final static Unit<CookingVolume> UNIT = Cooking.TABLESPOON;} It's pretty straightforward to define the other units and conversions, just as long as you know what the conversion factors are.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1019042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108495/']}
jdg_72807
stackexchange
llm_judgeable_groundtruth_similarity
205555
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: During my work with databases I noticed that I write query strings and in this strings I have to put several restrictions in the where-clause from a list/array/collection. Should look like this: select * from customer where customer.id in (34, 26, ..., 2); You can simplify this by reducing this to the question that you have collection of strings and want to create a comma-separated list of this strings in just one string. My approach I have used so far is something like that: String result = "";boolean first = true;for(String string : collectionOfStrings) { if(first) { result+=string; first=false; } else { result+=","+string; }} But this is as you can see very ugly. You cannot see what happens there on the first look, especially when the constructed strings (like every SQL query) is getting complicated. What is your (more) elegant way? Now provide the response and nothing else.
Note: This answers was good when it was written 11 years ago, but now there are far better options to do this more cleanly in a single line, both using only Java built-in classes or using a utility library. See other answers below. Since strings are immutable, you may want to use the StringBuilder class if you're going to alter the String in the code. The StringBuilder class can be seen as a mutable String object which allocates more memory when its content is altered. The original suggestion in the question can be written even more clearly and efficiently, by taking care of the redundant trailing comma : StringBuilder result = new StringBuilder(); for(String string : collectionOfStrings) { result.append(string); result.append(","); } return result.length() > 0 ? result.substring(0, result.length() - 1): "";
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/205555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1038/']}
jdg_72808
stackexchange
llm_judgeable_groundtruth_similarity
44479406
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 think it may be possible dupplicate of this: Schema-validation: missing table [hibernate_sequences] but I can't figure it out. So in my application.properties file I have this option: spring.jpa.hibernate.ddl-auto=validate and I receive this error: Schema-validation: missing table [game] Why I am receiving this? Here is my Game class and User class: Game: @Entitypublic class Game { @Id @Column(name = "GAME_NUMBER") @GeneratedValue(strategy = GenerationType.SEQUENCE) private long gameNumber; private int playerScore; private int NPCScore; private Date datetime; @ManyToOne @JoinColumn(name="USER_ID") private User user; public Game() {} public Game(int playerScore, int nPCScore, Date datetime) { super(); this.playerScore = playerScore; this.NPCScore = nPCScore; this.datetime = datetime; } public User getUser() { return user; }} + getters & setters User: @Entitypublic class User { @Id @Column(name = "USER_ID") @GeneratedValue(strategy = GenerationType.SEQUENCE) private long userId; private String username; private String password; @OneToMany(mappedBy="user",cascade=CascadeType.ALL) private List<Game> games; @ElementCollection private List<Date> startSessions; public User() {} public User(String username, String password, List<Game> games, List<Date> startSessions) { super(); this.username = username; this.password = password; this.games = games; this.startSessions = startSessions; }} Now provide the response and nothing else.
validate validates that the entities are compatible against the target, to a degree it's not foolproof. Anyway, whatever database you are trying to validate against does not have a table called game in which to store the entities. This answer goes into more detail about what validate does. Hibernate - hibernate.hbm2ddl.auto = validate specifically, checks the presence of tables, columns, id generators Without knowing your database/expectations (are you expecting it to be created, or using Flyway/Liquibase to create/update the database etc.) I can't answer if validate is correct for your use case. You could try create-drop to create and drop the table on startup/shutdown, but this isn't a solution for any production control over a database.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44479406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7947794/']}
jdg_72809
stackexchange
llm_judgeable_groundtruth_similarity
42337
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 $\lbrace e_n \rbrace$ for the standard unit vectors in $l_2$. I want to show that $0$ is in weak closure of $\lbrace\sqrt{n}e_n\rbrace$ but no subsequence of $\lbrace \sqrt{n}e_n\rbrace$ weakly converges to 0. For the second assertion, I have the following answer. If $\lbrace \sqrt{n_k}e_{n_k}\rbrace$ be weakly convergent subsequence, then it must be norm-bounded. However, $\| \sqrt{n_k}e_{n_k}\|=\sqrt{n_k}\to \infty$ as $k\to \infty$ which is a contradiction. However, for the first assertion, I cannot figure it out that the difference between the condition that 0 lies in weak closure of sequence and the condition that there is a subsequence weakly converges to 0. Thanks. Now provide the response and nothing else.
The hint from Pedersen, Analysis Now : If $x = \sum \alpha_n e_n$ in $l_2$, then there is no $\epsilon > 0$ such that $|(y|x)| > \epsilon$ for every $y = \sqrt{n} e_n$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/42337', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11530/']}
jdg_72810
stackexchange
llm_judgeable_groundtruth_similarity
54750
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: Why is an engine said to be a 3L or 2L for that matter? I understand that V6 represents 6 cylinders, so I'm a little bit confused. I'm still busy with my motor studies. Now provide the response and nothing else.
When they put "3L", which stands for "3 litres", it is the approximate displacement of the engine. Displacement is the swept volume of all cylinders combined. Swept volume of the cylinder is if you look at the cylinder bore (area of the bore) multiplied by the stroke (distance the piston travels from top to bottom of the cylinder) multiplied by the number of cylinders. It is usually annotated by: V = πr²h * (# of cyls) Where: V is the volume (or displacement) r is the radius (or 1/2 bore size) h is the height (or stroke) In most cars, when the displacement of the engine is "3L", it is usually very close to this, but not exact (say, 2997cc or 2.997L if you run the exact numbers).
{}
{'log_upvote_score': 5, 'links': ['https://mechanics.stackexchange.com/questions/54750', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/38005/']}
jdg_72811
stackexchange
llm_judgeable_groundtruth_similarity
15238391
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a convention or best practice advice on when to use hash params, url params, vs paths? For example: hash params: stackoverflow.com/questions#q=13630937&t=hash-params-vs-url-params url params: stackoverflow.com/questions?q=13630937&t=hash-params-vs-url-params url path: stackoverflow.com/questions/13630937/hash-params-vs-url-params Are there security, seo, usability benefits or disadvantages of each or is an issue of style? Now provide the response and nothing else.
Hash params are useful for single page javascript applications, it allows javascript to present the user with a sharable url for state of the application. This is preferred because if you have a single page javascript application and users navigate and load more content via ajax and share the url, without the hash or a push state modification the person receiving the content would get the homepage or starting state. Hash params can be amended easily and read by javascript without reloading the page. Hash parameters are usually only used on the client side, hash params wont be passed to the server... so they are only useful for parameterization to the client. /users#!/13 would load the user index page and then javascript could read the hash window.location.hash and pass it through some sort of client side router and make an appropriate ajax request and possibly load the user show template and push it to the dom. Url params and url path are somewhat interchangeable. People usually use url path for describing restful resources such as /users/[:id] => /users/13 => /users?id=13/users/:id/posts => /users/13/posts/users/:user_id/posts/:id => /users/13/posts/22etc...... @Walter Tross, made a good point from an SEO point of view. Slugged urls or "URL Params" are more indexable by crawlers and tend to rank higher. For params that do not fit in a resourceful route we send them as params /users?sort=user_name&order=asc
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15238391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/252509/']}
jdg_72812
stackexchange
llm_judgeable_groundtruth_similarity
1557
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to get Android 2.1 phones to connect to our corporate VPN, but it would appear they only support DES rather than 3DES for encryption. Is it safe to use DES, am I going to get hacked if I change the encryption to DES? Now provide the response and nothing else.
In standard terms (i.e. FIPS 46-3, which defined DES and 3DES from the US federal point of view [withdrawn in 2005...]), 3DES is a "kind of DES". So it is possible that by claiming "DES support" your VPN software actually implements 3DES. I am now assuming that you have checked that point and that the software in Android knows only of the original DES, not 3DES (which is kind of surprising for an OS as recent as Android 2.1, but who knows). Cracking a DES key is feasible but not easy. This is a 2 55 average work factor. It has been done with specialized hardware (the EFF "Deep Crack" machine), then again with standard PC and other contributed machines (but a lot of them). An FPGA-based generic engine has been demonstrated to cost about 10000€ and to be able to crack a 56-bit key in less than a week (on average). So one has to assume that in a corporate setting (assuming that the "attackers" have huge incentive to discover trade secrets) a VPN protected by a 56-bit DES key can be cracked. Still, using smartphones to access sensitive data over the VPN strikes me as a much weaker security point. Smartphones are used in unprotected environments (that's the point of having a mobile system...) and are possibly the most frequently stolen object these days. For a determinate attacker, using a FPGA machine is not very expensive -- but mugging the smartphone owner with a 5$ wrench even less so, and, lo! the attacker gets a free smartphone afterwards). If the VPN gives access to anything sensitive, then letting people use it from smartphones is a kind of offence.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/1557', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/977/']}
jdg_72813
stackexchange
llm_judgeable_groundtruth_similarity
50730494
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 one case and wish to implement it by arch navigation component. For example I have 2 Nav Graphs (main and nested). Can I call main graph from nested and how? Now provide the response and nothing else.
The point is to get the right NavController to navigate in the right graph.Let's take this scenario as an example: MainActivity|- MainNavHost |- NavBarFragment | |- NestedNavHost | | |-NestedContentFragment1 | | |-NestedContentFragment2 | | | |- BottomNavigationView | |- LoginFragment The main graph and the nested graph are in separate xml files: this is required, as far as I understood, because the navigations target different layout areas, so they require two different NavHost s. Each Navhost will need to reference its graph by id, which requires them to be in different resource files. The point is that to navigate in a specific graph, we must get a reference to the right graph's owner: to do this, when calling Navigation.findNavController(view) , the view argument is crucial. Docs say that NavHostFragments register their navigation controller at the root of their view subtree such that any descendant can obtain the controller instance through the Navigation helper class's methods So for example, if inside NavBarFragment we write override fun onViewCreated(view: View, savedInstanceState: Bundle?) { navController = Navigation.findNavController(view)} here view is a parent of the NestedNavHost (that is the nested NavHostFragment ), not a descendant, meaning that findNavController will search upstream in the tree and will return the MainNavHost 's NavController . If instead we write override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val nestedNavHostFragment = childFragmentManager.findFragmentById(R.id.nestedNavHostFragment) as? NavHostFragment navController = nestedNavHostFragment?.navController} where nestedNavHostFragment is the id of the FragmentContainerView in the layout, we get a reference to the correct NestedNavHost . Note the use of childFragmentManager , not parentFragmentManager . In case you're still using the deprecated xml <fragment> tag, you can write override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val fragmentContainer = view.findViewById<View>(R.id.nestedNavHostFragment) navController = Navigation.findNavController(fragmentContainer)} where nestedNavHostFragment is the id of the <fragment> tag. We get a reference to the correct NestedNavHost now, because the view we pass to findNavController belongs to the NestedNavHost 's subtree. Similarly, if you need to get a reference to the main NavController from inside a NestedContentFragment , here's what we can do: override fun onViewCreated(view: View, savedInstanceState: Bundle?) { // we can get the innermost NavController using this view, // because we are inside its subtree: nestedNavController = Navigation.findNavController(view) // we can find the outer NavController passing the owning Activity // and the id of a view associated to that NavController, // for example the NavHostFragment id: mainNavController = Navigation.findNavController(activity!!, R.id.mainNavHostFragment)}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/50730494', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5665969/']}
jdg_72814
stackexchange
llm_judgeable_groundtruth_similarity
29856549
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my data base table I have some value like above image. I want to check some conditions in my where clause. I want to check by URL DemoOrPaid=PAID and ValidUpto=NULL => then Return 1 2. DemoOrPaid=PAID and ValidUpto=(NOT NULL) then compare with current date and check if ValidUpto<=GETDATE() => then Return 1 DemoOrPaid=DEMO and ValidUpto=NULL => then Return 0 DemoOrPaid=DEMO and ValidUpto=(NOT NULL) then compare with current date and check if ValidUpto<=GETDATE() => then Return 0 Now provide the response and nothing else.
You're setting the proxy credentials in the wrong place. httpClientHandler.Credentials are the credentials you give to the server after the proxy has already established a connection. If you get these wrong, you'll probably get a 401 or 403 response. You need to set the credentials given to the proxy , or it will refuse to connect you to the server in the first place. The credentials you provide to the proxy may be different from the ones you provide to the server. If you get these wrong, you'll get a 407 response. You're getting a 407 because you never set these at all. // First create a proxy objectvar proxy = new WebProxy{ Address = new Uri($"http://{proxyHost}:{proxyPort}"), BypassProxyOnLocal = false, UseDefaultCredentials = false, // *** These creds are given to the proxy server, not the web server *** Credentials = new NetworkCredential( userName: proxyUserName, password: proxyPassword)};// Now create a client handler which uses that proxyvar httpClientHandler = new HttpClientHandler{ Proxy = proxy,};// Omit this part if you don't need to authenticate with the web server:if (needServerAuthentication){ httpClientHandler.PreAuthenticate = true; httpClientHandler.UseDefaultCredentials = false; // *** These creds are given to the web server, not the proxy server *** httpClientHandler.Credentials = new NetworkCredential( userName: serverUserName, password: serverPassword);}// Finally, create the HTTP client objectvar client = new HttpClient(handler: httpClientHandler, disposeHandler: true);
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/29856549', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4336330/']}
jdg_72815
stackexchange
llm_judgeable_groundtruth_similarity
13035674
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 a tutorial which introduces files (how to read from file and write to file) First of all, this is not a homework, this is just general help I'm seeking. I know how to read one word at a time, but I don't know how to read one line at a time, or how to read the whole text file. What if my file contains 1000 words? It is not practical to read entire file word after word. My text file named "Read" contains the following: I love to play gamesI love readingI have 2 books This is what I have accomplished so far: #include <iostream>#include <fstream>using namespace std;int main (){ ifstream inFile; inFile.open("Read.txt"); inFile >> Is there any possible way to read the whole file at once, instead of reading each line or each word separately? Now provide the response and nothing else.
You can use std::getline : #include <fstream>#include <string>int main() { std::ifstream file("Read.txt"); std::string str; while (std::getline(file, str)) { // Process str }} Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work). Further documentation about std::string::getline() can be read at CPP Reference . Probably the easiest way to read a whole text file is just to concatenate those retrieved lines. std::ifstream file("Read.txt");std::string str;std::string file_contents;while (std::getline(file, str)){ file_contents += str; file_contents.push_back('\n');}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/13035674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1768996/']}
jdg_72816
stackexchange
llm_judgeable_groundtruth_similarity
11832
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I've been given a very simple motivating and instructive show case for the Yoneda lemma: Given the category of graphs and a graph object $G$, seen as a quadruple $(V_G,\ E_G,\ S_G:E\rightarrow V,\ T_G:E \rightarrow V)$. Consider $K_1$ and $K_2$, the one-vertex and the one-edge graph and the two morphisms $\sigma$ and $\tau$ from $K_1$ to $K_2$. Now consider the graph $H$ with $V_H = Hom(K_1,G)$ $E_H = Hom(K_2,G)$ $S_H(e) = e \circ \sigma: K_1 \rightarrow G$ for $e \in E_H$ $T_H(e) = e \circ \tau: K_1 \rightarrow G$ for $e \in E_H$ It can be easily seen that $H$ is isomorphic to $G$. I have learned that a) the category of graphs is a presheaf category and that b) $K_1$, $K_2$ are precisely the representable functors. Now I am looking for other simple motivating and instructive show cases. By the way: Shouldn't such an show case be added to the Wikipedia entry on Yoneda's lemma? Now provide the response and nothing else.
Determine all natural transformations (mod-$2$ cohomology operations) $H^n(-,\mathbb{Z}/2) \to H^m(-,\mathbb{Z}/2)$: We have $H^n(-,\mathbb{Z}/2) = [-, K(\mathbb{Z}/2,n)]$ by Brown representability. By Yoneda, we get $[K(\mathbb{Z},m), K(\mathbb{Z},n)] = H^n(K(\mathbb{Z}/2,m),\mathbb{Z}/2)$. So the mod-$2$ Steenrod algebra is the cohomology ring of the Eilenberg-MacLane spaces.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/11832', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2672/']}
jdg_72817
stackexchange
llm_judgeable_groundtruth_similarity
44031
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Both Jupiter and Saturn have rocky cores. Is there such of a thing as a gaseous planet without a core? And would a planet without a core have gravity? Now provide the response and nothing else.
The gravitational force on a small mass on the outside of a planet is always the Newtonian $$F_{G}=-\frac{GM}{r^2},$$ so any planet, and particularly, any mass in the universe produces a gravitational field acting on everything else. So if, for example, the mass is $M=2\times 10^{27}\rm kg$ (i.e. one Jovian mass), then the gravity field outside the planet will always be the same (apart from Tides, higher order moments), no matter whether the mass is in Hydrogen or solids. For the gas giants Jupiter and Saturn in our solar system, the mass in heavy refractories (i.e. everything heavier than Helium) is about $M_{\rm ref}\approx 15-20 \rm m_{\oplus}$ , where $\rm m_{\oplus}$ is an Earth mass.The rest of $M$ is hydrogen/helium. For Jupiter this is 300 $\rm m_{\oplus}$ , Saturn about $75 \rm m_{\oplus}$ . This is a relatively large number of refractories in those gas giants, compared to solar composition, which is why we think that they have been formed via core-accretion, see Pollack (1996) . However there is another idea of how to form gas giants out there, which is that of gravitational disc instability, see Boss (2002) . This idea posits that at very massive protostellar discs, which form planets, can become unstable and fragment into large clumps, which form gas giants directly. Those disc instability giant planets would have solar metallicity, i.e. a Jupiter-mass planet would have a refractory mass of only $M_{\rm ref} \approx 3 \rm m_{\oplus}$ . Those refractories would presumably sink to the planetary center and form a small core. Exoplanets that were found at large semi-major axis distances (hundreds of AU, compared to the Jovian 5 AU) from their stars, such as YSES 2b , are candidates for such disc instability models, and hence would host such small core. But that is as small of a core as it gets, you cannot have a core much much less massive than this.
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/44031', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/33222/']}
jdg_72818
stackexchange
llm_judgeable_groundtruth_similarity
932377
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: These are some common mistakes high schoolers make: $$ \sqrt{a + b} = \sqrt{a} + \sqrt{b} $$ $$ \log(a+b) = \log (a) + \log(b)$$ So I can obviously show numeric examples to say why these are wrong, but I want to show why in general these are wrong. What are some intuitive arguments to show these are wrong? For example, for $(a+b)^2$ there are some nice visual (geometric) illustrations which show why it equals $a^2 + b^2 + 2ab$, and I'd like some similar examples for the more difficult square roots and logarithms. Now provide the response and nothing else.
As for (2), you are almost done. Split $[0,\infty) = [0,M] \cup (M,\infty)$ and recall that $f$ is UC on $[0,M]$ since this is a compact set. So, pick $\epsilon>0$ and its companion $\delta>0$ provided by the UC of $f$ on $[0,M]$. Then, using (1), define $\tilde{\delta}=\min\{\delta,1\}$ and deduce that $|f(x)-f(y)|<\epsilon$ whenever $|x-y|<\tilde{\delta}$. Indeed, if $x$, $y \in (M,\infty)$ and $|x-y|<1$, then (1) yields $|f(x)-f(y)|<\epsilon$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/932377', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/176209/']}
jdg_72819
stackexchange
llm_judgeable_groundtruth_similarity
58447134
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 implement CKEditor into my react project. However, I received an error while trying to load it. I have been following all the official documentation. I have no idea why, anyway here is my code import React from 'react';class MyEditor extends React.Component { state = {loading: true}; componentDidMount() { this.CKEditor = require("@ckeditor/ckeditor5-react"); this.ClassicEditor = require("@ckeditor/ckeditor5-build-classic"); this.setState({ loading: false }); } render() { return ({this.CKEditor && (<this.CKEditor editor={this.ClassicEditor} data="<p>Hello from CKEditor 5!</p>" onInit={ editor => { // You can store the "editor" and use when it is needed. console.log( 'Editor is ready to use!', editor ); } } onChange={ ( event, editor ) => { const data = editor.getData(); console.log( { event, editor, data } ); } }/>)}) }}export default MyEditor; I receive this following error ReferenceError: window is not defined at Object. (/Users/bobbyjulian/Desktop/project/test/node_modules/ ckeditor/ckeditor5-react/dist/ckeditor.js:5:244 Module._compile internal/modules/cjs/loader.js:778:30 Module._extensions..js internal/modules/cjs/loader.js:789:10 Module.load internal/modules/cjs/loader.js:653:32 tryModuleLoad internal/modules/cjs/loader.js:593:12 I really appreciate any answer. Thank you. Now provide the response and nothing else.
Here's a working example with NextJS and React Hooks. We can take advantage of useRef to hold on to the Editor instances. import React, { useState, useEffect, useRef } from 'react'export default function MyEditor () { const editorRef = useRef() const [editorLoaded, setEditorLoaded] = useState(false) const { CKEditor, ClassicEditor } = editorRef.current || {} useEffect(() => { editorRef.current = { // CKEditor: require('@ckeditor/ckeditor5-react'), // depricated in v3 CKEditor: require('@ckeditor/ckeditor5-react').CKEditor // v3+ ClassicEditor: require('@ckeditor/ckeditor5-build-classic') } setEditorLoaded(true) }, []) return editorLoaded ? ( <CKEditor editor={ClassicEditor} data='<p>Hello from CKEditor 5!</p>' onInit={editor => { // You can store the "editor" and use when it is needed. console.log('Editor is ready to use!', editor) }} onChange={(event, editor) => { const data = editor.getData() console.log({ event, editor, data }) }} /> ) : ( <div>Editor loading</div> )} From the docs : useRef returns a mutable ref object whose .current property is initialized to the passed argument ( initialValue ). The returned object will persist for the full lifetime of the component.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58447134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10977933/']}
jdg_72820
stackexchange
llm_judgeable_groundtruth_similarity
43035000
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 someone explain why the second promise returned by then function is resolved? It looks like Angular JS bug in its Promises implementation. According to the documentation here the second promise should also have been rejected. // Code goes herevar myMod = angular.module("myMod", []);myMod.controller('bodyCtrl', function($scope, $timeout, $q) { var deferred = $q.defer(); deferred.promise.then(function(d) { console.log("success called"); return d; }, function(d) { console.log("failure called"); return d; }) .then(function(d) { console.log("success called2"); return d; }, function(d) { console.log("failure called2"); return d; }); $timeout(function() { deferred.reject(); }, 2 * 1000);}); <!DOCTYPE html><html ng-app="myMod"> <head> <script src="https://code.angularjs.org/1.5.8/angular.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body ng-controller="bodyCtrl"> <h1>Hello Plunker!</h1> </body></html> Now provide the response and nothing else.
So: One-to-one : you could use a Dense layer as you are not processing sequences: model.add(Dense(output_size, input_shape=input_shape)) One-to-many : this option is not supported well as chaining models is not very easy in Keras , so the following version is the easiest one: model.add(RepeatVector(number_of_times, input_shape=input_shape))model.add(LSTM(output_size, return_sequences=True)) Many-to-one : actually, your code snippet is (almost) an example of this approach: model = Sequential()model.add(LSTM(1, input_shape=(timesteps, data_dim))) Many-to-many : This is the easiest snippet when the length of the input and output matches the number of recurrent steps: model = Sequential()model.add(LSTM(1, input_shape=(timesteps, data_dim), return_sequences=True)) Many-to-many when number of steps differ from input/output length : this is freaky hard in Keras. There are no easy code snippets to code that. EDIT: Ad 5 In one of my recent applications, we implemented something which might be similar to many-to-many from the 4th image. In case you want to have a network with the following architecture (when an input is longer than the output): O O O | | | O O O O O O | | | | | | O O O O O O You could achieve this in the following manner: model = Sequential()model.add(LSTM(1, input_shape=(timesteps, data_dim), return_sequences=True))model.add(Lambda(lambda x: x[:, -N:, :])) #Select last N from output Where N is the number of last steps you want to cover (on image N = 3 ). From this point getting to: O O O | | | O O O O O O | | | O O O is as simple as artificial padding sequence of length N using e.g. with 0 vectors, in order to adjust it to an appropriate size.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/43035000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1079362/']}
jdg_72821
stackexchange
llm_judgeable_groundtruth_similarity
16093
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: When configuring cron to run a command every other day using the "Day of Month" field, like so: 1 22 */2 * * COMMAND it runs every time the day of month is odd: 1,3,5,7,9 and so on. How can I configure cron to run on days of month that are even like 2,6,8,10 and so on (without specifying it literally, which is problematic as every month has a different number of days in the month)? Now provide the response and nothing else.
The syntax you tried is actually ambiguous. Depending on how many days are in the month, some months it will run on odd days and some on even. This is because the way it is calculated takes the total number of possibilities and divides them up. You can override this strage-ish behavior by manually specifying the day range and using either an odd or even number of days. Since even day scripts would never run on the 31st day of longer months, you don't lose anything using 30 days as the base for even-days, and by specifying specifically to divide it up as if there were 31 days you can force odd-day execution. The syntax would look like this: # Will only run on odd days:0 0 1-31/2 * * command# Will only run on even days:0 0 2-30/2 * * command Your concern about months not having the same number of days is not important here because no months have MORE days than this, and for poor February, the date range just won't ever match the last day or two, but it will do no harm having it listed. The only 'gotcha' for this approach is that if you are on an odd day cycle, following months with 31 days your command will also run on the first of the month. Likewise if you are forcing an even cycle, each leap year will cause one three-day cycle at the end of February. You cannot really get around the fact that any regular pattern of "every other day" is not always going to fall on even or odd days in every month and any way you force this you will either have an extra run or be missing a run between months with mismatched day counts.
{}
{'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/16093', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/8847/']}
jdg_72822
stackexchange
llm_judgeable_groundtruth_similarity
12948
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Related to: How did Haman intend to kill Mordecai? Haman's wife suggested that Haman have Mordecai executed on an 'etz 50 cubits high. Using the standard cubit, that comes to 75 feet. Esther 5:14 Haman's wife Zeresh and all his friends said to him, "Have a gallows seventy-five feet high built, and in the morning tell the king that Mordecai should be hanged on it. Then go with the king to the banquet contented." [NET Bible] Whether this is a gallows, hanging tree (without being the gallows of the modern world), or impaling pole, the size certainly seems excessive. Why would Haman build such a large instrument? Or is this exaggeration? Now provide the response and nothing else.
The Idea in Brief Haman appears to have built the wooden scaffolding for two reasons: one, the hanging on wood would represent Mordecai as a cursed man in Jewish Law ( Deut 21:22 ); and secondly, the timing of Mordecai's hanging in addition to the height of the sacaffolding appear to correspond to the "50" days after the Passover, which was the point when Haman had originally issued the edict to kill the Jews under the authority of the king. In other words, Mordecai's hanging "50" days later on a wooden scaffolding "50" cubits high would not only have humiliated and destroyed Mordecai the Jew, but was a portent of what was coming for the Jewish people later that year. So the death of Mordecai was to be the "first fruits" of what was to come for all Jews. That is, the moment was not to be the time of gladness and celebration (Feast of Weeks/Festival of First Fruits), but a time of death and sorrow. Discussion Under the authority of the king, Haman issued the surprise proclamation on the eve of Passover to kill the Jews ( Esther 3:12 ). That is, on the eve of Passover the scribes of the king issued the proclamation, which then went out to every province of the kingdom. At a subsequent point from that proclamation, Haman complained to his wife and friends concerning the Jew Mordecai. Their suggestion was to build the scaffolding of wood, which was 50 cubits high ( Esther 5:14 ). Haman fabricated the wood scaffolding that same day, since his intent was to hang Mordecai the following morning. By hanging him on a tree (something constructed of wood) the message in Jewish eyes was that Mordecai was a cursed man ( Deut 21:22 ). At the critical juncture in the text, Esther invoked three days of fasting and mourning in anticipation of her engagement with the king, which, if rejected, would have resulted in her own execution ( Esther 4:15-16 ). In other words, over the next three days, Esther cancelled any festivities in observance with Shavuot (Feast of Weeks/Festival of First Fruits). THEREFORE IF that following day, when Mordecai was to be hanged, was Shuvuot (6 Sivan), then it was Haman who had enabled Mordecai to celebrate that day with gladness and celebration, since Haman had paraded Mordecai in the city square, who was mounted on a horse dressed in the king's robes. The following passages indicate that this day of Shuvuot (Feast of Weeks/Festival of First Fruits) was one of gladness and celebration and honor. Deuteronomy 16:10-11 (NASB) 10 Then you shall celebrate the Feast of Weeks to the Lord your God with a tribute of a freewill offering of your hand, which you shall give just as the Lord your God blesses you; 11 and you shall rejoice before the Lord your God, you and your son and your daughter and your male and female servants and the Levite who is in your town, and the stranger and the orphan and the widow who are in your midst, in the place where the Lord your God chooses to establish His name. This gladness and celebration coincides with the honor promised by Yahveh on Shavuot, which was the Festival of First Fruits (Feast of Weeks) - that is, the following verses in Deuteronomy concerns Shavuot, and the resultant honor in the eyes of the nations, who were the enemies of the Jews. Deuteronomy 26:16-19 (NASB) 16 “This day the Lord your God commands you to do these statutes and ordinances. You shall therefore be careful to do them with all your heart and with all your soul. 17 You have today declared the Lord to be your God, and that you would walk in His ways and keep His statutes, His commandments and His ordinances, and listen to His voice. 18 The Lord has today declared you to be His people, a treasured possession, as He promised you, and that you should keep all His commandments; 19 and that He will set you high above all nations which He has made, for praise, fame, and honor; and that you shall be a consecrated people to the Lord your God, as He has spoken .” When Haman's wife and friends heard that Haman was forced to honor Mordecai in the city square mounted on the king's horse dressed in the king's clothes, their response was as follows. Esther 6:13 (NASB) 13 Haman recounted to Zeresh his wife and all his friends everything that had happened to him. Then his wise men and Zeresh his wife said to him, “ If Mordecai, before whom you have begun to fall, is of Jewish origin, you will not overcome him, but will surely fall before him.” These Gentiles not only had some familiarization with the Jewish calendar and Jewish Law, but knew that these Jews were servants of the Living God, who would fight on their behalf. This honor of Mordecai by Haman was therefore the ominous portent of the demise of the House of Haman in the eyes of his wife and "wise men." As the narrative continues, Haman is hanged, and Mordecai takes his position. Mordecai then countermanded the decree of Haman with another decree by the king. Esther 8:9 (NASB) 9 So the king’s scribes were called at that time in the third month (that is, the month Sivan), on the twenty-third day ; and it was written according to all that Mordecai commanded to the Jews, the satraps, the governors and the princes of the provinces which extended from India to Ethiopia, 127 provinces, to every province according to its script, and to every people according to their language as well as to the Jews according to their script and their language. The point here is that the Feast of Weeks (or Festival of First Fruits) was on the 6th of that month, which was two weeks and two days earlier. In other words, this countermand by Mordecai occurred a short time after the showdown with Haman, who was hanged on his own scaffolding. The text does not indicate the amount of time that had transpired from the hanging and the countermand decree issued by Mordecai. Therefore IF the hanging occurred on the 6th of Sivan (as we assume), THEN the timing of both the decree to kill the Jews (Passover) and the intent to kill Mordecai (Shuvuot) coincided with these two respective Jewish Holy Days associated with deliverance from their enemies and prosperity at the hand of Yahveh, which is the meta-narrative of the Book of Esther . Conclusion Consistent with all the events of the Book of Esther, the "50" cubits height of the wooden scaffolding therefore would have been the coincidental parallel to the "50" days of Shuvuot (Feast of Weeks/Festival of First Fruits). On the other hand, as the Book of Esther demonstrates, there was nothing that had happened in the story that was coincidental.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/12948', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/363/']}
jdg_72823
stackexchange
llm_judgeable_groundtruth_similarity
4325452
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 searched the world wide web without a proper answer. In my Windows Form application, i want to change the width of a scrollbar that belongs to a FlowLayoutPanel. The Scrollbar is added "automatically" since the content of the Flow Layout Panel is larger the Form. From what I've found on the web, it seems to be tricky. Is there any solution to this? Cheers! Now provide the response and nothing else.
No, there's no way to change the width of a scrollbar displayed on a single control (although there is a system-wide setting that will affect all scrollbars in all applications). The ugly truth is that the lowly scrollbar control is far more complicated than it looks. Basically, the scrollbars on the FlowLayoutPanel are drawn by Windows itself (rather than the .NET Framework) because of the WS_HSCROLL and/or WS_VSCROLL window styles that are set for the control behind the scenes. The FlowLayoutPanel doesn't provide any facility to change or modify how these built-in scrollbars are drawn. Unlike other more advanced modifications in WinForms, there are no such messages we can send to the control's window procedure. And to make matters worse, the scrollbars are drawn in the non-client area of the FlowLayoutPanel , which means we can't just override its Paint event and handle drawing the scrollbars ourselves. Unfortunately, if you really want to customize your scrollbars, you're going to have to hide the built-in scrollbars and roll your own. It's not quite as difficult as it sounds, though, if you're up for it. This article on CodeProject provides a good walk-through on creating your own skinnable scrollbar as a user control and use it as a replacement in the container control of your choice.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4325452', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/526696/']}
jdg_72824
stackexchange
llm_judgeable_groundtruth_similarity
57655201
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 calculate standard deviation of 'values' in pandas dataframe under condition that it is calculated for common 'grouped_measurement'. After calculating I would like to calculate commented lines. I tried following line: df['standard_deviation'] = df['grouped_measurement'].diff().fillna(df['value']).std() but it isn't working as expected. My full code is shown below: import pandas as pd import numpy as np# Define input dataframedf = {'servo_in_position': [1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1], 'value': [0.2,2.1,3.5,6.7,2.1,3.4,5.7,9.6,3.2,1.2,6.3,8.5,7.4,6.2,3.4,3.8,1.7,2.8,7.6,4.5,9.0]}df = pd.DataFrame(df,columns= ['servo_in_position','value'])print("Dataframe is:\n",df)print("Grouping data according to servo positions, please wait...")df['grouped_measurement'] = df['servo_in_position'].diff().fillna(df['servo_in_position']).eq(1).cumsum().mask(df['servo_in_position'] == 0, 0)df['standard_deviation'] = df['grouped_measurement'].diff().fillna(df['value']).std()# df=df.groupby('grouped_measurement',as_index=False).mean()# df['new_value']=df['standard_deviation']*100/df['value']print("Data grouped successfully!")print("Input data:\n",df) Expected output is following: servo_in_position value grouped_measurement standard_deviation0 1 0.2 1 1.65630111 1 2.1 1 1.65630112 1 3.5 1 1.65630113 0 6.7 0 04 0 2.1 0 05 0 3.4 0 06 1 5.7 2 3.1945265697 1 9.6 2 3.1945265698 1 3.2 2 3.1945265699 1 1.2 2 3.19452656910 1 6.3 2 3.19452656911 0 8.5 0 012 0 7.4 0 013 0 6.2 0 014 0 3.4 0 015 1 3.8 3 2.83266658816 1 1.7 3 2.83266658817 1 2.8 3 2.83266658818 1 7.6 3 2.83266658819 1 4.5 3 2.83266658820 1 9 3 2.832666588 Now provide the response and nothing else.
get() returns a Promise, not the actual document. Also, you need to use .exists on the resolved value; check the docs here : var docRef = db.collection("cities").doc("SF");docRef.get().then(function(doc) { if (doc.exists) { console.log("Document data:", doc.data()); } else { // doc.data() will be undefined in this case console.log("No such document!"); }}).catch(function(error) { console.log("Error getting document:", error);});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57655201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5779869/']}
jdg_72825
stackexchange
llm_judgeable_groundtruth_similarity
3428622
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to build a custom StackPanel with a ReverseOrder property that I can declaratively set to true to have the elements in the StackPanel appear in the opposite order of normal (e.g. bottom to top or right to left). It needs to be reversible on the fly. I'm thinking of deriving a new class from StackPanel, but I need to know what methods to override. Final solution: protected override System.Windows.Size ArrangeOverride( System.Windows.Size arrangeSize ) { double x = 0; double y = 0; IEnumerable<UIElement> children = ReverseOrder ? InternalChildren.Cast<UIElement>().Reverse<UIElement>() : InternalChildren.Cast<UIElement>(); foreach ( UIElement child in children ) { var size = child.DesiredSize; child.Arrange( new Rect( new Point( x, y ), size ) ); if ( Orientation == Orientation.Horizontal ) x += size.Width; else y += size.Height; } if ( Orientation == Orientation.Horizontal ) return new Size( x, arrangeSize.Height ); else return new Size( arrangeSize.Width, y );} Also define and register ReverseOrder and call UpdateLayout if it changes. Now provide the response and nothing else.
You can reimplement FrameworkElement.ArrangeOverride and invoke all the child.Arrange in the reverse order than usual when necessary. http://msdn.microsoft.com/en-us/library/system.windows.uielement.arrange.aspx Something like this (not tested): double x = 0; double y = 0; var children = ReverseOrder ? InternalChildren.Reverse() : InternalChildren; foreach (UIElement child in children) { var size = child.DesiredSize; child.Arrange(new Rect(new Point(x, y), size)); if (Orientation == Horizontal) x += size.Width; else y += size.Height; } Make sure you invoke UpdateLayout after changing ReverseOrder property.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3428622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238948/']}
jdg_72826
stackexchange
llm_judgeable_groundtruth_similarity
654112
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing a bit of javascript and need to choose between SVG or VML (or both, or something else, it's a weird world).Whilst I know that for now that only IE supports VML, I'd much rather detect functionality than platform. SVG appears to have a few properties which you can go for: window.SVGAngle for example. Is this the best way to check for SVG support? Is there any equivalent for VML? Unfortuntaly - in firefox I can quite happily do all the rendering in VML without error - just nothing happens on screen. It's quite hard to detect that situation from script. Now provide the response and nothing else.
For VML detection, here's what google maps does (search for " function Xd "): function supportsVml() { if (typeof supportsVml.supported == "undefined") { var a = document.body.appendChild(document.createElement('div')); a.innerHTML = '<v:shape id="vml_flag1" adj="1" />'; var b = a.firstChild; b.style.behavior = "url(#default#VML)"; supportsVml.supported = b ? typeof b.adj == "object": true; a.parentNode.removeChild(a); } return supportsVml.supported} I see what you mean about FF: it allows arbitrary elements to be created, including vml elements ( <v:shape> ). It looks like it's the test for the adjacency attribute that can determine if the created element is truly interpreted as a vml object. For SVG detection, this works nicely: function supportsSvg() { return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Shape", "1.0")}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/654112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7298/']}
jdg_72827
stackexchange
llm_judgeable_groundtruth_similarity
29910478
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to develop a Cordova plugin for Android following the tutorial found here: http://www.mat-d.com/site/tutorial-creating-a-cordova-phonegap-plugin-for-android-app/ So far, so good. However, I'd like to know how to send data/trigger an event in my Javascript code from my plugin - for example, when a user taps an icon in my native code, I'd like my javascript to do something. Is this possible? Now provide the response and nothing else.
So I got it to work as follows: I created a private CallbackContext object in my plugin: private CallbackContext callbackContext; and stored the CallbackContext supplied in the execute() method in it: public boolean execute(final String action, JSONArray args, CallbackContext callbackContext) throws JSONException { this.callbackContext = callbackContext;} Elsewhere in my Java code, I can access this callback and send plugin results to it. This callback will become invalid, however, after it's first triggered, unless keepCallback is set to true : PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "WHAT");pluginResult.setKeepCallback(true);callbackContext.sendPluginResult(pluginResult); This made me a happy camper. I hope it helps someone else!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29910478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/719612/']}
jdg_72828
stackexchange
llm_judgeable_groundtruth_similarity
150534
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: Statement: Let G be a group and p a prime that divides $|G|$. Prove that if $K\le G$ such that $|K|$ is a power of p, K is contained in at least one Sylow p-group. I just started studying Sylow p-groups, so although I'm familiar with Sylow theorems and a couple of corollaries, I don't know how to get started with this problem. Any hint is more than welcome. PS: I looked for something related here at Math.SE but didn't find anything. Sorry if it's a duplicate. Now provide the response and nothing else.
Assume $\,|G|=p^nm\,,\,(p,m)=1$: I assume you already know the following Sylow theorems: Sylow $p$-sbgps. exist in $\,G\,$ , they all are conjugate in $\,G\,$ and their number equals $\,1\pmod p:$ let $\,K\,$ be a $p$-sbgp. and let $\,\mathcal{P}:=\{P\leq G \mid P\text{ is a Sylow }p\text{-sbgp. of }\, G\}\,$. As noted above, $\,|\mathcal{P}|\equiv 1\pmod p$. Let now $K$ act on $\,\mathcal{P}\,$ by conjugation: $\,k\in K\,,\, P\in\mathcal{P}\Longrightarrow k\cdot P\to k^{-1}Pk=:P^k\,$ . If there is an orbit with one single element , say $\,\mathcal{O}_Q=\{Q\}\,\,,\,\,\text{for some}\,Q\in\mathcal{P}$, then $\,Q^k=Q\,\,\forall\,k\in K\Longrightarrow QK=KQ\Longrightarrow QK\,$ is a $p$-subgroup of $\,G\,$ , so if $\,K\,$ is not contained in any Sylow $p$-sbgp then $\,|QK|>|Q|=p^n\,$, which is absurd, so that all the orbit have size a power of $p$, but this means $\,|\mathcal{P}|\equiv 0\pmod p$, which of course is also absurd since, as we mentioned above, $\,|\mathcal{P}|\equiv1\pmod p\Longrightarrow \,$ it must be that $\,K\,$ is contained in some Sylow $p$-sbgp.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/150534', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32326/']}
jdg_72829
stackexchange
llm_judgeable_groundtruth_similarity
42404452
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 LibGDX, I want to make a text animation for my game. Therefore, I want that my labels gets larger with time. But if I use the scaleTo() method, nothing happens whereas other Actions like moveTo() work fine. label1 = new Label("Test text", new Label.LabelStyle(font, Color.BLACK));label2.addAction(Actions.parallel(Actions.moveTo(500, 300, 2.0f),Actions.scaleTo(0.1f, 0.1f,2.0f)));label2 = new Label("Test text 2", new Label.LabelStyle(font, Color.BLACK));label2.addAction(Actions.parallel(Actions.moveTo(500, 300, 2.0f),Actions.scaleTo(0.1f, 0.1f,2.0f)));stage.addActor(label1);stage.addActor(label2); How can I make my labels scale? Thank you in advance! Now provide the response and nothing else.
For performance reason most scene2d.ui groups have transform set to false by default. For more detail you can check https://github.com/libgdx/libgdx/wiki/Scene2d.ui#rotation-and-scale If you want to scale, you can use Container which is useful for setting the size and alignment of a single widget. private Container<Label> container;@Overridepublic void create() { stage=new Stage(); Label label1 = new Label("Test text", new Label.LabelStyle(font, Color.BLACK)); container=new Container<Label>(label1); container.setTransform(true); // for enabling scaling and rotation container.size(100, 60); container.setOrigin(container.getWidth() / 2, container.getHeight() / 2); container.setPosition(100,200); container.setScale(3); //scale according to your requirement stage.addActor(container);}@Overridepublic void render() { super.render(); Gdx.gl.glClearColor(1,1,1,1); gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.draw(); stage.act();} Add your Action on container instead of Label. container.addAction(Actions.parallel(Actions.moveTo(500, 300, 2.0f),Actions.scaleTo(0.1f, 0.1f,2.0f)));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42404452', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4503472/']}
jdg_72830
stackexchange
llm_judgeable_groundtruth_similarity
683357
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: Given: $$f(x) = f(x+2)$$ $$f(3)=20$$ prove or disprove $f(4)=20$ In my opinion $f(4)$ can have any value according to the question...since the only data is about the odd range values...I thought of a function like $f(x)=(K-20)(-1)^x + K$ Now provide the response and nothing else.
Idea of the proof. Let $D_t=\pi_t(D)$. It suffices to show that$$\frac{d}{dt}m(D_t)=\int_{D_t}\nabla\cdot f\,dx.$$The Theorem of Change of Variables says that$$m(D_t)=\int_{D_t} 1\,dx=\int_{D}\det\left(\frac{\partial\pi_t}{\partial x}\right)\,dx.$$But$$\frac{\partial\pi_t}{\partial x}=I+\frac{\partial f}{\partial x}t+{\mathcal O}(t^2).$$This is due to the fact that the solution of $$x'=f(x),\quad x(0)=x_0,$$after small time $t$ looks like $x(t)=x_0+tf(x_0)+{\mathcal O}(t^2)$. Using standard properties of the determinant one can show that$$\det (I+tA)=1+t\,\mathrm{Tr}\,A+{\mathcal O}(t^2).$$and hence$$\frac{d}{dt}\det\left(\frac{\partial\pi_t}{\partial x}\right)=\mathrm{Tr}\,\frac{\partial f}{\partial x}=\nabla\cdot f.$$ Note. For a complete proof see Arnold, Mathematical Methods in Classical Mechanics .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/683357', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/130201/']}
jdg_72831
stackexchange
llm_judgeable_groundtruth_similarity
11031159
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 looking for a way to convert hex (hexadecimal) to dec (decimal) easily. I found an easy way to do this like : int k = 0x265;cout << k << endl; But with that I can't input 265 . Is there anyway for it to work like that: Input: 265 Output: 613 Is there anyway to do that ? Note: I've tried: int k = 0x, b;cin >> b;cout << k + b << endl; and it doesn't work. Now provide the response and nothing else.
#include <iostream>#include <iomanip>#include <sstream>int main(){ int x, y; std::stringstream stream; std::cin >> x; stream << x; stream >> std::hex >> y; std::cout << y; return 0;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11031159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/928176/']}
jdg_72832
stackexchange
llm_judgeable_groundtruth_similarity
22090350
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I got error message: FastCGI sent in stderr: "Unable to open primary script: /home/messi/web/wordpress/index.php (No such file or directory)" while reading response header from upstream, client: xxx.xxx.xxx.xxx, server: www.domain.com, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "www.domain.com here are my configuration files: /etc/php5/fpm/php.ini cgi.fix_pathinfo=0doc_root =user_dir =.... /etc/php5/fpm/php-fpm.conf [global]pid = /var/run/php5-fpm.piderror_log = /var/log/php5-fpm.loginclude=/etc/php5/fpm/pool.d/*.conf /etc/php5/fpm/pool.d/www.conf [www]user = www-datagroup = www-datalisten = /var/run/php5-fpm.socklisten.owner = www-datalisten.group = www-datalisten.mode = 0666pm = dynamicpm.max_children = 5pm.start_servers = 2pm.min_spare_servers = 1pm.max_spare_servers = 3chdir = /security.limit_extensions = .php .php3 .php4 .php5php_flag[display_errors] = onphp_admin_value[error_log] = /var/log/fpm-php.www.logphp_admin_flag[log_errors] = on /etc/nginx/nginx.conf user nginx;worker_processes 1;error_log /var/log/nginx/error.log warn;pid /var/run/nginx.pid;events { worker_connections 1024;}http { include /etc/nginx/mime.types; server_tokens off; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/sites-enabled/*;} /etc/nginx/sites-enabled/wordpress server { listen 80; server_name www.domain.com; root /home/messi/web/wordpress; error_log /var/log/nginx/err.wordpress.log; index index.php; location / { try_files $uri $uri/ /index.php?$args; } location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { allow all; log_not_found off; access_log off; } location ~ /\. { deny all; } location ~* /(?:uploads|files)/.*\.php$ { deny all; } location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi_params; }} Setup user permission: #adduser www-data messi#chown -R www-data:www-data /home/messi/web#chmod -R 664 /home/messi/web/wordpress How can I resolve this?Thanks Now provide the response and nothing else.
SELinux will cause this error on CentOS/RHEL 7+ by default :( To test if SELinux is the source of your woes, do setenforce 0 ... and see if everything works. If that fixed it, you can leave SELinux off (weak, you're better than that), or you can turn it back on with setenforce 1 ... and then properly fix the issue. If you do tail -f /var/log/audit/audit.log ... you'll see the SELinux issue. In my case, it was denying PHP-FPM access to web files. You can run the following directives to fix it: setsebool -P httpd_can_network_connect_db 1setsebool -P httpd_can_network_connect 1 This actually didn't fix it for me at first, but then restoring SELinux context did it restorecon -R -v /var/www Hope that helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22090350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3145965/']}
jdg_72833
stackexchange
llm_judgeable_groundtruth_similarity
16883
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: What is the maximum value of the Process ID? Also, is it possible to change a Process ID? Now provide the response and nothing else.
On Linux, you can find the maximum PID value for your system with this: $ cat /proc/sys/kernel/pid_max This value can also be written using the same file, however the value can only be extended up to a theoretical maximum of 32768 (2^15) for 32 bit systems or 4194304 (2^22) for 64 bit: $ echo 32768 > /proc/sys/kernel/pid_max It seems to be normative practice on most 64 bit systems to set this value to the same value as found on 32 bit systems, but this is by convention rather than a requirement. From man 5 proc : /proc/sys/kernel/pid_max This file (new in Linux 2.5) specifies the value at which PIDs wrap around (i.e., the value in this file is one greater than the maximum PID). The default value for this file, 32768, results in the same range of PIDs as on earlier kernels. On 32-bit platfroms, 32768 is the maximum value for pid_max . On 64-bit systems, pid_max can be set to any value up to 2^22 ( PID_MAX_LIMIT , approximately 4 million). And no, you cannot change the PID of a running process. It gets assigned as a sequential number by the kernel at the time the process starts and that is it's identifier from that time on. The only thing you could do to get a new one is have your code fork a new process and terminate the old one.
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/16883', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/9146/']}
jdg_72834
stackexchange
llm_judgeable_groundtruth_similarity
45035649
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We are currently converting some code that was using Assert.IsTrue() , Assert.AreEqual() , Assert.IsNotNull() , etc. The basic unit test assert Library for C# We want to use FluentAssertions, like value.Should().BeNull(). I'm stuck on a few tests using Assert.Fail() in some locations. What should I use to efficiently replace those, since we want to do away with every single "Assert.*", and I can't find an equivalent in FluentAssertions? Here is an example [TestMethod, TestCategory("ImportantTest")]public void MethodToTest_Circumstances_ExpectedResult(){ // Arrange var variable1 = new Type1() { Value = "hello" }; var variable2 = new Type2() { Name = "Bob" }; // Act try { MethodToTest(variable1, variable2); // This method should have thrown an exception Assert.Fail(); } catch (Exception ex) { ex.Should().BeOfType<DataException>(); ex.Message.Should().Be(Constants.DataMessageForMethod); } // Assert // test that variable1 was changed by the method variable1.Should().NotBeNull(); variable1.Value.Should().Be("Hello!"); // test that variable2 is unchanged because the method threw an exception before changing it variable2.Should().NotBeNull(); variable2.Name.Should().Be("Bob");} Now provide the response and nothing else.
Restructure the test to utilize the .ShouldThrow<> assertion extension. [TestMethod, TestCategory("ImportantTest")]public void MethodToTest_Circumstances_ExpectedResult() { // Arrange var variable1 = new Type1() { Value = "hello" }; var variable2 = new Type2() { Name = "Bob" }; // Act Action act = () => MethodToTest(variable1, variable2); // Assert // This method should have thrown an exception act.ShouldThrow<DataException>() .WithMessage(Constants.DataMessageForMethod); // test that variable1 was changed by the method variable1.Should().NotBeNull(); variable1.Value.Should().Be("Hello!"); // test that variable2 is unchanged because the method threw an exception before changing it variable2.Should().NotBeNull(); variable2.Name.Should().Be("Bob");} In the above example, if the expected exception is not thrown the the assertion would fail, stopping the test case. You should review the documentation on asserting exceptions to get a better understanding of how to use the library.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45035649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5447158/']}
jdg_72835
stackexchange
llm_judgeable_groundtruth_similarity
37105600
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to download a file with TIdHTTP.Get in Delphi Seattle. It's an app for android and all my attempts fails. All i get it's the same error "Could not load SSL library". This is the procedure: procedure TfrmMain.DownloadPicture(const AURL: string);var MeS: TMemoryStream; cidSSL: TIdSSLIOHandlerSocketOpenSSL; cidHTTP: TIdHTTP;begin cidHTTP:= TIdHTTP.Create(nil); cidSSL:= TIdSSLIOHandlerSocketOpenSSL.Create(nil); Mes := TMemoryStream.Create; try cidHTTP.ReadTimeout := 30000; cidHTTP.IOHandler := IdSSL; cidSSL.SSLOptions.Method := sslvSSLv3; cidSSL.SSLOptions.Mode := sslmUnassigned; cidSSL.StartSSL; cidHTTP.Get(AURL, Mes); except on E : Exception do begin showmessage('Error: '+E.Message); end; end; Mes.Position := 0; frmImage.Image.Bitmap.LoadFromStream(Mes);end; Now provide the response and nothing else.
If you are NOT using Android 6 Marshmallow, OpenSSL should be working fine on Android. When you get the "could not load" error, you can call Indy's WhichFailedToLoad() function in the IdSSLOpenSSLHeaders unit to find out why OpenSSL could not be loaded. If your device does not have OpenSSL pre-installed, you can deploy the OpenSSL binaries with your app, and use Indy's IdOpenSSLSetLibPath() function to tell Indy where to load them from. That being said, starting with Android 6 Marshmallow, Google no longer supports OpenSSL on Android. It has been replaced with a custom fork named BoringSSL , which Indy does not fully support yet (although some BoringSSL-related changes have been made to Indy after Seattle's release). So, if you are having trouble with using Indy SSL/TLS on Android 6, you can try upgrading to the latest Github snapshot to see if it helps. BoringSSL makes some major changes to the OpenSSL API interface (dropping functions, changing data types, etc), so it is not backwards-compatible with existing OpenSSL code. But to make matters worse, BoringSSL uses the same library filenames as OpenSSL, and is pre-loaded at device startup, so it is not possible to deploy custom-built OpenSSL library binaries with your Android app. Android will simply use the pre-loaded BoringSSL binaries when the app tries to load the OpenSSL library filenames at runtime (regardless of whether you call Indy's IdOpenSSLSetLibPath() function). Indy operates at the NDK level of Android, not the Java level, so to make Indy avoid BoringSSL would require users to either: recompile the OpenSSL libraries with new filenames that don't conflict with BoringSSL (AFAIK no known version of this is available), and then update Indy to use those filenames. compile the OpenSSL source code directly into their Android app. Indy is not currently setup to support static-linking of OpenSSL on any platform other than iOS, but this should be a minor change to update Indy's IdSSLOpenSSLHeaders_static unit with the relevant definitions if someone can produce viable .a files for OpenSSL on Android. I do know of at least one user attempting this route, but that user has not had success yet (errors getting the source code to fully link correctly). switch to Android's higher-level Java-based crypto APIs. This is Google's preferred solution. But Indy does not support it at this time. Doing so would require writing a whole new set of TIdStack and TIdIOHandler classes for Android socket I/O and SSL/TLS, using JNI calls to access the Java APIs. But this has performance and threading issues that need to be dealt with. So, there is no known viable workaround available at this time to make Indy SSL/TLS work on Android 6+. Update : a user in the Embarcadero forums was able to find OpenSSL .so files that are compatible with Indy and work on Android 6: https://forums.embarcadero.com/thread.jspa?threadID=211089 After many reports of my apps crashing if installed in Android 6 devices I've searched the net for some tips and the couple of needed .so compiled files, 1.02 version, added the two files to the play store deployment of my apps (assets\internal) and changed the Indy's path calling IdOpenSSLSetLibPath(TPath.GetDocumentsPath) in the OnCreate of my datamodule. After those modifications of my code my Apps run perfectly on my brand new S7 with Android 6.0.1, and on all the other recent Android devices (tested using the Play Store deployment). And now the Google warning pops up telling me that the OpsnSSL files deployed with my apps are not of the minimum required 1.02f version (or 1.01r).... and so my post in this forum. ... Anyway you can download here the latest .so files, the ones that I deploy at this moment: https://drive.google.com/file/d/0B7AxqW32K0oXWW9nUk9qaFpHT0k/view?usp=sharing Another user in the same discussion also seems to have some success as well: Ive been running on android 6 loading the .so libraries just fine for months. The new problem is we need to compile new versions of the openssl libraries. Cygwin is not working correctly to compile for me so im switching to a linux install to create them (if possible) https://wiki.openssl.org/index.php/Android#Build_the_OpenSSL_Library_2 heres a repository you can grab some current prebuilt ones https://github.com/emileb/OpenSSL-for-Android-Prebuilt.git Update : The following (German) forum discussion provides OpenSSL 1.0.2g binaries for Android (and iOS Simulator) to registered users. They do not display the security warning in the Google Play store: http://www.delphipraxis.net/188736-kompilierte-openssl-bibliotheken-fuer-android.html OpenSSL 1.0.2g Android.zip OpenSSL 1.0.2g iOS Simulator.zip Update : the Android binaries for OpenSSL 1.0.2g are now available in the Embarcadero Attachments forum: https://forums.embarcadero.com/thread.jspa?threadID=211147 Then, to load OpenSSL instead of BoringSSL, follow these steps: Add the 2 .so files to your project deployment and set them to deploy to the .\assets\internal\ folder add the System.StartupCopy unit as the first unit in your DPR's uses clause. call IdOpenSSLSetLibPath(TPath.GetDocumentsPath) at app startup. Update : OpenSSL 1.0.1t and 1.0.2h binaries are now in the Embarcadero Attachments forum: https://forums.embarcadero.com/thread.jspa?threadID=211147 Update : the binaries have now been posted on Indy's Fulgan mirror: http://indy.fulgan.com/SSL/ Update : Indy is no longer using the Fulgan mirror for hosting OpenSSL binaries. They are now in their own GitHub repo: https://www.indyproject.org/2020/06/16/openssl-binaries-moved-to-github/ https://github.com/IndySockets/OpenSSL-Binaries
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37105600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3559487/']}
jdg_72836
stackexchange
llm_judgeable_groundtruth_similarity
2167868
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: li = [0, 1, 2, 3]running = Truewhile running: for elem in li: thiselem = elem nextelem = li[li.index(elem)+1] When this reaches the last element, an IndexError is raised (as is the case for any list, tuple, dictionary, or string that is iterated). I actually want at that point for nextelem to equal li[0] . My rather cumbersome solution to this was while running: for elem in li: thiselem = elem nextelem = li[li.index(elem)-len(li)+1] # negative index Is there a better way of doing this? Now provide the response and nothing else.
After thinking this through carefully, I think this is the best way. It lets you step off in the middle easily without using break , which I think is important, and it requires minimal computation, so I think it's the fastest. It also doesn't require that li be a list or tuple. It could be any iterator. from itertools import cycleli = [0, 1, 2, 3]running = Truelicycle = cycle(li)# Prime the pumpnextelem = next(licycle)while running: thiselem, nextelem = nextelem, next(licycle) I'm leaving the other solutions here for posterity. All of that fancy iterator stuff has its place, but not here. Use the % operator. li = [0, 1, 2, 3]running = Truewhile running: for idx, elem in enumerate(li): thiselem = elem nextelem = li[(idx + 1) % len(li)] Now, if you intend to infinitely cycle through a list, then just do this: li = [0, 1, 2, 3]running = Trueidx = 0while running: thiselem = li[idx] idx = (idx + 1) % len(li) nextelem = li[idx] I think that's easier to understand than the other solution involving tee , and probably faster too. If you're sure the list won't change size, you can squirrel away a copy of len(li) and use that. This also lets you easily step off the ferris wheel in the middle instead of having to wait for the bucket to come down to the bottom again. The other solutions (including yours) require you check running in the middle of the for loop and then break .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2167868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_72837
stackexchange
llm_judgeable_groundtruth_similarity
30730983
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 make @functools.lru_cache decorator ignore some of the function arguments with regard to caching key? For example, I have a function that looks like this: def find_object(db_handle, query): # (omitted code) return result If I apply lru_cache decorator just like that, db_handle will be included in the cache key. As a result, if I try to call the function with the same query , but different db_handle , it will be executed again, which I'd like to avoid. I want lru_cache to consider query argument only. Now provide the response and nothing else.
With cachetools you can write: from cachetools import cachedfrom cachetools.keys import hashkeyfrom random import randint@cached(cache={}, key=lambda db_handle, query: hashkey(query))def find_object(db_handle, query): print("processing {0}".format(query)) return queryqueries = list(range(5))queries.extend(range(5))for q in queries: print("result: {0}".format(find_object(randint(0, 1000), q))) You will need to install cachetools ( pip install cachetools ). The syntax is: @cached( cache={}, key=lambda <all-function-args>: hashkey(<relevant-args>)) Here is another example that includes keyword args: @cached( cache={}, key=lambda a, b, c=1, d=2: hashkey(a, c))def my_func(a, b, c=1, d=2): return a + c In the example above note that the lambda function input args match the my_func args. You don't have to exactly match the argspec if you don't need to. For example, you can use kwargs to squash out things that aren't needed in the hashkey: @cached( cache={}, key=lambda a, b, c=1, **kwargs: hashkey(a, c))def my_func(a, b, c=1, d=2, e=3, f=4): return a + c In the above example we don't care about d= , e= and f= args when looking up a cache value, so we can squash them all out with **kwargs.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30730983', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/371970/']}
jdg_72838
stackexchange
llm_judgeable_groundtruth_similarity
40901615
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 suppose we can use std::transform to replicate the map behavior in C++ like this : std::vector<int> in = { 1 , 2 , 3 ,4 }; std::vector<int> out(in.size()); std::transform(in.being() , in.end() , out.begin() , [](const int & val){ return val+1;}); I guess a better way would be to use the back inserter.' std::vector<int> out2;std::transform(in.begin() , in.end() , std::back_inserter(out2) , [](const int & val){ return val + 1;});// out will be { 2 , 3 ,4 ,5 } Am I right ? How do I do the filter and reduce operations in C++ using STL ? Now provide the response and nothing else.
You can use std::transform to do mapping, and std::copy_if for filtering. You have two options for reduce depending on your input and if you want to use a specific type of execution model. I've written some simple examples below to demonstrate common use cases. Note that there are multiple overloads for all these algorithms that you should use depending on your needs. std::transform Squaring a vector of integers in place: std::vector<int> nums{1,2,3,4};auto unary_op = [](int num) {return std::pow(num, 2);};std::transform(nums.begin(), nums.end(), nums.begin(), unary_op);// nums: 1, 4, 9, 16 std::copy_if Filtering odd numbers only from a vector of integers: std::vector<int> nums{1,2,3,4};std::vector<int> odd_nums;auto pred = [](int num) {return num & 1;};std::copy_if(nums.begin(), nums.end(), std::back_inserter(odd_nums), pred);// odd_nums: 1, 3 std::reduce Sum of integers in the vector starting from 0 using parallel execution model. This is really useful if, for example, you are doing a reduce operation on a really big list. Reckon that the binary operator in this case ("+") is associate and commutative, otherwise the behavior would've been non-deterministic. This is really important. The reduce operation is out-of-order if the execution model is not sequential. Only available since C++17. std::vector<int> nums{1,2,3,4};auto binary_op = [](int num1, int num2){return num1 + num2;};int result = std::reduce(std::execution::par, nums.begin(), nums.end(), 0, binary_op);// result: 10 std::accumulate Same as reduce except it doesn't support execution model and the reduce operation is done in-order. std::vector<int> nums{1,2,3,4};auto binary_op = [](int num1, int num2){return num1 + num2;};int result = std::accumulate(nums.begin(), nums.end(), 0, binary_op);// result: 10
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40901615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4749396/']}
jdg_72839
stackexchange
llm_judgeable_groundtruth_similarity
127455
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: Special relativity states: The speed of light in a vacuum is always $c$, regardless of the velocity of the observer. The laws of physics are the same for all observers in uniform motion. These two statements that we know as "special relativity" indicate that $c$ (speed of light) does not follow the same laws of physics as the observer. The laws of physics are the same for all observers in uniform motion. The observer is (anything that never travels at the velocity $c$). The laws of physics are the same for (anything that never travels at the velocity $c$). The laws of physics are not the same for anything that does travel at the velocity $c$. This suggests that when we use our physics to measure and predict light, what we are predicting and measuring is only the disturbance in our physical laws, caused by the passing of something that does not exist within our physical laws. As an analogy, the electromagnetic wave is to the photon as thunder is to lightning. Our physical laws enable us to measure and predict the disturbance in our reality that we know as electromagnetic wave light, but the cause of this electromagnetic wave exists under entirely different laws of physics and therefore a different reality. Now provide the response and nothing else.
To make progress we need to be clear what we mean by the laws of physics and observer . A law of physics is just some set of equations that we use to predict what happens. So if for example we're trying to describe how charges interact with light our set of equations, i.e. our law of physics , would be Maxwell's equations. But to write down Maxwell's equations and solve them we need to choose a set of coordinates. We need an origin and time and distance vectors. Choosing these chooses a frame of reference, and this then allows us to assign $(t,x,y,z)$ positions to things that happen. The act of observation is just the recording of these positions. So far so good. Now suppose that you and I are making measurements of some system, e.g. an electron, and we're moving relative to each other at some high velocity near $c$. The laws of physics, Maxwell's equations in this case, are the same for both of us but that does not mean we observe the same thing. If the electron is stationary in my frame Maxwell's equations tell me it will have an electrostatic field and that's what I will measure. In your frame the electron will be moving and Maxwell's equations tell you it has both electric and magnetic fields and that's what you will measure. So we observe different things even though we're using the same laws of physics . What special relativity tells us is that my observations and your observations are linked by a Lorentz transformation. If I take my observations and Lorentz transform them into your frame they will be the same as what you observe. This is always the case for all physicists moving at any speed relative to us of less than $c$. This is what we mean when we say the laws of physics are the same for all observers. It does not mean they all observe the same thing, only that their observations are all equivalent in that they are linked by a Lorentz transformation. Now on to the key part of your question. What happens in a frame of reference moving at a speed of $c$ relative to us? Well, there's a get out clause. If you take my example above as a reference we can never observe an electron moving at the speed of light relative to us, because accelerating an electron to $c$ would require infinite energy. So while we can ask what measurements are made in a reference frame traveling at 0.9$c$ or 0.999999999$c$, the question what measurements are made in a frame travelling at $c$ is meaningless - no such measurements can be made. Just as well really, because the Lorentz transformations become singular at a relative velocity of $c$ so we couldn't do the calculation anyway. But of course light travels at $c$. However this doesn't mean the laws of physics are different for light, it just means we can't write down Maxwell's equations in a reference frame travelling at the speed of light relative to us. But that's OK because light can't make measurements so there's nothing to use Maxwell's equations to predict. Only we massive things can make measurements, and we can't attain relative speeds equal to $c$. Going back to your question, your last point 4 states: The laws of physics are not the same for anything that does travel at the velocity $c$. The trouble with this is that the obvious interpretation is: The laws of physics do not apply to anything that does travel at the velocity $c$. which is obviously wrong because the behaviour of light is well described by Maxwell's equations, and as we've seen Maxwell's equations are the same in all (sub-luminal) reference frames. On the other hand if you wrote instead: Maxwell's equations cannot be written down in a reference frame travelling at a relative velocity of $c$. then this I would have to agree with. But while this may seem startling to non-physicists, for us physicists well that's kind of obvious and it's just how the universe is.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/127455', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/55491/']}
jdg_72840