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
44898248
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 login form created by Form.create(), but I can't pass any props to this form from parent component, compiler always notify a error like error TS2339: Property 'loading' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{}, ComponentState>> & Readonly<{ childr...'. LoginForm.tsx import * as React from 'react';import { Form } from 'antd';import { WrappedFormUtils } from 'antd/lib/form/Form';interface Props { form: WrappedFormUtils; loading: boolean; username?: string;}class LoginForm extends React.Component<Props, {}> { render() { const { loading } = this.props; return (<div>form {loading ? 'true' : 'false'}</div>); }}export default Form.create()(LoginForm); LoginPage.tsx import LoginForm from './components/loginForm';const loginPage: React.SFC<Props> = (props) => { return ( <div> <LoginForm loading={true}/> ^ error here! </div> ); }; My antd version is 2.11.2 Finally I found a solution class LoginForm extends React.Component<Props & {form: WrappedFormUtils}, State> { render() { const { loading } = this.props; return (<div>form {loading ? 'true' : 'false'}</div>); }}export default Form.create<Props>()(LoginForm); Now provide the response and nothing else.
Import the FormComponentProps import {FormComponentProps} from 'antd/lib/form/Form'; Then have your component interface YourProps { test: string;} class YourComponent extends React.Component<YourProps & FormComponentProps> { constructor(props: YourProps & FormComponentProps) { super(props); ... }} Then export the class using Form.create() export default Form.create<YourProps>()(YourComponent); The generic argument on Form.create casts the result to a React ComponentClass with YourProps - without FormComponentProps, because these are being injected through the Form.create wrapper component.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44898248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1551109/']}
jdg_374141
stackexchange
llm_judgeable_groundtruth_similarity
63124742
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 data.json file containing this, [ { "question": "TEST QUESTIONS", "answer" : ["Answer1", "Answer2"], "correctAnswer": "Answer " }, { "question" : "TEST QUESTION 2", "answer" : ["Answer1", "Answer2"], "correctAnswer" : "Answer 2" }] And i parse the data with this function func Parser() -> [Questions] { let url = Bundle.main.url(forResource: "data", withExtension: "json")! let data = try! Data(contentsOf: url) let decoder = JSONDecoder() let questions = try? decoder.decode([Questions].self, from: data) return questions!} When i call Parser() how do I get the information such as question or answer, I thought to use let question = Parser().question but that doesn't work. Any help would be appreciated Now provide the response and nothing else.
So far what is working for me on the majority of devices I have tested with, with a fallback option to at least stop the dreaded 'looping request' and to allow a successful manual connection The below code is written in Kotlin, please google how to covert to Java if needed. Create a NetworkCallback which is required for API >= 29 (prior it was not required but could be used) val networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { super.onAvailable(network) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // To make sure that requests don't go over mobile data connectivityManager.bindProcessToNetwork(network) } else { connectivityManager.setProcessDefaultNetwork(network) } } override fun onLost(network: Network) { super.onLost(network) // This is to stop the looping request for OnePlus & Xiaomi models connectivityManager.bindProcessToNetwork(null) connectivityManager.unregisterNetworkCallback(networkCallback) // Here you can have a fallback option to show a 'Please connect manually' page with an Intent to the Wifi settings }} Connect to a network as follows: val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder() .setSsid(ssid) .setWpa2Passphrase(pass) .build()val networkRequest = NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)// Add the below 2 lines if the network should have internet capabilities.// Adding/removing other capabilities has made no known difference so far// .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)// .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED) .setNetworkSpecifier(wifiNetworkSpecifier) .build()connectivityManager.requestNetwork(networkRequest, networkCallback) As stated here by Google , some OEM Roms are not 'holding on to the request' and therefore the connection is dropping instantly. OnePlus have fixed this problem in some of their later models but not all. This bug will continuously exist for certain phone models on certain Android builds, therefore a successful fallback (i.e. a manual connection with no network disruption) is required. No known workaround is available, but if found I will update it here as an option. To remove the network, do the following: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //This is required for Xiaomi models for disconnecting connectivityManager.bindProcessToNetwork(null)} else { connectivityManager.setProcessDefaultNetwork(null)}connectivityManager.unregisterNetworkCallback(it) Please keep in mind, an automatic connection allows for an automatic & manual disconnection. A manual connection (such as the suggested fallback for OnePlus devices) does not allow an automatic disconnection. This will also need to be handled within the app for a better UX design when it comes to IoT devices. Some extra small tips & info: now that a system dialog opens, the app calls onPause and onResume respectively. This affected my logic regarding automatic connection to IoT devices. In some case, onResume is called before the network callback is finished. In regards to tests, I have yet to be able to get around the dialog by just using espresso and it may block some tests that were working before API 29. It may be possible using other frameworks such as uiautomator. In my case I adjusted the tests to work up until the dialog shows, and run further tests thereafter.Using Intents.init() does not work. onUnavailable is called when the the network has been found, but the user cancels. It is not called when the network was not found or if the user cancels the dialog before the network has been found, in this case no other methods are called, use onResume to catch it. when it fails on the OnePlus it called onAvailable() -> onCapabilitiesChanged() -> onBlockedStatusChanged (blocked: false) -> onCapabilitiesChanged() -> onLost() respectively removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) wont help keep the connection on a OnePlus as stated here setting the Bssid wont help keep the connection on a OnePlus as stated here google cannot help, they have stated it is out of their hands here OnePlus forum posts confirming it working for some models (but not all) after an update, see here , here & here when GPS is switched off, the SSID names of networks are not available if the dialog comes several times, check your own activity lifecycle, in my case some models were calling onResume before the network callback was received. manually connecting to a network without internet capabilities needs user confirmation to keep the connection (sometimes in the form of a dialog or as a notification), if ignored, the system will disconnect from the network shortly afterwards List of devices tested: Google Pixel 2 - No issues found Samsung S10 SM-G970F - No issues found Samsung S9 SM-G960F - No issues found One Plus A5000 (OxegenOS 10.0.1) - Major Issue with automatic connection HTC One M8 (LineageOS 17.1) - No issues found Xiaomi Mi Note 10 - Issue with disconnecting (Fixed, see code example) Samsung A50 - Dialog repetitively appears after successful connection (sometimes) Huawei Mate Pro 20 - Dialog repetitively appears after successful connection (sometimes) Huawei P40 Lite - Doesn't call onLost() CAT S62 Pro - No issues found Sony Xperia SZ2 - No issues found Samsung Note10 - No issues found
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63124742', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4569940/']}
jdg_374142
stackexchange
llm_judgeable_groundtruth_similarity
266007
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 question is that $e^{2\pi i/6r}$ is a root of the polynomial $X^{2r}-X^{r}+1 \in \mathbb Q[X]$ , we want to prove that $X^{2r}-X^{r}+1$ is irreducible if and only if $r$ is of the form $2^{a}3^{b}(a,b\geq 0)$, and the following question $X^{2r}+X^{r}+1$ is irreducible if and only if $r$ is of the form a power of $3$. Now provide the response and nothing else.
Note that $$X^{2r}-X^r+1=\frac{X^{3r}+1}{X^r+1}=\frac{X^{6r}-1}{(X^r+1)(X^{3r}-1)}$$ $\Rightarrow$ Assume by contradiction that $r$ has a prime factor $p \geq 5$. Let $r=pq$. Then$e^{\frac{2 \pi i }{6q}}$ is a root of $X^{6r}-1$ but not of $(X^r+1)(X^{3r}-1)$. This shows that the minimal polynomial of $e^{\frac{2 \pi i }{6q}}$ divides $X^{2r}-X^r+1$. Since the degree of the minimal polynomial is $\phi(6q) \neq 2r$, it follows that the minimal polynomial of $e^{\frac{2 \pi i }{6q}}$ is a proper divisor of $X^{2r}-X^r+1$. $\Leftarrow$ If $r=2^a3^b$. It should be easy to prove from $$X^{2r}-X^r+1=\frac{X^{6r}-1}{(X^r+1)(X^{3r}-1)}$$that $X^{2r}-X^r+1$ is a cyclotomic polynomial. Note that $$\phi(6r)=2^a\cdot 3^b \cdot 2=2r=6r-r-3r=\deg(X^{6r}-1)-\deg(X^r+1))-\deg(X^{3r}-1)$$ The second part should follow by the same idea, using $$X^{2r}+X^r+1=\frac{X^{3r}-1}{X^r-1}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/266007', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/53800/']}
jdg_374143
stackexchange
llm_judgeable_groundtruth_similarity
2281633
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 PHP you can do if(isset($array['foo'])) { ... } . In JavaScript you often use if(array.foo) { ... } to do the same, but this is not exactly the same statement. The condition will also evaluate to false if array.foo does exists but is false or 0 (and probably other values as well). What is the perfect equivalent of PHP's isset in JavaScript? In a broader sense, a general, complete guide on JavaScript's handling of variables that don't exist, variables without a value, etc. would be convenient. Update : 11 years and 11 months ago I posted this question, and wow, it still gets a lot of activity. Now, I'm pretty sure that when I wrote this, I only wanted to know how to check for the presence of a property in an associative array (a.k.a. dictionary), and as such the correct (for me) answers involve hasOwnProperty or the in operator. I wasn't interested in checking local or global variables. But while I remember that well, that intent is not quite clear in the question as written, or even directly contradicted by it! I never mentioned the associative array, and PHP's isset does also do those other things. Let this be a lesson to all of us about how important it is to properly state your requirements in a question, and also how global variables, local variables, object properties, dictionary keys and what-have-you aren't Huey, Dewey, and Louie. In the meantime (heh), many many people have provided answers to that effect as well, so for those of you who found this question through Google, well, I'm glad my vagueness helped in a way I guess. Anyway, just wanted to clarify that. Now provide the response and nothing else.
I generally use the typeof operator: if (typeof obj.foo !== 'undefined') { // your code here} It will return "undefined" either if the property doesn't exist or its value is undefined . (See also: Difference between undefined and not being defined. ) There are other ways to figure out if a property exists on an object, like the hasOwnProperty method: if (obj.hasOwnProperty('foo')) { // your code here} And the in operator: if ('foo' in obj) { // your code here} The difference between the last two is that the hasOwnProperty method will check if the property exist physically on the object (the property is not inherited). The in operator will check on all the properties reachable up in the prototype chain, e.g.: var obj = { foo: 'bar'};obj.hasOwnProperty('foo'); // trueobj.hasOwnProperty('toString'); // false'toString' in obj; // true As you can see, hasOwnProperty returns false and the in operator returns true when checking the toString method, this method is defined up in the prototype chain, because obj inherits form Object.prototype .
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/2281633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85821/']}
jdg_374144
stackexchange
llm_judgeable_groundtruth_similarity
23563510
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I want do deparse the argument of a function for an error or a warning, something strange is happening if the argument is converted to a data.table within the function: e <- data.frame(x = 1:10)### something strange is happeningfoo <- function(u) { u <- data.table(u) warning(deparse(substitute(u)), " is not a data.table") u}foo(e)## foo(e)## x## 1: 1## 2: 2## 3: 3## 4: 4## 5: 5## 6: 6## 7: 7## 8: 8## 9: 9## 10: 10## Warning message:## In foo(e) :## structure(list(x = 1:10), .Names = "x", row.names = c(NA, -10L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x10026568>) is not a data.table If I deparse it before data.table everything works fine: ### okfoo1 <- function(u) { nu <- deparse(substitute(u)) u <- data.table(u) warning(nu, " is not a data.table") u}## foo1(e)## x## 1: 1## 2: 2## 3: 3## 4: 4## 5: 5## 6: 6## 7: 7## 8: 8## 9: 9## 10: 10## Warning message:## In foo1(e) : e is not a data.table There is by the way no difference if e already is a data.table or not.I found it on purpose, when I was profiling some code, where deparse was very time consuming because e was quite big. What's happening here and how can I handle such functions for data.frame and data.table input? nachti Now provide the response and nothing else.
This is because substitute behaves differently when you are dealing with a normal variable instead of a promise object. A promise object is a formal argument and has a special slot that contains the expression that generated it. In other words, a promise object is a variable in a function that is part of the argument list of that function. When you use substitute on a promise object in a function, then it will retrieve the expression in the call to the function that was assigned to that formal argument. From ?substitute : Substitution takes place by examining each component of the parse tree as follows: If it is not a bound symbol in env, it is unchanged. If it is a promise object, i.e., a formal argument to a function or explicitly created using delayedAssign(), the expression slot of the promise replaces the symbol. If it is an ordinary variable, its value is substituted , unless env is .GlobalEnv in which case the symbol is left unchanged. In your case, you actually overwrite the original promise variable with a new one with: u <- data.table(u) at which point u becomes a normal variable that contains a data table. When you substitute on u after this point, substitute just returns the data table, which deparse processes back to the R language that would generate it, which is why it is slow. This also explains why your second example works. You substitute while the variable is still a promise (i.e. before you overwrite u ). This is also the answer to your second question. Either substitute before you overwrite your promise, or don't overwrite your promise. For more details, see section 2.1.8 of the R Language Definition (promises) which I excerpt here: Promise objects are part of R’s lazy evaluation mechanism. They contain three slots: a value, an expression, and an environment. When a function is called the arguments are matched and then each of the formal arguments is bound to a promise. The expression that was given for that formal argument and a pointer to the environment the function was called from are stored in the promise.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23563510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3536376/']}
jdg_374145
stackexchange
llm_judgeable_groundtruth_similarity
46266
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've read the documentation, but am still very unclear as to what the difference is between ViewVector and ViewPoint for Graphics3D . Could someone explain it concisely and clearly enough so that an amateur like myself could understand? Now provide the response and nothing else.
If ViewVector is set to be Automatic it will be the vector that starts at ViewPoint and ends at ViewCenter , which means that ViewVector and ViewPoint are tied to each other. You can think of the origin of ViewVector as the position where the camera filming the scene is located, and its direction as what direction it points in. So as long as ViewVector is automatic you can implicitly set the ViewVector by positioning ViewPoint and ViewCenter , ViewVector will just be the vector between those two points. However if you change ViewVector that change will override any changes that you've made to ViewPoint and ViewCenter . One important difference, as Kuba says, is that ViewCenter deals with relative coordinates, not absolut ones. ViewVector uses actual points in the room, but ViewCenter uses a fraction of the plot range. So if the plot range is {100, 200, 300} then ViewCenter -> {0.5, 0.5, 0.5} puts the view center at {50, 100, 150} .
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/46266', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/11498/']}
jdg_374146
stackexchange
llm_judgeable_groundtruth_similarity
16524225
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 create Git hook(s) that will populate the commit id of the commit I am about to make into a file (basically variable substitution) in my source code. Is this possible with Git? Or is the fact that by resolving the variable to the git id, I am going to be changing the sha 1, thereby winding up with a "chicken or the egg" problem. Now provide the response and nothing else.
The solution I have used for a similar situation is this: Put the string $Id$ somewhere in the file you want to have identified (e.g. test.html ), probably within a comment or other non-functional section of the file where it won't cause issues. In your .gitattributes , flag the file in question with the ident keyword (e.g. *.html ident ). The result of this is that when git checkout copies the file out of the object database into your working directory, it expands the $Id$ string to read $Id: <sha-1 of file>$ , and git add reverses that transformation when you want to check it in, so the versions of that file in your object database only ever contain $Id$ , not the expanded forms. That's a start, but unfortunately, finding the commit that contains a file with a specific hash is not so easy, and not necessarily one-to-one either. So, in addition, I also tag those files with the export-subst attribute (e.g. *.html ident export-subst in .gitattributes ), and add an additional string, like $Format:%ci$ ($Format:%h$) somewhere in the file as well. git checkout and git add don't affect these tags, though, so the versions in my repository always have exactly that string. In order to get those tags expanded, you have to use git archive to create a tar-ball (or .zip) of a specific version of your project, which you then use to deploy that version - you won't be able to just copy the files, or make install or whatever, since git archive is the only thing that will expand those tags. The two tags I gave as an example expand to YYYY-MM-DD HH:MM:SS +TZOFFSET (HASH) , where the HASH in this case is the actual commit hash, so it's more useful. You can find other potentially usefull $Format:$ specifiers in the git log help page under the --pretty-format specifiers.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16524225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/203802/']}
jdg_374147
stackexchange
llm_judgeable_groundtruth_similarity
42334646
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 way to pad a tensor of variable size to a given shape with a specific pad value? For example given the tensors: [[1, 2], [3, 4]] and [[1, 2, 3], [4, 5, 6]] Is there a way to have a generic operation which would take either and pad them with a value (say, to shape [2, 4] with value -1 ) to result in: [[1, 2, -1, -1], [3, 4, -1, -1]] and [[1, 2, 3, -1], [4, 5, 6, -1]] respectively? My reasoning (in case there is a better solution) is that I have examples from a TFRecords file, part of which has a variable length. For processing, a static length makes them easier to work with. Now provide the response and nothing else.
Yes. There is. Provided you do not need to change the rank of the tensor, it's very simple. tf.pad() accepts regular python lists with tensors. The format of the padding is a list of pairs of how much to pad on each side of that dimension. e.g. t = tf.constant([[1, 2], [3, 4]])paddings = [[0, 0], [0, 4-tf.shape(t)[0]]]out = tf.pad(t, paddings, 'CONSTANT', constant_values=-1)sess.run(out)# gives: # array([[ 1, 2, -1, -1],# [ 3, 4, -1, -1]], dtype=int32) If you want to generalise this to a useful function, you could do something like: def pad_up_to(t, max_in_dims, constant_values): s = tf.shape(t) paddings = [[0, m-s[i]] for (i,m) in enumerate(max_in_dims)] return tf.pad(t, paddings, 'CONSTANT', constant_values=constant_values) where max_in_dims is essentially the desired shape of the output. Note: this function will fail if you provide a shape that is strictly smaller than t in any dimension. You can use it like: t = tf.constant([[1, 2], [3, 4]]) # shape = [2, 2]t_padded = pad_up_to(t, [2, 4], -1) # shape = [2, 4], padded with -1s or t = tf.placeholder(tf.float32, [None, None]) # shape = [?, ?]t_padded = pad_up_to(t, [5,5], -1) # shape = [5, 5], padded with -1st_np = np.random.uniform(0, 1, [3,4]) # shape = [3,4], no paddingt_padded_out = sess.run(t_padded, {t: t_np})t_np2 = np.random.uniform(0, 1, [2,1]) # shape = [2,1], no paddingt_padded_out2 = sess.run(t_padded, {t: t_np2}) Although the dimension sizes are calculated dynamically, the number of dimensions is not, so make sure that max_in_dims has the same number of elements as t.shape.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42334646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1191087/']}
jdg_374148
stackexchange
llm_judgeable_groundtruth_similarity
34661858
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the exact same methods and calls in onRefresh() and onRestart(), but for some reason onRestart() does what I want exactly, yet onRefresh() acts differently. What I want to happen is for app to understand when the location is disabled while running. onRestart() does this: I start the app, get the Forecast data, disable location from status bar, press the home button and open the app again. As expected, onRestart() tries to check for GPS status(with gpsTracker.getIsGPSEnabled()), sees that location is disabled, and sends the according Toast message. onRefresh() does this: I start the app, get the Forecast data, disable location from status bar, even wait few seconds and then refresh the app. Unexpectedly, onRefresh() gives sends the "Data Refreshed" toast, even though it gets "null, null" as location latitude and longitude. I could provide other codes as well, but if there was a problem with the rest of the code, why would onRestart() act the way I want? I'm not getting any errors. Any help would be highly appreciated. Thanks. @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); final GPSTracker gpsTracker = new GPSTracker(this); mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { mSwipeRefreshLayout.setRefreshing(false); if (gpsTracker.getIsGPSTrackingEnabled()) { gpsTracker.getLocation(); getForecast(gpsTracker); Toast.makeText(MainActivity.this, "Data Refreshed", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show(); } } }, 3000); } });}@Overrideprotected void onRestart() { super.onRestart(); final GPSTracker gpsTracker = new GPSTracker(this); new Handler().postDelayed (new Runnable () @Override public void run() { gpsTracker.getLocation(); if (gpsTracker.getIsGPSTrackingEnabled()) { getForecast(gpsTracker); Toast.makeText(MainActivity.this, "Data Refreshed", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show(); } }}, 3000);} Now provide the response and nothing else.
I had a similar problem and I solved it by explicitly creating and passing a new instance to the serializer. In the UserVoteViewSet you have to substitute perform_create with create : def create(self, request, *args, **kwargs): uv = UserVote(created_by=self.request.user) serializer = self.serializer_class(uv, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34661858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4436664/']}
jdg_374149
stackexchange
llm_judgeable_groundtruth_similarity
12067697
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 convert the current date to integer value. By default, it returns long. When I try to convert long to integer, and afterwards I convert the integer value to date, means it shows 1970's date, int i = (int) new Date().getTime(); System.out.println("Integer : " + i); System.out.println("Long : "+ new Date().getTime()); System.out.println("Long date : " + new Date(new Date().getTime())); System.out.println("Int Date : " + new Date(i)); the output as follows: Integer : 1292838124Long : 1345617601771Long date : Wed Aug 22 12:10:01 IST 2012Int Date : Fri Jan 16 04:37:18 IST 1970 Any one please help me out, how to convert current date to integer(10 digit number)? Now provide the response and nothing else.
The issue is that an Integer is not large enough to store a current date, you need to use a Long. The date is stored internally as the number of milliseconds since 1/1/1970. The maximum Integer value is 2147483648, whereas the number of milliseconds since 1970 is currently in the order of 1345618537869 Putting the maximum integer value into a date yields Monday 26th January 1970. Edit: Code to display division by 1000 as per comment below: int i = (int) (new Date().getTime()/1000); System.out.println("Integer : " + i); System.out.println("Long : "+ new Date().getTime()); System.out.println("Long date : " + new Date(new Date().getTime())); System.out.println("Int Date : " + new Date(((long)i)*1000L));Integer : 1345619256Long : 1345619256308Long date : Wed Aug 22 16:37:36 CST 2012Int Date : Wed Aug 22 16:37:36 CST 2012
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12067697', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1280229/']}
jdg_374150
stackexchange
llm_judgeable_groundtruth_similarity
10201880
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 Cocos2D-X game where the player, enemies and other characters store their attributes in a CCMutableDictionary , which is somewhat of a decorator class for std::map<std::string, CCObject*> . A value in the dictionary can be accessed via the CCMutableDictionary::objectForKey(const std::string& key) method. Now, in a header file included by many of my .cpp files, I've got a few const char * const strings for accessing values in the dictionaries, like this: // in Constants.hconst char* const kAttributeX = "x";const char* const kAttributeY = "y";// in a .cpp fileCCObject* x = someDictionary->objectForKey(kAttributeX); So, correct me if I'm wrong, but std::string 's copy constructor is being called and a temporary std::string is on the stack every time I call one of the above objectForKey methods using a const char* const , right? If so, I feel that it would be more efficient at runtime if those constant attribute keys were already std::string objects. But how do I do that the right way? Defining them in the Constants.h file like the following compiles fine, but I have a feeling that something just isn't right: // in Constants.hconst std::string kAttributeX = "x";const std::string kAttributeY = "y"; My apologies if this question has already been asked. I couldn't seem to find the exact answer I was looking for here on StackOverflow. Now provide the response and nothing else.
The code you wrote is perfectly fine, at least as you only #include the Constants.h file in only one source file. If you use the header file in multiple source files, you will have the same variables defined multiple times. The correct use of constants in header files are to split them into a header ( Constants.h ) which contains the declarations of the variables, and a source file ( Constants.cpp ) which contains the definitions of the variables: The header file: #ifndef CONSTANTS_H#define CONSTANTS_Hextern const std::string kAttributeX;extern const std::string kAttributeY;#endif The source file: const std::string kAttributeX = "x";const std::string kAttributeY = "y";
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10201880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1108586/']}
jdg_374151
stackexchange
llm_judgeable_groundtruth_similarity
12539631
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 heard some programmers use if(1 == var) instead of if(var == 1) to avoid unintended assignment. Why or in what cases does it cause unintended assignment? Now provide the response and nothing else.
The problem is if you mistype the statement: if (var = 1) vs if (1 = var) In the first case, the code after the if is executed unconditionally (with no more than a warning from the compiler, which isn't obliged to produce a warning for you — but the good ones do; if you aren't using a good compiler, get one!). In the second case, you get a syntax error at compile time, so the problem has to be fixed before the code can compile. The problem isn't always as blatant: if (var = 0) never executes the code after the if , of course. Often though, you'll have: if (var = function(arg1, arg2)) and it won't be clear whether you intended to assign or compare. You can make it clear to the compiler and code readers (humans) by writing: if ((var = function(arg1, arg2)) != 0) or if (var == function(arg1, arg2)) I don't use the 'back-to-front' comparison technique. I dislike the inverted conditions because they almost invariably read 'wrong' to me. I'm not comparing 1 with my variable; I'm comparing my variable with 1. So, even though logically the == operator is commutative, I don't think commutatively and prefer that 'riskier' way. I have not found myself making the assignment vs equality mistake often enough for the issue to be a problem. The compiler warns me if I do make a mistake (and I pay attention to the warning and fix the code so that there isn't a problem).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12539631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1513286/']}
jdg_374152
stackexchange
llm_judgeable_groundtruth_similarity
168704
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have considered an ideal Fermi gas. Then, we can obtain an expression for chemical potential as a function of temperature. I want to understand the physical significance to it or what it really means. Isn't chemical potential generally a function of temperature for all kinds of gases? Now provide the response and nothing else.
I think the best way to think about it is in terms of entropy ($S$). The chemical potential $\mu$ is related to the entropy $S$ by $\mu = -T \frac{\partial S}{\partial N} .$ The entropy $S$=$S(N,V,T)$ (or (N,V,E), or etc...) is a function of N. Chemical potential is a useful concept because it tells you how the entropy changes due to changes in N, the number of particles or whatever in your system. Then statements like "particles will go from high chemical potential to low chemical potential" are just code for "the entropy isn't maximized right now, so the particles will move around so that the entropy is maximized".
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/168704', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/14087/']}
jdg_374153
stackexchange
llm_judgeable_groundtruth_similarity
2569399
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: Make sequence of $9$ balls from 3 red, 3 blue, 3 green, in such a way that no two balls of the same colour are next to each other. In how many different ways can you do this? (symmetric arrangements must be counted only once). To start with, all possible arrangements are $9! = 362880$. Now provide the response and nothing else.
We have nine positions to fill with three blue, three green, and three red balls. We can fill three of the nine positions with blue balls in $\binom{9}{3}$ ways, three of the remaining positions with green balls in $\binom{6}{3}$ ways, and the remaining three positions with red balls in $\binom{3}{3}$ ways. Hence, the number of distinguishable arrangements of three blue, three green, and three red balls is $$\binom{9}{3}\binom{6}{3}\binom{3}{3} = \frac{9!}{3!3!3!}$$The factors of $3!$ in the denominator represent the number of ways balls of the same color can be permuted among themselves within a given arrangement since permuting balls of the same color among themselves does not produce an arrangement that is distinguishable from the given arrangement. From these, we must exclude those arrangements in which there is at least one pair of adjacent balls of the same color. A pair of adjacent balls of the same color: There are three ways to pick the color. We have eight objects to arrange, the block of two adjacent balls, the other ball of that color, and the other six balls. We have eight positions to fill. Say the block consists of blue balls. Then we can fill three of those eight positions with green balls in $\binom{8}{3}$ ways, three of the remaining positions with red balls in $\binom{5}{3}$ ways, place the block in one of the two remaining positions in $2$ ways, and place the other blue ball in the final open position in one way. Hence, there are$$\binom{8}{3}\binom{5}{3}2! = \frac{8!}{3!3!}$$such arrangements. Since there are three ways of selecting the color, there are $$\binom{3}{1}\frac{8!}{3!3!}$$ arrangements in which a pair of adjacent balls are of the same color. Two pairs of adjacent balls of the same color: There are two cases. Both pairs of adjacent balls are of the same color : This means that all three balls of that color are adjacent. Thus, we have seven objects to arrange, the block of three balls of the same color and the other six objects. Since there are three ways to select the color, the number of arrangements in which there are two pairs of adjacent balls of the same color is $$\binom{3}{1}\frac{7!}{3!3!}$$ Two colors in which there is a pair of adjacent balls of that color : There are $\binom{3}{2}$ ways to select the colors of the pairs. We have seven objects to arrange, the two blocks, the two single balls of those colors, and the three balls of the other color. Thus, there are$$\binom{3}{2}\frac{7!}{3!}$$arrangements in which there are two colors in which there is a pair of adjacent balls of that color. Three pairs of adjacent balls of the same color: There are again two cases. Two pairs of adjacent balls of the same color and one pair of adjacent balls of a different color : There are three ways to pick the color in which there are two pairs of adjacent balls and two ways to pick the other color in which there is one pair of adjacent balls of that color. We have six objects to arrange, the block of three balls, the pair, the other ball of that color, and the three balls of the remaining color. Hence, there are $$\binom{3}{1}\binom{2}{1}\frac{6!}{3!}$$arrangements of this type. Three colors in which there is a pair of adjacent balls of that color : We have six objects to arrange, the three blocks and the three individual balls. Since the objects are all distinct, there are $$6!$$arrangements of this type. Four pairs of adjacent balls of the same color: We again have two cases. Two colors in which there are two pairs of adjacent balls of that color : There are $\binom{3}{2}$ ways to select the two colors. We have five objects to arrange, the two blocks of three adjacent balls of the same color and the three balls of the third color. Hence, there are $$\binom{3}{2}\frac{5!}{3!}$$arrangements of this type. One color in which there are two pairs of adjacent balls of that color and two other colors in which there is one pair of adjacent balls of that color : There are three ways to select the color with two pairs of adjacent balls of that color. We have five objects to arrange, the block of three balls, the two blocks of two balls, and the other two balls. Since the five objects are distinct, there are $$\binom{3}{1}5!$$arrangements of this type. Five pairs of adjacent balls of the same color: There must be two colors in which there are two pairs of adjacent balls of that color and there must also be a pair of adjacent balls of the third color. There are $\binom{3}{2}$ ways of selecting the two colors in which there are two pairs of adjacent balls of that color. We have four objects to arrange, the two blocks of three balls, the block of two balls, and the other ball of that color. Since the objects are distinct, there are $$\binom{3}{2}4!$$arrangements of this type. Six pairs of adjacent balls of the same color: There must be two pairs of adjacent balls of the same color in each of the three colors. Hence, we have three objects to arrange, a block of three blue balls, a block of three green balls, and a block of three red balls. Since these objects are distinct, there are $$3!$$arrangements of this type. By the Inclusion-Exclusion Principle , the number of distinguishable arrangements of three blue, three green, and three red balls in which no two balls of the same color are adjacent is $$\frac{9!}{3!3!3!} - \binom{3}{1}\frac{8!}{3!3!} + \binom{3}{1}\frac{7!}{3!3!} + \binom{3}{2}\frac{7!}{3!} - \binom{3}{1}\binom{2}{1}\frac{6!}{3!} - 6! + \binom{3}{2}\frac{5!}{3!} + \binom{3}{1}5! - \binom{3}{2}4! + 3!$$ This brings us to the question of symmetry. Notice that none of these $174$ arrangements can be a palindrome since for the two colors that do not occupy the middle position, there must be an odd number of balls of that color on one side of the middle ball and an even number of balls of that color on the other side of the middle ball. If we equate two arrangements that can be obtained through reflection, we are left with $87$ distinguishable arrangements of the balls.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2569399', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/447881/']}
jdg_374154
stackexchange
llm_judgeable_groundtruth_similarity
57997
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $G$ be a linear algebraic group over some field, and let $V$ and $W$ be two simple rational representations of $G.$ Is $V\otimes W$ semi-simple? I was trying to convince myself that if $G$ has a faithful semi-simple representation, then $G$ is linearly reductive, and was reduced to the question above. The problem I have in mind is over characteristic 0, but answers addressing char. $p$ is equally appreciated too! Now provide the response and nothing else.
If $G$ is a(ny) group, if $k$ is a field of characteristic 0, and if $V$ and $W$ are semisimple finite dimensional $kG$ modules, then $V \otimes_k W$ is indeed semisimple as a $kG$-module. This is due to Chevalley, and (I think I'm not off-base in saying this) inspired the characteristic $p>0$ result of Serre mentioned in other answers/comments. The argument goes as follows: it is enough to prove the result after replacing $k$ by an algebraic closure. Now replace $G$ by the Zariski closure of its image in $GL(V) \times GL(W)$ -- this Zariski closure leaves invariant the same subspaces of $V \otimes_k W$ as does $G$, so we may suppose $G$ to be a linear algebraic group over $k$. Since representations of finite groups in char. 0 are semisimple, a $G$-representationis semisimple just in case that is true upon restriction to the connected component $G^0$. Thus we may and will suppose $G$ to be connected. Finally, note that $G$ has a faithful semisimple representation, namely $V \oplus W$. Thusthe unipotent radical of $G$ is trivial so that $G$ is a connected and reductive group over $k$. Now the semisimplicity of $V \otimes W$ follows ( every finite dimensional rational representation of $G$ is semisimple).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/57997', 'https://mathoverflow.net', 'https://mathoverflow.net/users/370/']}
jdg_374155
stackexchange
llm_judgeable_groundtruth_similarity
21439359
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 just found out that it's legal to signal a condition variable if you're not holding the lock in c++11. That seems to open the door to some nasty race condition: std::mutex m_mutex;std::condition_variable m_cv;T1: std::unique_lock<std::mutex> lock(m_mutex); m_cv.wait(lock, []{ return !is_empty(); });T2: generate_data(); m_cv.notify(); Is it guaranteed that T1 will never end up in a situation where we check is_empty() first (it returning true), then getting preempted by T2 which creates some data and signals the condition variable before we can actually wait on it? If this is guaranteed to work (I'd guess so, otherwise it would seem like an intentionally bad API design), how is this actually implemented for say linux and stdlibc++ ? Seems we'd need another lock to avoid this situation. Now provide the response and nothing else.
Checking the predicate and waiting are not performed atomically in std::condition_variable::wait (unlocking the lock and sleeping are performed atomically). If it is possible for another thread to change the value of the predicate while this thread holds the mutex, then it is possible for notifications to occur between the predicate check and going to sleep, and effectively be lost. In your example, if generate_data() in T2 can alter the result of is_empty() without holding m_mutex , it's possible for a notification to happen between T1 checking is_empty() and sleeping on m_cv . Holding the mutex at any time between the change to the predicate and the notification is sufficient to guarantee the atomicity of the predicate check and wait call in the other thread. That could look like: { std::lock_guard<std::mutex> lk(m_mutex); generate_data();}m_cv.notify(); or even generate_data();std::lock_guard<std::mutex>(m_mutex); // Lock the mutex and drop it immediatelym_cv.notify();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21439359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/144746/']}
jdg_374156
stackexchange
llm_judgeable_groundtruth_similarity
40992178
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using a web service which is returning response in string format, below is the response form URLdecoded token: PjXoTuRmatcMCFXgQ43Jr8vb4Ux9mdqJyxYsVZ170NS76Q== base64 decoded in byte: [B@16c1d8a7 random code in byte: [B@1076c79d newhash in byte: [B@662b1cdc concatData in byte: [B@1873e3eb Base64.encodeBase64String(concatData): PjXoTuRmatcMCFXgQ43Jr8vb4Ux9mdqJyxYsVZ170NS76Q== localToken: PjXoTuRmatcMCFXgQ43Jr8vb4Ux9mdqJyxYsVZ170NS76Q%3D%3D sms code: 225182; OK - International My question is how to fetch it as currently its going in failure block and error is shown that response is not object type. Now provide the response and nothing else.
There are several ways to do it. 1) Using a service: A service generally has a single instance in the application and can be used to share data between the components easily.E.g. create a service userService and inject it in components where ever you want to use it. 2) using Emit: Emit is used to emit an event in the application and corresponding action can be taken. this.eventInChild.emit(data); Two actions can be taken on event emission. calling a function of parent : <child-component (eventInChild)="parentFunction($event)"></child-component> Emitting from service and Subscribing to an event(can be subscribed in service as well as components) : In Service It goes like this: getEmitStatus() { return this.eventInService;}//In component or service - to listen to eventthis.subscription = this.userService.getEmitStatus() .subscribe(item => { //thing to do here});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40992178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3953441/']}
jdg_374157
stackexchange
llm_judgeable_groundtruth_similarity
23046213
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 setting up webservices for an application and I have the following models: class Parent(models.Model): ...class Child(models.Model): parent = models.ForeignKey(Course) ... The relation is One to Many (1 Parent, many Children) Now, I would like to get all the Parent objects with its particular Child and send it as a JSON Request. Is it possible to do so without having to first get all the "Childs" and iterate through them looking for the ones related to the particular parent? I think that would be extremely inefficient for really large databases, plus the "Childs" won't be repeated in other "Parents" Thank you very much Now provide the response and nothing else.
Every relationship in Django automatically gets its reverse relation added to the model. In the case of a ForeignKey or ManyToManyField that relation contains several objects. In that case, the default attribute name is set to <model>_set , so in this case child_set . This is a manager and can be used as such, so e.g. to iterate over all children: for child in parent.child_set.all(): do_something() You can also specify the attribute name used for the reverse relation using the related_name attribute: class Child(models.Model): parent = models.ForeignKey(Parent, related_name='children')for child in parent.children.filter(some_field=True): do_something() Read more in the documentation on following relations backwards and how are backward relationships possible .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23046213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3146655/']}
jdg_374158
stackexchange
llm_judgeable_groundtruth_similarity
41716380
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the docs , the predict_proba(self, x, batch_size=32, verbose=1) is Generates class probability predictions for the input samples batch by batch. and returns A Numpy array of probability predictions. Suppose my model is binary classification model, does the output is [a, b] , for a is probability of class_0 , and b is the probability of class_1 ? Now provide the response and nothing else.
Here the situation is different and somehow misleading, especially when you are comparing predict_proba method to sklearn methods with the same name. In Keras (not sklearn wrappers) a method predict_proba is exactly the same as a predict method. You can even check it here : def predict_proba(self, x, batch_size=32, verbose=1): """Generates class probability predictions for the input samples batch by batch. # Arguments x: input data, as a Numpy array or list of Numpy arrays (if the model has multiple inputs). batch_size: integer. verbose: verbosity mode, 0 or 1. # Returns A Numpy array of probability predictions. """ preds = self.predict(x, batch_size, verbose) if preds.min() < 0. or preds.max() > 1.: warnings.warn('Network returning invalid probability values. ' 'The last layer might not normalize predictions ' 'into probabilities ' '(like softmax or sigmoid would).') return preds So - in a binary classification case - the output which you get depends on the design of your network: if the final output of your network is obtained by a single sigmoid output - then the output of predict_proba is simply a probability assigned to class 1. if the final output of your network is obtained by a two dimensional output to which you are applying a softmax function - then the output of predict_proba is a pair where [a, b] where a = P(class(x) = 0) and b = P(class(x) = 1) . This second method is rarely used and there are some theorethical advantages of using the first method - but I wanted to inform you - just in case.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41716380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5046896/']}
jdg_374159
stackexchange
llm_judgeable_groundtruth_similarity
430548
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is my code: records_hash = records[:id].inject({}) { |result,h| if result.has_key?(h) result[h] += 1 else result[h] = 1 end result}@test2 = records_hash.each{|key,value| puts "#{key} is #{value}"} My output should look like this: bozo is 3bubba is 4bonker is 5 But it renders on the page ( <%= @test2 %> ) as this: bozo3bubba4bonker5 I've tried .each_key & .each-value with similar blocks and they all return the same string above. I run the same code in IRB and it works as expected. What am I doing wrong? Now provide the response and nothing else.
Your problem is that you are using the each method to build your string. What you want is the map method. each method returns the hash and map returns the value of the block. You want something like this: @test2 = records_hash.map { |k,v| "#{k} is #{v}" } Also, you shouldn't be building view code like this, unless it is a simple string. Your example implies you want each unique element on each line. So your view should be like this: <% @records_hash.each do |k,v| %><%= "#{k} is #{v}" %><% end -%> If your view is an HTML one, you'll want some separator between each line as well: <% @records_hash.each do |k,v| %><%= "#{k} is #{v}" %><br/><% end -%> or <ul> <% @records_hash.each do |k,v| %> <li><%= "#{k} is #{v}" %></li> <% end -%></ul>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/430548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32154/']}
jdg_374160
stackexchange
llm_judgeable_groundtruth_similarity
122748
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: There are of course lots of definitions and references for this, but in the same way that, on a manifold $M$, a Riemannian metric is a section of positive definite symmetric bilinear forms on $TM$ or an almost complex structure is a section $J$ of $\textrm{End}(TM)$ which is everywhere an anti-involution ( i.e. $J_x^2 = - \mathrm{Id}_{T_x M} $) or an orientation is a non-vanishing section of $\Lambda^m TM$ is a spin structure, a section of quadratic forms $Q$ on $TM$ (of type $(s,t)$) and a vector bundle $S$ so that $\textrm{End}(S) \simeq \textrm{C}\ell(TM,Q)$? ...or something of the like? any references where it may be stated in this fashion? Now provide the response and nothing else.
Chapter 9 of Elements of Noncommutative Geometry, by Gracia-Bondia, Varilly, and Figueroa, has this perspective on spin$^c$ and spin structures. The way to think about this algebraically is that the module of (continuous, say) sections of a spinor bundle over a (compact, Riemannian) manifold $M$ is Morita equivalence bimodule for the algebras $C(M)$ and $Cl(M)$, where $C(M)$ is the algebra of continuous functions and $Cl(M)$ is the algebra of continuous sections of the Clifford bundle (formed using the Riemannian metric). You can replace "continuous" with "smooth" here with no problems.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/122748', 'https://mathoverflow.net', 'https://mathoverflow.net/users/18974/']}
jdg_374161
stackexchange
llm_judgeable_groundtruth_similarity
6957775
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why do I read in the answer to most questions here a lot about AsyncTask and Loaders but nothing about Services ? Are Services just not known very well or are they deprecated or have some bad attributes or something? What are the differences? (By the way, I know that there are other threads about it, but none really states clear differences that help a developer to easily decide if he is better off using the one or the other for an actual problem.) Now provide the response and nothing else.
In some cases it is possible to accomplish the same task with either an AsyncTask or a Service however usually one is better suited to a task than the other. AsyncTask s are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed. Service s are designed to be continually running in the background. In the example above of fetching data when a button is pressed, you could start a service, let it fetch the data, and then stop it, but this is inefficient. It is far faster to use an AsyncTask that will run once, return the data, and be done. If you need to be continually doing something in the background, though, a Service is your best bet. Examples of this include playing music, continually checking for new data, etc. Also, as Sherif already said, services do not necessarily run off of the UI thread. For the most part, Service s are for when you want to run code even when your application's Activity isn't open. AsyncTask s are designed to make executing code off of the UI thread incredibly simple.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/6957775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131120/']}
jdg_374162
stackexchange
llm_judgeable_groundtruth_similarity
14179
Below is a question asked on the forum devops.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm configuring a kubernetes cluster (using microk8s) and cert-manager. Certificates work fine to traefik dashboard and to other sites but I have an issue with kubernates dashboard as it's already server via SSL (service is on port 443) and I currently expose a Let'sEncrypt certificate. When I try to reach the dashboard the dashboard's pod logs: 2021/06/17 07:43:20 http: TLS handshake error from 213.215.191.83:39484: remote error: tls: bad certificate2021/06/17 07:43:23 http: TLS handshake error from 213.215.191.83:39500: remote error: tls: bad certificate The IngressRoute I'm using is: apiVersion: traefik.containo.us/v1alpha1kind: IngressRoutemetadata: name: dashboard-k8s namespace: kube-systemspec: entryPoints: - websecure routes: - match: "Host(`k.example.com`)" kind: Rule services: - name: kubernetes-dashboard port: 443 tls: secretName: k8s-dashboard-http-cert I have no clear idea of how should SSL work in this scenario.Would it be safe to have dashboard served on 80 and SSL terminated on traefik? Now provide the response and nothing else.
There are multiple ways to expose Dashboard through traefik. Traefik terminates HTTPS from client and as client opens new HTTPS request to Dashboard. +-------------+ HTTPS +-------------+ HTTPS +-------------+ | Client -----(session 1)----- Traefik ------(session 2)---- Dashboard | +-------------+ +-------------+ +-------------+ This is what you are using. The problem with your configuration is, on second session, Traefik will verify Dashboard's TLS certificate. When Dashboard certificate is not signed by any of CA in Traefik list, it closes connection, then Dashboard raises error message. If you want to use this scenario, you need to skip Dashboard certificate verification, or add Dashboard certificate to Traefik list of trusted CA. Below configuration works by skipping Dashboard certificate verification. apiVersion: traefik.containo.us/v1alpha1 kind: ServersTransport metadata: name: mytransport namespace: kube-system spec: serverName: "k.example.com" insecureSkipVerify: true --- apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: name: dashboard-k8s namespace: kube-system spec: entryPoints: - websecure routes: - match: "Host(`k.example.com`)" kind: Rule services: - name: kubernetes-dashboard port: 443 serversTransport: mytransport tls: secretName: k8s-dashboard-http-cert Traefik passes the TLS traffic to Dashboard without any processing. +-------------+ +-------------+ +-------------+ | Client -------HTTPS-------Traefik(passthrough)---------------- Dashboard | +-------------+ +-------------+ +-------------+ In this scenario, Traefik does not do any TLS termination, the traffic passes as it is to Dashboard. This works for me. apiVersion: traefik.containo.us/v1alpha1 kind: IngressRouteTCP metadata: name: dashboard-k8s namespace: kube-system spec: entryPoints: - websecure routes: - match: HostSNI(`k.example.com`) services: - name: kubernetes-dashboard namespace: kubernetes-dashboard port: 443 tls: passthrough: true Traefik terminates HTTPS from client and open new plain HTTP request to Dashboard. +-------------+ +-------------+ +-------------+ | Client -------HTTPS--------- Traefik ---------HTTP-------- Dashboard | +-------------+ +-------------+ +-------------+ In this scenario, Dashboard need to provide plain HTTP termination. I am not sure whether Dashboard support it.
{}
{'log_upvote_score': 4, 'links': ['https://devops.stackexchange.com/questions/14179', 'https://devops.stackexchange.com', 'https://devops.stackexchange.com/users/28405/']}
jdg_374163
stackexchange
llm_judgeable_groundtruth_similarity
41504106
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 run newly created project in Rails 4.0.8 but I receive and error: rails s=> Booting WEBrick=> Rails 4.0.8 application starting in development on http://0.0.0.0:3000=> Run `rails server -h` for more startup options=> Ctrl-C to shutdown server/usr/local/lib/ruby/gems/2.4.0/gems/activesupport-4.0.8/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Fixnum is deprecated/usr/local/lib/ruby/gems/2.4.0/gems/activesupport-4.0.8/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Bignum is deprecatedExiting/usr/local/lib/ruby/gems/2.4.0/gems/activesupport-4.0.8/lib/active_support/core_ext/numeric/conversions.rb:124:in `block (2 levels) in <class:Numeric>': stack level too deep (SystemStackError) from /usr/local/lib/ruby/gems/2.4.0/gems/activesupport-4.0.8/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>' from /usr/local/lib/ruby/gems/2.4.0/gems/activesupport-4.0.8/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>' from /usr/local/lib/ruby/gems/2.4.0/gems/activesupport-4.0.8/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>' from /usr/local/lib/ruby/gems/2.4.0/gems/activesupport-4.0.8/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>' from /usr/local/lib/ruby/gems/2.4.0/gems/activesupport-4.0.8/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>' from /usr/local/lib/ruby/gems/2.4.0/gems/activesupport-4.0.8/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>' from /usr/local/lib/ruby/gems/2.4.0/gems/activesupport-4.0.8/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>' from /usr/local/lib/ruby/gems/2.4.0/gems/activesupport-4.0.8/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>' ... 5532 levels... from /usr/local/lib/ruby/gems/2.4.0/gems/railties-4.0.8/lib/rails/commands.rb:71:in `tap' from /usr/local/lib/ruby/gems/2.4.0/gems/railties-4.0.8/lib/rails/commands.rb:71:in `<top (required)>' from bin/rails:4:in `require' from bin/rails:4:in `<main>' Ruby version: Rails 4.0.8 My Gemefile: source 'https://rubygems.org'# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'gem 'rails', '4.0.8'# Use sqlite3 as the database for Active Recordgem 'sqlite3'# Use SCSS for stylesheetsgem 'sass-rails', '~> 4.0.2'# Use Uglifier as compressor for JavaScript assetsgem 'uglifier', '>= 1.3.0'# Use CoffeeScript for .js.coffee assets and viewsgem 'coffee-rails', '~> 4.0.0'# See https://github.com/sstephenson/execjs#readme for more supported runtimes# gem 'therubyracer', platforms: :ruby# Use jquery as the JavaScript librarygem 'jquery-rails'# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinksgem 'turbolinks'# Build JSON APIs with ease. Read more: https://github.com/rails/jbuildergem 'jbuilder', '~> 1.2'gem 'json', github: 'flori/json', branch: 'v1.8'group :doc do # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', require: falseend I tried to reinstall rails because before I have 5.0 Rails installed on my machine. Local gems: *** LOCAL GEMS ***autoprefixer-rails (6.6.0)coffee-rails (4.2.1, 4.0.1)font-awesome-rails (4.7.0.1)jquery-atwho-rails (1.3.2)jquery-rails (4.2.2, 3.1.4)rails (4.0.8, 4.0.0)rails-dom-testing (2.0.2)rails-html-sanitizer (1.0.3)rails_12factor (0.0.3)rails_serve_static_assets (0.0.5)rails_stdout_logging (0.0.5)sass-rails (5.0.6, 4.0.5)sprockets-rails (3.2.0, 2.3.3, 2.0.1) Meybe unistall: ruby and rails will solve this problem, but I dont want to do that. Beasically I whant to have installed both version of rails, for exampole: rails 4 and rails 5 as well. Is that configuration possible ? Now provide the response and nothing else.
In Ruby 2.4, there was a unification of integer types (i.e. Fixnum and Bignum are now the very same thing: Integer ). This results on quite a few incompatibilities with existing gems which relied on the distinction of the classes. Older versions of ActiveSupport are among those which don't like this unification and barf over it when trying to serialize data. As such, you have one of two options: You can downgrade Ruby to a version earlier than 2.4, e.g. Ruby 2.3.x. Or you could upgrade Rails to a newer version. Preferably, that could be Rails 5.x. There is also a patch in the 4.2-stable branch which was released with Rails 4.2.8 , making it the first version of the Rails 4.2 series that officially supports Ruby 2.4. Earlier Rails versions are not compatible with Ruby 2.4.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/41504106', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4332524/']}
jdg_374164
stackexchange
llm_judgeable_groundtruth_similarity
48475
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How would you design a database to support the following tagging features: items can have a large number of tags searches for all items that are tagged with a given set of tags must be quick (the items must have ALL tags, so it's an AND-search, not an OR-search) creating/writing items may be slower to enable quick lookup/reading Ideally, the lookup of all items that are tagged with (at least) a set of n given tags should be done using a single SQL statement. Since the number of tags to search for as well as the number of tags on any item are unknown and may be high, using JOINs is impractical. Any ideas? Thanks for all the answers so far. If I'm not mistaken, however, the given answers show how to do an OR-search on tags. (Select all items that have one or more of n tags). I am looking for an efficient AND-search. (Select all items that have ALL n tags - and possibly more.) Now provide the response and nothing else.
About ANDing: It sounds like you are looking for the "relational division" operation. This article covers relational division in concise and yet comprehendible way. About performance: A bitmap-based approach intuitively sounds like it will suit the situation well. However, I'm not convinced it's a good idea to implement bitmap indexing "manually", like digiguru suggests: It sounds like a complicated situation whenever new tags are added(?) But some DBMSes (including Oracle) offer bitmap indexes which may somehow be of use, because a built-in indexing system does away with the potential complexity of index maintenance; additionally, a DBMS offering bitmap indexes should be able to consider them in a proper when when performing the query plan.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5035/']}
jdg_374165
stackexchange
llm_judgeable_groundtruth_similarity
10359661
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 this from a link which talks about external merge sort. From slide 6 Example: with 5 buffer pages, to sort 108 page file Pass0: [108/5] = 22 sorted runs of 5 pages each (last run only with 3 pages) Pass1 [22/4] = 6 sorted runs of 20 pages each (last run only with 8 pages) Pass2: [6/3] = 2 sorted runs, 80 pages and 28 pages Pass 3: [2/2] = 1 Sorted file of 108 pages Question: My understanding is in external merge sort, in pass 0 you create chunks and then sort each chunk. In remaining passes you keep merging them.So, applying that to the above example, since we have only 5 buffer pages, in Pass 0 its clear we need 22 sorted runs of 5 pages each. Now, why are we doing sorted runs for remaining passes instead or merging ? How come it tells for pass 1, 6 sorted runs of 20 pages each when we have only 5 buffer pages ? Where exactly is merge happening here ? and how is N reducing in each pass i.e from 108 to 22 to 6 to 2 ? Now provide the response and nothing else.
External Merge Sort is necessary when you cannot store all the data into memory. The best you can do is break the data into sorted runs and merge the runs in subsequent passes. The length of a run is tied to your available buffer size. Pass0 : you are doing the operations IN PLACE. So you load 5 pages of data into the buffers and then sort it in place using an in place sorting algorithm. These 5 pages will be stored together as a run. Following passes : you can no longer do the operations in place since you're merging runs of many pages. 4 pages are loaded into the buffers and the 5th is the write buffer. The merging is identical to the merge sort algorithm, but you will be dividing and conquering by a factor of B-1 instead of 2. When the write buffer is filled, it is written to disk and the next page is started. Complexity :When analyzing the complexity of external merge sort, the number of I/Os is what is being considered. In each pass, you must read a page and write the page. Let N be the number of pages. Each run will cost 2N. Read the page, write the page. Let B be the number of pages you can hold buffer space and N be the number of pages. There will be ceil(log_B-1(ceil(N/B))) passes. Each pass will have 2N I/Os. So O(nlogn). In each pass, the page length of a run is increasing by a factor of B-1, and the number of sorted runs is decreasing by a factor of B-1. Pass0: ceil(108 / 5) = 22, 5 pages per run Pass1: ceil(22 / 4) = 6, 20 pages per run Pass2: ceil(6 / 4 ) = 2, 80 pages per run Pass3: ceil(2 / 4 ) = 1 - done, 1 run of 108 pages
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10359661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/258956/']}
jdg_374166
stackexchange
llm_judgeable_groundtruth_similarity
30090309
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to add a score to the top of my scene in the game I am working on. The score is going to based on how long you last, and will increase every second. Thanks for the help in advance! import SpriteKitclass easyScene: SKScene { let scrollBarEasyBottom = SKSpriteNode(imageNamed: "scrollBarEasyBottom") let scrollBarEasyTop = SKSpriteNode(imageNamed: "scrollBarEasyTop") let ball = SKSpriteNode(imageNamed: "ball") var origSBEBpositionX = CGFloat(0) var origSBETpositionX = CGFloat(0) var maxSBEBX = CGFloat(0) var SBEBSpeed = 5 var maxSBETX = CGFloat(0) var SBETSpeed = 5 var score = 0 var timer: NSTimer? var scoreText = SKLabelNode(fontNamed: "Kailasa") override func didMoveToView(view: SKView) { println("Easy Scene is the location") self.backgroundColor = UIColor.blackColor() self.scrollBarEasyBottom.position = CGPoint(x:0, y:270) self.addChild(self.scrollBarEasyBottom) self.scrollBarEasyBottom.yScale = 0.2 self.origSBEBpositionX = self.scrollBarEasyBottom.position.x // end scrollBarEasyBottom self.scrollBarEasyTop.position = CGPoint(x:20, y:400) self.addChild(self.scrollBarEasyTop) self.scrollBarEasyTop.yScale = 0.2 self.origSBETpositionX = self.scrollBarEasyTop.position.x // end scrollBarEasyTop self.ball.position = CGPoint(x:40, y:293) self.addChild(self.ball) self.ball.yScale = 0.17 self.ball.xScale = 0.17 // end ball self.maxSBEBX = self.scrollBarEasyBottom.size.width - self.frame.size.width self.maxSBEBX *= -1 self.maxSBETX = self.scrollBarEasyTop.size.width - self.frame.size.width self.maxSBETX *= -1 // self.scoreText.text = "0" self.scoreText.fontSize = 60 self.scoreText.position = CGPoint(x: CGRectGetMidX(self.frame), y: 500) self.scoreText.text = String(self.score) self.addChild(self.scoreText) timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("scoreIncrease") , userInfo: nil, repeats: true) func scoreIncrease (){ score++ println(score) } } override func update(currentTime: NSTimeInterval) { if self.scrollBarEasyBottom.position.x <= maxSBEBX + 1200 { self.scrollBarEasyBottom.position.x = self.origSBEBpositionX } if self.scrollBarEasyTop.position.x <= maxSBETX + 1200 { self.scrollBarEasyTop.position.x = self.origSBETpositionX } scrollBarEasyBottom.position.x -= CGFloat(self.SBEBSpeed) scrollBarEasyTop.position.x -= CGFloat(self.SBETSpeed) // moving bars var degreeRotation = CDouble(self.SBEBSpeed) * M_PI / 180 self.ball.zRotation -= CGFloat(degreeRotation) //rotate ball } } After running this code, I always get an unrecognized selector sent to instance error Now provide the response and nothing else.
You can use one like this: var timer = NSTimer()override func viewDidLoad() { scheduledTimerWithTimeInterval()}func scheduledTimerWithTimeInterval(){ // Scheduling timer to Call the function "updateCounting" with the interval of 1 seconds timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateCounting"), userInfo: nil, repeats: true)} func updateCounting(){ NSLog("counting..")} Swift 3: var timer = Timer()override func viewDidLoad() { // Use for the app's interface scheduledTimerWithTimeInterval()}override func didMove(to view: SKView) { // As part of a game scheduledTimerWithTimeInterval()}func scheduledTimerWithTimeInterval(){ // Scheduling timer to Call the function "updateCounting" with the interval of 1 seconds timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateCounting), userInfo: nil, repeats: true)}@objc func updateCounting(){ NSLog("counting..")} Swift 5: Note: this solution is compatible with iOS 10.0+. // If needing to check for iOS compatibility use// if #available(iOS 10.0, *) {code}var timer = Timer()override func viewDidLoad() { self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { _ in updateCounting() })}func updateCounting(){ print("counting...")} You can then invalidate (stop) the timer using: timer.invalidate()
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30090309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4868111/']}
jdg_374167
stackexchange
llm_judgeable_groundtruth_similarity
4824613
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 recursively call a block from within itself. In an obj-c object, we get to use "self", is there something like this to refer to a block instance from inside itself? Now provide the response and nothing else.
Fun story! Blocks actually are Objective-C objects. That said, there is no exposed API to get the self pointer of blocks. However, if you declare blocks before using them, you can use them recursively. In a non-garbage-collected environment, you would do something like this: __weak __block int (^block_self)(int);int (^fibonacci)(int) = [^(int n) { if (n < 2) { return 1; } return block_self(n - 1) + block_self(n - 2);} copy];block_self = fibonacci; It is necessary to apply the __block modifier to block_self , because otherwise, the block_self reference inside fibonacci would refer to it before it is assigned (crashing your program on the first recursive call). The __weak is to ensure that the block doesn't capture a strong reference to itself, which would cause a memory leak.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4824613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247151/']}
jdg_374168
stackexchange
llm_judgeable_groundtruth_similarity
1342442
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 $H$ be a subgroup of $G$. What is the stabilizer of the coset $aH$ for the action of $G$ on $X=G/H$ by left multiplication? So, I think I've done this one correctly:The Stabilizer is of the form:$G_{aH} = \{g \in G | gaH=aH \} \implies g \in aH \implies g=ah$ for some $h \in H \implies G_{aH} = aH$. Have I missed something? Now provide the response and nothing else.
Not quite. Especially, your solution $aH$ fails to be a group in general.$$gaH=aH\iff a^{-1}gaH= H\iff a^{-1}ga\in H\iff g\in aHa^{-1}$$ Alternatively: "Clearly" the stabilizer of $H$ is $H$. And for any action with $a\cdot x_1=x_2$ we have $G_{x_2}=aG_{x_1}a^{-1}$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1342442', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/174166/']}
jdg_374169
stackexchange
llm_judgeable_groundtruth_similarity
3640993
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Prior to Rails 3, you could modify the script/server file to add in SSL parameters and tell the server command to use the HTTPS version of WEBrick. Now that all of those scripts are gone, does anyone know how to get this to work with Rails 3 or 4? Now provide the response and nothing else.
An Alternative to SSL/HTTPS on WEBrick: SSL/HTTPS on Thin As an alternative to trying to set up WEBrick to use HTTPS/SSL for your Rails app, you can try switching to using the Thin server instead, because it comes with convenient options for setting up HTTPS/SSL out-of-the-box. Installing Thin First, add Thin as a gem to your Gemfile: gem 'thin' Then run bundle install from the command line. Using Thin HTTPS/SSL for Development Environments If you just want to test your Rails app using HTTPS/SSL in your local development environment , then you simply run thin start --ssl I have to emphasize that this is not suitable for production environments , because you need to use a valid SSL certificate from a Certificate Authority in order for SSL/HTTPS connections to be verifiable and secure. Additional Options There are also other options that you can pass to Thin. You can get a full list of them by running thin --help . For example, I like to specify my own ip-address and port, as well as daemonizing Thin into a background process: thin start --ssl \ --address <ip-address> \ --port <port> \ --daemonize Using Thin HTTPS/SSL with an SSL Certificate If you want to tell Thin to use an SSL certificate (for example, one that you've obtained from a valid Certificate Authority), then you can use these options: thin start --ssl \ --ssl-cert-file <path-to-public-certificate> \ --ssl-key-file <path-to-private-key>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3640993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/439456/']}
jdg_374170
stackexchange
llm_judgeable_groundtruth_similarity
2575977
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: In number fields that are PIDs, i.e., with class number 1, we have unique factorization of integral elements into primes, much like we do in $\Bbb Z$. Suppose $\pi$ is such a prime element in $R$, the integer ring of our number field. What can we say about the structure of $R/\pi R$? In the case $R=\Bbb Z$, the quotient has a cyclic multiplicative group, i.e., primitive roots exist for rational primes. Is that also true in other uniquely factoring integer rings? I know that rational primes are not necessarily prime in such rings; I’m asking about elements that are prime. Can we state necessary and sufficient conditions on an integral ring for the primitive root theorem to hold? I have searched for an answer on MSE and Google to no avail. I have also looked at the proof that rational primes have primitive roots, but it is not clear to me whether this generalizes to integer rings in other number fields. Now provide the response and nothing else.
\begin{align*}\sum_{k=2}^{N}\dfrac{1}{2k(2k-1)}\leq\sum_{k=2}^{N}\dfrac{1}{2k(2k-(k/2))}=\dfrac{1}{3}\sum_{k=2}^{N}\dfrac{1}{k^{2}}<\dfrac{1}{3}\sum_{k=2}^{\infty}\dfrac{1}{k^{2}}<\infty,\end{align*}so $\{S_{2N}\}$ is convergent, so is $\{S_{2N+1}\}$ because $\lim_{N}(S_{2N+1}-S_{2N})=0$ (so they have the same limit). Then $\{S_{N}\}$ is convergent.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2575977', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/92129/']}
jdg_374171
stackexchange
llm_judgeable_groundtruth_similarity
600910
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: Find the general solution of: $$\sin^3 \theta - \sin \theta = 0$$ Working out: (Factorise out) $$\sin \theta (\sin^2 \theta - 1) = 0$$ Solve for $\sin \theta$ and $\sin^2 \theta - 1$: For $\sin \theta = 0$ $$\sin \theta = 0$$ $$\therefore \theta = 0$$ $$\therefore \theta = n \pi$$ For $\sin^2 \theta - 1 = 0$: $$\sin^2 \theta - 1 = 0$$ $$\sin^2 \theta = 1$$ $$\sin \theta = \pm1$$ $$\theta = - \pi/2, \pi/2$$ $$\therefore \theta = n\pi + (-1)^n(\pm\pi/2)$$ So i get the two solutions as: $$\theta = n\pi\text{ and }\theta = n\pi + (-1)^n(\pm\pi/2)$$ However a complication occurs because wolframalpha says otherwise, help would be greatly appreciated. Wolframalpha Now provide the response and nothing else.
Holder's inequality says:$$ E(UV) \le (E|U|^p)^{1/p} (E|V|^q)^{1/q} $$for any $1 < p,q < \infty$ with $\frac1p+\frac1q = 1$. Put $U = \exp((1-\theta)\lambda_0 Z)$, $V = \exp(\theta\lambda_1 Z)$, $p=\frac1{1-\theta}$, $q=\frac1\theta$ for any $0<\theta<1$, take logs of both sides, and you get$$ \log E(\exp(((1-\theta)\lambda_0+\theta\lambda_1)Z)) \le (1-\theta) \log E(\exp(\lambda_0 Z)) + \theta \log E(\exp(\lambda_1 Z)) .$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/600910', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/67436/']}
jdg_374172
stackexchange
llm_judgeable_groundtruth_similarity
17095
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have done some basic object oriented programming with C++ (creating a B-Tree, Hashing Algorithms, Double Linked Lists) and I have done small project in C (like making a scientific calculator etc.) How different is hardware programming (specifically for micro controllers) from software/object oriented programming in terms of the mindset and "thinking" that the programmer has to have? Is one usually considered harder than the other my most people? With my background (as described above) would I need a lot of preparation for going into hardware programming or can I dive straight in without too much preparation? Now provide the response and nothing else.
You will have to completely abandon the object-oriented paradigm when dealing with most microcontrollers. Microcontrollers are generally register- and RAM-limited, with slow clock rates and no pipelining / parallel code paths. You can forget about Java on a PIC, for example. You have to get into an assembly-language mindset, and write procedurally. You have to keep your code relatively flat and avoid recursion, as RAM limitations can often lead to stack issues. You have to learn how to write interrupt service routines which are efficient (usually in assembly language). You may have to refactor parts of the code manually, in assembly language, to implement functionality that the compiler doesn't support (or supports poorly). You have to write mathematical code that takes into account the word size and lack of FPU capabilities of most microcontrollers (i.e. doing 32-bit multiplication on an 8-bit micro = evil). It is a different world. To me, having a computer science or professional programming background can be as much of a hindrance as having no knowledge at all when dealing with microcontrollers.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/17095', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/4711/']}
jdg_374173
stackexchange
llm_judgeable_groundtruth_similarity
14960121
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 about to migrate some code to the PSR-2 standard. In my code i have if statements with multiple lines as expression: if ( $field->getBlockMode() == FieldInterface::BLOCK_MODE_HIDEVAR && !isset($this->enabledBlocks[$field->getBlock()])) {} What's the best practice to write such expressions? Now provide the response and nothing else.
How about making it a one-liner to avoid that problem and make the statement more readable: $blockModeIsHidevar = $field->getBlockMode() == FieldInterface::BLOCK_MODE_HIDEVAR;$blockNotEnabled = !isset($this->enabledBlocks[$field->getBlock()]);if ($blockModeIsHidevar && $blockNotEnabled) {} Alternative: I usually do it with methods, this could looke like that: if ($this->blockModeIsHidevar($field) && $this->blockNotEnabled($field)) {}// ...private function blockModeIsHidevar($field){ return $field->getBlockMode() == FieldInterface::BLOCK_MODE_HIDEVAR}private function blockNotEnabled($field){ return !isset($this->enabledBlocks[$field->getBlock()])} This way, the optimization of && still takes place.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14960121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/894982/']}
jdg_374174
stackexchange
llm_judgeable_groundtruth_similarity
242110
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I am looking for a character in Unix and Windows filesystems that is not allowed in file and directory names and I was wondering if there is such a character. I have noticed that * and % are allowed? Now provide the response and nothing else.
There is no such thing as a "Unix" filesystem. Nor a "Windows" filesystem come to that. Do you mean NTFS, FAT16, FAT32, ext2, ext3, ext4, etc. Each have their own limitations on valid characters in names. Also, your question title and question refer to two totally different concepts? Do you want to know about the subset of legal characters, or do you want to know what wildcard characters can be used in both systems? http://en.wikipedia.org/wiki/Ext3 states "all bytes except NULL and '/'" are allowed in filenames. http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx describes the generic case for valid filenames "regardless of the filesystem". In particular, the following characters are reserved < > : " / \ | ? * Windows also places restrictions on not using device names for files: CON, PRN, AUX, NUL, COM1, COM2, COM3, etc. Most commands in Windows and Unix based operating systems accept * as a wildcard. Windows accepts % as a single char wildcards, whereas shells for Unix systems use ? as single char wildcard.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/242110', 'https://serverfault.com', 'https://serverfault.com/users/26257/']}
jdg_374175
stackexchange
llm_judgeable_groundtruth_similarity
14371335
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 the usage of the spring @ScopedProxy annotation? I thought it had something to do with session scoped beans, but I'm not quite sure what. In my usage of scopes, I've used session scoped beans without the @ScopedProxy annotation (or without aop scoped proxies), so I'm really sure how to use it properly. Now provide the response and nothing else.
Section 3.4.4.5 of the spring docs explains it pretty well: (please note that the following 'userPreferences' bean definition as it stands is incomplete): <!-- an HTTP Session-scoped bean --><bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/><!-- a singleton-scoped bean --><bean id="userManager" class="com.foo.UserManager"> <property name="userPreferences" ref="userPreferences"/></bean> From the above configuration it is evident that the singleton bean 'userManager' is being injected with a reference to the HTTP Session-scoped bean 'userPreferences'. The salient point here is that the 'userManager' bean is a singleton ... it will be instantiated exactly once per container , and its dependencies (in this case only one, the 'userPreferences' bean) will also only be injected (once!) . This means that the 'userManager' will (conceptually) only ever operate on the exact same 'userPreferences' object, that is the one that it was originally injected with. This is not what you want when you inject a HTTP Session-scoped bean as a dependency into a collaborating object (typically). Rather, what we do want is a single 'userManager' object per container , and then, for the lifetime of a HTTP Session, we want to see and use a 'userPreferences' object that is specific to said HTTP Session . Rather what you need then is to inject some sort of object that exposes the exact same public interface as the UserPreferences class (ideally an object that is a UserPreferences instance) and that is smart enough to be able to go off and fetch the real UserPreferences object from whatever underlying scoping mechanism we have chosen (HTTP request, Session, etc.). We can then safely inject this proxy object into the 'userManager' bean, which will be blissfully unaware that the UserPreferences reference that it is holding onto is a proxy . In our case, when a UserManager instance invokes a method on the dependency-injected UserPreferences object, it will really be invoking a method on the proxy ... the proxy will then go off and fetch the real UserPreferences object from (in this case) the HTTP Session, and delegate the method invocation onto the retrieved real UserPreferences object. That is why you need the following, correct and complete, configuration when injecting request-, session-, and globalSession-scoped beans into collaborating objects: <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"> <aop:scoped-proxy/></bean><bean id="userManager" class="com.foo.UserManager"> <property name="userPreferences" ref="userPreferences"/></bean>
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14371335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/121993/']}
jdg_374176
stackexchange
llm_judgeable_groundtruth_similarity
3207814
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 cross-platform approach to taking screenshots from a firefox extension? Ideally I'd like to be able to take a screenshot of a dom element (irrespective of whether it's visible on the page or not), something like: var screenshot = screenshot(document.getElementById('example'); Any pointers or suggestions would be nice, searching https://developer.mozilla.org/ only yields screenshots they've used in various guides. Now provide the response and nothing else.
After examining the code of several extensions. I took the following approach (to take a snapshot of a particular dom element). This can be used in a Firefox extension to take screenshots of the whole page, to take screenshots of the browser window and to take screenshots of a particular dom element (and all of its child nodes): Add canvas to xul. Find dimensions and top-left co-ordinates of element. Copy portion of window to canvas. Convert canvas to base64 PNG file. function getElementScreenshot(elm) { var x = findPosX(elm); var y = findPosY(elm); var width = elm.clientWidth; var height = elm.clientHeight; var cnvs = document.getElementById("aCanvas"); cnvs.width = width; cnvs.height = height; var ctx = cnvs.getContext("2d"); // To take a snapshot of entire window // ctx.drawWindow(mainWindow.content, 0, 0, mainWindow.innerWidth, mainWindow.innerHeight, "rgb(255,255,255)"); ctx.drawWindow(mainWindow.content, x, y, width, height, "rgb(255,255,255)"); return(cnvs.toDataURL());} To find top left coordinate of an element function findPosX(obj) { var curleft = 0; if (obj.offsetParent) { while (1) { curleft += obj.offsetLeft; if (!obj.offsetParent) { break; } obj = obj.offsetParent; } } else if (obj.x) { curleft += obj.x; } return curleft;}function findPosY(obj) { var curtop = 0; if (obj.offsetParent) { while (1) { curtop += obj.offsetTop; if (!obj.offsetParent) { break; } obj = obj.offsetParent; } } else if (obj.y) { curtop += obj.y; } return curtop;} To get access to browser.xul from sidebar var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIWebNavigation) .QueryInterface(Components.interfaces.nsIDocShellTreeItem) .rootTreeItem .QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIDOMWindow);mainWindow.gBrowser.addTab(...);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3207814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/339471/']}
jdg_374177
stackexchange
llm_judgeable_groundtruth_similarity
414350
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Description: I'd like to access a D-Bus system service from another machine, knowing only machine's IP address and the service to connect to. What I have recently found is Gabriel (D-Bus over SSH). I have compiled its GIT version (hosted on Sourceforge) and this seems to work, but I keep getting a problem with the lack of "keep-alive". This means that after some period of inactivity the SSH tunnel fails to forward D-Bus requests to remote PC and I must restart Gabriel. Since Gabriel uses socat on the PC it connects to, I've just had an idea of using socat also on local PC (replacing Gabriel with it). Questions: Could anyone more familiar with setting up "socat" confirm that solution please? Could such solution handle many client applications connecting to the same remote D-Bus service at once? As it is unneccessary for me to have the connection secured - would using "socat" on both sides make the connection significantly faster (in opposite to Gabriel's SSH tunnel, if the SSH gives too much overhead)? Does anyone have any better solution for accessing D-Bus remotely maybe? Any comments appreciated. Now provide the response and nothing else.
I'll post an answer to my own question, as I have worked out a working solution. Note: I have sacrificed all security via SSH as it wasn't needed for development in my own LAN.Changing DBus to listen on TCP instead unix sockets was also not possible. Step 1 On the remote host with an example IP address 192.168.1.100 (and to which D-Bus I'd like to have access to) I run: socat TCP-LISTEN:7272,reuseaddr,fork UNIX-CONNECT:/var/run/dbus/system_bus_socket Now socat listens for connections on 7272 port and creates a separate thread for each client. This allows multiple connections at the same time. Step 2 On local machine (which I'd like to connect to remote D-Bus) I run: socat ABSTRACT-LISTEN:/tmp/custom_dbus_name,fork TCP:192.168.1.100:7272 This connects to the port exposed remotely with socat and creates a local abstract socket to which we can connect to. Sample usage Python: import dbussysbus = dbus.bus.BusConnection("unix:abstract=/tmp/custom_dbus_name")proxy_obj = sysbus.get_object('com.some.service.name', '/com/some/service/name')my_interface = dbus.Interface(proxy_obj, dbus_interface = 'com.some.interface.name')my_interface.SomeDBusExposedMethod()my_interface.OtherRemoteMethod() D-Feet One can also use D-Feet to browse remote D-Bus services and their methods. It can be done with "File / Connect to other bus" menu option and putting your custom abstract socket name defined in second step.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/414350', 'https://serverfault.com', 'https://serverfault.com/users/130988/']}
jdg_374178
stackexchange
llm_judgeable_groundtruth_similarity
37173580
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 series of monthly gridded datasets in CSV form. I want to read them, add a few dimensions, and then write to netcdf. I've had great experience using xarray (xray) in the past so thought I'd use if for this task. I can easily get them into a 2D DataArray with something like: data = np.ones((360,720))lats = np.arange(-89.75, 90, 0.5) * -1lngs = np.arange(-179.75, 180, 0.5)coords = {'lat': lats, 'lng':lngs}da = xr.DataArray(data, coords=coords) But when I try to add another dimension, which would convey information about time (all data is from the same year/month), things start to go sour. I've tried two ways to crack this: 1) expand my input data to m x n x 1, something like: data = np.ones((360,720))lats = np.arange(-89.75, 90, 0.5) * -1lngs = np.arange(-179.75, 180, 0.5)coords = {'lat': lats, 'lng':lngs}data = data[:,:,np.newaxis] Then I follow the same steps as above, with coords updated to contain a third dimension. lats = np.arange(-89.75, 90, 0.5) * -1lngs = np.arange(-179.75, 180, 0.5)coords = {'lat': lats, 'lng':lngs}coords['time'] = pd.datetime(year, month, day))da = xr.DataArray(data, coords=coords)da.to_dataset(name='variable_name') This is fine for creating a DataArray -- but when I try to convert to a dataset (so I can write to netCDF), I get an error about 'ValueError: Coordinate objects must be 1-dimensional' 2) The second approach I've tried is taking my dataarray, casting it to a dataframe, setting the index to ['lat','lng', 'time'] and then going back to a dataset with xr.Dataset.from_dataframe() . I've tried this -- but it takes 20+ min before I kill the process. Does anyone know how I can get a Dataset with a monthly 'time' dimension? Now provide the response and nothing else.
Your first example is pretty close: lats = np.arange(-89.75, 90, 0.5) * -1lngs = np.arange(-179.75, 180, 0.5)coords = {'lat': lats, 'lng': lngs}coords['time'] = [datetime.datetime(year, month, day)]da = xr.DataArray(data, coords=coords, dims=['lat', 'lng', 'time'])da.to_dataset(name='variable_name') You'll notice a few changes in my version: I'm passing in a first for the 'time' coordinate instead of a scalar. You need to pass in a list or 1d array to get a 1D coordinate variable, which is what you need if you also use 'time' as a dimension. That's what the error ValueError: Coordinate objects must be 1-dimensional is trying to tell you (by the way -- if you have ideas for how to make that error message more helpful, I'm all ears!). I'm providing a dims argument to the DataArray constructor. Passing in a (non-ordered) dictionary is a little dangerous because the iteration order is not guaranteed. I also switched to datetime.datetime instead of pd.datetime . The later is simply an alias for the former. Another sensible approach is to use concat with a list of one item once you've added 'time' as a scalar coordinate, e.g., lats = np.arange(-89.75, 90, 0.5) * -1lngs = np.arange(-179.75, 180, 0.5)coords = {'lat': lats, 'lng': lngs, 'time': datetime.datetime(year, month, day)}da = xr.DataArray(data, coords=coords, dims=['lat', 'lng'])expanded_da = xr.concat([da], 'time') This version generalizes nicely to joining together data from a bunch of days -- you simply make the list of DataArrays longer. In my experience, most of the time the reason why you want the extra dimension in the first place is to be able to able to concat along it. Length 1 dimensions are not very useful otherwise.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37173580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684543/']}
jdg_374179
stackexchange
llm_judgeable_groundtruth_similarity
892861
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do you replace an element in jQuery and have the replacement element returned instead of the element that was removed? I have the following scenario. I have many checkboxes and once you click one of them, that checkbox is replaced by a loading icon. Once some AJAX stuff happens, the loading icon is replaced by a tick icon. Using jQuery's replaceWith , you'd do something like: $("input[type='checkbox']").click(function() { $(this).replaceWith("<img src='loading.jpg' alt='loading'/>"); $.post("somepage.php"); $(this).replaceWith("<img src='tick.jpg' alt='done'/>"); }); However, this doesn't work because replaceWith returns the element that was removed, not the one which was added. So after the AJAX stuff completes, loading.jpg will just stay there forever. Is there some way I can return the replacement element without selecting it? Thanks in advance. Now provide the response and nothing else.
Give the loading image a class, then in the post callback, use the class as a selector to find the image you've just injected. $("input[type='checkbox']").click(function() { $(this).replaceWith("<img src='loading.jpg' alt='loading' class='loading-image' />"); $.post("somepage.php", function() { $('.loading-image').replaceWith("<img src='tick.jpg' alt='done'/>"); });}); If you may have several of these running at a time, you can get the closest parent of this and use that as the context when searching for the class. EDIT : Another alternative that uses a variable to store the new element and removes the need to apply the class and search for the new element when the function returns. $("input[type='checkbox']").click(function() { var loading = $("<img src='loading.jpg' alt='loading' />"); $(this).replaceWith(loading); $.post("somepage.php", function() { loading.replaceWith("<img src='tick.jpg' alt='done'/>"); });});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/892861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/21709/']}
jdg_374180
stackexchange
llm_judgeable_groundtruth_similarity
52894546
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 React Native for my application, and at one point, I noticed that I have to type this.state.bar[this.state.foo][SOME_NUMBER] every time, within my components. This works perfectly fine, but I want to make my code cleaner by calling a function instead. So, I constructed this: function txt(n){ return this.state.bar[this.state.foo][n];} However, when I run this in the Expo client, I get the following error: TypeError: undefined is not an object (evaluating 'this.state.bar')This error is located at: in App... .... Here is my entire code. import React, { Component } from 'react';import { ... } from 'react-native';export default class App extends React.Component { state = { foo: 'ABC', bar: { 'ABC': [ '...', '...', '...' ] } }; render() { function txt(n){ return this.state.bar[this.state.foo][n]; } return ( <View> ... </View> ); }} I tried placing the text() function outside the App class, but got the same error. When I placed it outside render() in App , I got an unexpected token error. When I defined this.state within a constructor(props) and placed text() within the constructor , I got ReferenceError: Can't find variable: text Now provide the response and nothing else.
Your problem is scoping. The this that you're trying to access inside the txt() function is pointing to its own this , and not the outer component this . There are several ways to fix this. here's a few: Use arrow functions You can transform txt into an arrow function to use the outer this : render() { const txt = (n) => { return this.state.bar[this.state.foo][n]; } return ( <View> ... </View> );} You can bind the function to use the outer this render() { function _txt(n){ return this.state.bar[this.state.foo][n]; } const txt = _txt.bind(this); return ( <View> ... </View> );} You can create an additional variable that points to the outer this render() { const self = this; function txt(n){ return self.state.bar[self.state.foo][n]; } return ( <View> ... </View> );} Other approaches You can move the txt function to outside of the render function and bind it to the component this . You can use an arrow function inside the component class block, which will seem like you've bound it to the component's this . You can pass the state as a parameter to the function ...and I'm sure that there are several other ways to fix this behaviour. You just need to know when you're using the component's this or some other this .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52894546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7813854/']}
jdg_374181
stackexchange
llm_judgeable_groundtruth_similarity
9957936
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After trying to make access to a storage class a little easier, I ended up in a situation that I don't have a lot of knowledge on. And, finding people that are trying to do the same thing as me isn't easy. What I'm trying to do, is have a class that stores an array of values as strings internally, but allows simple type casting from the user's end. What I had planned on doing is use the array subscript operator to return whichever type they specify through a template. Although, it sounds a lot better than it works in practice. Here's a simple example of what I'm doing, to give you an idea of how it should work. class StringList{ public: template <typename T> T operator[](const int i)} From there, I would define a few specific templates, and any user could very easily define more if needed. But, the biggest problem with this is, I don't know how to call the subscript operator with a template. At first I assumed the following(which apparently isn't correct), considering it's similar to the standard way of calling a template method. StringList list;T var = list<T>[0]; Does anyone know the proper way of calling the subscript operator as a template? Or, should I just avoid doing this, and use a named method? Now provide the response and nothing else.
The only way calling your operator is explicitly writing list.operator[]<T>() . There are two basic ways out: Write a function template like list.get<int>() (as proposed by templatetypedef) Return a proxy with automatic conversation to T . The code would look like: // in the classstruct proxy { proxy(StringList *list, int i) : list(list), i(i) {} StringList *list; int i; template <typename T> operator T() { return list->get<T>(i); }};proxy operator[](int i) { return proxy(this, i); }template <typename T> T get(int i) { return ...; T(); }// how to use it:StringList list;int var = list.get<int>(0);float var2 = list[0];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9957936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305262/']}
jdg_374182
stackexchange
llm_judgeable_groundtruth_similarity
23964
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: A friend of mine told my wife that carbon dating is unreliable because it has been performed on live humans and indicated that the test subject(s) are 4000 years old. Is there any truth to this claim? I'm having a hard time finding anything about it. Now provide the response and nothing else.
The use of Carbon-14 for dating is not completely precise. In general, 500 years is the minimum and 50,000 years is the maximum due to the need to calibrate for background C-14 levels, and to have sufficient breakdown to establish the half-life proportions but not so much that the sample is too small to measure. That said, they're using Carbon-14 dating on recent human remains in forensic science , although the technique works best on bodies around the 1940s to 1960s due to the increased presence of C-14 due to atomic bomb testing. Currently, the atmospheric levels of C-14 are dropping again, so the method will be less feasible for people deceased after that point. Given the difficulty of dating samples less than 500 years old, I could readily see your friend, or the person who gave him that information, latching on to the idea of less aged items being hard to date and the actual figure involved getting enlarged with the telling.
{}
{'log_upvote_score': 7, 'links': ['https://skeptics.stackexchange.com/questions/23964', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/22711/']}
jdg_374183
stackexchange
llm_judgeable_groundtruth_similarity
16613809
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 create a circle (without any animation) which is surrounded by other circles, like this: but i would like to build in a phonegap app, so i don't want to increase the file size to big. somebody know a plugin/method or any other solution? I searched on the internet, but the methods i found are increase the size of my files too big. Now provide the response and nothing else.
No one addressed the javascript aspect of this question. Below is a complete (albeit quick and dirty) web page that will draw 6 perfectly spaced circles around a parent circle's center using html, css3, and javascript; it uses pure javascript so no need to reference a jquery library. You should be able to see how you could easily extract methods from the code to control the number of satellite circles, their distance from the center of the parent, parent and satellite radii, satellite offset, etc: var div = 360 / 6;var radius = 150;var parentdiv = document.getElementById('parentdiv');var offsetToParentCenter = parseInt(parentdiv.offsetWidth / 2); //assumes parent is squarevar offsetToChildCenter = 20;var totalOffset = offsetToParentCenter - offsetToChildCenter;for (var i = 1; i <= 6; ++i) { var childdiv = document.createElement('div'); childdiv.className = 'div2'; childdiv.style.position = 'absolute'; var y = Math.sin((div * i) * (Math.PI / 180)) * radius; var x = Math.cos((div * i) * (Math.PI / 180)) * radius; childdiv.style.top = (y + totalOffset).toString() + "px"; childdiv.style.left = (x + totalOffset).toString() + "px"; parentdiv.appendChild(childdiv);} #parentdiv { position: relative; width: 150px; height: 150px; background-color: #ac5; border-radius: 150px; margin: 150px;}.div2 { position: absolute; width: 40px; height: 40px; background-color: #ac5; border-radius: 100px;} <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <title></title></head><body> <div id="parentdiv"></div></body></html>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16613809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1876896/']}
jdg_374184
stackexchange
llm_judgeable_groundtruth_similarity
21437386
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 used BeautifulSoup for Python 3.3 to successfully pull desired info from a web page. I have also used BeautifulSoup to generate new HTML code to display this info. Currently, my Python program prints out the HTML code, which I then have to copy, paste, and save as an HTML file, then from there, I can test it in a browser. So my question is this, is there a way in Python to launch the HTML code generated by BeautifulSoup in a web browser so that I don't have to go through the copy and paste method I use now? Now provide the response and nothing else.
Using webbrowser.open : import osimport webbrowserhtml = '<html> ... generated html string ...</html>'path = os.path.abspath('temp.html')url = 'file://' + pathwith open(path, 'w') as f: f.write(html)webbrowser.open(url) Alternative using NamedTemporaryFile (to make the file eventually deleted by OS): import tempfileimport webbrowserhtml = '<html> ... generated html string ...</html>'with tempfile.NamedTemporaryFile('w', delete=False, suffix='.html') as f: url = 'file://' + f.name f.write(html)webbrowser.open(url)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21437386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3108789/']}
jdg_374185
stackexchange
llm_judgeable_groundtruth_similarity
832364
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm thinking on building my own (micro-atx) router for business and personal projects at home. My question is what kind of network card do I need to receive the fiber optic connection? I'm currently using the router my ISP provides me but I want to replace it. I've been looking and I can only find super expensive cards (more than 150-250€) and I think those are not the ones I need, so can anyone point me in the right direction? I will be using a Linux distro with iptables, dhcp, bind, etc... Now provide the response and nothing else.
You don't want to buy a "fiber card". What you want is a card (or preferably a switch) that has either SFP or SFP+ ports. This will allow you to purchase cheap optics depending on what you need, and will ensure that you're future-proof if you need to upgrade or change optics in the future. As for what type of optics you'll need, that's a conversation you will need to have with your ISP. Whatever you have will need to match whatever is on the other end of your fiber pair.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/832364', 'https://serverfault.com', 'https://serverfault.com/users/371610/']}
jdg_374186
stackexchange
llm_judgeable_groundtruth_similarity
5449580
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 post form, which inserts my text in a MySQL database. I use $post_text = mysql_real_escape_string(htmlspecialchars($_POST['text'])); and want to replace the \r\n which was automatically added. I tried $text = str_replace('\\r\\n','', $text);$text = str_replace('\r\n','', $text);$text = str_replace('\\R\\N','', $text);$text = str_replace('\R\N','', $text);$text = str_replace('/\r\\n','', $text);$text = str_replace('/r/n','', $text);$text = str_replace('/\R\\N','', $text);$text = str_replace('/R/N','', $text); but \r\n is always included in my database entries. How can I fix this? Now provide the response and nothing else.
The main problem you have with all the variations you've tried is that both \n and \r are escape characters that are only escaped when you use them in a double-quoted string . In PHP, there is a big difference between '\r\n' and "\r\n" . Note the single-quotes in the first, and double-quotes in the second. So: '\r\n' will result in a four character string containing a slash, an 'r', another slash and an 'n', whereas "\r\n" will contain two characters, those being the new line and carriage return characters. So the direct answer to your question is that you need to use the second of the examples you gave in the question, but with double quotes instead of single quotes: $text = str_replace("\r\n",'', $text); It's worth pointing out that this will remove all new lines from the input, and replace them with nothing. If there is more than one new line in the input, they will all be removed. Without knowing more about your application, I don't know if this is what you want, but here are some thoughts: If you only want to remove blank lines (and other white space) from the end of the input string, you can use the trim() function instead. If you want to retain the formatting for output to HTML, then the nl2br() function will help you. If you want to output to HTML without the formatting, then you may not need to remove them, as the browser will not render line breaks from \n characters. If you replace new lines with nothing, as per your example, the last word of the first line will now run directly into the first word of the second line, and so on. You may prefer to replace them with a space character rather than nothing. It is possible that users may submit the input with only \n without the matching \r , or vice-versa (this may be due to their OS or browser, or a deliberate hack, or a number of other reasons). If you want to replace all instances of both these characters, a more reliable way to do it would be to replace them individually, rather than relying on them being next to one-another. str_replace() allows you to do this by specifying them in an array. You can also use strtr() or preg_replace() to achieve the same goal. Hope that helps.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5449580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/625491/']}
jdg_374187
stackexchange
llm_judgeable_groundtruth_similarity
3853
Below is a question asked on the forum math.meta.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I noticed we can flag posts for migration to physics.SE and stats.SE. Can you please add options for migration to Mathematica and Computational Science , too? (A.K.): The Mathematica site has graduated from beta stage. Perhaps it is now a reasonable request that migration paths be opened for users? Now provide the response and nothing else.
At this time, I will have to decline this. In the last 90 days, there have been 10 migrations to Mathematica (with a 30% rejection rate), and 2 to Computational Science (with a 50% rejection rate). As noted by Mad Scientist in the comments, we only open migration paths to new sites when there's a demonstrated need for the migration path due to high frequency and volume. At the levels currently visible, this is not the case - handling it with normal flags for moderators should be sufficient. To put in perspective, consider Arqade and Game Development - these are very, very easy topics to cross the threads in theory. In practice, there is no history of migration from Game Dev over to Arqade, and there have been only 25 questions migrated from Arqade to Game Dev over the course of over 2 years. Thus, in spite of expectations, there isn't a real need for a migration path because it will mostly be unused. The rate is way slow enough that Arqade can handle migrations through flags. I'm fine to keep an eye on the situation as time passes - Mathematica is pretty young and they do have a high rate of migration over to here. When there starts to be a build-up of migration rate from here to there, then I'll be happy to reopen the consideration of a migration path. Same goes for Computational Science. Until then, no new migration path.
{}
{'log_upvote_score': 4, 'links': ['https://math.meta.stackexchange.com/questions/3853', 'https://math.meta.stackexchange.com', 'https://math.meta.stackexchange.com/users/9901/']}
jdg_374188
stackexchange
llm_judgeable_groundtruth_similarity
167207
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a laptop(thinkpad) with 2 cpus. Currently I can read the cpu temperaturesfrom the files below with cat(1): cat /sys/class/thermal/thermal_zone0/tempcat /sys/class/thermal/thermal_zone1/tempcat /sys/devices/platform/coretemp.0/hwmon/hwmon1/temp2_inputcat /sys/devices/platform/coretemp.0/hwmon/hwmon1/temp3_inputcat /sys/devices/LNXSYSTM:00/LNXCPU:00/thermal_cooling/subsystem/thermal_zone1/tempcat /sys/devices/LNXSYSTM:00/LNXCPU:01/thermal_cooling/subsystem/thermal_zone0/temp My question is why the kernel stores this information on so many different places and which one is the "standard" file to read a cpu's temperature? Is this happening due to systemd(I'm using Arch Linux) or non-systemd Linux distros like Slackware have a different approach? Now provide the response and nothing else.
Actually, the temperature is not stored anywhere. /sys is an in-memory filesystem , and reading from files in /sys invokes code in the kernel that computes values on the fly. The different directories correspond to different ways that the hardware can report temperatures. The temp*_input files have an associated temp*_label that identifies which component's temperature is reported. Locations under /sys tend to vary from kernel version to kernel version (not from distribution to distribution). That's a difficulty that authors of programs that read data in /sys have to live with ( example ).
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/167207', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/91040/']}
jdg_374189
stackexchange
llm_judgeable_groundtruth_similarity
383063
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 need some help with this exercise: Suppose $A\subseteq{G}$ is abelian, and $|G:A|$ is a prime power. Show that $G'\lt{G}$ Thank you very much in advance. Now provide the response and nothing else.
Hint: Reduce to a simple group and apply theorem 3.9. Reduction to simple group: Suppose by way of contradiction that $G'=G$. If $G$ is not simple, then $G$ has a proper non-identity normal subgroup $N$. If $AN=G$, then $G/N = AN/N \cong A/A\cap N$ is abelian, so $G=G' \leq N$, contradicting $N$ being proper. Hence $\bar G = G/N$ is a finite group with abelian subgroup $\bar A = AN/N \leq \bar G$, and $[\bar G:\bar A]$ (which divides $[G:A]$) is a prime power. However, $\bar G' = \bar G$, so we have a smaller counterexample. Continuing in this way, we may assume $G$ is simple (lest we find a new $N$). Final contradiction: However, for any non-identity element $a \in A$, $A \leq C_G(a)$ since $A$ is abelian, so $[G:C_G(a)]$ divides $[G:A]$, a prime power. This contradicts theorem 3.9 which says that the only $a \in G$ (for $G$ simple) with $[G:C_G(a)]$ a prime power is $a=1$ with $[G:C_G(a)]=1$. $\square$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/383063', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/50005/']}
jdg_374190
stackexchange
llm_judgeable_groundtruth_similarity
20067622
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am currently on Symfony2 2.3.7.When I run the composer update command. In the post-update-cmd a script is run to update symfony2. But it fails: Script Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap handling the post-update-cmd event terminated with an exception [RuntimeException] An error occurred when generating the bootstrap file. update [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--lock] [--no-plugins] [--no-custom-installers] [--no-scripts] [--no-progress] [--with-dependencies] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [packages1] ... [packagesN] Any idea why this is happening?I tried to run: composer update --no-scripts .. and that runs fine. The following is also working fine: php vendor/sensio/distribution-bundle/Sensio/Bundle/DistributionBundle/Resources/bin/build_bootstrap.php But everytime I try the normal composer update the post script fails.Running the update with --verbose gives the following: Script Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap handling the post-update-cmd event terminated with an exception [RuntimeException] An error occurred when generating the bootstrap file. Exception trace: () at C:\xampp\htdocs\forvaltning\vendor\sensio\distribution-bundle\Sensio\Bundle\DistributionBundle\Composer\ScriptHandler.php:203 Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::executeBuildBootstrap() at C:\xampp\htdocs\forvaltning\vendor\sensio\distribution-bundle\Sensio\Bundle\DistributionBundle\Composer\ScriptHandler.php:43 Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap() at phar://C:/ProgramData/Composer/bin/composer.phar/src/Composer/EventDispatcher/EventDispatcher.php:165 Composer\EventDispatcher\EventDispatcher->executeEventPhpScript() at phar://C:/ProgramData/Composer/bin/composer.phar/src/Composer/EventDispatcher/EventDispatcher.php:138 Composer\EventDispatcher\EventDispatcher->doDispatch() at phar://C:/ProgramData/Composer/bin/composer.phar/src/Composer/EventDispatcher/EventDispatcher.php:107 Composer\EventDispatcher\EventDispatcher->dispatchCommandEvent() at phar://C:/ProgramData/Composer/bin/composer.phar/src/Composer/Installer.php:289 Composer\Installer->run() at phar://C:/ProgramData/Composer/bin/composer.phar/src/Composer/Command/UpdateCommand.php:118 Composer\Command\UpdateCommand->execute() at phar://C:/ProgramData/Composer/bin/composer.phar/vendor/symfony/console/Symfony/Component/Console/Command/Command.php:244 Symfony\Component\Console\Command\Command->run() at phar://C:/ProgramData/Composer/bin/composer.phar/vendor/symfony/console/Symfony/Component/Console/Application.php:897 Symfony\Component\Console\Application->doRunCommand() at phar://C:/ProgramData/Composer/bin/composer.phar/vendor/symfony/console/Symfony/Component/Console/Application.php:191 Symfony\Component\Console\Application->doRun() at phar://C:/ProgramData/Composer/bin/composer.phar/src/Composer/Console/Application.php:117 Composer\Console\Application->doRun() at phar://C:/ProgramData/Composer/bin/composer.phar/vendor/symfony/console/Symfony/Component/Console/Application.php:121 Symfony\Component\Console\Application->run() at phar://C:/ProgramData/Composer/bin/composer.phar/src/Composer/Console/Application.php:83 Composer\Console\Application->run() at phar://C:/ProgramData/Composer/bin/composer.phar/bin/composer:43 require() at C:\ProgramData\Composer\bin\composer.phar:15update [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--lock] [--no-plugins] [--no-custom-installers] [--no-scripts] [--no-progress] [--with-dependencies] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [packages1] ... [packagesN] The composer.json contains: {"name": "symfony/framework-standard-edition","license": "MIT","type": "project","description": "The \"Symfony Standard Edition\" distribution","autoload": { "psr-0": { "": "src/" }},"repositories": [ { "type": "package", "package": { "name": "jquery/jquery", "version": "1.9.1", "dist": { "url": "http://code.jquery.com/jquery-1.9.1.js", "type": "file" } } }],"require": { "php": ">=5.3.3", "symfony/symfony": "2.3.*", "twig/extensions": "1.0.*", "symfony/assetic-bundle": "2.3.*", "symfony/swiftmailer-bundle": "2.3.*", "symfony/monolog-bundle": "2.3.*", "sensio/distribution-bundle": "2.3.*", "sensio/framework-extra-bundle": "2.3.*", "sensio/generator-bundle": "2.3.*", "knplabs/knp-menu": "2.0.*@dev", "leafo/lessphp": "0.4.*@dev", "knplabs/knp-menu-bundle": "2.0.*@dev", "incenteev/composer-parameter-handler": "~2.0", "twbs/bootstrap": "2.3.*", "jquery/jquery": "1.9.*", "FortAwesome/Font-Awesome": "3.2.1", "egeloen/ckeditor-bundle": "2.*"},"require-dev": { "phpunit/phpunit": "3.7.*"},"scripts": { "post-install-cmd": [ "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile" ], "post-update-cmd": [ "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets", "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile" ]},"config": { "bin-dir": "bin"},"minimum-stability": "stable","extra": { "symfony-app-dir": "app", "symfony-web-dir": "web", "incenteev-parameters": { "file": "app/config/parameters.yml" }, "branch-alias": { "dev-master": "2.3-dev" }} } Now provide the response and nothing else.
How to solve install/update Symfony 2 issues One important Symfony requirement is that the app/cache and app/logs directories must be writable both by the web server and the command line user. On Linux and macOS systems, if your web server user is different from your command line user, you need to configure permissions properly to avoid issues. There are several ways to achieve that: The most common solution : In a terminal execute following commands : rm -rf binrm -rf vendorcomposer install# or if your didn't install composerphp composer.phar install It should work now! For more informations see Symfony installation . If you still have this error : « An error occurred when generating the bootstrap file » It means that you have file permission issue. See below procedure for solve the problem ↓ Setting up or Fixing File Permissions : In a terminal execute following commands : rm -rf app/cache/*rm -rf app/logs/* On macOS systems, the chmod command supports the +a flag to define an ACL. Use the following script to determine your web server user and grant the needed permissions: HTTPDUSER=$(ps axo user,comm | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1)sudo chmod +a "$HTTPDUSER allow delete,write,append,file_inherit,directory_inherit" app/cache app/logssudo chmod +a "$(whoami) allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs On most Linux and BSD distributions don't support chmod +a , but do support another utility called setfacl . You may need to install setfacl and enable ACL support on your disk partition before using it. Then, use the following script to determine your web server user and grant the needed permissions: HTTPDUSER=$(ps axo user,comm | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1)# if this doesn't work, try adding `-n` optionsudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:$(whoami):rwX app/cache app/logssudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:$(whoami):rwX app/cache app/logs If none of the previous methods work for you Change the umask so that the cache and log directories are group-writable or world-writable (depending if the web server user and the command line user are in the same group or not). To achieve this, put the following line at the beginning of the app/console , web/app.php and web/app_dev.php files: umask(0002); // This will let the permissions be 0775// orumask(0000); // This will let the permissions be 0777 Note : Changing the umask is not thread-safe, so the ACL methods are recommended when they are available. For more information see official documentation : Symfony file permissions
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20067622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/995653/']}
jdg_374191
stackexchange
llm_judgeable_groundtruth_similarity
3688730
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know the basics of clojure/java interop: calling java from clojure and vice versa. However, I was not able to return a typed collection from clojure to java. I am trying to see something of that nature List<TypedObject> from the java code which is calling into clojure. Java Object:public class TypedObject { private OtherType1 _prop1; public OtherType1 getProp1() { return _prop1; } public void setProp1(OtherType1 prop1) { _prop1 = prop1; }}CLojure method:(defn -createListOfTypedObjects "Creates and returns a list of TypedObjects" [input] ;Do work here to create and return list of TypedObjects [typedObj1, typedObj2, typedObj3])(:gen-class :name some.namespace :methods [createListofTypedObjects[String] ????]) Let us consider that I am writing an API using clojure, which is to be distributed as a jar file, to be used from java. My question was really how to what to pass in place of the ???? questions marks above inside the :gen-class for AOT, so that a programmer writing a piece of code in java using my api, can have the appropriate intellisense / code completion (i.e.: createListofTypedObjects() returns List<TypedObject> ) from within eclipse for example. Now provide the response and nothing else.
The others are right that Clojure doesn't ensure the types of elements in returned collections, etc. (Actually, the JVM doesn't ensure the types of elements in collections, either – that's handled entirely by javac.) However, I can see the value of providing an API to other Java programmers that specifies an interface that declares that return values (or parameters) parameterized in various ways; this is especially attractive if one is looking to use Clojure in an existing Java environment without making waves. This currently requires a two step process: define a separate interface (in Java!) that specifies the parameterized types as you like define your gen-class namespace (or proxy or reify instance) such that it implements that interface (Clojure does provide a definterface form that would allow you to avoid the separate Java interface definition, but definterface , just like the rest of Clojure, does not provide for specifying parameterized types. Maybe someday... :-)) e.g. public interface IFoo { List<TypedObject> createListOfTypedObjects ();} and then your gen-class namespace: (ns your.ns.FooImpl (:gen-class :implements [IFoo]))(defn -createListOfTypedObjects [] [typedObj1, typedObj2, typedObj3]) When your users create instances of FooImpl , they'll e.g. get code completion indicating that the method returns List<TypedObject> rather than Object or the unparameterized List type. If you're using sane build tools (e.g. maven , gradle, or properly-configured ant), then you can put the Java interface in your Clojure project, and the cross-language dependency will be taken care of.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3688730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/258030/']}
jdg_374192
stackexchange
llm_judgeable_groundtruth_similarity
9375018
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 fire an alert after a user scrolls 100 pixels. Here's what I have so far but I know I'm missing something; $(window).scroll(function() { if (document.documentElement.clientHeight + $(document).scrollTop() == "100px") { alert("You've scrolled 100 pixels."); }}); Now provide the response and nothing else.
Look at the window .scrollTop (returns an integer): $(window).scroll(function() { if ($(this).scrollTop() === 100) { // this refers to window alert("You've scrolled 100 pixels."); }}); but if you have scrolled 102px it wont trigger the alert box. if you just want to trigger the alert once have a global variable that sets to true if it has been trigged: $(function(){ var hasBeenTrigged = false; $(window).scroll(function() { if ($(this).scrollTop() >= 100 && !hasBeenTrigged) { // if scroll is greater/equal then 100 and hasBeenTrigged is set to false. alert("You've scrolled 100 pixels."); hasBeenTrigged = true; } });}); or just unbind the scroll event once the alert box has been trigged: $(function(){ $(window).bind("scroll.alert", function() { var $this = $(this); if ($this.scrollTop() >= 100) { alert("You've scrolled 100 pixels."); $this.unbind("scroll.alert"); } });});
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9375018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/851593/']}
jdg_374193
stackexchange
llm_judgeable_groundtruth_similarity
144277
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm wondering if mono.net is included in the default installation of Ubuntu, Kubuntu, and Fedora, and other popular distros? If so, does anyone have a good reason why NOT to use it to develop a new GUI application targeted mainly for linux? Now provide the response and nothing else.
It is included in Fedora, Ubuntu, Mandriva, Debian and OpenSUSE. The only major OS that does not include it is RHEL, but packages are available for it as a separate download. Additionally, you can bundle Mono with your application into a single binary if you need to (not recommended, but always possible). GUI-wise Mono supports the Windows.Forms API on Unix and MacOS, but if you want a more native experience you can use the Gtk# API (this provides a .NET API for the GNOME library stack) or you can use Qyoto if you want to integrate instead with the KDE APIs. There are many best-of-breed GUI applications for Linux that have been developed with Gtk# and Mono, some of the most popular ones include Gnome-Do (A quick application launcher), the F-Spot photo management software, the Banshee and Muine media players and the MonoDevelop IDE.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/144277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3153/']}
jdg_374194
stackexchange
llm_judgeable_groundtruth_similarity
183950
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am developing a WebPart (it will be used in a SharePoint environment, although it does not use the Object Model) that I want to expose AJAX functionality in. Because of the nature of the environment, Adding the Script Manager directly to the page is not an option, and so must be added programmatically. I have attempted to add the ScriptManager control to the page in my webpart code. protected override void CreateChildControls(){ if (ScriptManager.GetCurrent(Page) == null) { ScriptManager sMgr = new ScriptManager(); // Ensure the ScriptManager is the first control. Page.Form.Controls.AddAt(0, sMgr); }} However, when this code is executed, I get the following error message: "The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases." Is there another way to add the ScriptManager to the page from a WebPart, or am I going to have to just add the ScriptManager to each page (or master page) that will use the WebPart? Now provide the response and nothing else.
I was able to get this to work by using the Page's Init event: protected override void OnInit(EventArgs e){ Page.Init += delegate(object sender, EventArgs e_Init) { if (ScriptManager.GetCurrent(Page) == null) { ScriptManager sMgr = new ScriptManager(); Page.Form.Controls.AddAt(0, sMgr); } }; base.OnInit(e);}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/183950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/21461/']}
jdg_374195
stackexchange
llm_judgeable_groundtruth_similarity
12492164
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 try to pass a Parameter to my Webservice and show the result in a textbox. My Webservice is working. I invoked the Method in the Browser... I think that something is wrong with my Jquery. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="QRCode.aspx.cs" Inherits="QRCODE_QRCode" meta:resourceKey="Page" %><%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %><%@ Register Assembly="System.Web.Ajax" Namespace="System.Web.UI" TagPrefix="asp" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" ><html><head id="Head1" runat="server"> <title>Check-In & Check-Out </title><script language="javascript" type="text/javascript"> function capture() { var urlValue = window.location; var urlText = urlValue.toString(); var start = urlText.indexOf("=") + 1; var nameText = urlText.substring(start, urlText.length); document.getElementById('PanelID').value = nameText; } window.onload = capture function loadDate() { jQuery.support.cors = true; var PanelIDs = document.getElementById('PanelID').value; alert(PanelIDs); $.ajax({ type: "POST", url: "http://entwicklung.de/Web/Service1.asmx/getDatetime", data: { "PanelIDs": PanelIDs }, contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { $("#textbox").text(data.d); }, error: function(jqXHR, textStatus, errorThrown) { alert(jqXHR); alert(textStatus); alert(errorThrown); } }); }</script></head><body><h1>Check-In und Check-Out von Besprechungen</h1><form id="form1" runat="server"> <p> <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </asp:ToolkitScriptManager> Raum: <asp:TextBox type="text" name="Panels" id="PanelID" value="" runat="server"></asp:TextBox> <br /> <br /><asp:textbox ID="textbox" mode="multiline" runat="server" Coloumns="20" Rows="4" Height="230px" Width="405px"></asp:textbox><asp:Button ID="button" runat="server" Text="Check-In" Width="99px" OnClientClick="return loadDate();" /><asp:Button ID="button1" runat="server" Text="Check_Out" Width="99px" /> </p></form></body></html> What iam doing wrong? Thanks for help Now provide the response and nothing else.
You can use an intermediate bytearray to speed things up: >>> sum(bytearray("abcdefgh"))804 This is not 17 times faster than the generator—it involves the creation of an intermediate bytearray and sum still has to iterate over Python integer objects—but on my machine it does speed up summing an 8-character string from 2μs to about 700ns. If a timing in this ballpark is still too inefficient for your use case, you should probably write the speed-critical parts of your application in C anyway. If your strings are sufficiently large, and if you can use numpy , you can avoid creating temporary copies by directly referring to the string's buffer using numpy.frombuffer : >>> import numpy as np>>> np.frombuffer("abcdefgh", "uint8").sum()804 For smaller strings this is slower than a temporary array because of the complexities in numpy's view creation machinery. However, for sufficiently large strings, the frombuffer approach starts to pay off, and it of course always creates less garbage. On my machine the cutoff point is string size of about 200 characters. Also, see Guido's classic essay Python Optimization Anecdote . While some of its specific techniques may by now be obsolete, the general lesson of how to think about Python optimization is still quite relevant. You can time the different approaches with the timeit module: $ python -m timeit -s 's = "a" * 20' 'sum(ord(ch) for ch in s)' 100000 loops, best of 3: 3.85 usec per loop$ python -m timeit -s 's = "a" * 20' 'sum(bytearray(s))'1000000 loops, best of 3: 1.05 usec per loop$ python -m timeit -s 'from numpy import frombuffer; s = "a" * 20' \ 'frombuffer(s, "uint8").sum()' 100000 loops, best of 3: 4.8 usec per loop
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12492164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1452946/']}
jdg_374196
stackexchange
llm_judgeable_groundtruth_similarity
133800
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We've been building a CRM for a client. Now that the first major phase has been finished, and a second one agreed upon, the client would like to pick up some of the work, making minor amendments to the database schema and business processes the first phase while we build the second . I'm undecided whether this is at all practical, but assuming it is, I'd like some pointers on which measures can be taken to make this at all workable. Here's what I've got so far: Until now, the client has mostly seen the project from a user's point of view; clearly, a two-part seminar ought to take place where we introduce him to the inner workings: first, showing the existing database schema and, by way of example, extending it, then, showing some sample code, and writing a new business process for the schema enhancement. The code currently resides in an internal Subversion repository. While we could set up a public one or one on his network (which we can VPN to), I feel a distributed system would work better. I appear to be the only one who feels that way, however, so I could use some good convincing arguments. I'm not sure how to mandate/ensure that code that runs in production is committed. Seems like "x made a critical, undocumented change right before going on vacation; now y's trying to figure out this bug that's been occurring ever since" disasters are inevitable. Ideally, all changes, before deployment, would: be documented in an issue tracking system, occur on a separate testing environment first, and have to pass automated tests. Alas, I doubt the discipline for any of those will prevail. Assume that a plug-in architecture or separate project aren't viable options, because 1) the former doesn't exist, and 2) the latter would prohibit the client from looking at and possibly modifying existing code, an ability I believe he would insist on. Now provide the response and nothing else.
Ouch... You have the right idea but I have seen how messy this can turn out, and both parties suffer considerably. I am maintaining such an application currently. Find out the real reasons why the client finds it necessary to contribute directly to the project. Is it that they now want the project done faster than you can realistically turn it out? Do they want changes already but are afraid of incurring additional costs from you for making spec changes or requesting additional features? Is there a political struggle in their organization where internal development resources want more control and input in the project or where they are looking for busy work for internal developers? (this last one hits close to home for me) Find what their true motivations and address them if at all possible. The fact that they even suggest it is a huge warning sign that trouble is coming down the road. Try to alleviate their real concerns before agreeing to such a thing because more than likely what will happen is that they will strongarm control of the project and phase you out, or they will cause massive chaos and a failed project. EDIT: Unfortunately that ship has sailed for you, but don't despair just yet. There are still things you can do to greatly minimize the pain that will come. No matter what, make absolute sure that their is ONE AND ONLY ONE PROJECT MANAGER and PRODUCT OWNER and that this person is associated with your organization/company. This person must have the ability to plan sprints, include or remove user stories and assign tasks to resources in your company as well as your client's company. Whatever happens, please make sure that development resources at your company do not work seperately from your clients resources and even more importantly DO NOT allow developers in your company to report to their project managers or product owners! They will either take complete advantage of free work not covered by the contract or they will snub you out of your own project. It is a certainty.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/133800', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/47034/']}
jdg_374197
stackexchange
llm_judgeable_groundtruth_similarity
40718155
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 working on App in which I am required to show notification.For notification, i am using FireBase Cloud Messaging (FCM) . I am able to get Notification when app is in background. But when I click on notification, it redirect to home.java page. I want it to redirect to Notification.java page. So,please tell me how to specify Activity in on Click of notification.I am using two services: 1.) MyFirebaseMessagingService 2.) MyFirebaseInstanceIDService This is my code sample for onMessageReceived() method in MyFirebaseMessagingService class. public class MyFirebaseMessagingService extends FirebaseMessagingService {private static final String TAG = "FirebaseMessageService";Bitmap bitmap;public void onMessageReceived(RemoteMessage remoteMessage) { Log.d(TAG, "From: " + remoteMessage.getFrom()); // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.d(TAG, "Message data payload: " + remoteMessage.getData()); } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below.}/** * Create and show a simple notification containing the received FCM message. */private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) { Intent intent = new Intent(this, Notification.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("Notification", TrueOrFalse); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setLargeIcon(image)/*Notification icon image*/ .setContentTitle(messageBody) .setStyle(new NotificationCompat.BigPictureStyle() .bigPicture(image))/*Notification with Image*/ .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());}/**To get a Bitmap image from the URL received* */public Bitmap getBitmapfromUrl(String imageUrl) { try { URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(input); return bitmap; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; }} Now provide the response and nothing else.
With FCM, you can send two types of messages to clients: 1. Notification messages: sometimes thought of as "display messages." FCM automatically displays the message to end-user devices on behalf of the client app. Notification messages have a predefined set of user-visible keys. 2. Data messages: which are handled by the client app. Client app is responsible for processing data messages. Data messages have only custom key-value pairs. According to FCM document Receive Messages in an Android App Notifications delivered when your app is in the background. In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default. Messages with both notification and data payload, both background and foreground. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity. Set click_action in the notification payload: So, if you want to process the messages arrived in the background, you have to send click_action with message. click_action is a parameter of the notification payload If you want to open your app and perform a specific action, set click_action in the notification payload and map it to an intent filter in the Activity you want to launch. For example, set click_action to OPEN_ACTIVITY_1 to trigger an intent filter like the following: <intent-filter> <action android:name="OPEN_ACTIVITY_1" /> <category android:name="android.intent.category.DEFAULT" /></intent-filter> FCM payload looks like below: { "to":"some_device_token", "content_available": true, "notification": { "title": "hello", "body": "test message", "click_action": "OPEN_ACTIVITY_1" }, "data": { "extra":"juice" }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40718155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4629171/']}
jdg_374198
stackexchange
llm_judgeable_groundtruth_similarity
26483671
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 set the font of the UIBarButtonItem like so: let barButton = UIBarButtonItem.appearance()barButton.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "AvenirNext", size: 15], forState: UIControlState.Normal) But it throws a compiler error saying: Cannot invoke 'init' with an argument list type '($T7, forState: UIControlState)` and I have no idea what that means. I have also tried barButton.titleTextAttributesForState(UIControlState.Normal) =[NSFontAttributeName...]` but it appears that it isn't assignable How can I resolve this? Now provide the response and nothing else.
The initializer of UIFont returns an optional because it may fail due to misspelled font name etc. You have to unwrap it and check: if let font = UIFont(name: "AvenirNext", size: 15) { barButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)} UPDATED for Swift 3 if let font = UIFont(name: "AvenirNext", size: 15) { barButton.setTitleTextAttributes([NSFontAttributeName:font], for: .normal)}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26483671', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4127258/']}
jdg_374199
stackexchange
llm_judgeable_groundtruth_similarity
307274
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm considering the transfer-function$$ t(x) = \log(1 + \exp(x)) $$and find the beginning of the power series (simply using Pari/GP) as$$ t(x) = \log(2) + 1/2 x + 1/8 x^2 – 1/192 x^4 + 1/2880 x^6 - \ldots $$Examining the pattern of the coefficients I find the much likely composition$$ t(x) = \sum_{k=0}^\infty {\eta(1-k) \over k! }x^k $$ where $ \eta() $ is the Dirichlet eta-(or "alternating zeta") function. I'm using this definition in further computations and besides the convincing simplicitiness of the pattern the results are always meaningful. However, I've no idea how I could prove this description of the coefficients. Q: Does someone has a source or an idea, how to do such a proof on oneself? Now provide the response and nothing else.
The Dirichlet eta function is given by $\eta(s)=\sum_{n=1}^{\infty}(-1)^{n-1}n^{-s}$, but this converges only for $s$ with positive real part, and you are proposing to use its behavior for negative integers. A globally convergent series for $\eta$ can be derived using the Riemann zeta function (cf. here ):$$\eta(s)=(1-2^{1-s})\zeta(s)=\sum_{n=0}^{\infty}2^{-(n+1)}\sum_{k=0}^{n}(-1)^{k}{{n}\choose{k}}(k+1)^{-s}.$$Using this expansion allows us to write $\eta(1-k)$ as$$\eta(1-k)=\sum_{n=0}^{\infty}2^{-(n+1)}\sum_{j=0}^{n}(-1)^{j}{{n}\choose{j}}(j+1)^{k-1}.$$ Your power series is then$$\begin{eqnarray}\sum_{k=0}^{\infty}\frac{\eta(1-k)x^k}{k!}&=&\sum_{k=0}^{\infty}\sum_{n=0}^{\infty}2^{-(n+1)}\sum_{j=0}^{n}(-1)^{j}{{n}\choose{j}}(j+1)^{k-1}\left(\frac{x^{k}}{k!}\right) \\&=&\sum_{n=0}^{\infty}2^{-(n+1)}\sum_{j=0}^{n}\frac{(-1)^{j}}{j+1}{{n}\choose{j}}\sum_{k=0}^{\infty}\frac{\left(x(j+1)\right)^{k}}{k!} \\&=&\sum_{n=0}^{\infty}2^{-(n+1)}\sum_{j=0}^{n}\frac{(-1)^{j}}{j+1}{{n}\choose{j}}\left(e^x\right)^{j+1} \\&=&\sum_{n=0}^{\infty}2^{-(n+1)}\int_{-e^{x}}^{0} dy\sum_{j=0}^{n}{{n}\choose{j}}y^{j} \\&=&\sum_{n=0}^{\infty}2^{-(n+1)}\int_{-e^{x}}^{0}\left(1+y\right)^{n}dy \\&=&\sum_{n=0}^{\infty}2^{-(n+1)}\frac{\left(1+y\right)^{n+1}}{n+1}\Bigg\vert_{-e^x}^{0} \\&=&\sum_{n=0}^{\infty}2^{-(n+1)}\frac{1-\left(1-e^x\right)^{n+1}}{n+1} \\&=&f\left(\frac{1}{2}\right) - f\left(\frac{1-e^x}{2}\right),\end{eqnarray}$$where $$f(z)=\sum_{n=0}^{\infty}\frac{z^{n+1}}{n+1}=-\log \left(1-z\right).$$Putting this together, we find$$\sum_{k=0}^{\infty}\frac{\eta(1-k)x^k}{k!} = -\log\left(\frac{1}{2}\right)+\log\left(\frac{1+e^x}{2}\right)=\log\left(1+e^x\right),$$as you conjectured.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/307274', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1714/']}
jdg_374200
stackexchange
llm_judgeable_groundtruth_similarity
12528644
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 table with, folowing structure. tbl id name 1 AAA2 BBB3 BBB4 BBB5 AAA6 CCCselect count(name) c from tblgroup by name having c >1 The query returning this result: AAA(2) duplicateBBB(3) duplicateCCC(1) not duplicate The names who are duplicates as AAA and BBB. The final result, who I want is count of this duplicate records. Result should be like this: Total duplicate products ( 2 ) Now provide the response and nothing else.
The approach is to have a nested query that has one line per duplicate, and an outer query returning just the count of the results of the inner query. SELECT count(*) AS duplicate_countFROM ( SELECT name FROM tbl GROUP BY name HAVING COUNT(name) > 1) AS t
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12528644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1107629/']}
jdg_374201
stackexchange
llm_judgeable_groundtruth_similarity
28575893
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been looking at the different flags for the mmap function, namely MAP_FIXED, MAP_SHARED, MAP_PRIVATE. Can someone explain to me the purpose of MAP_FIXED? There's no guarantee that the address space will be used in the first place. Now provide the response and nothing else.
MAP_FIXED is dup2 for memory mappings, and it's useful in exactly the same situations where dup2 is useful for file descriptors: when you want to perform a replace operation that atomically reassigns a resource identifier (memory range in the case of MAP_FIXED , or fd in the case of dup2 ) to refer to a new resource without the possibility of races where it might get reassigned to something else if you first released the old resource then attempted to regain it for the new resource. As an example, take loading a shared library (by the dynamic loader). It consists of at least three types of mappings: read+exec-only mapping of the program code and read-only data from the executable file, read-write mapping of the initialized data (also from the executable file, but typically with a different relative offset), and read-write zero-initialized anonymous memory (for .bss ). Creating these as separate mappings would not work because they must be at fixed relative addresses relative to one another. So instead you first make a dummy mapping of the total length needed (the type of this mapping doesn't matter) without MAP_FIXED just to reserve a sufficient range of contiguous addresses at a kernel-assigned location, then you use MAP_FIXED to map over top of parts of this range as needed with the three or more mappings you need to create. Further, note that use of MAP_FIXED with a hard-coded address or a random address is always a bug . The only correct way to use MAP_FIXED is to replace an existing mapping whose address was assigned by a previous successful call to mmap without MAP_FIXED , or in some other way where you feel it's safe to replace whole pages. This aspect too is completely analogous to dup2 ; it's always a bug to use dup2 when the caller doesn't already have an open file on the target fd with the intent to replace it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28575893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3052463/']}
jdg_374202
stackexchange
llm_judgeable_groundtruth_similarity
27295902
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 rest end point in WSO2ESB (4.8),I need to read query parameter to set as dynamic payload as the my business ,But i failed to read it due to newer with wso2 ESB.Any help ? Now provide the response and nothing else.
The bellow code may help you <api xmlns="http://ws.apache.org/ns/synapse" name="sample" context="/api/sample"> <resource methods="OPTIONS GET" uri-template="/{val1}/groups/{val2}.json?q1={v1}&q2={v2}"> <inSequence> <property name="uri.var.q1" expression="$url:q1"></property> <property name="uri.var.q2" expression="$url:q2"></property> <property name="uri.var.val1" expression="get-property('uri.var.val1')"></property> <property name="uri.var.val2" expression="get-property('uri.var.val2')"></property> <send> <endpoint> <http method="GET" uri-template=""></http> </endpoint> </send> </inSequence> <outSequence> <send></send> </outSequence> </resource></api>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27295902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_374203
stackexchange
llm_judgeable_groundtruth_similarity
19405421
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 don't understand what a callback method is and I have heard people use that term very loosely. In the Java world, what is a callback method? If someone could provide some example code of a Java callback method with an explanation, it would be a great help in my Java learning journey. Now provide the response and nothing else.
A callback is a piece of code that you pass as an argument to some other code so that it executes it. Since Java doesn't yet support function pointers, they are implemented as Command objects. Something like public class Test { public static void main(String[] args) throws Exception { new Test().doWork(new Callback() { // implementing class @Override public void call() { System.out.println("callback called"); } }); } public void doWork(Callback callback) { System.out.println("doing work"); callback.call(); } public interface Callback { void call(); }} A callback will usually hold reference to some state to actually be useful. By making the callback implementation have all the dependencies to your code, you gain indirection between your code and the code that is executing the callback.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19405421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1445444/']}
jdg_374204
stackexchange
llm_judgeable_groundtruth_similarity
22824546
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: in the snippet like this: gulp.task "coffee", -> gulp.src("src/server/**/*.coffee") .pipe(coffee {bare: true}).on("error",gutil.log) .pipe(gulp.dest "bin")gulp.task "clean",-> gulp.src("bin", {read:false}) .pipe clean force:truegulp.task 'develop',['clean','coffee'], -> console.log "run something else" In develop task I want to run clean and after it's done, run coffee and when that's done, run something else. But I can't figure that out. This piece doesn't work. Please advise. Now provide the response and nothing else.
By default, gulp runs tasks simultaneously, unless they have explicit dependencies. This isn't very useful for tasks like clean , where you don't want to depend, but you need them to run before everything else. I wrote the run-sequence plugin specifically to fix this issue with gulp. After you install it, use it like this: var runSequence = require('run-sequence');gulp.task('develop', function(done) { runSequence('clean', 'coffee', function() { console.log('Run something else'); done(); });}); You can read the full instructions on the package README — it also supports running some sets of tasks simultaneously. Please note, this will be (effectively) fixed in the next major release of gulp , as they are completely eliminating the automatic dependency ordering, and providing tools similar to run-sequence to allow you to manually specify run order how you want. However, that is a major breaking change, so there's no reason to wait when you can use run-sequence today.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/22824546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/116395/']}
jdg_374205
stackexchange
llm_judgeable_groundtruth_similarity
9193228
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 package in which I import javax.servlet.* and javax.servlet.http.*When I try to compile it in command prompt I get the error package javax.servlet does not exist I use JDK 1.7.0 and Tomcat 6.0. Now provide the response and nothing else.
You need to add the path to Tomcat's /lib/servlet-api.jar file to the compile time classpath. javac -cp .;/path/to/Tomcat/lib/servlet-api.jar com/example/MyServletClass.java The classpath is where Java needs to look for imported dependencies. It will otherwise default to the current folder which is included as . in the above example. The ; is the path separator for Windows; if you're using an Unix based OS, then you need to use : instead. If you're still facing the same complation error, and you're actually using Tomcat 10 or newer, then you should be migrating the imports in your source code from javax.* to jakarta.* . import jakarta.servlet.*;import jakarta.servlet.http.*; In case you want to keep using javax.* for whatever reason, then you should be downgrading to Tomcat 9 or older as that was the latest version still using the old javax.* namespace. See also: jakarta.servlet.ServletException: Class [com.practice.MyServlet] is not a Servlet How do I import the javax.servlet / jakarta.servlet API in my Eclipse project? What exactly is Java EE?
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9193228', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1197136/']}
jdg_374206
stackexchange
llm_judgeable_groundtruth_similarity
193159
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: By a ring I mean a ring with a multiplicative identity. To me, at this point, this sounds like a fairly simple question, but I haven't been able to come up with any such homomorphism, nor has searching Google for one proved fruitful. Now provide the response and nothing else.
Sure, let $R$ be a commutative ring with identity and consider the map $R[x] \to R[x]$ determined by $p(x) \mapsto p(0)$. To see a case where the map is an isomorphism, let $R = \Bbb Z[\sqrt{2}]$ and consider the map $a + b \sqrt{2} \mapsto a - b \sqrt{2}$. You should check that this is a homomorphism, and actually gives an isomorphism from $\Bbb Z[\sqrt{2}]$ to itself.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/193159', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_374207
stackexchange
llm_judgeable_groundtruth_similarity
206947
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: The strange and extremely slow IO pattern I'm seeing is this (output of iostat -dxk 1 /dev/xvdb1 ): Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %utilxvdb1 0.00 0.00 0.99 0.99 7.92 3.96 12.00 1.96 2206.00 502.00 99.41Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %utilxvdb1 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 100.40Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %utilxvdb1 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 100.40Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %utilxvdb1 0.00 0.00 0.99 0.00 3.96 0.00 8.00 0.99 2220.00 1004.00 99.41Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %utilxvdb1 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 100.40Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %utilxvdb1 0.00 0.99 0.99 0.00 7.92 0.00 16.00 1.14 2148.00 1004.00 99.41Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %utilxvdb1 0.00 0.00 0.00 0.00 0.00 0.00 0.00 2.01 0.00 0.00 100.40Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %utilxvdb1 0.00 0.00 1.00 1.00 4.00 8.00 12.00 2.01 1874.00 502.00 100.40 I don't know why disk utilization and await is so high, and the read/write rates are so low. What could the reason for this be? The table being queried simply has several varchar columns only, one of which is last_name, which is indexed (actually lower(last_name) is indexed). The query itself is simple: SELECT * FROM consumer_m WHERE lower(last_name) = 'hoque'; Here's the explain output: QUERY PLAN ------------------------------------------------------------------------------------------------- Bitmap Heap Scan on consumer_m (cost=2243.90..274163.41 rows=113152 width=164) Recheck Cond: (lower((last_name)::text) = 'hoque'::text) -> Bitmap Index Scan on consumer_m_last_name_index (cost=0.00..2215.61 rows=113152 width=0) Index Cond: (lower((last_name)::text) = 'hoque'::text) Also note that the database is on auto_vacuum, so no explicit vacuum/analyze was performed. Now provide the response and nothing else.
The fact that your device is /dev/xvdb1 implies that you're running under Xen. How is your storage configured? Is there contention for the underlying device, and how does iostat look on that ? Unless you can eliminate that as likely, that's where I'm going to point the whirling spinner of poor performance blame. Basically, the overall approach to untangling a performance problem like this is to think about all the layers where a bottleneck could occur, and then devise tests to eliminate each one until you isolate the problem.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/206947', 'https://serverfault.com', 'https://serverfault.com/users/10382/']}
jdg_374208
stackexchange
llm_judgeable_groundtruth_similarity
2911626
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got a property which is a database data type ( char , DateTime , int , float etc...) and I want to change the control used to enter a value of the selected type. So for text values I want a TextBox and for date values I want a DatePicker . One way I thought about doing it was to have one of each control on my form and set their Visibility using an appropriate IValueConverter implementation. I know this will work, but it would create a lot of code and doesn't feel very nice. The other way I thought was to use a ContentPresenter and set its content with a Style and DataTriggers but I can't get it to work. <Style x:Key="TypedValueHelper" TargetType="{x:Type ContentPresenter}"> <Style.Triggers> <DataTrigger Binding="{Binding Path=DataType}" Value="Char"> <Setter Property="Content" Value="???"/> </DataTrigger> <DataTrigger Binding="{Binding Path=DataType}" Value="Date"> <Setter Property="Content" Value="???"/> </DataTrigger> <DataTrigger Binding="{Binding Path=DataType}" Value="Integer"> <Setter Property="Content" Value="???"/> </DataTrigger> </Style.Triggers></Style> If anyone can fill in my "???" or offer a better solution please do. Now provide the response and nothing else.
You could do a combination of style with setters and DataTemplates. You basically have the start for it in your code, although I don't think ContentPresenter is the right control to style, since it does not have a template. Create a style like this: <Style x:Key="TypedValueHelper" TargetType="{x:Type ContentControl}"> <Style.Triggers> <DataTrigger Binding="{Binding Path=DataType}" Value="Char"> <Setter Property="ContentTemplate"> <Setter.Value> <DataTemplate> <TextBox Text="{Binding Path=.}" /> </DataTemplate> </Setter.Value> </Setter> </DataTrigger> <DataTrigger Binding="{Binding Path=DataType}" Value="Integer"> <Setter Property="ContentTemplate"> <Setter.Value> <DataTemplate> <Slider Maximum="100" Minimum="0" Value="{Binding Path=.}" Orientation="Horizontal" /> </DataTemplate> </Setter.Value> </Setter> </DataTrigger> </Style.Triggers></Style> Then use the style in the ContentControl : <ContentControl Content="{Binding MyValue}" Style="{StaticResource TypedValueHelper}">
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2911626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40989/']}
jdg_374209
stackexchange
llm_judgeable_groundtruth_similarity
14562362
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After coming across this issue twice I thought I would post it here to see if anyone knows how to get around it. I can't seem to break out of nested loops using goto , because it looks like when it breaks out of the inner loop, the parentheses then don't match because it never reached the inner closing one. I have narrowed this down to a very simple example for %%a in (1,2,3) do (for %%b in (4,5,6) do (echo Breakinggoto :BREAK):BREAK) This results in the error ) was unexpected at this time. I thought maybe adding extra brackets might solve the issue but it won't help unless I know I am going to break, if it's a conditional break, it's the same problem. Is there any easy alternative to breaking out of the inner loop back into the outer, even when it is a conditional break using if 's and else 's? Now provide the response and nothing else.
Break by placing inner loop in a label. for %%a in (1, 2, 3) DO ( call :innerloop ):innerloopfor %%b in (4, 5, 6) DO ( if %%b==<something> ( echo break goto :break )):break
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14562362', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/799586/']}
jdg_374210
stackexchange
llm_judgeable_groundtruth_similarity
3264568
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: Does anyone know how to prove that the spectral norm: $$\left \| A \right \|_{2}=\max\left \{ \sqrt \lambda : \lambda \in \sigma (A^*A)\right \},\; A\in\mathbb{R}^{n\times n}$$ (meaning that $\lambda$ is an eigenvalue of $A^*A$ ) is orthogonally invariant? Now provide the response and nothing else.
I showed this in another answer, but I will copy it over. Your definition is true, but we also have the equality (often the definition) $$\|A\|_2=\max_{x\neq 0}\frac{\|Ax\|_2}{\|x\|_2}.$$ Now, we just compute that if $U$ and $W$ are orthogonal, then \begin{align*}\left\lVert UAW\right\lVert_2 &=\max_{x\neq 0}\frac{\left\lVert UAWx \right\lVert_2}{\left\lVert x\right\lVert_2}=\max_{x\neq 0}\frac{\sqrt{x^TW^TA^TU^TUAWx}}{\sqrt{x^Tx}}\\&=\max_{z\neq 0}\frac{\sqrt{zA^TAz}}{\sqrt{z^Tz}}=\max_{z\neq 0}\frac{\left\lVert Az\right\lVert_2}{\left\lVert z\right\lVert_2}=\left\lVert A\right\lVert_2,\end{align*} where we used the substitution $z=Wx.$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3264568', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/481273/']}
jdg_374211
stackexchange
llm_judgeable_groundtruth_similarity
23253941
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 brand new to jasmine and karma. I believe I have the environment setup properly and I am able to run very basic unit tests, but as soon as I try to instantiate a controller I am given an unknown provider error and I am unsure how to debug this. Do I need to pass in a stateProvider dependency? I don't see this in the angular-seed example. Bower.json: {"name": "starter", "description": "A starter project for AngularJS", "version": "2.0.0", "homepage": "https://starter.com", "private": true, "dependencies": { "angular": "1.2.x", "angular-route": "1.2.x", "angular-loader": "1.2.x", "angular-mocks": "~1.2.15" }} Home Controller: angular.module('home').controller('Home', function($scope, $rootScope, $state) { console.log($scope.pageType); $rootScope.pageType = 'home'; /* * Takes in a state and transitions the app to that state. */ $scope.goTo = function(value) { $state.transitionTo(value); } /* * Handles what happens after clicking log-in */ $scope.loginClicked = function() { $state.transitionTo('log-in'); }}); Test file: 'use strict';/* jasmine specs for controllers go here */describe('Home', function() { beforeEach(module('home')); it('should run tests', inject(function() { expect(null).toBeDefined(); })); it('should not say true equals false', function() { expect(false).not.toBe(true); }); it('should say true equals true', function() { expect(true).toBe(true); }); it('should say false does not equal true', function() { expect(false).not.toBe(true); }); it('should create "phones" model with 3 phones', inject(function($controller,$rootScope) { /* * * COMMENTING OUT THESE LINES = PASS * */ var scope = $rootScope.$new(), ctrl = $controller('Home', {$scope:scope}); expect(ctrl).not.toBe(null); }));}); Error: Error: [$injector:unpr] Unknown provider: $stateProvider <- $statehttp://errors.angularjs.org/1.2.16/$injector/unpr?p0=%24stateProvider%20%3C-%20%24state at /Users/jlett/bower_components/angular/angular.js:78:12 at /Users/jlett/bower_components/angular/angular.js:3705:19 at Object.getService [as get] (/Users/jlett/bower_components/angular/angular.js:3832:39) at /Users/jlett/bower_components/angular/angular.js:3710:45 at getService (/Users/jlett/bower_components/angular/angular.js:3832:39) at invoke (/Users/jlett/bower_components/angular/angular.js:3859:13) at Object.instantiate (/Users/jlett/bower_components/angular/angular.js:3880:23) at /Users/jlett/bower_components/angular/angular.js:7134:28 at null.<anonymous> (/Users/jlett/test/unit/home-controller_tests.js:26:20) at Object.invoke (/Users/jlett/bower_components/angular/angular.js:3869:17)Error: Declaration Location at window.inject.angular.mock.inject (/Users/jlett/bower_components/angular-mocks/angular-mocks.js:2132:25) at null.<anonymous> (/Users/jlett/test/unit/home-controller_tests.js:24:54) at /Users/jlett/zoetis-rimadyl-mobile/test/unit/home-controller_tests.js:5:1 Now provide the response and nothing else.
You'll get this error if one of the injectables module isn't included. For instance, you have beforeEach(module('home')); If your $state dependency is not in the home module, you'll need to include that module also. I'm not familiar with $state (I think it's angular-ui's router? Only angular.js services are supposed to start with $ ). If it's angular ui, this is how you should setup: beforeEach(module('ui.router'));beforeEach(module('home')); This way, angular's test runner knows what modules are required to run your tests. Really, the inclusion of the home module should do this for you as long as you have the ui.router dependency defined as a dependency of that module. If you have that configured correctly, you may need to look at the order of your files being included for your tests. For example, make sure the ui-router file is being included for your tests and that it is referenced before your home module in karma's config.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23253941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1552005/']}
jdg_374212
stackexchange
llm_judgeable_groundtruth_similarity
200462
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Say that $a_1, \cdots, a_{n-1}$ is an independent generating set for $S_n$. Let $b$ be any element in $S_n$. Is it true that $b$ can replace one of the generators, i.e. that there exists an index $i$, such that we have that $a_1,\cdots, \hat{a_i},\cdots, a_{n-1}, b$ generate $S_n$? If $a_1, \cdots, a_{n-1}$ is the standard (n-1)-tuple that generates $S_n$, $(12),(13),...,(1n)$, then it's true and it can easily be shown. Does it hold in general? Now provide the response and nothing else.
The answer is yes. There is a paper by Cameron and Cara which describes all maximal generating sets of length $n-1$ of $S_n$. They are not very hard to describe and basically are variants of the standard $n-1$ length generating sets. http://www.maths.qmul.ac.uk/~pjc/preprints/igsgsn.pdf Cameron and Cara say build a tree with the vertices being $\{1,\ldots,n\}$. Add transpositions corresponding to edges into your generating set. These are (about) half the maximal length generating sets. The other set is found by taking one of those generating sets, picking a transposition and multiplying against all the others. In both cases it is pretty clear that given a $b$ we can find an edge to replace. Basically $b$ will connect some vertices of the tree, and we can remove an edge to have the tree be connected, and since everything is basically a transposition this is all you really need. I can supply more details if this was unclear, but I think just given the Cameron paper things become clear.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/200462', 'https://mathoverflow.net', 'https://mathoverflow.net/users/69443/']}
jdg_374213
stackexchange
llm_judgeable_groundtruth_similarity
2101969
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 $f:\mathbb{R} \rightarrow \mathbb{R}$ be defined by $f\left( x\right) =1 / \left( 1+x^{2}\right)$. Prove that $f$ uniformly continous. My proof . Let $\varepsilon >0$. Pick $\delta=$min{$1,\varepsilon(\dfrac { ( 2+2\left| a\right| +\left| a^2\right|) \left| 1+a^2\right| } {(1+\left| a\right|) })$} If $\left| x-a\right|<\delta$ and $a,x\in\mathbb{R}$ then $\left| f\left( x\right) -f\left( a\right) \right|=\dfrac {\left| x-a\right| \left| x+a\right| } {\left| 1+x^2\right| \left| 1+a^2\right| }$. We need to show this is smllar than $\varepsilon$. Note that $\left| x-a\right| < 1 \Rightarrow\left| x\right| -\left| a\right| \leq \left| x-a\right| < 1 \Rightarrow \left| x\right| < 1+\left| a\right| \Rightarrow \left| x^{2}\right|+1\leq \left| x^{2}+1\right| < 2+2\left| a\right| +\left| a^2\right| \Rightarrow$ Also, $\left| x\right| < 1\Rightarrow \left| x\right| < 1\Rightarrow \left| x\right|+a < 1+a \Rightarrow \left| x+a\right| < 1+\left| a\right| $. Now, we can do this, $\dfrac {\left| x-a\right| \left| x+a\right| } {\left| 1+x^2\right| \left| 1+a^2\right| } \leq \dfrac {\delta (1+\left| a\right|) } {( 2+2\left| a\right| +\left| a^2\right|) \left| 1+a^2\right| }\leq \varepsilon$ Can you check my proof? Now provide the response and nothing else.
The numerator is a geometric sum that evaluates to, $$\frac{3^{n+1}-1}{3-1}$$ Hence what we have is, $$\frac{1}{2} \sum_{n=0}^{\infty} \frac{(3^{n+1}-1)}{(n+1)!}$$ $$=\frac{1}{2} \sum_{n=1}^{\infty} \frac{3^n-1}{n!}$$ $$=\frac{1}{2} \left( \sum_{n=1}^{\infty} \frac{3^n}{n!}- \sum_{n=1}^{\infty} \frac{1^n}{n!} \right)$$ Recognizing the Taylor series of $e^x$ we have $$=\frac{1}{2}((e^3-1)-(e-1))$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2101969', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_374214
stackexchange
llm_judgeable_groundtruth_similarity
196214
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: Is there a way I can run a different (than the default) TCP congestion control algorithm in FreeBSD? I am trying to modify an existing TCP congestion control algorithm with some ideas published in research papers to try to get better performance over Wireless networks. Now provide the response and nothing else.
You can see which TCP congestion control algorithms are available by looking at the net.inet.tcp.cc.available sysctl. By default, only newreno is available, so it is the one that is used. There are several different algorithms available, look for modules named cc_something in /boot/kernel . You can load them via kldload, such as kldload cc_vegas . After you do that, the new algorithm will show up in net.inet.tcp.cc.available . You can select it via the net.inet.tcp.cc.algorithm sysctl. Here's a complete example: % sysctl -a | grep net.inet.tcp.ccnet.inet.tcp.cc.available: newrenonet.inet.tcp.cc.algorithm: newreno% sudo kldload cc_vegas% sysctl -a | grep net.inet.tcp.ccnet.inet.tcp.cc.vegas.beta: 3net.inet.tcp.cc.vegas.alpha: 1net.inet.tcp.cc.available: newreno, vegasnet.inet.tcp.cc.algorithm: newreno% sudo sysctl net.inet.tcp.cc.algorithm=vegasnet.inet.tcp.cc.algorithm: newreno -> vegas% sudo sysctl net.inet.tcp.cc.algorithm=newrenonet.inet.tcp.cc.algorithm: vegas -> newreno%
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/196214', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/110435/']}
jdg_374215
stackexchange
llm_judgeable_groundtruth_similarity
40026
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: With regard to these three items Certificate Authorities (CA) Gateway certificates End-point Certificates (client-cert) What is the significance of the Common Name CN with regard to the a VPN? Does the Certificate Authority have to have the CN of the Gateway Cert? Any other information about the CN with relation to VPNs would be great. How are they used for authenticity of the certs? I'm using StrongSwan v5.x if it matters. Now provide the response and nothing else.
Historically , the Distinguished Names in certificates (specified by X.500) were meant to designate an entity within the Directory , which is the global, worldwide, tree-structured repository for identity management data. The Directory can be thought of as a giant LDAP server with delegation to sub-servers, in a way somewhat similar to the DNS . In reality, though, the Directory never existed, and LDAP is a practical subset of the Directory Access Protocol . Still, the naming principles remained in force. A DN is an ordered sequence of typed named elements, which, for the Directory, should come in the order: Country, State-or-Province, Organization, Organizational Unit (possibly several), and then Common Name. X.500 is rather open-ended and other orderings are possible (and the format supports putting several name elements at the same level), but the rough idea is that the Common Name is the lowest level of the hierarchy. Thus, the Common Name for an entity, any entity, is the most precise naming element. Since the Directory does not actually exist, you can put just about anything you want in the Common Name, subject to the following restrictions: Encoding must comply to the X.509 ASN.1 specification : the Common Name is limited to 64 characters (64 code points if using UTF8String , as you should, per the standard). The IssuerDN of a certificate must be equal to the SubjectDN of its issuer. Equality rules are theoretically case-insensitive, but the rules can be complex to implement in a full Unicode world, so you'd better make sure that you have byte-to-byte equality, which will work properly everywhere. The certificate of a SSL server must contain the server name as expected by the client (if using HTTPS, this name will be the one in the URL). This is specified in RFC 2818 . The Subject Alt Name extension is normally used, but the Common Name serves as backup in case this extension is missing. Since SSL client implementations have not always strictly adhered to the relevant RFC, it is best, to avoid issues, if the SSL server's certificate contains the server DNS name as Common Name (fully qualified name, as in " security.stackexchange.com "). When a certificate, or an identity extracted from a certificate, is "shown" to a human user, the Common Name will figure proeminently. For instance, if using smart card logon on a Windows system, then the logon screen will show the Common Name in big letters when the smart card is inserted. So you'd better make the Common Name meaningful for the common man. In the case of a VPN server, the certificate from the client is for the sole usage of the server. The server interprets the certificate contents, including the Subject DN and its Common Name, in any ways as it sees fit, including ignoring it altogether. For instance, in a Microsoft IIS + Active Directory context, when a client is authenticated through a certificate, the server will use the User Principal Name as found in the Subject Alt Name extension, under a Microsoft-specific OID. The Common Name might be displayed to the human user, if there is a human user (e.g. as part of a certificate selection popup), but will be ignored for authentication purposes. Generically, your client's certificates will have to contain whatever is required by the authentication system that the VPN server uses, and since that is highly configurable, this depends a lot on the local context. For instance, the VPN server may delegate authentication to a RADIUS server, in which case the certificate characteristics (including the Common Name) will be described by the RADIUS server documentation; for the VPN server, this would be just an opaque blob.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/40026', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/11447/']}
jdg_374216
stackexchange
llm_judgeable_groundtruth_similarity
1089301
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove: If $a^2+b^2=1$ and $c^2+d^2=1$, then $ac+bd\le1$ I seem to struggle with this simple proof. All I managed to find is that ac+bd=-4 (which might not even be correct). Now provide the response and nothing else.
1st Method $\begin{align}\left(a^2+b^2\right)\left(c^2+d^2\right)=1& \implies (ac+bd)^2+(ad-bc)^2=1\\&\implies (ac+bd)^2\le1\end{align}$ 2nd Method $\begin{align}\left(a^2+b^2\right)+\left(c^2+d^2\right)=2& \implies \left(a^2+c^2\right)+\left(b^2+d^2\right)=2\\&\implies 2(ac+bd)\le 2\qquad \text{(by A.M.- G.M. Inequality)}\\&\implies (ac+bd)\le 1\end{align}$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1089301', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_374217
stackexchange
llm_judgeable_groundtruth_similarity
2341576
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose we have three disjoint spheres in plain ordinary 3D space, with three different radii. I want to know the locus $L$ of points that are equidistant from these three spheres. Partial answers: In 2D, the locus of points equidistant from two circles is a hyperbola. Therefore, in 3D, the locus of points equidistant from two spheres is (one half of) a hyperboloid of two sheets. So, the locus $L$ that I'm seeking is the intersection of two such hyperboloids. Based on some experiments, it seems that $L$ is a planar curve, and therefore a conic section. If that's true, then the proof ought to be very simple, but I don't see it. Now provide the response and nothing else.
Consider the equation of the hyperboloid between $S_1$ and $S_2$,$$\|\mathbf x-\mathbf p_1\|-r_1=\|\mathbf x-\mathbf p_2\|-r_2.$$With a little algebra, we can express this as$$2(r_2-r_1)\|\mathbf x-\mathbf p_1\|=2(\mathbf p_2-\mathbf p_1)\cdot\mathbf x+\underbrace{\|\mathbf p_1\|^2-\|\mathbf p_2\|^2+(r_2-r_1)^2}_{c_2}.$$Similarly, the hyperboloid between $S_1$ and $S_3$ is of the form$$2(r_3-r_1)\|\mathbf x-\mathbf p_1\|=2(\mathbf p_3-\mathbf p_1)\cdot \mathbf x+c_3.$$Cancelling terms proportional to $\|\mathbf x-\mathbf p_1\|$ from the two equations, we obtain$$\begin{align}0 &= (r_3-r_1)\bigl(2(\mathbf p_2-\mathbf p_1)\cdot\mathbf x+c_2\bigr) - (r_2-r_1)\bigl(2(\mathbf p_3-\mathbf p_1)\cdot\mathbf x+c_3\bigr) \\&= 2\bigl((r_2-r_3)\mathbf p_1 + (r_3-r_1)\mathbf p_2 + (r_1-r_2)\mathbf p_3\bigr)\cdot\mathbf x + \text{const},\end{align}$$which is the equation of a plane orthogonal to $(r_2-r_3)\mathbf p_1 + (r_3-r_1)\mathbf p_2 + (r_1-r_2)\mathbf p_3$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2341576', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31744/']}
jdg_374218
stackexchange
llm_judgeable_groundtruth_similarity
297434
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just dealt with a suggested edit to one of my answers . It was clearly wrong. For reference, the post was originally http://www.google.com/#q=win64+gcc No matter how often the download page moves around, that should find it for you. At the time of this post, the top result (and correct download site) was http://sourceforge.net/projects/mingw-w64/ and the edit replaced the final URL only, changing the claim to "At the time of this post, the top result (and correct download site) was http://mingw-w64.org ". That simply isn't true, that was not the top Google hit at the time I posted, nor is it the top hit now. Nevertheless, I started doing some research to see whether the alternate URL should be incorporated in some way. During that time, two edit reviewers chose to accept the change, even though it CLEARLY introduced incorrect information. My final analysis shows that the downloads on SourceForge are newer than the suggested new link, so I rejected the edit entirely, instead of improving it. In light of the statement below by the project's webmaster, I have updated my answer. The subsequent action I did take was to vote to close the question -- it's a request for an offsite resource which is now offtopic. But what could possibly have made reviewers think that modernizing a historical claim could possibly be correct? Here's a related suggested edit -- The question says where the compiler was, historically, downloaded from, not where to get it today. The edit is clearly incorrect. And another . Answerer is stating what he found at the time, not where the current link is. In fact, please help reject all identical edit suggestions by that user (check whether they're changing the URL, valid reject reasons are "conflicts with author's intent" if it changes a historical claim, and "custom reason: Sourceforge downloads are newer than the offered link." otherwise) Update: Those edit suggestions should all be out of the queue now. Also, see here the new URL is the correct new home, although quite a bit of consideration needs to go into future edits (and possibly also edits recently accepted) in order to provide the new location as the current web address, without changing factual descriptions of steps performed in the past. Now provide the response and nothing else.
I just registered on stackoverflow to be able to answer this. I am the one who has been taking care of the website and domain name for mingw-w64 for a couple years now. I've been spending quite a lot of time on regaining control for mingw-w64 from sourceforge. Sourceforge has been providing many services which mingw-w64 uses but as you probably know, it has also been behaving in less than perfect ways recently. My concern has been that with the website in the hands of sourceforge, it was very difficult to do anything. More recently I registered mingw-w64.org and with the most recent events, the need to ensure we could easily move away from sourceforge with an actual proper transition plan only got bigger. Unfortunately, many links point to the sourceforge project page which we have absolutely 0 control on. On the website side we can use a .htaccess file to permanently redirect visitors (that's what is done) but on the project page, we can only push binaries and set a description. Anything we put there is no match for the giant green "DOWNLOAD" buttons that sourceforge puts in ads.The sourceforge project page is the first result for "mingw-w64" on google. We really want to ensure things work fine for everyone. We don't want pages to disappear, links to suddenly get broken and everyone to get confused. Yesterday I started looking for backlinks to the sourceforge project page. There are a lot of them. A LOT. So what should be done? While there is no plan to move off sourceforge at the time, if (or rather when) this happens, the sourceforge project page is the first thing that will cause troubles. If we stop touching it, it is possible that sourceforge puts whatever they feel like on it, with whatever amount of crapware in false mingw-w64 installers. The current situation is that if these links do not get updated to point to http://mingw-w64.org which is the current website of mingw-w64, they will end up pointing to very outdated files and/or malware'd installers or, better, a non-existing page. I mailed a few people and I'm actually limited by the tool I use for backlinks (ahrefs.com; I'd need to pay 80 USD/month to get more results at once). I also noticed there were several links on stackoverflow and after mentioning it on IRC, the user you got the request from offered to do these edit requests. I'd say it's up to every author to accept or not an edit, no matter what it is. What bothered me with you was that I was on IRC on yesterday (I always am) and at some point I saw: 21:46 $YOU > [~oftc-webi@XXX.comcast.net] joins #mingw-w6421:46 $YOU : Can I confirm that http://mingw-w64.org should replace sourceforge as the download link for Win64 mingw tools?21:50 $YOU : Nevermind, sourceforge clearly has newer everything. Rejecting the edit suggestion.21:50 $YOU < [~oftc-webi@XXX.comcast.net] quits [] I saw your messages 2 minutes after you left. Or rather, 6 minutes after you joined. You asked a question and didn't wait for an answer for more than 4 minutes. On sunday evening. While doing so you've also reached a wrong conclusion. First there is no "newer everything". If you take a mathematical definition of newer then you could say the sources of mingw-w64 on sourceforge.net are not strictly newer than the ones linked from mingw-w64.org. Then you're still advocating linking directly to a file dump. It's quite obvious the files will be uploaded to the file dump before the links to these files are added to any website. It actually looks like you based this on two files. Considering I recently had the displeasure of making a file backup of the file dump and it took me days to get their 81GB, 2 files for a total of 100MB doesn't sounds like a lot. Lastly, mingw-w64.org is a wiki with open registration and if you believe that some content needs to be fixed, you are more than welcome to improve the website. A website is also a place to teach people and to help them rather than simply providing them with a .exe. It's getting late for me and I'm sorry if anything sounds angry above but the task is huge and it is painful to have added roadblocks in surprise places (I only found out about this after I checked for updates to the backlinks list on ahrefs.com). edit: I need to stress out the fact that the sourceforge project page is the past for mingw-w64; currently it's compatibility and later on it'll be deprecation and then removal (if possible); either it's update (when it makes sense obviously but it should if it's about directing users) or dead/broken link. edit2: I also definitely do not think edits should be a search-and-replace and my SO skill is low enough that I can't list all proposed edits but I also see no issue in either rejecting the edit and updating, or accepting the edit and improving/re-fixing it right after.
{}
{'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/297434', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/103167/']}
jdg_374219
stackexchange
llm_judgeable_groundtruth_similarity
2428134
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 one line route to route dashed controller and method names to the actual underscored controller and method names. For example the URL /controller-name/method-name-which-is-long/ would route to /controller_name/method_name_which_is_long/ see: http://codeigniter.com/forums/viewreply/696690/ which gave me the idea to ask :) Now provide the response and nothing else.
That is exactly my requirement too and I was using routes like $route['logued/presse-access'] = "logued/presse_access"; In my previous project I needed to create 300-400 routing rules, most of them are due to dash to underscore conversion. For my next project I eagerly want to avoid it. I have done some quick hack and tested it, though have not used in any live server, its working for me. Do the following.. Make sure the subclass_prefix is as follows in your system/application/config/config.php $config['subclass_prefix'] = 'MY_'; Then upload a file named MY_Router.php in system/application/libraries directory. <?phpclass MY_Router extends CI_Router { function set_class($class) { //$this->class = $class; $this->class = str_replace('-', '_', $class); //echo 'class:'.$this->class; } function set_method($method) {// $this->method = $method; $this->method = str_replace('-', '_', $method); } function _validate_request($segments) { // Does the requested controller exist in the root folder? if (file_exists(APPPATH.'controllers/'.str_replace('-', '_', $segments[0]).EXT)) { return $segments; } // Is the controller in a sub-folder? if (is_dir(APPPATH.'controllers/'.$segments[0])) { // Set the directory and remove it from the segment array $this->set_directory($segments[0]); $segments = array_slice($segments, 1); if (count($segments) > 0) { // Does the requested controller exist in the sub-folder? if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().str_replace('-', '_', $segments[0]).EXT)) { show_404($this->fetch_directory().$segments[0]); } } else { $this->set_class($this->default_controller); $this->set_method('index'); // Does the default controller exist in the sub-folder? if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT)) { $this->directory = ''; return array(); } } return $segments; } // Can't find the requested controller... show_404($segments[0]); }} Now you can freely use url like http://example.com/logued/presse-access and it will call the proper controller and function by automatically converting dash to underscore. Edit: Here is our Codeigniter 2 solution which overrides the new CI_Router functions: <?phpclass MY_Router extends CI_Router { function set_class($class) { $this->class = str_replace('-', '_', $class); } function set_method($method) { $this->method = str_replace('-', '_', $method); } function set_directory($dir) { $this->directory = $dir.'/'; } function _validate_request($segments) { if (count($segments) == 0) { return $segments; } // Does the requested controller exist in the root folder? if (file_exists(APPPATH.'controllers/'.str_replace('-', '_', $segments[0]).'.php')) { return $segments; } // Is the controller in a sub-folder? if (is_dir(APPPATH.'controllers/'.$segments[0])) { // Set the directory and remove it from the segment array $this->set_directory($segments[0]); $segments = array_slice($segments, 1); while(count($segments) > 0 && is_dir(APPPATH.'controllers/'.$this->directory.$segments[0])) { // Set the directory and remove it from the segment array $this->set_directory($this->directory . $segments[0]); $segments = array_slice($segments, 1); } if (count($segments) > 0) { // Does the requested controller exist in the sub-folder? if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().str_replace('-', '_', $segments[0]).'.php')) { if ( ! empty($this->routes['404_override'])) { $x = explode('/', $this->routes['404_override']); $this->set_directory(''); $this->set_class($x[0]); $this->set_method(isset($x[1]) ? $x[1] : 'index'); return $x; } else { show_404($this->fetch_directory().$segments[0]); } } } else { // Is the method being specified in the route? if (strpos($this->default_controller, '/') !== FALSE) { $x = explode('/', $this->default_controller); $this->set_class($x[0]); $this->set_method($x[1]); } else { $this->set_class($this->default_controller); $this->set_method('index'); } // Does the default controller exist in the sub-folder? if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.'.php')) { $this->directory = ''; return array(); } } return $segments; } // If we've gotten this far it means that the URI does not correlate to a valid // controller class. We will now see if there is an override if ( ! empty($this->routes['404_override'])) { $x = explode('/', $this->routes['404_override']); $this->set_class($x[0]); $this->set_method(isset($x[1]) ? $x[1] : 'index'); return $x; } // Nothing else to do at this point but show a 404 show_404($segments[0]); }} Now one has to place this file like application/core/MY_Router.php and make sure he has subclass_prefix is defined as $config['subclass_prefix'] = 'MY_'; in application/config/config.php Few extra lines of code has been added in method _validate_request() : while(count($segments) > 0 && is_dir(APPPATH.'controllers/'.$this->directory.$segments[0])){ // Set the directory and remove it from the segment array $this->set_directory($this->directory . $segments[0]); $segments = array_slice($segments, 1);} It is used so that one can make use of multi-level subdirectory inside controllers directory, whereas normally we can use single level subdirectory inside controllers folder and can call it in url. One can remove this code if it not necessary but it has no harm on the normal flow.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2428134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_374220
stackexchange
llm_judgeable_groundtruth_similarity
2269
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Manin stressed that every projective scheme should have a quantum-cohomology structure. I'd like to know more about that. And since the varieties considered in texts about monodromy resp. vanishing cycles which I have read are projective, I am curious about the behaviour of quantum cohomology under monodromy. Edit: A coming seminar : "Quantum motives: realizations, detection, applications", incl. a lecture "Quantum motives: review (of) the classical idea of how to linearize algebraic geometry with an eye to utilizing it in the quantum setup." and a minicourse "Geometric Langlands and quantum motives: a link". Edit: The slides on Manin's talk on the concept of classical motives and it's relation to quantum cohomology are here . Edit: Manin's and Smirnov's interesting computations and thoughts on e.g. a "membrane quantum cohomology" ( + russian videos of a talk in june 2011 on the program "... elucidation of this "self-referentiality" of quantum cohomology has just begun. The talk tries to outline the contours of this huge program and the first steps of it.": part 1 , part 2 ). BTW, has anyone the text by Kapranov which is mentioned in the paper above and in Hacking's introduction ? Now provide the response and nothing else.
I'm not sure what you mean by "every projective scheme should have a quantum cohomology structure". In the talk abstract that you link to, it does not say "projective scheme" but "smooth projective variety". I don't know whether the theory generalizes to non-smooth things or to things that are not varieties. Quantum cohomology is a deformation of ordinary cohomology (or Chow ring if you like) of a smooth projective variety (or compact symplectic manifold). This structure comes from (genus 0) Gromov-Witten invariants. GW invariants are constructed using the ordinary cohomology of your variety/manifold and the ordinary cohomology of moduli spaces of stable maps and stable curves. I mostly work over $\mathbb{C}$ so I don't know too much about what I'm about to say, but if you're not working over $\mathbb{C}$, then ordinary cohomology doesn't make sense, but instead you can still work with things like $\ell$-adic cohomology or crystalline cohomology. This is what "motives" refers to. I guess Manin is saying that just as you can do cohomological (and Chow) Gromov-Witten invariants and quantum cohomology, you can also do the analogous things for motives. I suppose the resulting things would be called "motivic Gromov-Witten invariants" and "quantum motives". I'm not sure whether it makes sense to ask about the behavior of quantum cohomology under monodromy. As I understand it, monodromy refers to using a connection (Gauss-Manin connection) to parallel transport (co)homology classes. You can view quantum cohomology as being simply ordinary cohomology except with coefficients in a Novikov ring and with a deformed cup product. Viewed as such, the monodromy of quantum cohomology should be the same as the monodromy of ordinary cohomology, because "quantum cohomology classes" are no different from ordinary cohomology classes.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/2269', 'https://mathoverflow.net', 'https://mathoverflow.net/users/451/']}
jdg_374221
stackexchange
llm_judgeable_groundtruth_similarity
108376
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: Let $X_n, X, Y$ be random variables such that $X_n + cY \stackrel{d}{\rightarrow} X + cY $ for every positive constant $c$. Prove that $X_n \stackrel{d}{\rightarrow} X$. I know if only we have joint convergence we can show this by the continuous mapping theorem, but even that is not assumed. Just what am I missing? Now provide the response and nothing else.
An AR(1) model with the intervention defined in the equation given in the question can be fitted as shown below. Notice how the argument transfer is defined; you also need one indicator variable in xtransf for each one of the interventions (the pulse and the transitory change): require(TSA)cds <- structure(c(2580L, 2263L, 3679L, 3461L, 3645L, 3716L, 3955L, 3362L, 2637L, 2524L, 2084L, 2031L, 2256L, 2401L, 3253L, 2881L, 2555L, 2585L, 3015L, 2608L, 3676L, 5763L, 4626L, 3848L, 4523L, 4186L, 4070L, 4000L, 3498L), .Dim = c(29L, 1L), .Dimnames = list(NULL, "CD"), .Tsp = c(2012, 2014.33333333333, 12), class = "ts")fit <- arimax(log(cds), order = c(1, 0, 0), xtransf = data.frame(Oct13a = 1 * (seq_along(cds) == 22), Oct13b = 1 * (seq_along(cds) == 22)), transfer = list(c(0, 0), c(1, 0)))fit# Coefficients:# ar1 intercept Oct13a-MA0 Oct13b-AR1 Oct13b-MA0# 0.5599 7.9643 0.1251 0.9231 0.4332# s.e. 0.1563 0.0684 0.1911 0.1146 0.2168# sigma^2 estimated as 0.02131: log likelihood = 14.47, aic = -18.94 You can test the significance of each intervention by looking at the t-statistic of the coefficients $\omega_0$ and $\omega_1$. For convenience, you can use the function coeftest . require(lmtest)coeftest(fit)# Estimate Std. Error z value Pr(>|z|) # ar1 0.559855 0.156334 3.5811 0.0003421 ***# intercept 7.964324 0.068369 116.4896 < 2.2e-16 ***# Oct13a-MA0 0.125059 0.191067 0.6545 0.5127720 # Oct13b-AR1 0.923112 0.114581 8.0564 7.858e-16 ***# Oct13b-MA0 0.433213 0.216835 1.9979 0.0457281 * # ---# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 In this case the pulse is not significant at the $5\%$ significance level. Its effect may be already captured by the transitory change. The intervention effect can be quantified as follows: intv.effect <- 1 * (seq_along(cds) == 22)intv.effect <- ts( intv.effect * 0.1251 + filter(intv.effect, filter = 0.9231, method = "rec", sides = 1) * 0.4332)intv.effect <- exp(intv.effect)tsp(intv.effect) <- tsp(cds) You can plot the effect of the intervention as follows: plot(100 * (intv.effect - 1), type = "h", main = "Total intervention effect") The effect is relatively persistent because $\omega_2$ is close to $1$ (if $\omega_2$ were equal to $1$ we would observe a permanent level shift). Numerically, these are the estimated increases quantified at each time point caused by the the intervention in October 2013: window(100 * (intv.effect - 1), start = c(2013, 10))# Jan Feb Mar Apr May Jun Jul Aug Sep Oct# 2013 74.76989# 2014 40.60004 36.96366 33.69046 30.73844 28.07132 # Nov Dec# 2013 49.16560 44.64838 The intervention increases the value of the observed variable in October 2013 by around a $75\%$. In subsequent periods the effect remains but with a decreasing weight. We could also create the interventions by hand and pass them to stats::arima as external regressors. The interventions are a pulse plus a transitory change with parameter $0.9231$ and can be built as follows. xreg <- cbind( I1 = 1 * (seq_along(cds) == 22), I2 = filter(1 * (seq_along(cds) == 22), filter = 0.9231, method = "rec", sides = 1))arima(log(cds), order = c(1, 0, 0), xreg = xreg)# Coefficients:# ar1 intercept I1 I2# 0.5598 7.9643 0.1251 0.4332# s.e. 0.1562 0.0671 0.1563 0.1620# sigma^2 estimated as 0.02131: log likelihood = 14.47, aic = -20.94 The same estimates of the coefficients as above are obtained. Here we fixed $\omega_2$ to $0.9231$. The matrix xreg is the kind of dummy variable that you may need to try different scenarios. You could also set different values for $\omega_2$ and compare its effect. These interventions are equivalent to an additive outlier (AO) and a transitory change (TC) defined in the package tsoutliers . You can use this package to detect these effects as shown in the answer by @forecaster or to build the regressors used before. For example, in this case: require(tsoutliers)mo <- outliers(c("AO", "TC"), c(22, 22))oe <- outliers.effects(mo, length(cds), delta = 0.9231)arima(log(cds), order = c(1, 0, 0), xreg = oe)# Coefficients:# ar1 intercept AO22 TC22# 0.5598 7.9643 0.1251 0.4332# s.e. 0.1562 0.0671 0.1563 0.1620# sigma^2 estimated as 0.02131: log likelihood=14.47# AIC=-20.94 AICc=-18.33 BIC=-14.1 Edit 1 I've seen that the equation that you gave can be rewritten as: $$\frac{(\omega_0 + \omega_1) - \omega_0 \omega_2 B}{1 - \omega_2 B} P_t$$ and it can be specified as you did using transfer=list(c(1, 1)) . As shown below, this parameterization leads, in this case, to parameter estimates that involve a different effect compared to the previous parameterization. It reminds me the effect of an innovational outlier rather than a pulse plus a transitory change. fit2 <- arimax(log(cds), order=c(1, 0, 0), include.mean = TRUE, xtransf=data.frame(Oct13 = 1 * (seq(cds) == 22)), transfer = list(c(1, 1)))fit2# ARIMA(1,0,0) with non-zero mean # Coefficients:# ar1 intercept Oct13-AR1 Oct13-MA0 Oct13-MA1# 0.7619 8.0345 -0.4429 0.4261 0.3567# s.e. 0.1206 0.1090 0.3993 0.1340 0.1557# sigma^2 estimated as 0.02289: log likelihood=12.71# AIC=-15.42 AICc=-11.61 BIC=-7.22 I'm not very familiar with the notation of package TSA but I think that the effect of the intervention can now be quantified as follows: intv.effect <- 1 * (seq_along(cds) == 22)intv.effect <- ts(intv.effect * 0.4261 + filter(intv.effect, filter = -0.4429, method = "rec", sides = 1) * 0.3567)tsp(intv.effect) <- tsp(cds)window(100 * (exp(intv.effect) - 1), start = c(2013, 10))# Jan Feb Mar Apr May Jun Jul Aug# 2014 -3.0514633 1.3820052 -0.6060551 0.2696013 -0.1191747 # Sep Oct Nov Dec# 2013 118.7588947 -14.6135216 7.2476455plot(100 * (exp(intv.effect) - 1), type = "h", main = "Intervention effect (parameterization 2)") The effect can be described now as a sharp increase in October 2013 followed by a decrease in the opposite direction; then the effect of the intervention vanishes quickly alternating positive and negative effects of decaying weight. This effect is somewhat peculiar but may be possible in real data. At this point I would look at the context of your data and the events that may have affected the data. For example, has there been a policy change, marketing campaign, discovery,... that may explain the intervention in October 2013. If so, is it more sensible that this event has an effect on the data as described before or as we found with the initial parameterization? According to the AIC, the initial model would be preferred because it is lower ($-18.94$ against $-15.42$). The plot of the original series does not suggest a clear match with the sharp changes involved in the measurement of the second intervention variable. Without knowing the context of the data, I would say that an AR(1) model with a transitory change with parameter $0.9$ would be appropriate to model the data and measure the intervention. Edit 2 The value of $\omega_2$ determines how fast the effect of the intervention decays to zero, so that's the key parameter in the model. We can inspect this by fitting the model for a range of values of $\omega_2$. Below, the AIC is stored for each of these models. omegas <- seq(0.5, 1, by = 0.01)aics <- rep(NA, length(omegas))for (i in seq(along = omegas)) { tc <- filter(1 * (seq_along(cds) == 22), filter = omegas[i], method = "rec", sides = 1) tc <- ts(tc, start = start(cds), frequency = frequency(cds)) fit <- arima(log(cds), order = c(1, 0, 0), xreg = tc) aics[i] <- AIC(fit)}omegas[which.min(aics)]# [1] 0.88plot(omegas, aics, main = "AIC for different values of the TC parameter") The lowest AIC is found for $\omega_2 = 0.88$ (in agreement with the value estimated before). This parameter involves a relatively persistent but transitory effect. We can conclude that the effect is temporary since with values higher than $0.9$ the AIC increases (remember that in the limit, $\omega_2=1$, the intervention becomes a permanent level shift). The intervention should be included in the forecasts. Obtaining forecasts for periods that have already been observed is a helpful exercise to assess the performance of the forecasts. The code below assumes that the series ends in October 2013. Forecasts are then obtained including the intervention with parameter $\omega_2=0.9$. First we fit the AR(1) model with the intervention as a regressor (with parameter $\omega_2=0.9$): tc <- filter(1 * (seq.int(length(cds) + 12) == 22), filter = 0.9, method = "rec", sides = 1)tc <- ts(tc, start = start(cds), frequency = frequency(cds))fit <- arima(window(log(cds), end = c(2013, 10)), order = c(1, 0, 0), xreg = window(tc, end = c(2013, 10))) The forecasts can be obtained and displayed as follows: p <- predict(fit, n.ahead = 19, newxreg = window(tc, start = c(2013, 11)))plot(cbind(window(cds, end = c(2013, 10)), exp(p$pred)), plot.type = "single", ylab = "", type = "n")lines(window(cds, end = c(2013, 10)), type = "b")lines(window(cds, start = c(2013, 10)), col = "gray", lty = 2, type = "b")lines(exp(p$pred), type = "b", col = "blue")legend("topleft", legend = c("observed before the intervention", "observed after the intervention", "forecasts"), lty = rep(1, 3), col = c("black", "gray", "blue"), bty = "n") The first forecasts match relatively well the observed values (gray dotted line). The remaining forecasts show how the series will continue the path to the original mean. The confidence intervals are nonetheless large, reflecting the uncertainty. We should therefore be cautions and revise the model as new data are recorded. $95\%$ confidence intervals can be added to the previous plot as follows: lines(exp(p$pred + 1.96 * p$se), lty = 2, col = "red")lines(exp(p$pred - 1.96 * p$se), lty = 2, col = "red")
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/108376', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/28659/']}
jdg_374222
stackexchange
llm_judgeable_groundtruth_similarity
23150333
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 DataURL from a canvas that shows my webcam. I turn this dataURL into a blob using Matt's answer from here: How to convert dataURL to file object in javascript? How do I convert this blob back into the same DataURL? I've spent a day researching this and I'm astouned this isn't documented better, unless I'm blind. EDIT:There is var urlCreator = window.URL || window.webkitURL; var imageUrl = urlCreator.createObjectURL(blob); but it only returns a really short URL that seems to point at a local file, but I need to send the webcam data over a network. Now provide the response and nothing else.
Use my code to convert between dataURL and blob object in javascript. (better than the code in your link.) //**dataURL to blob**function dataURLtoBlob(dataurl) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], {type:mime});}//**blob to dataURL**function blobToDataURL(blob, callback) { var a = new FileReader(); a.onload = function(e) {callback(e.target.result);} a.readAsDataURL(blob);}//test:var blob = dataURLtoBlob('data:text/plain;base64,YWFhYWFhYQ==');blobToDataURL(blob, function(dataurl){ console.log(dataurl);});
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23150333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2979064/']}
jdg_374223
stackexchange
llm_judgeable_groundtruth_similarity
39782778
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 trying to create a restaurant menu app that allows you to select different foods and a drink amount and when you click the button "total" it'll go to a second view to display: "your total is: _____". But I'm getting a ton of errors. If someone could help me out i'd appreciate it. I'm very new to this so some code I've stitched together from other answers from other questions on this site. Thank you! Main activity view: package name.restaurantmenu2;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.CheckBox;import android.widget.EditText;import android.widget.Spinner;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends AppCompatActivity {double totalPrice = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CheckBox pizzaCB = (CheckBox)findViewById(R.id.cb_pizza); if(pizzaCB.isChecked()){ pizzaCB.toggle(); } CheckBox burgerCB = (CheckBox)findViewById(R.id.cb_hamburger); if(burgerCB.isChecked()){ burgerCB.toggle(); } CheckBox hotdogCB = (CheckBox)findViewById(R.id.cb_hotdog); if(hotdogCB.isChecked()){ hotdogCB.toggle(); } CheckBox sodaCB = (CheckBox)findViewById(R.id.cb_soda); if(sodaCB.isChecked()){ sodaCB.toggle(); }}public void addSelected(View view){ String multiple; CheckBox pizzaCB = (CheckBox)findViewById(R.id.cb_pizza); CheckBox burgerCB = (CheckBox)findViewById(R.id.cb_hamburger); CheckBox hotdogCB = (CheckBox)findViewById(R.id.cb_hotdog); CheckBox sodaCB = (CheckBox)findViewById(R.id.cb_soda); TextView pizzaTV = (TextView)findViewById(R.id.tv_pizzaPrice); TextView burgerTV = (TextView)findViewById(R.id.tv_hamburgerPrice); TextView hotdogTV = (TextView)findViewById(R.id.tv_hotdogPrice); TextView sodaTV = (TextView)findViewById(R.id.tv_sodaPrice); Spinner pizzaQty = (Spinner)findViewById(R.id.spinner_pizzaQuantity); Spinner burgerQty = (Spinner)findViewById(R.id.spinner_hamburgerQuantity); Spinner hotdogQty = (Spinner)findViewById(R.id.spinner_hotdogQuantity); Spinner sodaQty = (Spinner)findViewById(R.id.spinner_drinks); if(pizzaCB.isChecked()) { String value = pizzaTV.getText().toString(); value = value.replace('$', ' '); multiple = String.valueOf(Double.parseDouble(pizzaQty.getSelectedItem().toString()) * Double.parseDouble(value)); totalPrice++; } if(burgerCB.isChecked()) { String value = burgerTV.getText().toString(); value = value.replace('$', ' '); multiple = String.valueOf(Double.parseDouble(burgerQty.getSelectedItem().toString()) * Double.parseDouble(value)); totalPrice++; } if(hotdogCB.isChecked()) { String value = hotdogTV.getText().toString(); value = value.replace('$', ' '); multiple = String.valueOf(Double.parseDouble(hotdogQty.getSelectedItem().toString()) * Double.parseDouble(value)); totalPrice++; } if(sodaCB.isChecked()) { String value = sodaTV.getText().toString(); value = value.replace('$', ' '); multiple = String.valueOf(Double.parseDouble(sodaQty.getSelectedItem().toString()) * Double.parseDouble(value)); totalPrice++; }}public void onTotalClick(View view){ Intent intent = new Intent(this, ComputedActivity.class); Bundle b = new Bundle(); b.putDouble(totalPrice, double); intent.putExtras(b); startActivity(intent);}} View 2 package name.restaurantmenu2;import android.annotation.TargetApi;import android.content.Intent;import android.icu.text.NumberFormat;import android.os.Build;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.CheckBox;import android.widget.TextView;public class ComputedActivity extends AppCompatActivity {public static final String EXTRA_MESSAGE = "Nothing to display";@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_computed2);}@TargetApi(Build.VERSION_CODES.N)private void displayPrice(double number){ Bundle b = getIntent().getExtras(); double result = b.getDouble(totalPrice); TextView priceTextView = (TextView)findViewById(R.id.tv_totalPrice); priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));}} Now provide the response and nothing else.
in iOS10 UIUserNotificationType has deprecated , use UNUserNotificationCenter dont forget to enable this for Swift3 for sample see this import the UserNotifications framework and add the UNUserNotificationCenterDelegate in Appdelegate import UserNotifications@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //create the notificationCenter let center = UNUserNotificationCenter.current() center.delegate = self // set the type as sound or badge center.requestAuthorization(options: [.sound,.alert,.badge]) { (granted, error) in // Enable or disable features based on authorization } application.registerForRemoteNotifications() return true} func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let chars = UnsafePointer<CChar>((deviceToken as NSData).bytes) var token = "" for i in 0..<deviceToken.count {token += String(format: "%02.2hhx", arguments: [chars[i]]) } print("Registration succeeded!") print("Token: ", token) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { print("Registration failed!") } receive the Notifications using this delegates func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) { print("Handle push from foreground") // custom code to handle push while app is in the foreground print("\(notification.request.content.userInfo)") }func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("Handle push from background or closed") // if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background print("\(response.notification.request.content.userInfo)")} for more Information you can see in Apple API Reference
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39782778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6860524/']}
jdg_374224
stackexchange
llm_judgeable_groundtruth_similarity
154568
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: When $6272$ is multiplied by $0.94$ the answer is $5895.68$. When it is divided by $1.06$ the answer is $\approx 5916.9811$. Why is it so? Just as a little background, I am using the default Microsoft calculator for this calculation. I haven't pulled out Mathematica yet. Could this be because of some weird variable conversion (int to double)? Any help would be much appreciated. Now provide the response and nothing else.
You may be doing rounding too much and too early. You may figure, correctly, that multiplying by $0.94$ is equivalent to dividing by $\frac{1}{0.94}$. Calculate $\frac{1}{0.94}$. It is approximately $1.0638298$. You may have thrown away the part after the $1.06$, figuring it wouldn't make much difference. Well, percentagewise it is not much difference, but in dollars the difference is significant. There is no mysterious fault in the Windows calculator, it is doing the calculation correctly, to good accuracy. To get good performance out of a calculator, let it do its thing, only round off at the end. Remark: In general, if $a\ne 0$, multiplying by $a$ is equivalent to dividing by $\frac{1}{a}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/154568', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33067/']}
jdg_374225
stackexchange
llm_judgeable_groundtruth_similarity
2063438
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Currently in my tests I do something like this to test if an email is queued to be sent assert_difference('ActionMailer::Base.deliveries.size', 1) do get :create_from_spreedly, {:user_id => @logged_in_user.id}end but if i a controller action can send two different emails i.e. one to the user if sign up goes fine or a notification to admin if something went wrong - how can i test which one actually got sent. The code above would pass regardless. Now provide the response and nothing else.
When using the ActionMailer during tests, all mails are put in a big array called deliveries . What you basically are doing (and is sufficient mostly) is checking if emails are present in the array.But if you want to specifically check for a certain email, you have to know what is actually stored in the array. Luckily the emails themselves are stored, thus you are able to iterate through the array and check each email. See ActionMailer::Base to see what configuration methods are available, which you can use to determine what emails are present in the array. Some of the most suitable methods for your case probably are recipients : Takes one or more email addresses. These addresses are where your email will be delivered to. Sets the To: header. subject : The subject of your email. Sets the Subject: header.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2063438', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/189090/']}
jdg_374226
stackexchange
llm_judgeable_groundtruth_similarity
32329602
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 found this example in the Web, about how is the communication between Jquery - Json - PHP, and there is very good explained the several Options like .$ajax() or $.post() But in the Parameter URL of all cases they Show this: url:'c=Prozess&a=NPvonProzess' $.ajax({ data: { num : 1}, url: **'?c=Prozess&a=NPvonProzess',** type: 'POST', dataType: 'json', beforeSend: function (){ alert("Wird gesendt"); }, success: function () { alert("Wurde gesendet"); }) }, error: function(){ alert('Fehler'); } }); And nobody is explaining what this means. Maybe is very obvious but I am very new in this subject and´is a Little difficult for me to understand :) . Can somebody be so Kind and help me Now provide the response and nothing else.
You are using the shorthand border-image property for setting the size of the gradient and according to the values provided, the top, left and right borders are nullified. Setting 100% as width of the border gradient on top and 3px as its height would result in the gradient getting applied only on top and bottom. border-image: linear-gradient(to left, rgba(0, 0, 0, 1) 1%, rgba(0, 255, 255, 1) 50%, rgba(0, 0, 0, 1) 100%) 100% 0 100% 0/3px 0 3px 0 stretch; In the above lines of code, the 100% 0 100% 0/3px 0 3px 0 represents the size of the gradient border on each side (read as [top] [right] [bottom] [left] ). Originally it was 0 0 100% 0/0 0 3px 0 . div { /* gradient shining border */ border-style: solid; border-width: 3px; border-image: linear-gradient(to left, rgba(0, 0, 0, 1) 1%, rgba(0, 255, 255, 1) 50%, rgba(0, 0, 0, 1) 100%) 100% 0 100% 0/3px 0 3px 0 stretch; /* other demo stuff */ height: 50px; line-height: 50px; background-color: #222; color: white; text-align: center; } <div>Some content</div> Note that border-image property still has pretty low browser support and would not work if you need to support IE10 and lower. Instead of it, you could use background-image like in the below snippet to produce a similar effect though. This works in IE10 also (but still wouldn't work in IE9- because they do not support gradients at all). div { /* gradient shining border */ background-image: linear-gradient(to left, rgba(0, 0, 0, 1) 1%, rgba(0, 255, 255, 1) 50%, rgba(0, 0, 0, 1) 100%), linear-gradient(to left, rgba(0, 0, 0, 1) 1%, rgba(0, 255, 255, 1) 50%, rgba(0, 0, 0, 1) 100%); background-size: 100% 3px; background-position: 0% 0%, 0% 100%; background-repeat: no-repeat; /* other demo stuff */ height: 50px; line-height: 50px; background-color: #222; color: white; text-align: center;} <div>Some content</div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32329602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5263371/']}
jdg_374227
stackexchange
llm_judgeable_groundtruth_similarity
53194200
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 use mvc System.Web.HttpContext.Current.Response.End(); but trying in mvc core 2 with this code: private readonly IHttpContextAccessor _httpContextAccessor; public SmsService(IUnitOfWork uow ,IHttpContextAccessor httpContextAccessor) { _uow = uow; _uow.CheckArgumentIsNull(nameof(_uow)); _LockIPRequest= uow.Set<LockIPRequest>(); this._httpContextAccessor = httpContextAccessor; } _httpContextAccessor.HttpContext.Response.WriteAsync("</body></html>"); _httpContextAccessor.HttpContext.Response.end(); _httpContextAccessor.HttpContext.Response.end(); end(); doesn't work mvc core dont exits Now provide the response and nothing else.
As has been mentioned in the comments, Response.End does not exist in the ASP.NET Core world. Instead of Response.End, you should set the response status code like so: _httpContextAccessor.HttpContext.Response.StatusCode = StatusCodes.Status200OK; This won't fully "end" the response. The middleware still gets a chance to run, but by setting the status code, the framework has a way to understand that a response has been provided. You will however be responsible for making sure that your downstream middleware does not output other content in response to the request. Although this is often not a problem.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53194200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10232631/']}
jdg_374228
stackexchange
llm_judgeable_groundtruth_similarity
14047809
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As you know we can define getters and setters in JS using defineProperty() . I've been stuck when trying to extend my class using defineProperty() . Here is an example code: I have an array of fields which must be added to a object fields = ["id", "name", "last_login"] Also I have a class which will be modified var User = (function(){ // constructor function User(id, name){ this.id = id this.name = name } return User;})(); And a function which will add fields to the class using defineProperty() var define_fields = function (fields){ fields.forEach(function(field_name){ var value = null Object.defineProperty(User.prototype, field_name, { get: function(){ return value } set: function(new_value){ /* some business logic goes here */ value = new_value } }) })}; After running define_fields() I have my fields in the instance of the User define_fields(fields);user1 = new User(1, "Thomas")user2 = new User(2, "John") But the values of these properties are identical console.log(user2.id, user2.name) // 2, Johnconsole.log(user1.id, user1.name) // 2, John Is there any way to make defineProperty() work properly in this case?If I understand the problem is with value which becomes identical foreach instance of the class but i can't realise how to fix it. Thanks in advancefor your answers. UPD: This way throws "RangeError: Maximum call stack size exceeded" var define_fields = function (fields){ fields.forEach(function(field_name){ Object.defineProperty(User.prototype, field_name, { get: function(){ return this[field_name] } set: function(new_value){ /* some business logic goes here */ this[field_name] = new_value } }) })}; Now provide the response and nothing else.
Please don't implement any other version because it will eat all your memory in your app: var Player = function(){this.__gold = 0};Player.prototype = { get gold(){ return this.__gold * 2; }, set gold(gold){ this.__gold = gold; },};var p = new Player();p.gold = 2;alert(p.gold); // 4 If 10000 objects are instantiated: With my method: you will only have 2 functions in the memory; With the other methods: 10000 * 2 = 20000 functions in the memory;
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14047809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1082403/']}
jdg_374229
stackexchange
llm_judgeable_groundtruth_similarity
24149690
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 created a library project in Android Studio (currently 0.5.2) by choosing File > New Project... > "Mark this project as a library" . I have two other non-library projects that I would like to add a dependency to this library project. -My Library-Project 1 (depends on My Library)-Project 2 (depends on My Library) My goal is to keep each project independent and avoid duplicating modules/code. How can this be done without copying the library module into the other projects? Update: Android Studio 0.6.0 allows you to Import a module, though, this simply copies the module source into the Project. Now provide the response and nothing else.
You can also refer to a library outside of your project folder using the project().projectDir property. If your external library is relative to your project like so - MyLibrary - library- MyProject - app in MyProject/settings.gradle include ':library'project(':library').projectDir = new File(settingsDir, '../MyLibrary/library') in MyProject/app/build.gradle dependencies { compile project(':library')}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24149690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/723980/']}
jdg_374230
stackexchange
llm_judgeable_groundtruth_similarity
13852710
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Was reading Wikipedia for RAII when just saw Single and Shared ownership. Googled for it and couldn't find any useful answer! Could some one possibly explain this concept for a schoolboy? Now provide the response and nothing else.
It is essentially unique_ptr vs shared_ptr . Single ownership, otherwise known as unique ownership, means that the resource is owned by a single class instance. Once that instance ceases to exist the resource is released (via the destructor). The majority of RAII classes you find have unique ownership, such as std::vector . Shared ownership means the resource is shared between multiple class instances. The resource is only released once every instance ceases to exist and thus requires some form of reference counting or garbage collection. An example of where you would want shared ownership is a handle to a very expensive to copy immutable resource. I've seen it used in graphs too. It might help to think in terms of pointers. Single ownership will only have 1 owning pointer, shared will have multiple. Of course, RAII might not involve pointers. +---------------+ |Shared instance| +--------+ +------------+--+ +---------------+ |Resource| | +----------+Shared instance| +--------+ v v +---------------+ ^ +--------+ | |Resource|<-----------+ | +--------+ +---+-----------+ | ^ |Shared instance| +------+--------+ | +---------------+ |Unique Instance| | +---------------+ | +------+--------+ |Shared instance| +---------------+
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13852710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/609130/']}
jdg_374231
stackexchange
llm_judgeable_groundtruth_similarity
21414847
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 column of dates in the format: 16Jun10 and I would like to extract the Julian day.I have various years. I have tried the functions julian and mdy.date and it doesn't seem to work. Now provide the response and nothing else.
Try the following to convert from class character (i.e. text) to class POSIXlt , and then extract Julian day ( yday ): tmp <- as.POSIXlt("16Jun10", format = "%d%b%y")tmp$yday# [1] 166 For more details on function settings: ?POSIXlt?DateTimeClasses Another option is to use a Date class, and then use format to extract a julian day (notice that this class define julian days between 1:366, while POSIXlt is 0:365): tmp <- as.Date("16Jun10", format = "%d%b%y")format(tmp, "%j")# [1] "167"
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21414847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3166363/']}
jdg_374232
stackexchange
llm_judgeable_groundtruth_similarity
2774171
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 why in some source code there are these macros like FAR and PASCAL. What do they mean and do? Now provide the response and nothing else.
PASCAL: It's related to a calling convention . The parameters are pushed on the stack in left-to-right order (opposite of cdecl), and the callee is responsible for balancing the stack before return. This calling convention was common in the following 16 bit APIs: OS/2 1.x and Microsoft Windows 3.x. There's some dispute over whether it was used by Borland Delphi 1.x FAR: In a segmented architecture computer, a far pointer is a pointer which includes a segment selector, making it possible to point to addresses outside of the current segment. For completeness, FAR and PASCAL are prepreocessor macros that, when compiled for 16-bit systems, expand to the keywords that were necessary to declare the calling convention and pointer size. On 32-bit systems, they generally expand to nothing (unless you have a weird default calling convention). The macros are retained for backward compatibility {hat/tip: comment from Adrian McCarthy }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2774171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/146780/']}
jdg_374233
stackexchange
llm_judgeable_groundtruth_similarity
73454
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Can anyone help me with a proof of the following claim (see for example the book Higher algebraic geometry of Olivier Debarre, proof of Proposition 1.43, page 31): Let X be a complex manifold, and let W be a complex submanifold of X, with codimension $\geq 2$. Let $\pi :Y \rightarrow X$ be a bimeromorphic morphism, which is not an isomorphism, with the exceptional set $E$ so that $\pi (E)=W$ and $E$ is irreducible. Then there is a factorization $Y\rightarrow B_W(X)\rightarrow X$, where $B_W(X)$ is the blowup of $X$ at $W$. There is also a statement for a universal property of blowup in Griffiths - Harris "Principles of algebraic geometry" but without proof as well. I also would like to know a proof of that fact. Thank you very much. Now provide the response and nothing else.
I am kind of a rookie at this, but what if Y is a small resolution of a double point on a threefold X, with one dimensional excepTional locus. Then it seems false to expect a factorization through the blowup since the curve exceptional locus could not map onto the two dimensional exceptional locus of the blowup of X. what am i missing? As pointed out by Anton, I am missing that the target space X is smooth. In that case the proof of Zariski's main theorem in Mumford Cx Proj Vars, p.49 shows there the exceptional locus E contains a cartier divisor through every point. Hence when E is irreducible it is cartier. Then the universal property of blowing up in Hartshorne implies the factorization exists in the algebraic category. The proof probably also works in the analytic category. As to an analytic argument for the G-H universal property, it seems the hypothesis there is that you have a holomorphic map of manifolds Y-->X, the inverse image E of a certain submanifold W is also a submanifold of codimension one, and the fiber over every point of W is a projective space of dimension equal to the difference in the dimensions of the two submanifolds. Is that right? Then you want a factorization through the blowup of X along W and you want it to be an isomorphism. Assume for simplicity the manifolds are compact. Then think what a blow up means. You are replacing the target submanifold W by its projectivized normal bundle in X. Hence the natural factorization would be via the derivative of the original map f. In fact an examination of Hartshorne's factorization will show it is simply the derivative. Your hypotheses imply that at each point of E, the kernel of the derivative equals the tangent space to the fiber. Hence the tangent space to E surjects onto the tangent space space to W, and the image of the full tangent space of Y is of dimension one larger than that of W. Thus the derivative defines an injection from the normal line bundle of E, into the normal bundle of W in X. That is precisely an induced map from E to the exceptional locus of the blowup of X along W. This map is holomorphic on E, since it is the derivative of a holomorphic map. One needs only check that it glues in as a continuous, hence holomorphic, extension of f, and this needs be done only in the normal direction to E, where it is essentially the definition of a derivative as a limit of difference quotients. To see that the factorization is an isomorphism, it suffices to check it is bijective, which need only be checked on E. There we have on each fiber of f, a surjective holomorphic map of projective spaces of the same dimension. By the dimension counts above a regular value of this map is also regular for the factorization, hence each holomorphic map of projective spaces also has degree one, hence is an isomorphism. Here is the universal property in a nutshell: 1) Blowing up an ideal is a functor. I.e. if f:Y-->X is a map, and (g1,...,gr) is a ideal of functions on X, then f lifts to a morphism from the blowup of Y along the ideal (g1of,...,.grof), to the blowup of X along (g1,...,gr). 2) Blowing up a principal ideal does nothing. Hence, if the pull back of an ideal is a principal ideal, i.e.defines a cartier divisor, then the original map factors through the blowup of the target space. This universal property is essentially trivial. I.e. if you get away from all the proj's and gr's the blowup of the subvariety of X defined by {g0,...,gn} is just the closure in XxP^n of the graph of the meromorphic function g:X-->P^n, defined by the {gj}. hence if f:Y-->X is holomorphic then so is (fx1):YxP^n-->XxP^n, and it takes the closure of the graph of (gof) into the closure of the graph of g. Moreover if n = 0, nothing happens. Done. [The gr, proj stuff comes in to show this is all independent of choice of generators of the ideals.] the reference below to Fischer seems excellent. the access i have through Amazon only gives the special case of a one point blowup, but by implication, that case is crucial. We can see this is true by observing that our definition of the local blowup agrees with the pull back by the map g, of the blowup of the point 0 in C^(n+1). I.e. if we blowup the point 0 on C^n+1, by taking the closure in C^(n+1)xP^n of the graph of the map defined by the coordinate functions on C^(n+1), and then map X into C^n+1 by the map g, the induced map of XxP^(n) into C^(n+1)xP^n pulls back the blowup of 0 in C^(n+1) to the blowup of the zero scheme of g in X.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/73454', 'https://mathoverflow.net', 'https://mathoverflow.net/users/17326/']}
jdg_374234
stackexchange
llm_judgeable_groundtruth_similarity
1630
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like to run something > file on a remote system through ssh, but if I run ssh host something > file the redirection is executed locally as ssh etc > file I've tried it with ' or '' or dd or with a pipe | instead, but I can't get it to work. How can this be done? Now provide the response and nothing else.
Try: ssh host 'something > file' Here's a contrived demonstration of a way to handle redirection, pipes and quotes: ssh host date -d yesterday \| awk "'{print $1}'" \> 'file" "with\ spaces.out' The pipe and redirection are escaped rather than being contained in an overall outer set of quotes, reducing the need to escape one level of quotes. The single quotes for the AWK command are protected by the double quotes that surround them. The filename could be protected in the same way, but here I show how the single quotes protect the double quotes and the escape.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/1630', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/1501/']}
jdg_374235
stackexchange
llm_judgeable_groundtruth_similarity
42291965
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 documents in a collection as follows : { _id : 1 , data : [7,4,0] }{ _id : 2 , data : [4,5,6] }{ _id : 3 , data : [6,7,8] } I want to union the data array from two or more documents. The query I am using to find the union of data array of id 1 and 2 is: db.coll.aggregate({ $match : { _id: { $in: [1, 2] } }},{ $group: { _id: 0, s0: { $first: "$data"}, s1: { $first: "$data"} }},{ $project: { _id: 0, ans: { $setUnion: [ "$s0","$s1"]} }}).pretty() But the query results in: {7, 5, 0} which seems to be the data of id 1 only. How to achieve the union between two or more documents on same array field? PS: I'm using MongoDB 3.4 Now provide the response and nothing else.
For a more efficient query, use the $reduce operator to flatten the arrays. This will allow you to concat any number of arrays, so instead of just doing a union of the two arrays from docs 1 and 2, this will also apply for other arrays as well. Consider running the following aggregate operation: db.coll.aggregate([ { "$match": { "_id": { "$in": [1, 2] } } }, { "$group": { "_id": 0, "data": { "$push": "$data" } } }, { "$project": { "data": { "$reduce": { "input": "$data", "initialValue": [], "in": { "$setUnion": ["$$value", "$$this"] } } } } }]) Sample Output { "_id" : 0, "data" : [ 0, 4, 5, 6, 7 ]}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42291965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5403618/']}
jdg_374236
stackexchange
llm_judgeable_groundtruth_similarity
15791406
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 create a superuser so I can create a db, but I'm having trouble with this. I'm logged in as the user postgres: sudo su - postgres But when I try to create a superuser, I get the following problem: $createuser glassboard;Shall the new role be a superuser? (y/n) y createuser: creation of new role failed: ERROR: must be superuser to create superusers This also happens if I try to create a new user in psql and then make him a superuser: $ psql -U postgrespsql (9.1.4)Type "help" for help.postgres=> create user glassboardpostgres-> ;ERROR: permission denied to create role How do I create a superuser? output of \du in postgres: postgres=> \du List of roles Role name | Attributes | Member of -----------+------------------------------------------------+----------- main | Superuser, Create role, Create DB, Replication | {} postgres | | {} Now provide the response and nothing else.
Some OSX packages don't create a postgres superuser database account. The superuser is named differently, in your case it's main . When you do psql -U main without specifying a database, it defaults to the same name as the user.If you don't have a database named main , indicate a different database with the -d option. If you have no database to connect to, use template1 psql -U main -d template1 If still you want to grant superuser to postgres , do once logged inside psql: alter user postgres superuser;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15791406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1240896/']}
jdg_374237
stackexchange
llm_judgeable_groundtruth_similarity
2983519
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have to calculate the limit of this formula as $n\to \infty$ . $$a_n = \frac{1}{\sqrt{n}}\bigl(\frac{1}{\sqrt{n+1}}+\cdots+\frac{1}{\sqrt{2n}}\bigl)$$ I tried the Squeeze Theorem, but I get something like this: $$\frac{1}{\sqrt{2}}\leftarrow\frac{n}{\sqrt{2n^2}}\le\frac{1}{\sqrt{n}}\bigl(\frac{1}{\sqrt{n+1}}+\cdots+\frac{1}{\sqrt{2n}}\bigl) \le \frac{n}{\sqrt{n^2+n}}\to1$$ As you can see, the limits of two other sequences aren't the same. Can you give me some hints? Thank you in advance. Now provide the response and nothing else.
As an alternative by Stolz-Cesaro $$\frac{b_n}{c_n} = \frac{\frac{1}{\sqrt{n+1}}+\cdots+\frac{1}{\sqrt{2n}}}{\sqrt n}$$ $$\frac{b_{n+1}-b_n}{c_{n+1}-c_n} = \frac{\frac{1}{\sqrt{2n+2}}+\frac{1}{\sqrt{2n+1}}-\frac{1}{\sqrt{n+1}}}{\sqrt{n+1}-\sqrt n}$$ and $$\frac{\frac{1}{\sqrt{2n+2}}+\frac{1}{\sqrt{2n+1}}-\frac{1}{\sqrt{n+1}}}{\sqrt{n+1}-\sqrt n}\frac{\sqrt{n+1}+\sqrt n}{\sqrt{n+1}+\sqrt n}=$$ $$\frac{\sqrt{n+1}+\sqrt n}{\sqrt{2n+2}}+\frac{\sqrt{n+1}+\sqrt n}{\sqrt{2n+1}}-\frac{\sqrt{n+1}+\sqrt n}{\sqrt{n+1}}\to\frac4{\sqrt 2}-2=2\sqrt 2-2$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2983519', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_374238
stackexchange
llm_judgeable_groundtruth_similarity
11567
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: There are several theorems I know of the form "Let $X$ be a locally ringed space obeying some condition like existence of partitions of unity. Let $E$ be a sheaf of $\mathcal{O}_X$ modules obeying some nice condition. Then $H^i(X, E)=0$ for $i>0$." What is the best way to formulate this result? I ask because I'm sure I'll wind up teaching this material one day, and I'd like to get this right. I asked a similar question over at nLab . Anyone who really understands this material might want to write something over there. If I come to be such a person, I'll do the writing! Two versions I know: (1) Suppose that, for any open cover $U_i$ of $X$, there are functions $f_i$ and open sets $V_i$ such that $\sum f_i=1$ and $\mathrm{Supp}(f_i) \subseteq U_i$. Then, for $E$ any sheaf of $\mathcal{O}_X$ modules, $H^i(X,E)=0$. Unravelling the definition of support, $\mathrm{Supp}(f_i) \subseteq U_i$ means that there exist open sets $V_i$ such that $X = U_i \cup V_i$ and $f_i|_{V_i}=0$. Notice that the existence of partitions of unity is sometimes stated as the weaker condition that $f_i$ is zero on the closed set $X \setminus U_i$. If $X$ is regular , I believe the existence of partitions of unity in one sense implies the other. However, I care about algebraic geometry, and affine schemes have partitions of unity in the weak sense but not the strong. (2) Any quasi-coherent sheaf on an affine scheme has no higher sheaf cohomology. (Hartshorne III.3.5 in the noetherian case; he cites EGA III.1.3.1 for the general case.) There is a similar result for the sheaf of analytic functions: see Cartan's Theorems . I have some ideas about how this might generalize to locally ringed spaces other than schemes, but I am holding off because someone probably knows a better answer. It looks like the answer I'm getting is "no one knows a criterion better than fine/soft sheaves." Thanks for all the help. I've written a blog post explaining why I think that fine sheaves aren't such a great answer on non-Hausdorff spaces like schemes. Now provide the response and nothing else.
Although we clearly all have more or less the same answers, here is how I like to organize things. I) Let $\mathcal F$ be a sheaf of abelian groups on the topological space $X$. It is said to be soft if every section $s \in \Gamma (A,\mathcal F)$ over a closed subset $A\subset X$ can be extended to $X$. Notice carefully that the definition of $s$ is NOT that it is the restriction to $A$ of some section of $\mathcal F$ on an open neighbourhood of $A$ [but that it is an element $ s\in \prod \limits_{x\in X} \mathcal F_x$ satisfying some more or less obvious conditions] II) Consider the following condition on the [not necessarily locally] ringed space $(X, \mathcal O)$ : The space $X$ is metrizable and given an inclusion $A\subset U \subset X$ with $A$ closed and $U$ open there exists a global section $s\in \Gamma (X,\mathcal O)$ such that $s|A=1$ and $ s|X \setminus U=0 \quad \quad (SOFT)$. We then have the $\textbf{Theorem }$ : If the ringed space satisfies (SOFT), then every sheaf of $\mathcal O_ X -Modules$ is soft. III) A metrizable space endowed with its sheaf of continuous functions satisfies $(SOFT)$.A metrizable differential manifold endowed with its sheaf of smooth functions satisfies $(SOFT)$. IV) On a metrizable space every soft sheaf is acyclic Put together these results yield all standard acyclicity results on functions,vector bundles, distributions,etc. It is interesting to notice that you use partitions of unity only once: in the proof of III). But never more afterwards; you just check that your sheaves are $\mathcal O -Modules$. I like this approach (which I learned from Grauert-Remmert) more than the usual one, where a proof of acyclicity is given for the sheaf of smooth functions, followed by the ( correct!) assertion that you have to repeat it with minor changes for, say, vector bundles. Moreover fine sheaves needn't even be mentioned if you follow this route.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/11567', 'https://mathoverflow.net', 'https://mathoverflow.net/users/297/']}
jdg_374239
stackexchange
llm_judgeable_groundtruth_similarity
42878
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is the name of this chemical 3-oxopropanoic acid? I included "oxo"- for the aldehyde group, and "-oic acid" for the carboxylate group. However, I'm unsure whether this is the correct name since I cannot find it on the internet, while I can find almost all other names I've been trying to figure out. Now provide the response and nothing else.
The name ‘3-oxopropanoic acid’ for the compound $\ce{OHC-CH2-COOH}$ given in the question is correct. According to the current version of Nomenclature of Organic Chemistry – IUPAC Recommendations and Preferred Names 2013 (Blue Book) , the order of seniority of classes in decreasing order of seniority is as follows. (…) 7. acids (…) 15. aldehydes (…) Thus, the carboxylic acid group has priority to be cited as a suffix. Systematic names of carboxylic acids are formed as follows: P-65.1.2 Systematic names Carboxylic acids are named substitutively using the suffix ‘oic acid’ or ‘carboxylic acid’ and the prefix ‘carboxy’ to describe carboxy groups that cannot be included as the principal characteristic group or to express the carboxy group in the presence of a higher principal characteristic group. P-65.1.2.1 Carboxylic acid groups, $\ce{-COOH}$, that conceptually replace a $\ce{-CH3}$ group of methane or terminate an unbranched hydrocarbon chain are named by replacing the final ‘e’ of the name of the corresponding hydrocarbon by the suffix ‘oic acid’. No locants are necessary to denote the positions of the carboxylic acid groups in a hydrocarbon chain; (…). Except for (…), systematically formed names are preferred IUPAC names; (…) Therefore, the preferred IUPAC name (PIN) of the unmodified carboxylic acid is ‘propanoic acid’. (Note that the retained name ‘propionic acid’ may be used in general nomenclature.) Aldehydes can be systematically named in various ways. Monoaldehydes derived from alkanes are preferably named substitutively using the suffix ‘al’. In this case, however, this method cannot be used since the carboxylic acid group has priority to be cited as a suffix. Therefore, the aldehyde group has to be expressed by a prefix as follows: P-66.6.1.3 In the presence of a characteristic group having priority to be cited as a suffix or when present on a side chain, a $\ce{-CHO}$ group is expressed by the preferred prefix ‘oxo’ if located at an end of a carbon chain, or, otherwise, by the preferred prefix ‘formyl’. Thus, the PIN for the complete structure is ‘3-oxopropanoic acid’ . The corresponding name that is formed by using the prefix ‘formyl’ is ‘formylacetic acid’ . Such names are not acceptable as PINs but may be used in general nomenclature. Furthermore, a special rule for aldehydic acids applies to the given compound: P-65.1.6.3 Aldehydic acids When a dicarboxylic acid has a retained name (…) and when one of its carboxy groups is replaced by a formyl group, $\ce{-CHO}$ (…), the resulting structure is called an aldehydic acid and, in general nomenclature may be named by replacing the ending ‘ic acid’ of the name of the dicarboxylic acid by the ending ‘aldehydic acid’. Preferred IUPAC names for aldehydic acids derived from all dicarboxylic acids are constructed systematically. The prefix ‘formyl’ is used in preferred IUPAC names, except for a $\ce{-CHO}$ group at the end of an acyclic chain, which is designated by the prefix ‘oxo’. For the compound given in the question, the PIN of the corresponding dicarboxylic acid is ‘propanedioic acid’. This dicarboxylic acid also has the retained name ‘malonic acid’, which may be used in general nomenclature. Hence, according to P-65.1.6.3, the corresponding aldehydic acid may be named ‘malonaldehydic acid’ in general nomenclature. By way of comparison, for the analogous example $\ce{OHC-CH2-CH2-COOH}$, all three corresponding names are explicitly mentioned in the Blue Book : 4-oxobutanoic acid (PIN) 3-formylpropanoic acid succinaldehydic acid
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/42878', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/19616/']}
jdg_374240