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
|
54586363
|
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 create module library with NDK. After updating Android Studio 3.3, open project on studio stuck on build project Project Setup:reading from cache... Every time needs to "Invalidate and Restart" android studio then after studio working. I have try to delete .gradle folder but still facing this issue. How can I solved this misbehavior of studio 3.3?
Now provide the response and nothing else.
|
I don't have enough reputation to comment so I'll post this as an answer. After you Invalidate and Restart have you tried Build->Clean Project and rebuilding then syncing again? Have you tried restarting your computer to turn of any processes that may keep caches from clearing? Have you tried upgrading your gradle version as well (inside your gradle-wrapper.properties)? Have you checked if your gradle path is correct at File -> Settings -> Build, Execution, Deployment -> Gradle ? Have you tried locating your gradlew and doing a gradlew cleanBuildCache ? Have you tried removing the C:\Users\{Your Username}\.gradle\caches folder? Have you tried disabling cache building altogether (will slow down your build and is not recommended)? To do this you have to go to your gradle.properties file and set android.enableBuildCache=false
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54586363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3273766/']}
|
jdg_378941
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2486721
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
according to Apache AVRO project, "Avro is a serialization system". By saying data serialization system, does it mean that avro is a product or api? also, I am not quit sure about what a data serialization system is? for now, my understanding is that it is a protocol that defines how data object is passed over the network. Can anyone help explain it in an intuitive way that it is easier for people with limited distributed computing background to understand? Thanks in advance!
Now provide the response and nothing else.
|
So when Hadoop was being written by Doug Cutting he decided that the standard Java method of serializing Java object using Java Object Serialization (Java Serialization) didn't meet his requirements for Hadoop. Namely, these requirements were: Serialize the data into a compact binary format. Be fast , both in performance and how quickly it allowed data to be transfered. Interoperable so that other languages plug into Hadoop more easily. As he described Java Serialization: It looked big and hairy and I though we needed something lean and mean Instead of using Java Serialization they wrote their own serialization framework. The main perceived problems with Java Serialization was that it writes the classname of each object being serialized to the stream, with each subsequent instance of that class containing a 5 byte reference to the first, instead of the classname. As well as reducing the effective bandwidth of the stream this causes problems with random access as well as sorting of records in a serialized stream. Thus Hadoop serialization doesn't write the classname or the required references, and makes the assumption that the client knows the expected type. Java Serialization also creates a new object for each one that is deserialized. Hadoop Writables, which implement Hadoop Serialization, can be reused. Thus, helping to improve the performance of MapReduce which accentually serializes and deserializes billions of records. Avro fits into Hadoop in that it approaches serialization in a different manner. The client and server exchange a scheme which describes the datastream. This helps make it fast, compact and importantly makes it easier to mix languanges together. So Avro defines a serialization format, a protocol for clients and servers to communicate these serial streams and a way to compactly persist data in files. I hope this helps. I thought a bit of Hadoop history would help understand why Avro is a subproject of Hadoop and what its meant to help with.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2486721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264984/']}
|
jdg_378942
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13784192
|
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 starting from the pandas DataFrame documentation here: Introduction to data structures I'd like to iteratively fill the DataFrame with values in a time series kind of calculation. So basically, I'd like to initialize the DataFrame with columns A, B and timestamp rows, all 0 or all NaN. I'd then add initial values and go over this data calculating the new row from the row before, say row[A][t] = row[A][t-1]+1 or so. I'm currently using the code as below, but I feel it's kind of ugly and there must be a way to do this with a DataFrame directly, or just a better way in general. Note: I'm using Python 2.7. import datetime as dtimport pandas as pdimport scipy as sif __name__ == '__main__': base = dt.datetime.today().date() dates = [ base - dt.timedelta(days=x) for x in range(0,10) ] dates.sort() valdict = {} symbols = ['A','B', 'C'] for symb in symbols: valdict[symb] = pd.Series( s.zeros( len(dates)), dates ) for thedate in dates: if thedate > dates[0]: for symb in valdict: valdict[symb][thedate] = 1+valdict[symb][thedate - dt.timedelta(days=1)] print valdict
Now provide the response and nothing else.
|
Here's a couple of suggestions: Use date_range for the index: import datetimeimport pandas as pdimport numpy as nptodays_date = datetime.datetime.now().date()index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')columns = ['A','B', 'C'] Note: we could create an empty DataFrame (with NaN s) simply by writing: df_ = pd.DataFrame(index=index, columns=columns)df_ = df_.fillna(0) # With 0s rather than NaNs To do these type of calculations for the data, use a NumPy array: data = np.array([np.arange(10)]*3).T Hence we can create the DataFrame: In [10]: df = pd.DataFrame(data, index=index, columns=columns)In [11]: dfOut[11]: A B C2012-11-29 0 0 02012-11-30 1 1 12012-12-01 2 2 22012-12-02 3 3 32012-12-03 4 4 42012-12-04 5 5 52012-12-05 6 6 62012-12-06 7 7 72012-12-07 8 8 82012-12-08 9 9 9
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/13784192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1707931/']}
|
jdg_378943
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24968843
|
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 this airline program. The program should ask the user how many seats on the plane are sold and then I have this for loop to allow a user to enter a name and a meal choice for each person on the plane. I have tried reading through some different questions about infinite for loops on stackoverflow, but I can't seem to figure out exactly what is going wrong with my code. I feel like there must be something about for loops that I am not understanding because I thought that it would only go through until your i < someNumber is no longer true. So when I run this program, say I enter 2 seats I would expect it to go through the loop just twice, but It just keeps going. asking for a name and then a meal. import java.util.Scanner;public class Flyers { String name; String mealType; int economySeats; int businessSeats; int firstClassSeats; int count; public Flyers() { } public String toString() { Scanner in = new Scanner(System.in); System.out.print("Enter a name: "); name = in.next(); System.out.print("Enter a meal: "); mealType = in.next(); return "Name: " + name + ", Meal " + mealType; } public void addEconomyFlyers() { Scanner in = new Scanner(System.in); System.out.print("Enter number of economy seats sold: "); economySeats = in.nextInt(); for(count = 0; count < economySeats; count++) { System.out.print("Enter a name: "); name = in.next(); System.out.print("Enter a meal: "); mealType = in.next(); Flyers newFlyer = new Flyers(); String seat = newFlyer.toString(); } } Here is my main class if that is helpful. import java.util.Scanner;public class Aviation { public Aviation() { } public static void main(String[] args) { int option; FlightCost newFlight = new FlightCost(); FlightProfit flight = new FlightProfit(); Flyers newFlyers = new Flyers(); Scanner in = new Scanner(System.in); System.out.print("Enter new flight location: "); String location = in.next(); do{ String menu = "\n Please select an option to perform" + "\n1 (1) Get flight costs." + "\n2 (2) Get flight profits." + "\n3 (3) Enter names/meals." + "\n4 (4) Exit."; System.out.println(menu); option = in.nextInt(); }while (option < 0 || option > 4); switch(option) { case 1: newFlight.getCost(location); break; case 2: flight.addEconomySeats(); flight.addBusinessSeats(); flight.addFirstClassSeats(); flight.getProfit(location); break; case 3: newFlyers.addEconomyFlyers(); break; case 4: System.out.println("Exit"); break; default: System.out.println("Error: must select menu option."); } } }
Now provide the response and nothing else.
|
Range queries is a prikly question.The way to perform a real range query is to use a compound primary key, making the range on the clustering part. Since the range is on clustering part you can't perform the queries you wrote: you need at least to have an equal condition on the whole partition key .Let's see an example: CREATE TABLE users ( mainland text, state text, uid int, name text, zip int, PRIMARY KEY ((mainland), state, uid)) The uid is now an int just to make tests easier insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'washington', 1, 'john', 98100);insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'texas', 2, 'lukas', 75000);insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'delaware', 3, 'henry', 19904);insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'delaware', 4, 'dawson', 19910);insert into users (mainland, state, uid, name, zip) VALUES ( 'centraleurope', 'italy', 5, 'fabio', 20150);insert into users (mainland, state, uid, name, zip) VALUES ( 'southamerica', 'argentina', 6, 'alex', 10840); Now the query can perform what you need: select * from users where mainland = 'northamerica' and state > 'ca' and state < 'ny'; Output mainland | state | uid | name | zip-------------+----------+-----+--------+-------northamerica | delaware | 3 | henry | 19904northamerica | delaware | 4 | dawson | 19910 if you put an int (age, zipcode) as first column of the clustering key you can perform the same queries comparing integers. TAKE CARE : most of people when looking at this situation starts thinking "ok, I can put a fake partition key that is always the same and then I can perform range queries". This is a huge error, the partition key is responsible for data distribution accross nodes. Setting a fix partition key means that all data will finish in the same node (and in its replica). Dividing the world zone into 15/20 zones (in order to have 15/20 partition key) is something but is not enough and is made just to create a valid example. EDIT: due to question's edit I did not say that this is the only possibility; if you can't find a valid way to partition your users and need to perform this kind of query this is one possibility, not the only one. Range queries should be performed on clustering key portion . A weak point of the AGE as partition key is that you can't perform an UPDATE over it, anytime you need to update the user's age you have to perform a delete and an insert (an alternative could be writing the birth_year/birth_date and not the age, and then calculate client side) To answer your question on adding a secondary index: actually queries on secondary index does not support IN operator. From the CQL message it looks like they're going to develop it soon Bad Request: IN predicates on non-primary-key columns (xxx) is not yet supported However even if secondary index would support IN operator your query wouldn't change from select * from users where age IN (15,16,17,....30) Just to clarify my concept: anything that does not have a "clean" and "ready" solution requires the effort of the user to model data in a way that satisfy its needs. To make an example (I don't say this is a good solution: I would not use it) CREATE TABLE users ( years_range text, age int, uid int, PRIMARY KEY ((years_range), age, uid)) put some data insert into users (years_range, age , uid) VALUES ( '11_15', 14, 1);insert into users (years_range, age , uid) VALUES ( '26_30', 28, 3);insert into users (years_range, age , uid) VALUES ( '16_20', 16, 2);insert into users (years_range, age , uid) VALUES ( '26_30', 29, 4);insert into users (years_range, age , uid) VALUES ( '41_45', 41, 5);insert into users (years_range, age , uid) VALUES ( '21_25', 23, 5); query data select * from users where years_range in('11_15', '16_20', '21_25', '26_30') and age > 14 and age < 29; output years_range | age | uid-------------+-----+----- 16_20 | 16 | 2 21_25 | 23 | 5 26_30 | 28 | 3 This solution might solve your problem and could be used in a small cluster, where about 20 keys (0_5 ...106_110) might have a good distribution. But this solution, like the one before, does not allow an UPDATE and reduces the distribution of key. The advantage is that you have small IN sets. In a perfect world where S.I. already allows IN clause I'd use the UUID as partition key, the years_range (set as birth_year_range) as S.I. and "filter" my data client side (if interested in 10 > age > 22 I would ask for IN('1991_1995', '1996_2000', '2001_2005', '2006_2010', '2011_2015') calculating and removing unuseful years on my application) HTH,Carlo
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24968843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3879141/']}
|
jdg_378944
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
61366836
|
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 multiple emails that contain an attachment. I would like to download the attachment for unread emails and with a specific subject line. for example, I got an email that has a subject "EXAMPLE" and contains an attachment. So how it would be Below code, I tried but it is not working"it's a Python code #Subject line can be "EXAMPLE" for subject_line in lst_subject_line: # typ, msgs = conn.search(None,'(UNSEEN SUBJECT "' + subject_line + '")') typ, msgs = conn.search(None,'("UNSEEN")') msgs = msgs[0].split() print(msgs) outputdir = "C:/Private/Python/Python/Source/Mail Reader" for email_id in msgs: download_attachments_in_email(conn, email_id, outputdir) Thank You
Now provide the response and nothing else.
|
Most answers I could find were outdated. Here's a python (>=3.6) script to download attachments from a Gmail account. Make sure to check the filter options at the bottom and enable less secure apps on your google account. import osfrom imbox import Imbox # pip install imboximport traceback# enable less secure apps on your google account# https://myaccount.google.com/lesssecureappshost = "imap.gmail.com"username = "username"password = 'password'download_folder = "/path/to/download/folder"if not os.path.isdir(download_folder): os.makedirs(download_folder, exist_ok=True) mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=None, starttls=False)messages = mail.messages() # defaults to inboxfor (uid, message) in messages: mail.mark_seen(uid) # optional, mark message as read for idx, attachment in enumerate(message.attachments): try: att_fn = attachment.get('filename') download_path = f"{download_folder}/{att_fn}" print(download_path) with open(download_path, "wb") as fp: fp.write(attachment.get('content').read()) except: print(traceback.print_exc())mail.logout()"""Available Message filters: # Gets all messages from the inboxmessages = mail.messages()# Unread messagesmessages = mail.messages(unread=True)# Flagged messagesmessages = mail.messages(flagged=True)# Un-flagged messagesmessages = mail.messages(unflagged=True)# Messages sent FROMmessages = mail.messages(sent_from='sender@example.org')# Messages sent TOmessages = mail.messages(sent_to='receiver@example.org')# Messages received before specific datemessages = mail.messages(date__lt=datetime.date(2018, 7, 31))# Messages received after specific datemessages = mail.messages(date__gt=datetime.date(2018, 7, 30))# Messages received on a specific datemessages = mail.messages(date__on=datetime.date(2018, 7, 30))# Messages whose subjects contain a stringmessages = mail.messages(subject='Christmas')# Messages from a specific foldermessages = mail.messages(folder='Social')""" For Self Sign Certificates use: ...import ssl context = ssl._create_unverified_context()mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=context, starttls=False)... Note: Less secure apps & your Google Account To help keep your account secure, from May 30, 2022, Google nolonger supports the use of third-party apps or devices which ask youto sign in to your Google Account using only your username andpassword. Important: This deadline does not apply to Google Workspace or GoogleCloud Identity customers. The enforcement date for these customerswill be announced on the Workspace blog at a later date. SRC UPDATE 2022/08/22: You should be able to create an App Password to get around the "less secure apps" functionality being gone. (The latter still works in my business account, but had to create an App Password for my consumer account.) Using imaplib, I am able to login with an App Password.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61366836', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12397035/']}
|
jdg_378945
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
314391
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The charge on my smartphone was zero. I charged my phone to its maximum capacity. How much mass $\Delta m$ did my mobile gained after charging the battery? Maximum capacity of the smartphone's battery: $2000mAh$ Weight of the smartphone with no charge: $200g$
Now provide the response and nothing else.
|
There will be an increase of the mass of the battery when you charge it, though that increase is going to be undetectably small. I would do the calculation in reverse i.e. start with a fully charged battery and calculate how much it decreases in mass when you run it down. The mass decreases because the battery does work $E$ on the electrons that flow through it and that work is related to the mass lost $\Delta m$ by Einstein's famous equation: $$ E = \Delta m c^2 \tag{1}$$ We can do an approximate calculation using the information you provided: Maximum capacity of the smartphone's battery: 2000mAh That capacity means the battery can supply a current of $2$ amps for an hour, so if the battery voltage is $V$ it can supply a power of $2V$ for an hour and the total energy is therefore: $$ E = 7200V \tag{2} $$ If we substitute this into equation (1) and rearrange we get: $$ \Delta m = \frac{7200V}{c^2} $$ Smartphone batteries have $V\approx 4$V and this gives us: $$ \Delta m \approx 3.2 \times 10^{-13}\,\text{kg} \approx 0.32\,\text{nanograms} $$ This is approximate because the battery voltage isn't constant as the battery discharges so our equation (2) isn't exact. However it gives us a good estimate of how much the mass decreases on discharging and increases again on recharging.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/314391', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/145086/']}
|
jdg_378946
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13211334
|
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 send a request to a server and process the returned value: private static string Send(int id){ Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa"); string result = string.Empty; responseTask.ContinueWith(x => result = Print(x)); responseTask.Wait(); // it doesn't wait for the completion of the response task return result;}private static string Print(Task<HttpResponseMessage> httpTask){ Task<string> task = httpTask.Result.Content.ReadAsStringAsync(); string result = string.Empty; task.ContinueWith(t => { Console.WriteLine("Result: " + t.Result); result = t.Result; }); task.Wait(); // it does wait return result;} Am I using Task correctly? I don't think so because the Send() method returns string.Empty every time, while Print returns the correct value. What am I doing wrong? How do I get the correct result from a server?
Now provide the response and nothing else.
|
Your Print method likely needs to wait for the continuation to finish (ContinueWith returns a task which you can wait on). Otherwise the second ReadAsStringAsync finishes, the method returns (before result is assigned in the continuation). Same problem exists in your send method. Both need to wait on the continuation to consistently get the results you want. Similar to below private static string Send(int id){ Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa"); string result = string.Empty; Task continuation = responseTask.ContinueWith(x => result = Print(x)); continuation.Wait(); return result;}private static string Print(Task<HttpResponseMessage> httpTask){ Task<string> task = httpTask.Result.Content.ReadAsStringAsync(); string result = string.Empty; Task continuation = task.ContinueWith(t => { Console.WriteLine("Result: " + t.Result); result = t.Result; }); continuation.Wait(); return result;}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13211334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_378947
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
191261
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to prove $$\lim_{x\to\infty}x^{\ln(x)} = \infty$$ I am going to break this into two methods: one my professor mentioned and my method (which is where the question lies - skip ahead if you must!). Note that this is not homework, but simply an exercise my professor decided to do during notes the other day. The problem is taken from Stewart 7e Calculus (#70a in section 6.3 if you want to bust out your (e)-book). Method 1: Recall $\ln(e^x) = x, e^{\ln(x)} = x$. Thus we can write the original limit as$$\lim_{x\to\infty}\left(e^{\ln(x)}\right)^{\ln(x)} = \lim_{x\to\infty}e^{\left(\ln (x)\right)^2}$$ He then let $u = \ln(x)$. As $x\to\infty$, then $u=\ln(x) \to\infty$. As $u\to\infty, v = u^2 \to\infty$. Also, as $v\to\infty, e^v \to\infty$. So, as $x\to\infty, e^{\left(\ln (x)\right)^2} \to\infty$. Thus it is sufficient to say $$\lim_{x\to\infty}x^{\ln(x)} = \infty \ \ \ \ \ \ \ \mathrm{Q.E.D.}$$ Method 2 (my attempt): Let $t = \ln x$. As $x\to\infty, t\to\infty$ because the $\ln$ function is strictly increasing. $$\lim_{x\to\infty}x^{\ln(x)} \equiv \lim_{t\to\infty}x^t \tag{1}$$ Does the last statement of line (1) make sense mathematically though since the limit is with the variable $t$, yet the argument contains an $x$ still? Since line (1) may not be formally correct, I decided to try to write $x$ in terms of $t$. Recall that I made the substitution $t = \ln x \implies e^t = e^{\ln x} = x$. Thus I rewrote the limit as $$\lim_{t\to\infty}\left(e^t\right)^t$$ which diverges to $\infty$ for sufficiently large values of $t$. As an added bonus, are there any other 'simple' proofs for this limit?
Now provide the response and nothing else.
|
Your statement (1) does not really make sense for the reason you cite. Also note that "converges to $\infty$" is generally not correct; instead one usually says "diverges to $\infty$". Simple proof: Observe that for $x\geq e$, we have $x^{\ln x}>x$. Thus $\lim\limits_{x\to\infty} x^{\ln x}\geq \lim\limits_{x\to\infty} x$, which is clearly $\infty$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/191261', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24942/']}
|
jdg_378948
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21301641
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working on an application which has a side bar and two divs in my main view. I'm trying to split the height of both equally within the container. I tried height = 50% but that didn't work out too well. <div id="mainView" ng-controller="userCtrl"> <div id="top"> <div id="topRow"> <label for="entityDropDown">Select a user: </label> <select id="entityDropDown" ng-model="selectedUser" ng-options="user as user.name for user in users" ng-change="getUserInfo(selectedUser)"> </select> </div> </br></br> <div id="entityStatus"> <div> <label for="entityAvailable">Available Groups</label> <select id="entityAvailable" multiple ng-model="selectedAvailableGroups" ng-options="g.name for g in availableGroups | orderBy:'name'"> </select> </div> <div id="moveButtons" > <button type="button" ng-disabled="!selectedUser || availableGroups.length === 0" ng-click="addUserToGroup()">Add User</button> <button type="button" ng-disabled="!selectedUser || assignedGroups.length == 0" ng-click="removeUserFromGroup()">Remove</button> </div> <div> <label for="entityAssigned">Assigned Groups</label> <select id="entityAssigned" multiple ng-model="selectedAssignedGroups" ng-options="g.name for g in assignedGroups | orderBy:'name'"> </select> </div> </div> <br class="clearfix"/> </div> <div id="middle" ng-show="selectedUser"> <div id="entityInfo"> <div> <label for="entityName">Name: </label> <input type="text" id="entityName" ng-model="selectedUser.name"/> </br> <label for="entityEmail">Email: </label> <input type="text" id="entityEmail" ng-model="selectedUser.email"/> </br> <button type="button" ng-disabled="!selectedUser" ng-click="updateUserInfo()">Update User</button> </div> <div> <label for="entityId">ID: {{selectedUser.id}} </label> </br> <label for="entityDomain">Domain: {{selectedUser.domain}} </label> </br> <label for="isAdmin">Admin: {{selectedUser.isAdmin}}</label> </br> </div> </div> <br class="clearfix"/> </div> </div> I put it in a fiddle: http://jsfiddle.net/crmyq/
Now provide the response and nothing else.
|
After almost a year of working on a hardcore project that uses Phalcon beyond its capacity, I wanted to clarify a few things and answer my own question. To understand how to properly do redirects and forwards you need to understand a little about how the Dispatcher::dispatch method works. Take a look at the code here , though it's all C mumbo-jumbo to most of us, its really well written and documented. In the nutshell this is what it does: The dispatcher enters the while loop until the _finished property becomes true or it discovers a recursion. Inside the loop, it immediately sets that property to true , so when it starts the next iteration it will automatically break . It then gets the controller / action information, which are originally supplied by the router in the application, and does various checks. Before and after that it also completes a lot of event-related business. Finally it calls the action method in the controller and updates the _returnedValue property with (guess what!) the returned value. If during the action call you call Dispatcher::forward method, it will update the _finished property back to false , which will allow the while loop to continue from the step 2 of this list. So, after you do redirect or forward, you need to ensure that you code doesn't get executed only if that is part of the expected logic. In other words you don't have to return the result of return $this->response->redirect or return $this->dispatcher->forward . Doing the last might seem convenient, but not very correct and might lead to problems. In 99.9% cases your controller should not return anything. The exception would be when you actually know what you are doing and want to change the behaviour of the rendering process in your application by returning the response object. On top of that your IDE might complain about inconsistent return statements. To finalise, the correct way to redirect from within the controller: // Calling redirect only sets the 30X response status. You also should// disable the view to prevent the unnecessary rendering.$this->response->redirect('/profile');$this->view->disable();// If you are in the middle of something, you probably don't want // the rest of the code running.return; And to forward: $this->dispatcher->forward(['action' => 'profile']);// Again, exit if you don't need the rest of the logic.return;
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21301641', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1297248/']}
|
jdg_378949
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
765162
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There is a post by Raymond Chen, where he tells how bad IsBadXxxPtr function is by eating guard page exception . I don't quite understand how it is applied to Delphi. Who and how should normally (i.e. without call to IsBadXxxPtr) process this exception? I do know that Delphi inserts a code, which (for example) access a memory for large static arrays - exactly for this reason: to expand stack. But if guard page exception is raised: who will handle it in a Delphi application? Can't I accidentally mess with it by using try/except in inappropriate way? Will Delphi's debugger notify me about these exceptions?
Now provide the response and nothing else.
|
Windows structured exception handling (SEH) is has a two-phase structure. When an exception occurs, Windows first looks for a handler for the exception by following the registered exception handler chain (the head of which is stored in fs:[0] on x86, i.e. the first dword in the segment pointed to by the FS segment register - all that ugly 16-bit segment-offset logic didn't go away in 32-bit, it just became less relevant). The search is done by calling a function with a particular flag, a pointer to which is stored in each exception frame on the stack. fs:[0] points to the topmost frame. Each frame points to the previous frame. Ultimately, the last frame on the list is one that has been provided by the OS (this handler will pop up a app-crash dialog if an unhandled exception reaches it). These functions normally check the type of the exception, and return a code to indicate what to do. One of the codes that can be returned is basically, "ignore this exception and continue". If Windows sees this, it will reset the instruction pointer to the point of the exception and resume execution. Another code indicates that this exception frame should handle the given exception. A third code is "I'm not going to catch this exception, keep searching". Windows keeps on calling these exception filter functions until it finds one that handles the exception one way or the other. If Windows finds one that handles the exception by catching it, then it will proceed to unwind the stack back to that handler, which consists of calling all the functions again, only passing in a different flag. It's at this point that the functions execute the finally logic, up until the handler which executes the except logic. However, with the stack page guard exception, the process is different. None of the language's exception handlers will elect to handle this exception, because otherwise the stack growth mechanism would break. Instead, the filter search filters all the way through to the base exception handler provided by the OS, which grows the stack allocation by committing the appropriate memory, and then returns the appropriate return code to indicate that the OS should continue where it left off, rather than unwind the stack. The tool and debugging infrastructure are designed to let these particular exceptions play out correctly, so you don't need to worry about handling them. You can read more about SEH in Matt Pietrek's excellent article in MSJ from over a decade ago .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/765162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92713/']}
|
jdg_378950
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
156497
|
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:
Using Solve , I can find the solutions to $$ w + x + y + z = 0. $$ where $(w,x,y,z)$ are all integers between $-n$ and $n$. This gives me all solutions, including ones which are identical up to permutation, i.e. $(1,0,1,-2)$ and $(0,1,-2,1)$. But I would like to consider these both to be the same solution. Using DeleteDuplicates it's easy enough to get the unique solutions (up to permutations), but both of these steps use up much more time than just generating non-duplicate solutions in the first place. My questions is: is there a way to generate non-duplicate solutions, and efficiently?
Now provide the response and nothing else.
|
A much faster approach using IntegerPartitions fs[n_]:=IntegerPartitions[0, {4}, Range[-n, n]]; For n=3 {{3, 3, -3, -3}, {3, 2, -2, -3}, {3, 1, -1, -3}, {3, 1, -2, -2}, {3, 0, 0, -3}, {3, 0, -1, -2}, {3, -1, -1, -1}, {2, 2, -1, -3}, {2, 2, -2, -2}, {2, 1, 0, -3}, {2, 1, -1, -2}, {2, 0, 0, -2}, {2, 0, -1, -1}, {1, 1, 1, -3}, {1, 1, 0, -2}, {1, 1, -1, -1}, {1, 0, 0, -1}, {0, 0, 0, 0}} Timing comparison: fa[n_] := {w, x, y, z} /. Solve[w + x + y + z == 0 && LessEqual @@ {-n, w, x, y, z, n}, {w, x, y, z}, Integers] (*Bob's solution *)fa[40];// AbsoluteTimingfs[40];// AbsoluteTimingSort[(Sort /@ fa[40])] == Sort[(Sort /@ fs[40])] {0.234222, Null} {0.00182044, Null} True
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/156497', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/48731/']}
|
jdg_378951
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55433
|
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In parallel computing, I know the speed up equation is $$ \frac{1}{ s + \frac{1-s}{p} } $$ But what is meant by superlinear speed up? Is it something theoritical? Could you explain it with equations?
Now provide the response and nothing else.
|
With equation: not really. Superlinear speedup comes from exceeding naively calculated speedup even after taking into account the communication process (which is fading, but still this is the bottleneck). For example, you have serial algorithm that takes $1t$ to execute. You have $1024$ cores, so naive speedup is $1024x$ , or it takes $t/1024$ , but it should be calculated like in your equation taking into account memory transfer, slight modifications to the algorithm, parallelisation time. So speedup should be lower than 1024x, but sometimes it happens that speedup is bigger, then we call it $superlinear$ . Where it comes from? From several places: cache usage (what fits into registers, main memory or mass storage, where very often more processing units gives overall more registers per subtask), memory hit patterns, simply better (or a slightly different) algorithm, flaws in the serial code. For example, a random process that searches space for a result is now divided into $1024$ searchers covering more space at once so finding the solution faster is more probable.There are byproducts (if you swap elements like in bubble sort and switch into GPU it swaps all pairs at once, while serial only up to point). On the distributed system communication is even more costly, so programs are changed to make memory usage local (which also changes memory access, divides problem differently than in sequential application). And the most important, the sequential program is not ideally the same as the parallel version - different technology, environment, algorithm, etc. so it is hard to compare them. Excerpt from "Introduction to Parallel Computing" Second edition by Ananth Grama, 2003 Theoretically speedup can never exceed the number of processing elements $p$ . If the best sequential algorithm takes $T_s$ units of time to solve a given problem on a single processing element, then a speedup of $p$ can be obtained on $p$ processing elements if none of them spends more than time $T_s/p$ . A speedup greater than $p$ is possible only if each processing element spends less than time $T_s/p$ solving the problem. In this case, a single processing element could emulate the $p$ processing elements and solve the problem in fewer than $T_s$ units of time. This is a contradiction because speedup, by definition is computed with respect to the best sequential algorithm . So the name "superlinear" in this context comes from the definition of speedup.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/55433', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/48945/']}
|
jdg_378952
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9627044
|
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 think I quite understand how exports work in Node.js . In a bit of sample code, I noticed the exports object used in this manner: exports = mongoose = require('mongoose')mongoose.connect(config.db.uri)exports = Schema = mongoose.Schema What is happening behind the scenes when you use exports = twice like that? Looks to me like "mongoose" should not be exported. I did this quick test: var foo , barexports = foo = 'foo'exports = bar = 'bar'// reports 'bar' onlyconsole.log(exports) and the second test does overwrite the first export.
Now provide the response and nothing else.
|
My guess is the original author of that sample code is confused about module.exports vs exports . To use the exports object, you must add properties to it like this: exports.size = 42; If you re-assign the exports variable to a new object, you basically lose access to the global exports object that node.js provided for you. If you do this twice or three or N times, the effect is the same. It's useless. For example: mod_b.js var realExports = exports;realExports.height = 42;var exports = {};exports.weight = 43; And in mod_a.js var mod_b = require('./mod_b');console.dir(mod_b); Run node mod_a.js and you get: { height: 42 } Notice height is there but weight is not. Now, what you can do is assign module.exports to be an object, and that is the object that will be returned when another module require s your module. So you will see things like. var x = 10;var y = 20;module.exports = {x: x, y: y}; Which will do what you expect. Here's some informative articles on the details. Node.js Module – exports vs module.exports What is the purpose of NodeJS module.exports and how do you use it? Mastering Node
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9627044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53653/']}
|
jdg_378953
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
306439
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this Trigger in Postgresql that I can't just get to work (does nothing). For understanding, there's how I defined it: CREATE TABLE documents ( ... modification_time timestamp with time zone DEFAULT now());CREATE FUNCTION documents_update_mod_time() RETURNS triggerAS $$ begin new.modification_time := now(); return new; end$$ LANGUAGE plpgsql;CREATE TRIGGER documents_modification_time BEFORE INSERT OR UPDATE ON documents FOR EACH ROW EXECUTE PROCEDURE documents_update_mod_time(); Now to make it a bit more interesting.. How do you debug triggers?
Now provide the response and nothing else.
|
Use the following code within a trigger function, then watch the 'messages' tab in pgAdmin3 or the output in psql: RAISE NOTICE 'myplpgsqlval is currently %', myplpgsqlval; -- either thisRAISE EXCEPTION 'failed'; -- or that To see which triggers actually get called, how many times etc, the following statement is the life-saver of choice: EXPLAIN ANALYZE UPDATE table SET foo='bar'; -- shows the called triggers Note that if your trigger is not getting called and you use inheritance, it may be that you've only defined a trigger on the parent table, whereas triggers are not inherited by child tables automatically. To step through the function, you can use the debugger built into pgAdmin3, which on Windows is enabled by default; all you have to do is execute the code found in ...\8.3\share\contrib\pldbgapi.sql against the database you're debugging, restart pgAdmin3, right-click your trigger function, hit 'Set Breakpoint', and then execute a statement that would cause the trigger to fire, such as the UPDATE statement above.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/306439', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/35189/']}
|
jdg_378954
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7107079
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working on 2 Windows Services that have a common database which I want to lock (cross-process) with a system Mutex. Now I'm wondering whether it's ok to just call WaitOne() and ReleaseMutex() in a try-finally block or should I also dispose the Mutex (e.g. in a using block). If so I guess I should always catch the AbandonedMutexException on the WaitOne() method or am I wrong here?
Now provide the response and nothing else.
|
A mutex is a Windows kernel object (here wrapped in a .NET object). As such, it is an unmanaged resource that should be disposed. More accurately, the .NET object contains a HANDLE to the mutex, which must be released/disposed of somehow. I don't trust that code sample in the Mutex class docs where the mutex object is not disposed. Although Henzi has a good point in comment: The Mutex object is static and would be either disposed by the finalizer or destroyed by the Windows kernel when the process exits. Also, note that Close() disposes the object as well. Of course, there's nothing wrong with keeping an existing Mutex object in your app even while you don't use it. They are light resources.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7107079', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/192961/']}
|
jdg_378955
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12683201
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to use python re.split() to split a string into individual words by spaces, commas and periods. But I don't want "1,200" to be split into ["1", "200"] or ["1.2"] to be split into ["1", "2"] . Example l = "one two 3.4 5,6 seven.eight nine,ten" The result should be ["one", "two", "3.4", "5,6" , "seven", "eight", "nine", "ten"]
Now provide the response and nothing else.
|
Use a negative lookahead and a negative lookbehind: > s = "one two 3.4 5,6 seven.eight nine,ten"> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten'] In other words, you always split by \s (whitespace), and only split by commas and periods if they are not followed (?!\d) or preceded (?<!\d) by a digit. DEMO . EDIT : As per @verdesmarald comment, you may want to use the following instead: > s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5'] This will split "1.2,a,5" into ["1.2", "a", "5"] . DEMO .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12683201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1200784/']}
|
jdg_378956
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16645268
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to have a countdown from the current time to a specific date and display that value in a label. I looked at some NSTimer tutorials but I could not figure out how to apply them to my situation. NSTimeInterval TimeInterval = [aString doubleValue]; NSDate* upperDate = [aDate dateByAddingTimeInterval:TimeInterval];NSDate* Today = [NSDate date];//cell.myLabel.text = here i should write a countdown. Sorry for insufficient code. I usually try to write some of my own code before asking a question here but this time I could not figure what to write. Edit So with the answer of PartiallyFinite i figured how i set timer. But because i am using tableview i could not implement the repeat message for MyTimerLabel. Here what i just did: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *CellIdentifier = @"MyCell"; MekanListesiViewCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:self options:nil]; cell = [nib objectAtIndex:0]; } aClass *aC = [myArray objectAtIndex:indexPath.row]; NSTimeInterval TimeInterval = [aC.aTimeIntervalwithString doubleValue]; NSDate* UpperDate = [aC.aNSDate dateByAddingTimeInterval:TimeInterval]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"YYYY-MM-dd"]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit; NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:[NSDate date] toDate:UpperDate options:0]; NSInteger days = [dateComponents day]; NSInteger months = [dateComponents month]; NSInteger years = [dateComponents year]; NSInteger hours = [dateComponents hour]; NSInteger minutes = [dateComponents minute]; NSInteger seconds = [dateComponents second]; NSString *countdownText = [NSString stringWithFormat:@"%d Days %d:%d:%d", days, hours, minutes, seconds]; cell.countdownText= countdownText; [self performSelector:@selector(updateCoundown)]; // The delay is in seconds, make it whatever you want. return cell;}At myCellView.h@interface MekanListesiViewCell : UITableViewCell@property (nonatomic, weak) IBOutlet UILabel *MyTimerLabel;@property(weak)NSString *countdownText;at myCellView.m-(void)updateCoundown{ MyTimerLabel.text = countdownText; [self performSelector:@selector(updateCoundown) withObject:nil afterDelay:1];} i get nothing in the MyTimerLabel.
Now provide the response and nothing else.
|
Using the code from this answer (copy pasted below for completeness of example) to get the individual components of the countdown period: - (void)updateCountdown { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"YYYY-MM-dd"]; NSDate *startingDate = [dateFormatter dateFromString:@"2005-01-01"]; NSDate *endingDate = [NSDate date]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit; NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0]; NSInteger days = [dateComponents day]; NSInteger months = [dateComponents month]; NSInteger years = [dateComponents year]; NSInteger hours = [dateComponents hour]; NSInteger minutes = [dateComponents minute]; NSInteger seconds = [dateComponents second]; We can then create a string with all of these numbers: NSString *countdownText = [NSString stringWithFormat:@"%d Years %d Months %d Days %d Hours %d Minutes %d Seconds", days, months, years, hours, minutes, seconds]; cell.myLabel.text = countdownText; Then, we can use performSelector:withObject:afterDelay: to make this method get called again after the specified delay (note that the delay is in seconds): [self performSelector:@selector(updateCountdown) withObject:nil afterDelay:1];}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16645268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2393702/']}
|
jdg_378957
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5586857
|
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 JavaScript above this html is there any way to pass it inside EditBanner(JS Variable Here) in code below ? //EditBanner to be changed to pass a Js variable.<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner();"/>
Now provide the response and nothing else.
|
There's an entire practice that says it's a bad idea to have inline functions/styles.Taking into account you already have an ID for your button, consider JS var myvar=15;function init(){ document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};}window.onload=init; HTML <input id="EditBanner" type="button" value="Edit Image" />
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5586857', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/608576/']}
|
jdg_378958
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1826120
|
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 can't we use count(distinct *) in SQL? As in to count all distinct rows?
Now provide the response and nothing else.
|
select count(*) from (select distinct * from MyTable) as T Although I strongly suggest that you re-think any queries that use DISTINCT . In a large percentage of cases, GROUP BY is more appropriate (and faster). EDIT: Having read the question comments, I should point out that you should never ask the DBMS to do more work than actually needs doing to get a result. If you know in advance that there will not be any duplicated rows in a table, then don't use DISTINCT .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1826120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/220903/']}
|
jdg_378959
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19180578
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to learn specflow and right now.Currently I have 2 feature files. In the second feature file, I am reusing a step from the first feature file. Specflow automatically recognizes the step from the first feature file and when specflow generated the steps for my second feature, it was smart and did not regenerated the step I am reusing. But this step is a Given step and it initializes a member field of the feature class. Without using scenario context, how can I reuse a step from another feature file that initialize a member of the class ? Edit For example, if you have a Given I am logged in that is used in several feature file.This "Given" creates a user object which is logged and store it as a member in .cs feature file. When you use the same Given in another .feature, Specflow does not regenerate it in the correspond .cs file. When you debug the a scenario which is using it, it executes it from the first .cs file. But I can't access the member of the first .cs feature file. I am planning to use a static member but perhaps there is another solution ? Thanks a lot.
Now provide the response and nothing else.
|
The big point here is that Step Binding s are global. This seems to be a common anti-pattern with Specflow that lots of people goes through. Initially you have a phase of creating hierarchies of binding classes that match your feature files. Instead you need to create collaborating classes that don't match the features but instead produce features through their collaboration. It's just like your main application code. You wouldn't have a single ATMMachineCashWithdrawal class, instead you would have an ATMMachine , that has a PINCodeCheck , an OperationSelection and a WithdrawalOperation . Those objects collaborate to make your "I want to withdraw cash" feature, and when you add a "Check my balance" feature, you can reuse everything except the WithdrawalOperation . The bindings in Specflow are the same. We might have an ATMTester that knows how to setup an ATMMachine and supplies your Given I have a cash machine full of cash and you could have a CustomerTester that knows how to fake/mock/setup your account balance with Given my account has loads of money in it . Fortunately SpecFlow provides ways to collaborate the classes too. Have a look at http://www.specflow.org/documentation/Sharing-Data-between-Bindings/
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19180578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2846391/']}
|
jdg_378960
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2556
|
Below is a question asked on the forum robotics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on an EKF and have a question regarding coordinate frame conversion for covariance matrices. Let's say I get some measurement $(x, y, z, roll, pitch, yaw)$ with corresponding 6x6 covariance matrix $C$. This measurement and $C$ are given in some coordinate frame $G_1$. I need to transform the measurement to another coordinate frame, $G_2$. Transforming the measurement itself is trivial, but I would also need to transform its covariance, correct? The translation between $G_1$ and $G_2$ should be irrelevant, but I would still need to rotate it. If I am correct, how would I do this? For the covariances between $x$, $y$, and $z$, my first thought was to simply apply a 3D rotation matrix, but that only works for a 3x3 submatrix within the full 6x6 covariance matrix. Do I need to apply the same rotation to all four blocks?
Now provide the response and nothing else.
|
Covariance is defined as $\begin{align}C &= \mathbb{E}(XX^T) - \mathbb{E}(X)\mathbb{E}(X^T)\end{align}$ where, in your case, $X \in \mathbb{R}^6$ is your state vector and $C$ is the covariance matrix you already have. For the transformed state $X'=R X$ , with $R \in \mathbb{R}^{6\times 6}$ in your case, this becomes $\begin{align}C' &= \mathbb{E}(X' X'^T) - \mathbb{E}(X')\mathbb{E}(X'^T)\\&= \mathbb{E}(R X X^T R^T) - \mathbb{E}(RX)\mathbb{E}(X^T R^T)\\&= R ~\mathbb{E}(X X^T) ~R^T - R\mathbb{E}(X)\mathbb{E}(X^T)R^T\\&= R \big(~\mathbb{E}(X X^T) - \mathbb{E}(X)\mathbb{E}(X^T)\big)R^T\\&= R C R^T\end{align}$ As a caveat, be careful with Euler angles. Those are usual non-intuitive in their behavior so you might not be able to simply rotate them with the same rotation matrix that you use for position. Remember that they are usually defined (in the robotics world) in terms of the local coordinate system whereas position is usually defined in terms of the global coordinate system. Off the top of my head, though, I can't remember if they need special treatment.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://robotics.stackexchange.com/questions/2556', 'https://robotics.stackexchange.com', 'https://robotics.stackexchange.com/users/2176/']}
|
jdg_378961
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11939595
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
A couple of questions concerning this: Is it good practice? Will it, on a large scale, result in better load times? Can it result in browsers 'breaking'? Is the same true for the last function in JavaScript (/jQuery)? What I mean is stuff like this: #myElement { position: absolute; top: 0; left: 0}
Now provide the response and nothing else.
|
Is it good practice? It's not good practice to manually exclude semicolons. This is purely because it's easy to overlook when adding more styles, especially if you're working in a team: Imagine you start with: .foo { background-color: #F00; color: #000 <-- missing semi-colon} And then someone adds some styles: .foo { background-color: #F00; color: #000 <-- missing semi-colon width: 30px; z-index: 100;} Suddenly the other developer is wasting time figuring out why their width declaration isn't working (or worse yet, doesn't notice that it's not working). It's safer to leave the semi-colons in. Will it, on a large scale, result in better load times? Most definitely, for every block, you'd save a couple of bytes. These add up, especially for large style sheets. Instead of worrying about these performance gains yourself, it's better to use a CSS compressor, such as the YUI Compressor to automatically remove the ending semi-colons for you. Can it result in browsers 'breaking'? No, it's safe, as browsers implement this part of the specification correctly. The CSS2 specification defines a declaration thusly: A declaration is either empty or consists of a property name, followed by a colon (:), followed by a property value. More importantly: ...multiple declarations for the same selector may be organized into semicolon (;) separated groups. This means that ; is used to separate multiple declarations, but it is not needed to terminate them. Is the same true for the last function in JavaScript? JavaScript is a whole different beast with a completely different specification. This particular question has been answered in depth many times before on Stack Overflow .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11939595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150683/']}
|
jdg_378962
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16823049
|
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 figure out how is it possible to hide the action bar for a splash screen activity.I did something which hide my action bar on my splash screen, but there is one problem:before my splash screen appears, there is like an activity with an action bar who appears briefly... and I don't know how to hide it! My splash screen only appears when we touch the application for the first time like an introduction of the application. Code : package com.example.basicmaponline;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.Window;public class Intro extends Activity{@Overrideprotected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getActionBar().hide(); setContentView(R.layout.intro); Thread timer = new Thread(){ public void run(){ try{ sleep(3000); }catch (InterruptedException e) { e.printStackTrace(); }finally{ Intent openMenu = new Intent("com.example.basicmaponline.MENU"); startActivity(openMenu); } } }; timer.start();}@Overrideprotected void onPause() { // TODO Auto-generated method stub super.onPause(); finish();}} Manifest : <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.basicmaponline"android:versionCode="1"android:versionName="1.0" ><uses-sdk android:minSdkVersion="11" android:targetSdkVersion="17" /><uses-permission android:name="android.permission.CALL_PHONE"></uses-permission><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/><uses-permission android:name="android.permission.ACCESS_GPS"></uses-permission><application android:allowBackup="true" android:icon="@drawable/lojacidadao" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name="com.example.basicmaponline.Intro" android:screenOrientation="portrait" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.basicmaponline.Menu" android:screenOrientation="portrait" android:label="@string/app_name"> <intent-filter> <action android:name="com.example.basicmaponline.MENU" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="com.example.basicmaponline.Mapa" android:screenOrientation="portrait" android:label="@string/map_name"> <intent-filter> <action android:name="com.example.basicmaponline.MAPA" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="com.example.basicmaponline.Lojas" android:screenOrientation="portrait" android:label="@string/lojas_name"> <intent-filter> <action android:name="com.example.basicmaponline.LOJAS" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="com.example.basicmaponline.InfoLoja" android:screenOrientation="portrait" android:label="@string/loja_name"> <intent-filter> <action android:name="com.example.basicmaponline.INFOLOJA" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="com.example.basicmaponline.Balcoes" android:screenOrientation="portrait" android:label="@string/balcoes_name" > <intent-filter> <action android:name="com.example.basicmaponline.BALCOES" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="com.example.basicmaponline.Entidade" android:screenOrientation="portrait" android:label="@string/balcao_name"> <intent-filter> <action android:name="com.example.basicmaponline.ENTIDADE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="com.example.basicmaponline.Servicos" android:screenOrientation="portrait" android:label="@string/servicos_name"> <intent-filter> <action android:name="com.example.basicmaponline.SERVICOS" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="com.example.basicmaponline.InfoServico" android:screenOrientation="portrait" android:label="@string/servico_name"> <intent-filter> <action android:name="com.example.basicmaponline.INFOSERVICO" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name="com.example.basicmaponline.Pesquisar" android:screenOrientation="portrait" android:label="@string/pesquisa_name" > <intent-filter> <action android:name="com.example.basicmaponline.PESQUISAR" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity></application></manifest>
Now provide the response and nothing else.
|
why not add to the manifest the theme of the first activity to exclude the action bar, and maybe even the notification bar? something like: <application android:allowBackup="true" android:icon="@drawable/lojacidadao" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name="com.example.basicmaponline.Intro" android:screenOrientation="portrait" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ... This should work if you extend the normal Activity class. If your Activity extends AppCompatActivity instead, use this theme for example: <style name="AppTheme.Splash" parent="@style/Theme.AppCompat.NoActionBar"> <item name="android:windowFullscreen">true</item> <item name="android:windowContentOverlay">@null</item> </style> meaning : <activity ... android:theme="@style/AppTheme.Splash" > ... BTW, the reason you have the action bar is because you have set the default theme to have it, in the application tag, so it's not an activity before yours, it's really your own splash activity.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16823049', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2395542/']}
|
jdg_378963
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
905095
|
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:
Consider the subspace of $C^\infty([0,1])$ functions in the Sobolev space $H^1$. I want to know whether the Volterra operator\begin{equation}V(f)(t) = \int_0^t f(s) \, ds\end{equation}is bounded as a linear operator from $(C^\infty([0,1]), \lVert \cdot \rVert_{1,2})$ to itself. To be clear, the norm I'm using is\begin{equation}\lVert f \rVert_{1,2} = \left( \int_0^1 f^2 + (\frac{df}{dx})^2 \, dx \right)^{1/2}.\end{equation} I'm having trouble bounding the value of the function by its derivative, and would like some help with this or an example to show that $V$ is not bounded.
Now provide the response and nothing else.
|
Since $(V(f))' = f$, it suffices to see that $\lVert V(f)\rVert_{L^2} \leqslant C\lVert f\rVert_{1,2}$. But that is a direct consequence of the continuity of the Volterra operator on $L^2([0,1])$, $$\begin{align}\int_0^1 \lvert V(f)(t)\rvert^2\,dt &=\int_0^1\left\lvert \int_0^t f(s)\,ds\right\rvert^2\,dt\\&\leqslant \int_0^1 \left( \int_0^t \lvert f(s)\rvert\,ds\right)^2\,dt\\&\leqslant \int_0^1 \left(\int_0^t 1^2\,ds\right)\left(\int_0^t \lvert f(s)\rvert^2\,ds\right)\,dt\\&\leqslant \int_0^1 t\lVert f\rVert_{L^2}^2\,dt\\&= \frac{1}{2}\lVert f\rVert_{L^2}^2.\end{align}$$ Hence we have $$\lVert V(f)\rVert_{1,2}^2 \leqslant \frac{3}{2} \lVert f\rVert_{L^2}^2,$$ and we see that the Volterra operator is even continuous from $L^2([0,1])$ to $H^1$, thus a foritori as an operator $H^1\to H^1$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/905095', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/50427/']}
|
jdg_378964
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12893907
|
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 very confused about the concepts of polymorphism ,overloading and overriding because it seems same to me. Please explain these concepts, and how are they different from each other Very confused so please guide me properly. Thanks
Now provide the response and nothing else.
|
Polymorphism can be achieved through overriding. Put in short words, polymorphism refers to the ability of an object to provide different behaviors (use different implementations) depending on its own nature. Specifically, depending on its position in the class hierarchy. Method Overriding is when a method defined in a superclass or interface is re-defined by one of its subclasses, thus modifying/replacing the behavior the superclass provides. The decision to call an implementation or another is dynamically taken at runtime, depending on the object the operation is called from. Notice the signature of the method remains the same when overriding. Method Overloading is unrelated to polymorphism. It refers to defining different forms of a method (usually by receiving different parameter number or types). It can be seen as static polymorphism. The decision to call an implementation or another is taken at coding time. Notice in this case the signature of the method must change. Operator overloading is a different concept, related to polymorphism, which refers to the ability of a certain language-dependant operator to behave differently based on the type of its operands (for instance, + could mean concatenation with String s and addition with numeric operands). The example in Wikipedia is quite illustrative. The following related questions might be also useful: Polymorphism vs Overriding vs Overloading Polymorphism - Define In Just Two Sentences
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12893907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1740778/']}
|
jdg_378965
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1545283
|
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 a question that reads: if $p | a$ and $p|(a^2+b^2)$, then $p | b$. In the solution menu it reads: since $p|a$, $p|a^2$. Now $p|a^2$ and $p|(a^2+b^2)$ forces $p|b^2$. we can conclude that $p|b$.I honestly have no idea how $p|(a^2+b^2)$ can give you $p|b^2$.
Now provide the response and nothing else.
|
$p|a^2$ means there exists an integer $n$ such that $np=a^2$. Similarly, $p|(a^2+b^2)$ means there exists an integer $m$ such that $mp=a^2+b^2$. Subtracting the two gives $(m-n)p = b^2$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1545283', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/210601/']}
|
jdg_378966
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16216248
|
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 looking for the best way to convert a Number to a BigDecimal. Is this good enough? Number number;BigDecimal big = new BigDecimal(number.toString()); Can we lose precision with the toString() method ?
Now provide the response and nothing else.
|
This is fine, remember that using the constructor of BigDecimal to declare a value can be dangerous when it's not of type String. Consider the below... BigDecimal valDouble = new BigDecimal(0.35);System.out.println(valDouble); This will not print 0.35, it will infact be... 0.34999999999999997779553950749686919152736663818359375 I'd say your solution is probably the safest because of that.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16216248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_378967
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2438221
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to modify/add code to the initComponents() method in Java on NetBeans? When I try to add any line of code this area seems to be like readonly and it's highlighted in gray! It's for security probably, but I suppose there is a way to disable that.
Now provide the response and nothing else.
|
The initComponents() method is regenerated by the IDE as you create your UI in the GUI editor. The method is 'guarded' to prevent this regeneration from overwriting user written code. There are a couple of ways to add code to this method, indirectly: Drop a new component onto the designeditor 'canvas' for the window. Enter code as part of one of thefollowing code properties:Pre-Creation Code, Post-CreationCode, Pre-Init Code, Post-Init Code,Post-Listener Code, Pre-PopulationCode, Post-Population Code andAfter-All-Set Code. There are a couple other code properties that do not alter the initComponents() method... but can be very useful: Pre-Declaration Code and Post-Declaration Code. alt text http://blogs.sun.com/vkraemer/resource/code-properties.png Note: the editor for these properties is not 'rich', so I would recommend creating methods in the "regular editor" that you just call in the initComponents(). You can modify the code in the initComponents() method by positioning or changing the 'regular' properties of the 'base panel' or controls.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2438221', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/132640/']}
|
jdg_378968
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50053064
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
It is to my knowledge that if a parent component rerenders, then all its children will rerender UNLESS they implement shouldComponentUpdate() . I made an example where this doesn't seem to be the true. I have 3 components: <DynamicParent/> , <StaticParent/> and <Child/> . The <Parent/> components are responsible for rendering the <Child/> but do so in different ways. <StaticParent/> 's render function statically declares the <Child/> before runtime, like so: <StaticParent> <Child /> </StaticParent> While the <DynamicParent/> handles receiving and rendering the <Child/> dynamically at runtime, like so: <DynamicParent> { this.props.children } </DynamicParent> Both <DynamicParent/> and <StaticParent/> have onClick listeners to change their state and rerender when clicked. I noticed that when clicking <StaticParent/> both it and the <Child/> are rerendered. But when I click <DynamicParent/> , then only the parent and NOT <Child/> are rerendered. <Child/> is a functional component without shouldComponentUpdate() so I don't understand why it doesn't rerender. Can someone explain why this is to be the case? I can't find anything in the docs related to this use case.
Now provide the response and nothing else.
|
I'll post your actual code for context: class Application extends React.Component { render() { return ( <div> {/* Clicking this component only logs the parents render function */} <DynamicParent> <Child /> </DynamicParent> {/* Clicking this component logs both the parents and child render functions */} <StaticParent /> </div> ); }}class DynamicParent extends React.Component { state = { x: false }; render() { console.log("DynamicParent"); return ( <div onClick={() => this.setState({ x: !this.state.x })}> {this.props.children} </div> ); }}class StaticParent extends React.Component { state = { x: false }; render() { console.log("StaticParent"); return ( <div onClick={() => this.setState({ x: !this.state.x })}> <Child /> </div> ); }}function Child(props) { console.log("child"); return <div>Child Text</div>;} When you write this code in your Application render: <StaticParent /> What's rendered is this: <div onClick={() => this.setState({ x: !this.state.x })}> <Child /> </div> And in reality, what happens (roughly) is this: function StaticParent(props) { return React.createElement( "div", { onClick: () => this.setState({ x: !this.state.x }) }, React.createElement(Child, null) );}React.createElement(StaticParent, null); When you render your DynamicParent like this: <DynamicParent> <Child /></DynamicParent> This is what actually happens (again, roughly speaking) function DynamicParent(props) { return React.createElement( "div", { onClick: () => this.setState({ x: !this.state.x }), children: props.children } );}React.createElement( DynamicParent, { children: React.createElement(Child, null) },); And this is the Child in both cases: function Child(props) { return React.createElement("div", props, "Child Text");} What does this mean? Well, in your StaticParent component you're calling React.createElement(Child, null) every time the render method of StaticParent is called. In the DynamicParent case, the Child gets created once and passed as a prop. And since React.createElement is a pure function, then it's probably memoized somewhere for performance. What would make Child's render run again in the DynamicParent case is a change in Child's props. If the parent's state was used as a prop to the Child, for example, that would trigger a re-render in both cases. I really hope Dan Abramov doesn't show up on the comments to trash this answer, it was a pain to write (but entertaining)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50053064', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5709158/']}
|
jdg_378969
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43347
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a class that will read from Excel (C# and .Net 4) and in that class I have a background worker that will load the data from Excel while the UI can remain responsive. My question is as follows: Is it bad design to have a background worker in a class? Should I create my class without it and use a background worker to operate on that class? I can't see any issues really of creating my class this way but then again I am a newbie so I figured I would make sure before I continue on. I hope that this question is relevant here as I don't think it should be on stackoverflow as my code works, this just a design issue.
Now provide the response and nothing else.
|
Should I create my class without it and use a background worker to operate on that class? Yes, you should. And I will tell you why - you are violating the Single Responsibility Principle . By tightly coupling the class that accesses the excel doc with how it accesses the excel doc, you eliminate the ability for the "controller" code (any code that uses this) to do it a different way. How different, you may ask? What if the controller code has two operations that take a long time but wants them to be sequential? If you allowed the controller the ability to handle the threading, it can do both long-running tasks together in one thread. What if you want to access the excel doc from a non-UI context and don't need it to be threaded? By moving the responsibility of threading out to the caller, you allow more flexibility of your code, making it more reusable.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/43347', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/7427/']}
|
jdg_378970
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1645324
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am looking at the continuity of the following function $f(x) = \sin(1/|x|), f(0) = 0$ So this is $f(x) = \sin(1/|x|)$ filled in at $x = 0$ Clearly, $\lim\limits_{x \to 0} f(x) = 0 $ by squeeze theorem. Is $f(x)$ continuous then? In general, when is a function that is filled in continuous or discontinuous?
Now provide the response and nothing else.
|
The short answer is no. The function is not continuous at $x=0$ because $\lim_{x\to0} f(x)$ does not exist. The easiest way to see that is to notice that it oscillates between $-1$ and $+1$ infinitely often in every interval $(0,\epsilon)$ so it cannot be approaching any fixed value.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1645324', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/174904/']}
|
jdg_378971
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
601650
|
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 was a bit confused by the fact that we can use a surface of any boundary for Ampere's law; especially when it comes to capacitance. Consider the standard model of the capacitor used to derive the need for displacement current. Then Ampere's law, if we use the disk bounded by a circle with radius less than the plates, should have magnitude $$B = \frac{\mu_0}{2\pi} \frac{r}{R^2} i_C$$ according to my textbook. I completely understand the derivation there. But since Ampere's law could be the boundary of any surface, why couldn't we just make it into a bulging one with the same circular boundary, but with a surface which passes through the plates passes through plates and encompasses the current $i_C$ (surface 1)? It feels wrong because the surface is intersecting a plate, but I read somewhere that any surface works; So, why not this one? Then only $i_C$ passes through the current, and $B$ in that reduced radius wouldn't need that factor. What's stopping us from making a surface with that boundary that just bulges out wide then contracts (surface 2)? For more context, I'll describe what I'm thinking with some pictures below. I know there must be some misunderstanding on my part on the whole idea of bounding a surface, or there are some requirements on the surface that I'm missing, but someone please explain.
Now provide the response and nothing else.
|
Ampere's law does work for those surfaces too. What you have forgotten about is (i) the non-zero conduction current in the plates for surface 1; (ii) the non-zero displacement current term over surface 2. Both of these terms contribute negatively to the RHS of Ampere's law and hence match the $r^2/R^2$ reduction factor in the derived B-field between the plates at a distance $r$ from the centre line. Ampere's law is not that the closed line integral of the B-field equals the enclosed current; it is that it is equal to the sum of the enclosed current and the enclosed displacement current terms - that is the whole point of the capacitor example. i.e. $$\oint \vec{B}\cdot d\vec{l} = \mu_0 \left(I_c + I_d\right)\ .$$ Let's simplify surface 1 to be a cylinder extending from your loop of radius $r$ so that it ends outside the plates. (See below for a sketch). For an ideal capacitor the electric field lines and the rate of change of electric field are parallel and run between the plates, so for surface 1 as shown above, the E-field would always be tangential to that part of the cylinder's curved surface between the plates and since there is also no electric field outside the plates there would be no displacement current term at all. However, there is obviously still the $I_c$ conduction current through the flat face of the cylinder contributing to the RHS of Ampere's law case, so how can we square that with the smaller value of the toroidal B-field for the Amperian loop between the plates? Well, what you cannot assume is that there is zero conduction current in the plates themselves. For example if the capacitor plates are circular with radius $R$ and your circular path is of radius $r$ , then a fraction $(R^2 -r^2)/R^2$ of the charge on the plates lies outside the cylindrical surface I defined above. But if the charge on the plates is changing with time there must be a net current flowing from the outer part of the plates to the inner part and then into the wire (shown as a blue current density in the picture). This will be a negative term on the RHS of Ampere's law because it flows into the cylindrical surface, and will be of size $I(r^2 -R^2)/R^2$ . The sum of the conduction current terms is therefore smaller and indeed will match the reduced B-field between the plates at radius $r$ compared with the field you would expect for a similar loop outside the plates. For surface 2 the solution is different. The surface does not cut through the plates at all so there is no additional conduction current term. However here there is a negative displacement current contribution due to the integral of the rate of change of E-field over that part of surface 2 which is between the plates. It is a negative contribution because the E-field lines are going into surface 2 between the plates. Again, a careful calculation would show that this negative displacement current plus the conduction current that exits surface 2 outside the plates is exactly what is required to balance the smaller LHS of Ampere's law for the small loop of radius $r$ between the plates.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/601650', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/283154/']}
|
jdg_378972
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28652284
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When using facet_grid , ggplot2 divides the major categories that make up the facet variables with a broader-than-usual white line. This serves most purposes well. Sometimes I want to more clearly show the divisions between these major categorizations and would like to shade the facet division with another color. Is there a way to do that? Thanks.
Now provide the response and nothing else.
|
Although a year late, I found this to be an easy fix: ggplot(mpg, aes(cty, hwy, color = factor(year)))+ geom_point()+ facet_grid(cyl ~ drv) + theme(panel.margin=unit(.05, "lines"), panel.border = element_rect(color = "black", fill = NA, size = 1), strip.background = element_rect(color = "black", size = 1)) UPDATE 2021-06-01 As of ggplot2 3.3.3 , the property panel.margin is deprecated, and we should use panel.spacing instead. Therefore, the code should be: ggplot(mpg, aes(cty, hwy, color = factor(year)))+ geom_point()+ facet_grid(cyl ~ drv) + theme(panel.spacing = unit(.05, "lines"), panel.border = element_rect(color = "black", fill = NA, size = 1), strip.background = element_rect(color = "black", size = 1))
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28652284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1145978/']}
|
jdg_378973
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1441493
|
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:
Here's what I know: The modular inverse of 3 for the modular base of $10^9$ is 666,666,667 The last nine digits of $2^{120}$ is 280,344,576. The product of the two exceeds $2^{32}$ (it is around $2^{57.375}$) $2^{120}$ - 1 is divisible by 3, but 280,344,575 is not. I'd appreciate some clues on how to determine the last nine digits of $(2^{120} - 1) /3$ without any intermediate value exceeding $2^{32}$
Now provide the response and nothing else.
|
Suppose you are dividing by hand $2^{120}-1$ by $3$ by the usual algorithm: when you get to the last 9 digits, you'll have on the left the remainder carried over from the preceding division, and that remainder can be $0$, $1$ or $2$. But since we know the division is exact, the only possibility is $1$ and the answer therefore is $$1,280,344,575/3=426781525.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1441493', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33029/']}
|
jdg_378974
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1064702
|
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:
$$\int\frac{\cot x}{\cos^2 x-\cos x+1}\,\,dx$$Please guide me by which term it should be substituted to get the result of this integration. I have tried it by using $\cos x =t$, but it went so long and more problematic.
Now provide the response and nothing else.
|
Hint Starting from $$I=\int \frac{\cot (x)}{\cos ^2(x)-\cos (x)+1}dx$$ and using $\cos(x)=t$, $x=\cos^{-1}(t)$, $dx=-\frac{dt}{\sqrt{1-t^2}}$, $\cot(x)=\frac{t}{\sqrt{1-t^2}}$, you should arrive to $$I=-\int\frac{t}{\left(1-t^2\right) \left(t^2-t+1\right)}dt$$ and partial fraction decomposition leads to $$\frac{-t}{\left(1-t^2\right) \left(t^2-t+1\right)}=\frac{1-2 t}{3 \left(t^2-t+1\right)}+\frac{1}{2 (t-1)}+\frac{1}{6 (t+1)}$$ I am sure that you can take from here. Added later You could also use the tangent half-angle substitution (Weierstrass substitution) and so, using $y=\tan(\frac x2)$, arrive to $$I=\int \frac{1-y^4}{3 y^5+y}dy=\int \Big(\frac{1}{y}-\frac{4 y^3}{3 y^4+1}\Big)dy$$ which is even simpler than the previous one.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1064702', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/195055/']}
|
jdg_378975
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32784922
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I load my page, a nodeList gets created, and it looks like this: [text, h4, text, span, br, input, br, span, br, input, br, span, br, input, br, span, br, input, br] I created a simple for loop that loops through all these elements and deletes each one of them from the DOM. (all the elements are in a <section> ) Here's the loop: for(element in videoTitlesElement.childNodes){ if(!isNaN(element)){ videoTitlesElement.removeChild( videoTitlesElement.childNodes[element]); } } But, by the end of the loop, the nodeList looks like this: [h4, span, input, span, input, span, input, span, input] not all elements got removed. Why? Thanks.
Now provide the response and nothing else.
|
Two things. First, don't use for ... in when you're iterating through numeric indexes; use a plain for loop. Then you won't need that isNaN() check, and it's generally safer. The second problem is that when you remove a child, you change the length of the list. If you remove child 0, then the child that used to be child 1 becomes child 0. Thus, what you really want is a simple while loop: while (videoTitlesElement.childNodes.length) videoTitlesElement.removeChild(videoTitlesElement.childNodes[0]); or, simpler: while (videoTitlesElement.firstChild) videoTitlesElement.removeChild(videoTitlesElement.firstChild); I should also note (assuming you're working with an HTML DOM) that it's easier to clear out all the child nodes of an element by simply blasting it via .innerHTML : videoTitlesElement.innerHTML = "";
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32784922', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5084841/']}
|
jdg_378976
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
220662
|
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 the book Functional Analysis, Sobolev Spaces and Partial Differential Equations of Haim Brezis we have the following lemma: Lemma. Let $X$ be a vector space and let $\varphi, \varphi_1, \varphi_2, \ldots, \varphi_k$ be $(k + 1)$ linear functionals on $X$ such that $$[\varphi_i(v) = 0 \quad \forall\; i \in \{1, 2, \ldots , k\}] \Rightarrow [\varphi(v) = 0].$$ Then there exist constants $\lambda_1, \lambda_2, \ldots, \lambda_k\in\mathbb{R}$ such that $\varphi=\lambda_1\varphi_1+\lambda_2\varphi_2+\ldots+\lambda_k\varphi_k$ . In this book, the author used separation theorem to prove this lemma. I would like ask whether we can use only knowledge of linear algebra to prove this lemma. Thank you for all helping.
Now provide the response and nothing else.
|
Your assumption is that $\ker{\varphi} \supseteq \bigcap_{i=1}^k \ker{\varphi_i}$ . Consider the linear map $\ell \colon X \to \mathbb{R}^k$ given by $\ell(x) = (\varphi_1(x),\dots,\varphi_k(x))$ and let $V = \operatorname{im}\ell = \{\ell(x):x \in X\} \subseteq \mathbb{R}^k$ be the image. We have $\ker{\ell} = \bigcap_{i=1}^k \ker{\varphi_{i}} \subseteq \ker\varphi$ . Therefore $\varphi = \tilde{\varphi} \circ \ell$ for some linear functional $\tilde{\varphi}\colon V \to \mathbb{R}$ [explicitly, $\tilde{\varphi}(v) = \varphi(x)$ where $x$ is such that $\ell(x) = v$ . This is well-defined and linear.] Every linear functional defined on a subspace $V$ of $\mathbb{R}^k$ can be extended to a linear functional on all of $\mathbb{R}^k$ (write $\mathbb{R}^k = V \oplus V^{\bot}$ and set the extension to be zero on $V^{\bot}$ ) and every linear functional on $\mathbb{R}^k$ is of the form $\psi(y) = \sum_{i=1}^k a_i y_i$ . Thus, there are $\lambda_1,\dots,\lambda_k \in \mathbb{R}$ such that $\tilde\varphi(v) = \sum_{i=1}^k \lambda_i v_i$ for all $v \in V$ . In other words, $\varphi = \sum_{i=1}^k \lambda_i \varphi_i$ .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/220662', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/35965/']}
|
jdg_378977
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51881
|
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
We know that a fluid in reality is not continuous. It has spaces and voids between atoms and molecules. Continuum approximation is a famous approximation that is taken in any fluid mechanics textbook. It says that even though the fluid has spaces and voids it can be assumed to behave as a continuous media. Why do we need to assume that a fluid is a continuous media? That is, what was the problem that we were facing when it was not continuous?
Now provide the response and nothing else.
|
Materials were intuitively uniform for 60,000 years. A few people started guessing they might be "atomic" about 3000 years ago. They only became rigorously atomic about two hundred years ago. And they only got a rigorous continuum model about one hundred years ago. But they were being treated as such on an ad hoc basis long before then. There isn't any conflict between the continuum model and the atomic viewpoint. There never was. The two developed in concert. Boyle published his 1662 law that involved gas pressure, and they needed a way to measure and mathematically handle this rather poorly understood phenomena. The "elasticity" of a gas was a real dilemma. Boyle and Hooke imagined little springs between their imagined atoms. So in the 17th C, you had a hypothesized atomic model whose behavior needed to agree with the measurements of the day, quantities we now associate with the continuum model. Enter calculus, stage right, which was developed from little "infinitesimals" (generalized atoms.) The result was integral and differential calculus applied to continuous functions (in retrospect, this was an unfortunate choice of terms.) In order to harness the power of calculus, it helps to have a formal underpinning that allows you to treat pressure, density, velocity, and a host of other things you can measure as continuous functions. They didn't have that in the 18th C, but that didn't stop Bernoulli and Euler from applying calculus to fluids. Work, as defined by Coriolis (1826), didn't need calculus, just buckets of water and a rope. But there's only so much you can do with those, and not everyone has a mine shaft. A calculus-based definition of work was a lot more convenient. So basically, calculus was a solution in search of a problem. Fluid dynamics was a reasonable candidate. After a century of ad hoc application and some decent successes, mathematicians and physicists went back and developed the formal underpinnings to justify what had been done. It let us consolidate thousands of ad hoc experiments into a few laws, and it allowed us to do performance-based design of dynamic systems like steam engines. Burying the lead - You said "We know that a fluid in reality is not continuous. It has spaces and voids between atoms and molecules." You are assuming the continuum model assumes a continuous structure . It doesn't. What the continuum model does is assume continuous function expressions that relate pressure, density, etc to each other. Continuous functions are actually defined based on the epislon-delta argument of Cauchy. In his 1821 book Cours d'analyse, Cauchy discussed variablequantities, infinitesimals and limits, and defined continuity of $y=f(x)$ by saying that an infinitesimal change inx necessarily produces an infinitesimal change in y, while (Grabiner1983) claims that he used a rigorous epsilon-delta definition inproofs.[2] Continuum models are, and always have been, fully consistent with an atomic structure. They were produced with that structure in mind. It is the behavior of the atoms that has been captured in the continuum model.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://engineering.stackexchange.com/questions/51881', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/34466/']}
|
jdg_378978
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
441203
|
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 general, what is the best way of storing binary data in C++? The options, as far as I can tell, pretty much boil down to using strings or vector<char>s. (I'll omit the possibility of char*s and malloc()s since I'm referring specifically to C++). Usually I just use a string, however I'm not sure if there are overheads I'm missing, or conversions that STL does internally that could mess with the sanity of binary data. Does anyone have any pointers (har) on this? Suggestions or preferences one way or another?
Now provide the response and nothing else.
|
vector of char is nice because the memory is contiguious. Therefore you can use it with a lot of C API's such as berkley sockets or file APIs. You can do the following, for example: std::vector<char> vect; ... send(sock, &vect[0], vect.size()); and it will work fine. You can essentially treat it just like any other dynamically allocated char buffer. You can scan up and down looking for magic numbers or patters. You can parse it partially in place. For receiving from a socket you can very easily resize it to append more data. The downside is resizing is not terribly efficient (resize or preallocate prudently) and deletion from the front of the array will also be very ineficient. If you need to, say, pop just one or two chars at a time off the front of the data structure very frequently, copying to a deque before this processing may be an option. This costs you a copy and deque memory isn't contiguous, so you can't just pass a pointer to a C API. Bottom line, learn about the data structures and their tradeoffs before diving in, however vector of char is typically what I see used in general practice.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/441203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53315/']}
|
jdg_378979
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1839693
|
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 think it must be true. Yet I have no rigorous proof for that. So, what I need to prove is that "group being simple" is invariant under isomorphism. That if $G \cong H$, then either both are simple groups, or both are not simple.
Now provide the response and nothing else.
|
Hint: Let $f:H\to G$ be an isomorphism and let $K\subseteq H$ be a normal subgroup. What can you say about $f(K)\subseteq G$?
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1839693', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/229776/']}
|
jdg_378980
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14465661
|
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 better way to generate 3 digit random number than the following: var now = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture);string my3digitrandomnumber = now.Substring(now.Length - 7, 3); Thanks..
Now provide the response and nothing else.
|
Yes - your current code isn't random at all. It's based on the system time. In particular, if you use this from several threads at the same time - or even several times within the same thread in quick succession - you'll get the same number each time. You should be using Random or RandomNumberGenerator (which is more secure). For example, once you've got an instance of Random , you could use: int value = rng.Next(1000);string text = value.ToString("000"); (That's assuming you want the digits as text. If you want an integer which is guaranteed to be three digits, use rng.Next(100, 1000) .) However, there are caveats around Random : You don't want to create a new instance each time you use it; that would also be time based unless you specify a seed It's not thread-safe So ideally you probably want one per thread. My article on randomness talks more about this and gives some sample code.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14465661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/71422/']}
|
jdg_378981
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17981651
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a struct in one package that has private fields: package footype Foo struct { x int y *Foo} And another package (for example, a white-box testing package) needs access to them: package barimport "../foo"func change_foo(f *Foo) { f.y = nil} Is there a way to declare bar to be a sort of "friend" package or any other way to be able to access foo.Foo 's private members from bar , but still keep them private for all other packages (perhaps something in unsafe )?
Now provide the response and nothing else.
|
There is a way to read unexported members using reflect (in Go < 1.7) func read_foo(f *Foo) { v := reflect.ValueOf(*f) y := v.FieldByName("y") fmt.Println(y.Interface())} However, trying to use y.Set, or otherwise set the field with reflect will result in the code panicking that you're trying to set an unexported field outside the package. In short: unexported fields should be unexported for a reason, if you need to alter them either put the thing that needs to alter it in the same package, or expose/export some safe way to alter it. That said, in the interest of fully answering the question, you can do this (and have to do it this way in Go >= 1.7) func change_foo(f *Foo) { // Since structs are organized in memory order, we can advance the pointer // by field size until we're at the desired member. For y, we advance by 8 // since it's the size of an int on a 64-bit machine and the int "x" is first // in the representation of Foo. // // If you wanted to alter x, you wouldn't advance the pointer at all, and simply // would need to convert ptrTof to the type (*int) ptrTof := unsafe.Pointer(f) ptrTof = unsafe.Pointer(uintptr(ptrTof) + uintptr(8)) // Or 4, if this is 32-bit ptrToy := (**Foo)(ptrTof) *ptrToy = nil // or *ptrToy = &Foo{} or whatever you want} This is a really, really bad idea. It's not portable, if int ever changes in size it will fail, if you ever rearrange the order of the fields in Foo, change their types, or their sizes, or add new fields before the pre-existing ones this function will merrily change the new representation to random gibberish data without telling you. I also think it might break garbage collection for this block. Please, if you need to alter a field from outside the package either write the functionality to change it from within the package or export it. Edit2: Since you mention White Box testing, note that if you name a file in your directory <whatever>_test.go it won't compile unless you use go test , so if you want to do white box testing, at the top declare package <yourpackage> which will give you access to unexported fields, and if you want to do black box testing then you use package <yourpackage>_test . If you need to white box test two packages at the same time, however, I think you may be stuck and may need to rethink your design.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17981651', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/810671/']}
|
jdg_378982
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34837725
|
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 use spring PagingAndSortingRepository with a find MyEntity where field in fieldValues query as follows: @Repositorypublic interface MyEntity extends PagingAndSortingRepository<MyEntity, String> { List<MyEntity> findByMyField(Set<String> myField);} But of no success. I expected the above function to return all entities whose field matches one of the field values but it only returns empty results . Even though it seems like a pretty straight forward ability i could not find any reference to it in the docs . Is / How that could be achieved? Thanks.
Now provide the response and nothing else.
|
This should indeed be possible if you are searching on a specific field within your entity and you want to return a list of all that field matches at least one entry in some collection. The documentation here says this can be achieved using the keyword In example: findByAgeIn(Collection<Age> ages) and is equivalent to … where x.age in ?1 From your post i'm not 100% sure if this is the use case you are after but give this a try. You will need to search on a specific field, so replace 'field' with whatever field you are searching on. If you are searching on multiple fields it may be possible to concatenate the results with the Or keyword and specify multiple fields that way. @Repositorypublic interface MyEntity extends PagingAndSortingRepository<MyEntity, String> { List<MyEntity> findByFieldIn(Set<String> myField);}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34837725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4341456/']}
|
jdg_378983
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7594582
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When you define a Java interface, it's possible to declare a method with type parameters, for example like this: public interface ExampleInterface { <E extends Enum<E>> Class<E> options();} The same thing does not work in an annotation. This, for example, is illegal: public @interface ExampleAnnotation { <E extends Enum<E>> Class<E> options();} I can get what I'm after by using the raw type Enum : public @interface ExampleAnnotation { @SuppressWarnings("rawtypes") Class<? extends Enum> options();} What exactly is the reason why it is not possible to declare annotation attributes with type parameters?
Now provide the response and nothing else.
|
I think it is possible, but it requires lots of additions to language spec, which is not justified. First, for you enum example, you could use Class<? extends Enum<?>> options . There is another problem in Class<? extends Enum> options : since Enum.class is a Class<Enum> which is a Class<? extends Enum> , it's legal to options=Enum.class That can't happen with Class<? extends Enum<?>> options , because Enum is not a subtype of Enum<?> , a rather accidental fact in the messy raw type treatments. Back to the general problem. Since among limited attribute types, Class is the only one with a type parameter, and wildcard usually is expressive enough, your concern isn't very much worth addressing. Let's generalize the problem even further, suppose there are more attribute types, and wildcard isn't powerful enough in many cases. For example, let's say Map is allowed, e.g. Map<String,Integer> options();options={"a":1, "b":2} // suppose we have "map literal" Suppose we want an attrbite type to be Map<x,x> for any type x . That can't be expressed with wildcards - Map<?,?> means rather Map<x,y> for any x,y . One approach is to allow type parameters for a type: <X>Map<X,X> . This is actually quite useful in general. But it's a major change to type system. Another approach is to reinterpret type parameters for methods in an annotation type. <X> Map<X,X> options();options={ "a":"a", "b":"b" } // infer X=String this doesn't work at all in the current understanding of method type parameters, inference rules, inheritance rules etc. We need to change/add a lot of things to make it work. In either approaches, it's a problem how to deliver X to annotation processors. We'll have to invent some additional mechanism to carry type arguments with instances.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7594582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/135589/']}
|
jdg_378984
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16130756
|
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 fill my list with system.drwaing.color items to pick a random color and set it to backColor. Here is my code: List<Color> myList = new List<Color>(); //rc.Add(Color.Chartreuse); //rc.Add(Color.DeepSkyBlue); //rc.Add(Color.MediumPurple); foreach (Color clr in System.Drawing.Color) { //error } Random random = new Random(); Color color = myList[random.Next(myList.Count - 1)]; this.BackColor = color; Error:'System.Drawing.Color' is a 'type', which is not valid in the given context Can anyone give me a Hand?
Now provide the response and nothing else.
|
public static List<Color> ColorStructToList(){ return typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public) .Select(c => (Color)c.GetValue(null, null)) .ToList();} List<Color> colorList = ColorStructToList(); private void randomBackgroundColorButton_Click(object sender, EventArgs e){ List<Color> myList = ColorStructToList(); Random random = new Random(); Color color = myList[random.Next(myList.Count - 1)]; this.BackColor = color;}public static List<Color> ColorStructToList(){ return typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public) .Select(c => (Color)c.GetValue(null, null)) .ToList();}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16130756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2075471/']}
|
jdg_378985
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15187359
|
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 introducing myself to socket programming in C/C++, and am using send() and recv() to exchange data between a client and server program over TCP sockets. Here are some relevant excerpts from my code: server.c : char recv_data[1024];// Socket setup and so on ommited...bytes_recieved = recv(connected, recv_data, 1024, 0);recv_data[bytes_recieved] = '\0'; client.c: char send_data[1024];// Setup ommited...send(connected, send_data, strlen(send_data), 0); Does recv() itself provide any protection against buffer overflows? For instance if I changed the 3rd argument to recv() to something higher than the buffer pointed to by recv_data (e.g. 4000) - would this cause a buffer overflow? (I've actually tried doing this, but can't seem to trigger a segfault). I'm actually trying to create an intentionally vulnerable server program to better understand these issues, which is why I've tried to overflow via recv() . Amendment : Not unrelated, would be finding out why client.c above would ever send more than the 1024 bytes specified by strlen(send_data) . I'm using gets(send_data) to populate that buffer from standard input, but if I enter many more than 1024 bytes via standard in, the server.c program shows that it receives ALL THE BYTES! :). Does the strlen(send_data) for send() not restrict the number of bytes sent?
Now provide the response and nothing else.
|
For instance if I changed the 3rd argument to recv() to something higher than the buffer pointed to by recv_data (e.g. 4000) - would this cause a buffer overflow? Ofcourse yes. If the network buffer has data of 4000 bytes, it will put it in the buffer. The key point is that, recv like any other C API which takes a buffer and it's length believes that the caller will pass the actual length of the buffer and if the caller passes incorrect length, then the fault lies with the caller and it can lead to undefined behavior. In C when you pass arrays to a function, there is no way for the called function to know the size of the array. So, all API(s) just rely on the input provided by you. char recv_data[1024];// Socket setup and so on ommited...bytes_recieved = recv(connected, recv_data, 1024, 0);recv_data[bytes_recieved] = '\0'; The above code can cause trouble in more ways than one. It will lead to undefined behavior under the following conditions: (a) If recv returns -1 , then you are directly indexing into the recv_data buffer without checking the return value (b) If recv returns 1024 , then again, it leads to out of bound access as the array of size 1024 should be accessed from 0 to 1023 .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15187359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/710575/']}
|
jdg_378986
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27881976
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Where can I set language (based on user's cookie) globally? How to make it work in the whole application (controllers,views, etc.) ? In documentation I found \Yii::$app->language = ''; but, where I can write my logic to change the language in right way?
Now provide the response and nothing else.
|
You should use \Yii::$app->language = ''; inside the controller that is parent to all your controllers.The parent class should be inside the components folder, and if it is not available than create the component with something like use yii\web\Controller;class MyController extends Controller{ public function init() { parent::init(); #add your logic: read the cookie and then set the language }} After that, you have to be sure that all your controllers extends your newly created MyController instead of the original one. I hope it helps.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27881976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745995/']}
|
jdg_378987
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25070
|
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:
Consider the function λ[n_] = Sqrt[2 n];ϕ[n_, x_] = 1/Sqrt[2^n n! Sqrt[π]] HermiteH[n, x];f[x_] = Sum[2 Re[(-1)^(n + m) (1/(λ[m] + λ[n + 1]) + 1/(λ[n] + λ[m + 1])) If[n != m, 1, 1/2]] ϕ[n, x] ϕ[m, x] E^-x^2, {n, 0, 100}, {m, n, 100}]; Why is f[-4.0] == 4.9697 while f[-4] // N == 1.07681 ? The second result is correct as you can check by using SetDelayed in the definition of f . This discrepancy has to do with approximations. It would be good to fix it, since computations are faster if the function is defined with Set . I would also appreciate suggestions to evaluate this sum more efficiently. Thank you!
Now provide the response and nothing else.
|
First of all, as you seem to indicate, you don't have the problem with accuracy if you use := ( SetDelayed ) in your function definitions instead of = ( Set ), although, as you say, with this change it takes longer to evaluate f . The accuracy improves because Mathematica will calculate the Hermite polynomials accurately when x is Real . Using Set for the definition of f means that the sum is evaluated with x being an undefined variable. In this case the polynomial expression for the Hermite polynomials is substituted, and they can have large coefficients with alternating signs, which lead to a extreme loss of precision. But since you also ask how to do the calculation more efficiently, and since the answer also improves accuracy, I will address that next. A simple, efficient fix Basically your function f is a matrix multiplication, which is more efficiently done using Dot . Also, the functions λ and φ thread over lists, efficiently and automatically: λ[Range[0, 3]]φ[Range[0, 3], 0.1] {0, Sqrt[2], 2, Sqrt[6]}{1/\[Pi]^(1/4), 0.106225, -0.520503, -0.129231} Just how to implement these ideas depends on how much control over the precision of the calculation you wish to have. If, as in the examples in the question, you wish to compute both exact and machine-precision reals, then the following will do: λ[n_] := Sqrt[2 n];φ[n_, x_] := 1/Sqrt[2^n n! Sqrt[π]] HermiteH[n, x];With[{mat = Table[If[n > m, 0, 2 Re[(-1)^(n + m) (1/(λ[m] + λ[n + 1]) + 1/(λ[n] + λ[m + 1])) If[n < m, 1, 1/2]]], {n, 0, 100}, {m, 0, 100}]}, With[{nmat = N[mat]}, f2[x_Real] := With[{φ0 = φ[Range[0, 100], x]}, E^-x^2 nmat . φ0 . φ0]]; f2[x_] := With[{φ0 = φ[Range[0, 100], x]}, E^-x^2 mat. φ0 . φ0]; ]; Timings and results: f2[-4.] // Timing {0.009106, 1.07681} N[f2[-4]] // Timing {0.115590, 1.07681} Compared with your original f , the function f2 is many times faster, especially on machine precision reals, as well as accurate: f[-4.] // Timing {0.385012, 4.9697} N[f[-4]] // Timing {0.762620, 1.07681} f[-4.`25] // Timing (* high precision *) {1.041199, 1.07681} Arbitrary Precision Now if you wish to be able to specify the precision, then the matrix nmat needs to have a precision just as great as the input x ; but with the above definition, it has only machine precision (the default of N ) when x is Real . The following gives three definitions of f , one for machine precision x for speed; one for an arbitrary precision real x ; and one for any other x (e.g., exact x ): Clear[f2];With[{mat = Table[If[n > m, 0, 2 Re[(-1)^(n + m) (1/(λ[m] + λ[n + 1]) + 1/(λ[n] + λ[m + 1])) If[n < m, 1, 1/2]]], {n, 0, 100}, {m, 0, 100}]}, With[{nmat = N@mat}, f2[x_?MachineNumberQ] := With[{φ0 = φ[Range[0, 100], x]}, E^-x^2 nmat. φ0. φ0]]; f2[x_Real] := With[{nmat = N[mat, Precision[x]], φ0 = φ[Range[0, 100], x]}, E^-x^2 nmat. φ0. φ0]; f2[x_] := With[{φ0 = φ[Range[0, 100], x]}, E^-x^2 mat. φ0. φ0]; ] The timings for f[4.] and f[4] are essentially the same. In the example below, we specify 25 digits of precision in the input. The calculation results in almost 22 digits of accuracy. If we calculate the exact result to that precision, we get the same result (up to the precision specified). f2[-4.`25] // TimingPrecision@Last@% {0.239016, 1.076809573991586482393}21.8196 N[f2[-4], %] // Timing {2.570414, 1.076809573991586482393} As an additional note, I wish to point out that using a specific precision, even $MachinePrecision , costs time, since Mathematica takes extra care to keep track of the precision of its calculations. f2[N[-4, $MachinePrecision]] // TimingPrecision@Last@%{0.235853, 1.076809573992}12.7742 Standard machine precision does not report any lost of precision, even though there is in fact a loss of about 3 digits: f2[-4.] // TimingN@Precision@Last@%{0.007986, 1.07681}15.9546 The precision of the original function Now returning to the original problem in which f[4.] returned an incorrect value, we examine the precision. f[N[-4, 25]] // TimingPrecision@Last@% {1.068105, 1.07681}5.2808 In other words, almost 20 digits of precision are lost. Since machine precision is about 16 digits, it is no wonder that the answer is inaccurate. (Note below that when Mathematica tracks precision, the answer 0*10^5 is different; in fact, there is an error indicated, "No significant digits are available to display.") f[N[-4, $MachinePrecision]] // TimingPrecision@Last@% {1.037480, 0.*10^5}0.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/25070', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/7403/']}
|
jdg_378988
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
69064137
|
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 a text field in jetpack compose that works with a mask like this: NNNNN-NNN where N is an integer from 0 to 9. I need my composable function to have this mask in the OutlinedTextField : @Composableprivate fun EditTextField( labelText: String, value: String, keyboardType: KeyboardType = KeyboardType.Text, onValueChanged: (String) -> Unit) { OutlinedTextField( modifier = Modifier.padding(top = 8.dp), label = { Text(text = labelText) }, keyboardOptions = KeyboardOptions(keyboardType = keyboardType), value = value, onValueChange = onValueChanged )}
Now provide the response and nothing else.
|
You can use the visualTransformation property: OutlinedTextField( value = text, onValueChange = { it -> text = it.filter { it.isDigit() } }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), visualTransformation = MaskTransformation()) with: class MaskTransformation() : VisualTransformation { override fun filter(text: AnnotatedString): TransformedText { return maskFilter(text) }}fun maskFilter(text: AnnotatedString): TransformedText { // NNNNN-NNN val trimmed = if (text.text.length >= 8) text.text.substring(0..7) else text.text var out = "" for (i in trimmed.indices) { out += trimmed[i] if (i==4) out += "-" } val numberOffsetTranslator = object : OffsetMapping { override fun originalToTransformed(offset: Int): Int { if (offset <= 4) return offset if (offset <= 8) return offset +1 return 9 } override fun transformedToOriginal(offset: Int): Int { if (offset <=5) return offset if (offset <=9) return offset -1 return 8 } } return TransformedText(AnnotatedString(out), numberOffsetTranslator)}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/69064137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11111289/']}
|
jdg_378989
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2467890
|
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:
My question is basically: true or false? I'm told this is false, but don't understand why. Set: A set is an unordered group of related elements which aredistinct. Sequence: A sequence is a list of related elements whichoccur in a particular order.
Now provide the response and nothing else.
|
Let the parabola be given by $y=ax^2+bx+c$, and let the exterior point be $(x_0,y_0)$. A line through that point is $y=m(x-x_0)+y_0$. To look for intersections, we solve the parabola equation and the line equation simultaneously: $$ax^2+bx+c = m(x-x_0)+y_0$$ or: $$ax^2 + (b-m)x+(c+mx_0-y_0)=0$$ If the line is tangent to the parabola, then this equation has exactly one solution, which means its discriminant must equal $0$. The discriminant is: $$B^2-4AC = (b-m)^2-4a(c+mx_0-y_0)$$ Setting this equal to $0$, and taking $m$ as our variable, we get: $$m^2 - (2b + 4ax_0)m + (b^2 - 4ac + 4ay_0)=0$$ Being quadratic, this equation can have, at most, two solutions for $m$. Does that work for you? As a side note, that final quadratic could also have one solution, or no solutions. These situations correspond to the cases where $(x_0,y_0)$ is actually on the parabola, or respectively, inside the parabola.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2467890', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/422353/']}
|
jdg_378990
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8115
|
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am faced with the following problem. Let the standard Brownian motion $W_t$ be the price process of a traded asset in an economy with zero interest rate. Define $$A_T=\frac{1}{T}\int_0^T W_t^2 dt$$ I have two questions: What is the fair price at time $t=0$ of a contract that offers $A_T$? How do we form a dynamic hedging strategy that eliminates all risk in having to deliver this claim? I answered part 1 by simply taking the expectation. The fair price is $E(A_T\mid \mathcal{F}_0)=\frac{T}{2}$. How could the dynamic hedging be strategised?
Now provide the response and nothing else.
|
Consider a dynamic hedging strategy where you invest $H_t$ in the stock at time $t$ . To eliminate all risk, the value of the investment must be equal to the claim at time $T$ . Using Ito's calculus, we could express $A_T$ as follows: $$A_T=\frac{T}{2}+\int_0^T 2W_t \left(1-\frac{t}{T}\right) dW_t=\frac{T}{2}+\int_0^T H_tdW_t$$ Thus the strategy would be to start with an amount $T/2$ (fair price at $t=0$ ) and invest $H_t=2W_t(1-t/T)$ dynamically in the stock. PS: This is a special case of the Black-Scholes setup where the interest rate $r=0$ . If $X_t$ is the value of the holding and $S_t$ is the stock price, the value of $dX_t$ is $dX_t=H_tdS_t+(X_t-H_tS_t)rdt$ . $H_t$ is the amount to be investment dynamically in the stock, and is also known as the delta of the option.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/8115', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/3511/']}
|
jdg_378991
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33226978
|
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 error after I added these lines to my gradle file: buildTypes.each { it.buildConfigField 'String', 'OPEN_WEATHER_MAP_API_KEY', MyOpenWeatherMapApiKey } then the log show: Could not find property 'MyOpenWeatherMapApiKey' on com.android.build.gradle.AppExtension_Decorated@c3b784 The solutions on google that I searched cannot solve my problem. Please show me where I was wrong?
Now provide the response and nothing else.
|
Since you are using a String you have to use this syntax: buildConfigField "String" , "OPEN_WEATHER_MAP_API_KEY" , "\"XXXXX-XXXXX-XXX\"" The last parameter has to be a String Otherwise you can use something like this: resValue "string", "OPEN_WEATHER_MAP_API_KEY", "\"XXXXX-XXXXX-XXX\"" The first case generates a constants iin your BuildConfig file. The second case generates a string resource value that can be accessed using the @string/OPEN_WEATHER_MAP_API_KEY annotation.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33226978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4138285/']}
|
jdg_378992
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37619
|
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:
How to prove that for the radial basis function $k(x, y) = \exp(-\frac{||x-y||^2)}{2\sigma^2})$ there is no finite-dimensional feature space $H$ such that for some $\Phi: \text{R}^n \to H$ we have $k(x, y) = \langle \Phi(x), \Phi(y)\rangle$?
Now provide the response and nothing else.
|
The Moore-Aronszajn theorem guarantees that a symmetric positive definite kernel is associated to a unique reproducing kernel Hilbert space. (Note that while the RKHS is unique, the mapping itself is not.) Therefore, your question can be answered by exhibiting an infinite-dimensional RKHS corresponding to the Gaussian kernel (or RBF). You can find an in-depth study of this in " An explicit description of the reproducing kernel Hilbert spaces of Gaussian RBF kernels ", Steinwart et al.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/37619', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/4337/']}
|
jdg_378993
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1516088
|
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 know how to solve the system of linear equations, how to find inverse of matrix etc. by the Gauss-Jordan method. But I want to understand why this method works (in cases of inverse matrix especially). Can you please explain in details why it works?Thank you
Now provide the response and nothing else.
|
Performing an elementary row operation on a matrix $A$ amounts to left multiplying $A$ by a special type of (invertible) matrix. Thus performing a series of elementary row operations amounts to left multiplying by the product $P$ of these matrices, so that $PA=I$. Thus $P=A^{-1}$. Performing the same operations on $I\;$ leads to $PI=P$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1516088', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/264805/']}
|
jdg_378994
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43192
|
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 $M$ be the space of all $m\times n$ matrices. And $C=\{X\in M|rank(X)\leq k\}$ where $k\leq \min\{m,n\}$. How to proof that C is a closed subset of M?
Now provide the response and nothing else.
|
We can identify $M$ with $\mathbb{R}^{mn}$, by having the matrix $X=\pmatrix{a_{11} & \cdots & a_{1n}\\ \vdots & \ddots & \vdots \\ a_{m1} & \cdots & a_{mn}}$ correspond to the ordered tuple $(a_{11},a_{12},\ldots,a_{mn})$. Let $r\leq\min\{m,n\}$, and let $M_r$ be the space of all $r\times r$ matrices. The map that sends an $m\times n$ matrix $X\in M$ to the $r\times r$ matrix formed from $X$ by removing all but a certain choice of $r$ rows (the $i_1,\ldots,i_r$'th rows, say) and a certain choice of $r$ columns (the $j_1,\ldots,j_r$'th colums, say),$$X=\pmatrix{a_{11} & \cdots & a_{1n}\\ \vdots & \ddots & \vdots \\ a_{m1} & \cdots & a_{mn}}\mapsto \pmatrix{a_{i_1j_1} & \cdots & a_{j_1j_r}\\ \vdots & \ddots & \vdots \\ a_{i_rj_1} & \cdots & a_{i_rj_r}}$$corresponds to the map from $\mathbb{R}^{mn}$ to $\mathbb{R}^{r^2}$ that sends$$(a_{11},a_{12},\ldots,a_{mn})\mapsto (a_{i_1j_1},a_{i_1j_2},\ldots,a_{i_rj_r}),$$which is continuous, for any choice of the $i$'s and $j$'s. Furthermore, the determinant map from $M_r$ to $\mathbb{R}$ that sends $Y\in M_r$ to $\det(Y)$ is continuous, because it is a polynomial in the entries of $Y$, i.e. it corresponds to a map from $\mathbb{R}^{r^2}$ to $\mathbb{R}$ that is a polynomial in $r^2$ variables. Suppose $k<\min\{m,n\}$. Then map $M$ to $\mathbb{R}^d$, where $d={\binom{m}{k+1}\cdot\binom{n}{k+1}}$, by sending a matrix to the ordered tuple of its $(k+1)\times(k+1)$ minors . For example, if $m=n=3$ and $k=1$, then we send $$\pmatrix{1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9}\mapsto\left( |\begin{smallmatrix} 1 & 2\\ 4 & 5\end{smallmatrix}|,|\begin{smallmatrix} 1 & 3\\ 4 & 6\end{smallmatrix}|,|\begin{smallmatrix} 2 & 3\\ 5 & 6\end{smallmatrix}|,|\begin{smallmatrix} 1 & 2\\ 7 & 8\end{smallmatrix}|,|\begin{smallmatrix} 1 & 3\\ 7 & 9\end{smallmatrix}|,|\begin{smallmatrix} 2 & 3\\ 8 & 9\end{smallmatrix}|,|\begin{smallmatrix} 4 & 5\\ 7 & 8\end{smallmatrix}|,|\begin{smallmatrix} 4 & 6\\ 7 & 9\end{smallmatrix}|,|\begin{smallmatrix} 5 & 6\\ 8 & 9\end{smallmatrix}| \right).$$ Because all $d$ of the projection maps from $M$ to $M_r$ are continuous, and because the determinant map from $M_r$ to $\mathbb{R}$ is continuous, this map is continuous. A matrix is of rank $\leq k$, i.e. $< k+1$, if and only if all of its $(k+1)\times(k+1)$ minors are zero. Thus, $C$ is the preimage of $0\in\mathbb{R}^d$ under a continuous map, and $\{0\}$ is a closed set in $\mathbb{R}^d$ because $\mathbb{R}^d$ is Hausdorff, so therefore $C$ is a closed set in $M$. If $k=\min\{m,n\}$, then $C=M$, and is a closed set.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/43192', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9980/']}
|
jdg_378995
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3742835
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the shape in the complex plane generated by all possible points $z_1 + z_2$ , where $z_1$ and $z_2$ can be any two points on the unit circle centered at $0$
Now provide the response and nothing else.
|
Start at the bottom left-hand corner, taking othonormal unit vectors $\pmb i$ horizontally, $\pmb j$ inward along the cross-member bottom left-hand edge, and $\pmb k$ upward and perpendicular to $\pmb i$ and $\pmb j$ . I'll take the long edge of a member as $5$ times its (unit) width; the exact number doesn't matter. Then, working by vector addition anticlockwise round the visible outer edge to get back to the starting point, we have $$5\pmb i+\pmb k+5\pmb j-\pmb i-5\pmb k-\pmb j=4\pmb i+4\pmb j-4\pmb k=\pmb0,$$ which of course is impossible.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/3742835', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/338774/']}
|
jdg_378996
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
146579
|
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've designed this circuit myself aiming to generate a sine wave at the collector of the transistor, but it doesn't work. The current at the collector is DC. Is it a simulator error or the is design wrong? What modifications should I make so that it works? I know that there are many oscillator circuits on the internet but I would like to know what the error in this circuit is.
Now provide the response and nothing else.
|
The basic problem is that there is no feedback thru the resonating components. Note that they are tied to the base directly from the power supply. There is nothing that will make them oscillate. There are many L-C oscillator circuits out there. No matter what topology you use, the frequency-setting components either need to be in the feedback path, or somehow arranged to kill the gain at all but the selected frequency.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/146579', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/50937/']}
|
jdg_378997
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37904
|
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 use the sign convention: Heat absorbed by the system = $q+$ (positive) Heat evolved by the system = $q-$ (negative) Work done on the system = $w +$ (positive) Work done by the system = $w -$ (negative) Could anyone please tell me, that volume increased in system does positive or negative work?
Now provide the response and nothing else.
|
Volume increase in the system is due to work done by the system. Therefore W is negative using your notation. Think of it this way, work done on the system would push the system inwards, decreasing volume. Therefore a volume increase is work done by the system. Alternatively you could reason using the formula:$dU = dQ - dW$ (using your notation conventions, were $U$ is internal energy, $W$ is work and $Q$ is heat added to the system) $dW = PdV.$ Therefore $dU = dQ - PdV$. Therefore if $dV$ (change in volume) is positive, $dU$ (change in internal energy) is negative.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/37904', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/12396/']}
|
jdg_378998
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
990
|
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:
Many years ago I saw an episode of ER where there was a person who suddenly experienced some heart rhythm problems in the hospital. There was a qualified doctor nearby and a defibrillator, but the latter was dysfunctional because of a drained battery. So the doctor filled a small bath with water and then with assistance of his colleagues submerged that person's face into water. As they described it, water got into person's nose, irritated nerves located there, his body reflectively assumed it was drowning and that had such a powerful impact that the person's heart resumed normal functioning. How realistic is that? Does such drowning imitation have enough effect to replace a defibrillator?
Now provide the response and nothing else.
|
I suspect that what happened in that ER episode was a patient who had an attack of tachycardia -- where the heart is beating so fast that it no longer pumps blood efficiently. This particular rhythm can be treated by harnessing the diving reflex . When cold water (specifically below 21 C or 70 F) contacts the face, the heart immediately slows down by 10 to 25%. Thus if the heart rate is too high, this will immediately address the problem. (Other effects take place afterwards, as described in the linked Wikipedia article, but the first effect is the relevant one.) This is ONLY effective when the problem with the heart is that it is beating too fast. Other arrythmias, such as fibrillation, may not be affected. Thus the need for defibrillators. Fibrillation is irregular and unsynchronized quivering of the muscles. The problem there is not necessarily that the heart is beating too fast, but that it is not beating properly. Defibrillation attempts to reset the rhythm. Again, according to Wikipedia, defibrillation is only used in cases of tachycardia where there is no pulse.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://skeptics.stackexchange.com/questions/990', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/666/']}
|
jdg_378999
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17434031
|
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 class for testing some of my code. I would like to parametrize the setup and rerun the class with different parameters: class TestNormalLTEPlasma: def setup(self, t=10000): self.plasma = plasma.LTEPlasma.from_abundance(t, {'Si':1.0}, 1e-13, atom_data, 10*86400) def test_beta_rad(self): assert self.plasma.beta_rad == 1 / (10000 * constants.k_B.cgs.value) def test_t_electron(self): assert self.plasma.t_electron == 0.9 * self.plasma.t_rad def test_saha_calculation_method(self): assert self.plasma.calculate_saha == self.plasma.calculate_saha_lte I would like to run this class going from t=2000 to t=20000 in steps of 1000.
Now provide the response and nothing else.
|
Instead of your setup function, create a parametrized test fixture: ts = range(2000, 20001, 1000) # This creates a list of numbers from 2000 to 20000 in increments of 1000.@pytest.fixture(params=ts)def plasma(request): return plasma.LTEPlasma.from_abundance(request.param, {'Si':1.0}, 1e-13, atom_data, 10*86400) A "parametrized test fixture" is one where, when you use it in a test case, pytest will create a new test case for each parameter and run each separately. You use the test fixture by adding a function argument called "plasma" to each of the test functions that want it: class TestNormalLTEPlasma: def test_beta_rad(self, plasma): assert plasma.beta_rad == 1 / (10000 * constants.k_B.cgs.value) def test_t_electron(self, plasma): assert plasma.t_electron == 0.9 * plasma.t_rad def test_saha_calculation_method(self, plasma): assert plasma.calculate_saha == plasma.calculate_saha_lte pytest takes care of collecting fixtures, collecting test functions, figuring out which test functions need which fixtures, and passing the fixture values to the test functions for execution. Check out the docs for more details: https://docs.pytest.org/en/latest/fixture.html#fixture-parametrize
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17434031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/288558/']}
|
jdg_379000
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2806886
|
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 a large multilingual website and I am considering different approaches for making it multilingual. The possible alternatives I can think of are: The Gettext functions with generation of .po files One MySQL table with the translations and a unique string ID for each text PHP-files with arrays containing the different translations with unique string IDs As far as I have understood the Gettext functions should be most efficient, but my requirement is that it should be possible to change a text string in the original reference language (English) without the other translations of that string automatically reverting back to English just because a couple of words changed. Is this possible with Gettext? What is the least resource demanding solution? Is using the Gettext functions or PHP files with arrays more or less equally resource demanding? Any other suggestions for more efficient solutions?
Now provide the response and nothing else.
|
A few considerations: 1. Translations Who will be doing the translations? People that are also connected to the site? A translation agency? When using Gettext you'll be working with 'pot' (.po) files. These files contain the message ID and the message string (the translation). Example: msgid "A string to be translated would go here" msgstr "" Now, this looks just fine and understandable for anyone who needs to translate this. But what happens when you use keywords, like Mike suggests, instead of full sentences? If someone needs to translate a msgid called "address_home", he or she has no clue if this is should be a header "Home address" or that it's a full sentence. In this case, make sure to add comments to the file right before you call on the gettext function, like so: /// This is a comment that will be included in the pot file for the translatorsgettext("ready_for_lost_episode"); Using xgettext --add-comments=/// when creating the .po files will add these comments. However, I don't think Gettext is ment to be used this way. Also, if you need to add comments with every text you want to display you'll a) probably make an error at some point, b) you're whole script will be filled with the texts anyway, only in comment form, c) the comments needs to be placed directly above the Gettext function, which isn't always convient, depending on the position of the function in your code. 2. Maintenance Once your site grows (even further) and your language files along with it, it might get pretty hard to maintain all the different translations this way. Every time you add a text, you need to create new files, send out the files to translators, receive the files back, make sure the structure is still intact (eager translators are always happy to translate the syntax as well, making the whole file unusable :)), and finish with importing the new translations. It's doable, sure, but be aware with possible problems on this end with large sites and many different languages. Another option: combine your 2nd and 3rd alternative: Personally, I find it more useful to manage the translation using a (simple) CMS, keeping the variables and translations in a database and export the relevent texts to language files yourself: add variables to the database (e.g.: id, page, variable); add translations to these variables (e.g.: id, varId, language, translation); select relevant variables and translations, write them to a file; include the relevant language file in your site; create your own function to display a variables text: text('var'); or maybe something like __('faq','register','lost_password_text'); Point 3 can be as simple as selecting all the relevant variables and translations from the database, putting them in an array and writing the serlialized array to a file. Advantages: Maintenance. Maintaining the texts can be a lot easier for big projects. You can group variables by page, sections or other parts within your site, by simply adding a column to your database that defines to which part of the site this variable belongs. That way you can quickly pull up a list of all the variables used in e.g. the FAQ page. Translating. You can display the variable with all the translations of all the different languages on a single page. This might be useful for people who can translate texts into multiple languages at the same time. And it might be useful to see other translations to get a feel for the context so that the translation is as good as possible. You can also query the database to find out what has been translated and what hasn't. Maybe add timestamps to keep track of possible outdated translations. Access. This depends on who will be translating. You can wrap the CMS with a simple login to grant access to people from a translation agency if need be, and only allow them to change certain languages or even certain parts of the site. If this isn't an option you can still output the data to a file that can be manually translated and import it later (although this might come with the same problems as mentioned before.). You can add one of the translations that's already there (English or another main language) as context for the translator. All in all I think you'll find that you'll have a lot more control over the translations this way, especially in the long run. I can't tell you anything about speed or efficiency of this approach compared to the native gettext function. But, depending on the size of the language files, I don't think it'll be a big difference. If you group the variables by page or section, you can alway include only the required parts.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2806886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/337734/']}
|
jdg_379001
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37251
|
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 find it rather amazing that by plotting the points (0,0),(0.5,0.25),(1,1),(2,4), one can "predict" what the graph will look like. In certain cases, a person may even be able to "sketch"(freehand) the in between values by "connecting the dots", without being told that the function giving the result is $f(x)=x^2$. Is there any way to get from a set of data to a prediction of what the plot will look like by having just a few data points?
Now provide the response and nothing else.
|
"In engineering and science one often has a number of data points, as obtained by sampling or experimentation, and tries to construct a function which closely fits those data points. This is called curve fitting or regression analysis. Interpolation is a specific case of curve fitting, in which the function must go exactly through the data points." Actually this is a very difficult task and there are quite a few approaches for it, the easiest one is probably that you assume the function has a certain form like $f(x)=a\exp(b\cdot x)+c$ and then optimize the parameters a,b and c to get the "best fitting" function. Of course the initial guess is very important and can also be automated. Like already mentioned when working in a very abstract context you are never sure if some very odd / oscilating function is hiding between the data points, but one might assume that this is not the case if you have enough data points. This is a very neat example from Wikipedia that shows that there are also interpolations which you wouldn't probably come up when fitting it from hand but if you optimize it by using splines on a formula level: Image and quote: http://en.wikipedia.org/wiki/Interpolation
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/37251', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4728/']}
|
jdg_379002
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18581459
|
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 quick node.js app using express and I am a newbie to NODE. For pages I am just using plain html. Basically I have a form as follows: <form id="tableForm" action="getJson"> <select class="selectpicker" data-style="btn-info" name="selectpicker"> <optgroup label="Select Table"> <option name="" value="0">Select table</option> <option name="table1" value="1">Table 1</option> <option name="table2" value="2">Table 2</option> <option name="table3" value="3">Table 3</option> </optgroup> </select> </form> Basically, I need to get the value selected once done I need it to be passed a app.get() call but my questions is how do I get the value and call the API? var express = require('express'),app = express();app.use(express.bodyParser()); // as only one page can use res.sendfile to render the page which will // contain the dropdowns ... app.get('/', function(req, res){ res.sendfile('views/index.html');});app.get('/getJson', function (req, res) { console.log(req.body.);});app.listen(process.env.PORT); So I need to call the getJson() with the value being passed in. Cheers!
Now provide the response and nothing else.
|
You need to submit the form somehow. The easiest way to do it would be with a submit button. You also need to put the method for the form, which by the way you phrased it it sounds like you're wanting to use GET. HTML <form id="tableForm" action="/getJson" method="get"> <select class="selectpicker" data-style="btn-info" name="selectpicker"> <optgroup label="Select Table"> <option name="" value="0">Select table</option> <option name="table1" value="1">Table 1</option> <option name="table2" value="2">Table 2</option> <option name="table3" value="3">Table 3</option> </optgroup> </select> <input type="submit" /></form> On the server side you need parse out the get request. You already have it set up to receive it, you just need to know what you're looking for. Since your select has the name "selectpicker" that's what you'll use in this case. JavaScript var express = require('express'), app = express();app.use(express.bodyParser());// as only one page can use res.sendfile to render the page which will contain the drop downsapp.get('/', function (req, res) { res.sendfile('views/index.html');});app.get('/getJson', function (req, res) { // If it's not showing up, just use req.body to see what is actually being passed. console.log(req.body.selectpicker);});app.listen(process.env.PORT); I haven't fully tested this code, but it should work.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18581459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/871415/']}
|
jdg_379003
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50803434
|
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 hide a vector field in my class but allow easy iteration through its elements but nothing else. So that class's client would be able to do for (auto element : foo.getElements()) { } but not foo.getElements()[42]; Is there some simple way of achieving this w/o creating new confusing types?
Now provide the response and nothing else.
|
I cannot say what is and is not a "new confusing type". But this is sufficient for the needs of a range-based for : template<typename Iter>class iterator_range{public: iterator_range(Iter beg, Iter end) : beg_(beg), end_(end) {} Iter begin() const {return beg_;} Iter end() const {return end_;}private: Iter beg_, end_;}; The Range TS adds more complexity to what constitutes a "range", but this is good enough for range-based for . So your foo.getElements function would look like this: auto getElements(){ return iterator_range<vector<T>::iterator>(vec.begin(), vec.end());}auto getElements() const{ return iterator_range<vector<T>::const_iterator>(vec.begin(), vec.end());};
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50803434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/68105/']}
|
jdg_379004
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53321133
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following 3 files, A.java: class A { private float b; public A(float b) { this.b = b; } public float getB() { return b; }} C.java: import java.util.Arrays;class C { private A[] d; private int i = 0; public C() { d = new A[2]; } public float totalB() { return Arrays.stream(d).reduce((e, f) -> e.getB() + f.getB()).get(); } public void addB(A b) { d[i++] = b; }} D.java: class D { public static void main(String[] args) { C c = new C(); c.addB(new A(3)); c.addB(new A(5)); System.out.println(c.totalB()) }} I was expecting the last line in D.java to output 8, however I get this error: error: incompatible types: bad return type in lambda expression return Arrays.stream(d).reduce((e, f) -> e.getB() + f.getB()).get(); ^ float cannot be converted to A Why does this happen? I don't see where I'm converting the floats to the object A.
Now provide the response and nothing else.
|
The single argument reduce() variant expects the final result of the reduce operation to be of the same type as the Stream elements. You need a different variant : <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner); which you can use as follows: public float totalB() { return Arrays.stream(d).reduce(0.0f,(r, f) -> r + f.getB(), Float::sum);}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53321133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8121375/']}
|
jdg_379005
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6241200
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Sometimes while I'm debugging an exception will be raised. For example, consider this code: def some_function(): # Pretend this function is in a library... # ...and deep within the library is an exception: raise Exception('An exception message with valuable information.')import pdb; pdb.set_trace()try: some_function() # Pretend I am debugging from this point using pdb.except: pass While debugging from the some_function() call, if I issue a next command I will see the following details about the exception that was raised [and caught]: Exception: Exceptio...ation.',) Here's a straight copy / paste from the terminal I was working in: > /tmp/test.py(7)<module>()-> some_function() # Pretend I am debugging from this point using pdb.(Pdb) nextException: Exceptio...ation.',)> /tmp/test.py(7)<module>()-> some_function() # Pretend I am debugging from this point using pdb.(Pdb) It would be useful to see the entire exception message. How can I do this in pdb?
Now provide the response and nothing else.
|
pdb stores the exception type and value in __exception__ . You can print the exception part of a traceback in pdb with: import traceback; print "".join(traceback.format_exception_only(*__exception__)) For example: > /tmp/test.py(7)<module>()-> some_function() # Pretend I am debugging from this point using pdb.(Pdb) nextException: Exceptio...ation.',)> /tmp/test.py(7)<module>()-> some_function() # Pretend I am debugging from this point using pdb.(Pdb) import traceback; print "".join(traceback.format_exception_only(*__exception__))Exception: An exception message with valuable information.(Pdb) Unfortunately this does not include the rest of the traceback, but all that information is available through the where command of pdb anyway. If you really want the full traceback, you can add the following to your ~/.pdbrc file or paste it into your terminal: !global __currentframe, __stack; from inspect import currentframe as __currentframe, stack as __stack!global __format_exception_only, __print_stack; from traceback import format_exception_only as __format_exception_only, print_stack as __print_stack!global __Pdb; from pdb import Pdb as __Pdb# find the last frame on the stack with an object named "pdb" or "self" that is a pdb.Pdb object# works for pdb called the usual way, or pdb.pm(), or pdb.set_trace()!global __pdb; __pdb = [__framerec[0].f_locals.get("pdb") or __framerec[0].f_locals.get("self") for __framerec in __stack() if (__framerec[0].f_locals.get("pdb") or __framerec[0].f_locals.get("self")).__class__ == __Pdb][-1]alias traceback __print_stack(__pdb.stack[-1][0]); print "".join(__format_exception_only(*__exception__)) Then you can just use the new traceback alias to get what you want: > /tmp/test.py(7)<module>()-> some_function() # Pretend I am debugging from this point using pdb.(Pdb) nextException: Exceptio...ation.',)> /tmp/test.py(7)<module>()-> some_function() # Pretend I am debugging from this point using pdb.(Pdb) traceback File "test.py", line 7, in <module> some_function() # Pretend I am debugging from this point using pdb. File "test.py", line 3, in some_function raise Exception('An exception message with valuable information.')Exception: An exception message with valuable information.(Pdb) Warning: all of this relies on undocumented pdb and bdb internals and is likely to break.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6241200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/565879/']}
|
jdg_379006
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2514937
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Steps to create File Upload field using Ext Js
Now provide the response and nothing else.
|
As far as specific steps are concerned, using functionality supported in ExtJS 3x, your best best is to use this module/plugin: http://dev.sencha.com/deploy/dev/examples/form/file-upload.html The core script comes with the Ext JS package, in your main HTML file (where you have linked to the core Ext scripts), in the head section after your other scripts put: <script type="text/javascript" src="nameofyourextfolder/examples/ux/fileuploadfield/FileUploadField.js"></script> Sadly, there isnt a huge amount of documentation on this element of Ext JS- however for basic functionality, you can create a form with an async upload field using the below: myuploadform= new Ext.FormPanel({ fileUpload: true, width: 500, autoHeight: true, bodyStyle: 'padding: 10px 10px 10px 10px;', labelWidth: 50, defaults: { anchor: '95%', allowBlank: false, msgTarget: 'side' }, items:[ { xtype: 'fileuploadfield', id: 'filedata', emptyText: 'Select a document to upload...', fieldLabel: 'File', buttonText: 'Browse' }], buttons: [{ text: 'Upload', handler: function(){ if(myuploadform.getForm().isValid()){ form_action=1; myuploadform.getForm().submit({ url: 'handleupload.php', waitMsg: 'Uploading file...', success: function(form,action){ msg('Success', 'Processed file on the server'); } }); } } }] }) What this code will do is create a new formpanel with an upload field and an upload button. When you click the upload button- the selected file will be sent to the serverside script handleupload.php (or whatever you call it). It is then this script that handles what you want to do with the file. An example of this could potentially be: $fileName = $_FILES['filedata']['name']; $tmpName = $_FILES['filedata']['tmp_name']; $fileSize = $_FILES['filedata']['size']; $fileType = $_FILES['filedata']['type']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); if(!get_magic_quotes_gpc()){ $fileName = addslashes($fileName); } $query = "INSERT INTO yourdatabasetable (`name`, `size`, `type`, `file`) VALUES ('".$fileName."','".$fileSize."', '".$fileType."', '".$content."')"; mysql_query($query); Which would inject the file into a SQL DB. The thing to remember is the server side file handles an upload just as a normal HTML form would... Hope this helps!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2514937', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/301627/']}
|
jdg_379007
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
116629
|
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:
Suppose I press the A key in a text editor and this inserts the character a in the document and displays it on the screen. I know the editor application isn't directly communicating with the hardware (there's a kernel and stuff in between), so what is going on inside my computer?
Now provide the response and nothing else.
|
There are several different scenarios; I'll describe the most common ones. The successive macroscopic events are: Input: the key press event is transmitted from the keyboard hardware to the application. Processing: the application decides that because the key A was pressed, it must display the character a . Output: the application gives the order to display a on the screen. GUI applications The de facto standard graphical user interface of unix systems is the X Window System , often called X11 because it stabilized in the 11th version of its core protocol between applications and the display server. A program called the X server sits between the operating system kernel and the applications; it provides services including displaying windows on the screen and transmitting key presses to the window that has the focus. Input +----------+ +-------------+ +-----+| keyboard |------------->| motherboard |-------->| CPU |+----------+ +-------------+ +-----+ USB, PS/2, … PCI, … key down/up First, information about the key press and key release is transmitted from the keyboard to the computer and inside the computer. The details depend on the type of hardware. I won't dwell more on this part because the information remains the same throughout this part of the chain: a certain key was pressed or released. +--------+ +----------+ +-------------+-------->| kernel |------->| X server |--------->| application | +--------+ +----------+ +-------------+interrupt scancode keysym =keycode +modifiers When a hardware event happens, the CPU triggers an interrupt , which causes some code in the kernel to execute. This code detects that the hardware event is a key press or key release coming from a keyboard and records the scan code which identifies the key. The X server reads input events through a device file , for example /dev/input/eventNNN on Linux (where NNN is a number). Whenever there is an event, the kernel signals that there is data to read from that device. The device file transmits key up/down events with a scan code, which may or may not be identical to the value transmitted by the hardware (the kernel may translate the scan code from a keyboard-dependent value to a common value, and Linux doesn't retransmit the scan codes that it doesn't know ). X calls the scan code that it reads a keycode . The X server maintains a table that translates key codes into keysyms (short for “key symbol”). Keycodes are numeric, whereas keysyms are names such as A , aacute , F1 , KP_Add , Control_L , … The keysym may differ depending on which modifier keys are pressed ( Shift , Ctrl , …). There are two mechanisms to configure the mapping from keycodes to keysyms: xmodmap is the traditional mechanism. It is a simple table mapping keycodes to a list of keysyms (unmodified, shifted, …). XKB is a more powerful, but more complex mechanism with better support for more modifiers, in particular for dual-language configuration, among others. Applications connect to the X server and receive a notification when a key is pressed while a window of that application has the focus. The notification indicates that a certain keysym was pressed or released as well as what modifiers are currently pressed. You can see keysyms by running the program xev from a terminal. What the application does with the information is up to it; some applications have configurable key bindings. In a typical configuration, when you press the key labeled A with no modifiers, this sends the keysym a to the application; if the application is in a mode where you're typing text, this inserts the character a . Relationship of keyboard layout and xmodmap goes into more detail on keyboard input. How do mouse events work in linux? gives an overview of mouse input at the lower levels. Output +-------------+ +----------+ +-----+ +---------+| application |------->| X server |---····-->| GPU |-------->| monitor |+-------------+ +----------+ +-----+ +---------+ text or varies VGA, DVI, image HDMI, … There are two ways to display a character. Server-side rendering : the application tells the X server “ draw this string in this font at this position ”. The font resides on the X server. Client-side rendering : the application builds an image that represents the character in a font that it chooses, then tells the X server to display that image . See What are the purposes of the different types of XWindows fonts? for a discussion of client-side and server-side text rendering under X11. What happens between the X server and the Graphics Processing Unit (the processor on the video card) is very hardware-dependent. Simple systems have the X server draw in a memory region called a framebuffer , which the GPU picks up for display. Advanced systems such as found on any 21st century PC or smartphone allow the GPU to perform some operations directly for better performance. Ultimately, the GPU transmits the screen content pixel by pixel every fraction of a second to the monitor. Text mode application, running in a terminal If your text editor is a text mode application running in a terminal, then it is the terminal which is the application for the purpose of the section above. In this section, I explain the interface between the text mode application and the terminal. First I describe the case of a terminal emulator running under X11. What is the exact difference between a 'terminal', a 'shell', a 'tty' and a 'console'? may be useful background here. After reading this, you may want to read the far more detailed What are the responsibilities of each Pseudo-Terminal (PTY) component (software, master side, slave side)? Input +-------------------+ +-------------+----->| terminal emulator |-------------->| application | +-------------------+ +-------------+keysym character or escape sequence The terminal emulator receives events like “ Left was pressed while Shift was down”. The interface between the terminal emulator and the text mode application is a pseudo-terminal (pty) , a character device which transmits bytes. When the terminal emulator receives a key press event, it transforms this into one or more bytes which the application gets to read from the pty device. Printable characters outside the ASCII range are transmitted as one or more byte depending on the character and encoding . For example, in the UTF-8 encoding of the Unicode character set, characters in the ASCII range are encoded as a single bytes, while characters outside that range are encoded as multiple bytes. Key presses that correspond to a function key or a printable character with modifiers such as Ctrl or Alt are sent as an escape sequence . Escape sequences typically consist of the character escape (byte value 27 = 0x1B = \033 , sometimes represented as ^[ or \e ) followed by one or more printable characters. A few keys or key combination have a control character corresponding to them in ASCII-based encodings (which is pretty much all of them in use today, including Unicode): Ctrl + letter yields a character value in the range 1–26, Esc is the escape character seen above and is also the same as Ctrl + [ , Tab is the same as Ctrl + I , Return is the same as Ctrl + M , etc. Different terminals send different escape sequences for a given key or key combination. Fortunately, the converse is not true: given a sequence, there is in practice at most one key combination that it encodes. The one exception is the character 127 = 0x7f = \0177 which is often Backspace but sometimes Delete . In a terminal, if you type Ctrl + V followed by a key combination, this inserts the first byte of the escape sequence from the key combination literally. Since escape sequences normally consist only of printable characters after the first one, this inserts the whole escape sequence literally. See key bindings table? for a discussion of zsh in this context. The terminal may transmit the same escape sequence for some modifier combinations (e.g. many terminals transmit a space character for both Space and Shift + Space ; xterm has a mode to distinguish modifier combinations but terminals based on the popular vte library don't ). A few keys are not transmitted at all, for example modifier keys or keys that trigger a binding of the terminal emulator (e.g. a copy or paste command). It is up to the application to translate escape sequences into symbolic key names if it so desires. Output +-------------+ +-------------------+| application |-------------->| terminal emulator |--->+-------------+ +-------------------+ character or escape sequence Output is rather simpler than input. If the application outputs a character to the pty device file, the terminal emulator displays it at the current cursor position. (The terminal emulator maintains a cursor position, and scrolls if the cursor would fall under the bottom of the screen.) The application can also output escape sequences (mostly beginning with ^[ or ^] ) to tell the terminal to perform actions such as moving the cursor, changing the text attributes (color, bold, …), or erasing part of the screen. Escape sequences supported by the terminal emulator are described in the termcap or terminfo database. Most terminal emulator nowadays are fairly closely aligned with xterm . See Documentation on LESS_TERMCAP_* variables? for a longer discussion of terminal capability information databases, and How to stop cursor from blinking and Can I set my local machine's terminal colors to use those of the machine I ssh into? for some usage examples. Application running in a text console If the application is running directly in a text console, i.e. a terminal provided by the kernel rather than by a terminal emulator application, the same principles apply. The interface between the terminal and the application is still a byte stream which transmits characters, with special keys and commands encoded as escape sequences. Remote application, accessed over the network Remote text application If you run a program on a remote machine, e.g. over SSH , then the network communication protocol relays data at the pty level. +-------------+ +------+ +-----+ +----------+| application |<--------->| sshd |<--------->| ssh |<--------->| terminal |+-------------+ +------+ +-----+ +----------+ byte stream byte stream byte stream (char/seq) over TCP/… (char/seq) This is mostly transparent, except that sometimes the remote terminal database may not know all the capabilities of the local terminal. Remote X11 application The communication protocol between applications an the server is itself a byte stream that can be sent over a network protocol such as SSH. +-------------+ +------+ +-----+ +----------+| application |<---------->| sshd |<------>| ssh |<---------->| X server |+-------------+ +------+ +-----+ +----------+ X11 protocol X11 over X11 protocol TCP/… This is mostly transparent, except that some acceleration features such as movie decoding and 3D rendering that require direct communication between the application and the display are not available.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/116629', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/885/']}
|
jdg_379008
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7374001
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi I don't want an image for my submit button so I have gone with the default submit button but I want to edit its width and height. How do I do that? <input type="submit" id="search" value="Search" /> Thanks! James
Now provide the response and nothing else.
|
Using CSS you can set a style for that specific button using the id (#) selector: #search { width: 20em; height: 2em;} or if you want all submit buttons to be a particular size: input[type=submit] { width: 20em; height: 2em;} or if you want certain classes of button to be a particular style you can use CSS classes: <input type="submit" id="search" value="Search" class="search" /> and input.search { width: 20em; height: 2em;} I use ems as the measurement unit because they tend to scale better .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7374001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/903323/']}
|
jdg_379009
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33307892
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using Django 1.8.4 in my dev machine using Sqlite and I have these models: class ModelA(Model): field_a = CharField(verbose_name='a', max_length=20) field_b = CharField(verbose_name='b', max_length=20) class Meta: unique_together = ('field_a', 'field_b',)class ModelB(Model): field_c = CharField(verbose_name='c', max_length=20) field_d = ForeignKey(ModelA, verbose_name='d', null=True, blank=True) class Meta: unique_together = ('field_c', 'field_d',) I've run proper migration and registered them in the Django Admin. So, using the Admin I've done this tests: I'm able to create ModelA records and Django prohibits me from creating duplicate records - as expected! I'm not able to create identical ModelB records when field_b is not empty But, I'm able to create identical ModelB records, when using field_d as empty My question is: How do I apply unique_together for nullable ForeignKey? The most recent answer I found for this problem has 5 year... I do think Django have evolved and the issue may not be the same.
Now provide the response and nothing else.
|
UPDATE : previous version of my answer was functional but had bad design, this one takes in account some of the comments and other answers. In SQL NULL does not equal NULL. This means if you have two objects where field_d == None and field_c == "somestring" they are not equal, so you can create both. You can override Model.clean to add your check: class ModelB(Model): #... def validate_unique(self, exclude=None): if ModelB.objects.exclude(id=self.id).filter(field_c=self.field_c, \ field_d__isnull=True).exists(): raise ValidationError("Duplicate ModelB") super(ModelB, self).validate_unique(exclude) If used outside of forms you have to call full_clean or validate_unique . Take care to handle the race condition though.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33307892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1239006/']}
|
jdg_379010
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14484787
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new to JavaScript and jQuery. I have a variable named as str in JavaScript and it contains very long text, saying something like "A quick brown fox jumps over a lazy dog". I want to wrap it and assign it to the same variable str by inserting the proper \n or br/ tags at the correct places. I don't want to use CSS etc. Could you please tell me how to do it with a proper function in JavaScript which takes the str and returns the proper formatted text to it? Something like: str = somefunction(str, maxchar); I tried a lot but unfortunately nothing turned up the way I wanted it to be! :( Any help will be much appreciated...
Now provide the response and nothing else.
|
This should insert a line break at the nearest whitespace of maxChar: str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It w as popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";str = wordWrap(str, 40);function wordWrap(str, maxWidth) { var newLineStr = "\n"; done = false; res = ''; while (str.length > maxWidth) { found = false; // Inserts new line at first whitespace of the line for (i = maxWidth - 1; i >= 0; i--) { if (testWhite(str.charAt(i))) { res = res + [str.slice(0, i), newLineStr].join(''); str = str.slice(i + 1); found = true; break; } } // Inserts new line at maxWidth position, the word is too long to wrap if (!found) { res += [str.slice(0, maxWidth), newLineStr].join(''); str = str.slice(maxWidth); } } return res + str;}function testWhite(x) { var white = new RegExp(/^\s$/); return white.test(x.charAt(0));};
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14484787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2004685/']}
|
jdg_379011
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9094
|
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a question about matched filtering. Does the matched filter maximise the SNR at the moment of decision only? As far as I understand, if you put, say, NRZ through a matched filter, the SNR will be maximised at the decision point only and that is the advantage of the matched filter. Does it maximise the SNR anywhere else in the output function, or just at the point of decision? According to Wikipedia The matched filter is the optimal linear filter for maximizing the signal to noise ratio (SNR) in the presence of additive stochastic noise This to me implies that it maximises it everywhere, but I don't see how that is possible. I've looked at the maths in my communications engineering textbooks, and from what I can tell, it's just at the decision point. Another question I have is, why not make a filter that makes a really tall skinny spike at the point of decision. Wouldn't that make the SNR even better? Thanks. Edit:I guess what I'm also thinking is, say you have a some NRZ data and you use a matched filter, the matched filter could be implemented with an I&D (integrate and dump). The I&D will basically ramp up until it gets to the sampling time and the idea is that one samples at the peak of the I&D because at that point, the SNR is a maximum. What I don't get is, why not create a filter that double integrates it or something like that, that way, you'd have a squared increase (rather than a ramp) and the point at which you sample would be even higher up and from what I can tell, more likely to be interpreted correctly by the decision circuit (and give a lower Pe (probability of error))?
Now provide the response and nothing else.
|
Since this question has multiple sub-questions in edits, comments on answers, etc., and these have not been addressed, here goes. Matched filters Consider a finite-energy signal $s(t)$ that is the input to a (lineartime-invariant BIBO-stable) filter with impulse response $h(t)$, transfer function $H(f)$,and produces the outputsignal$$y(\tau) = \int_{-\infty}^\infty s(\tau-t)h(t)\,\mathrm dt.\tag{1}$$What choice of $h(t)$ will produce a maximum response at a given time$t_0$? That is, we are looking for a filter such that the global maximumof $y(\tau)$ occurs at $t_0$. This really is a very loosely phrased(and really unanswerable) question because clearly the filterwith impulse response $2h(t)$ will have larger response thanthe filter with impulse response $h(t)$, and so there isno such thing as the filter that maximizes the response.So, rather than compare apples and oranges, let us include theconstraint that we seek the filter that maximizes $y(t_0)$ subjectto the impulse response having a fixed energy, for example, subject to$$\int_{-\infty}^\infty |h(t)|^2\,\mathrm dt = \mathbb E = \int_{-\infty}^\infty |s(t)|^2 \,\mathrm dt.\tag{2}$$ Here onwards, "filter" shall mean a linear time-invariant filter whose impulse response satisfies (2). The Cauchy-Schwarz inequality provides an answer to this question. We have$$y(t_0) = \int_{-\infty}^\infty s(t_0-t)h(t)\,\mathrm dt\leq \sqrt{\int_{-\infty}^\infty |s(t_0-t)|^2 \,\mathrm dt}\sqrt{\int_{-\infty}^\infty |h(t)|^2\,\mathrm dt}= \mathbb E$$with equality occurring if $h(t) = \lambda s(t_0-t)$ with $\lambda > 0$where from (2) we get that $\lambda = 1$, thatis, the filter with impulse response $h(t) = s(t_0-t)$ producesthe maximal response $y(t_0) = \mathbb E$ at the specified time $t_0$.In the (non-stochastic) sense described above, this filter issaid to be the filter matched to $s(t)$ at time $t_0$ or the matched filter for $s(t)$ at time $t_0.$ There are several points worth noting about this result. The output of the matched filter has a unique global maximum value of $\mathbb E$ at $t_0$; for any other$t$, we have $y(t) < y(t_0) = \mathbb E$. The impulse response $s(t_0-t) = s(-(t-t_0))$of the matched filter for time $t_0$ is just $s(t)$ "reversed in time"and moved to the right by $t_0$. a. If $s(t)$ has finite support, say, $[0,T]$, then the matched filter is noncausal if $t_0 < T$. b. The filter matched to $s(t)$ at time $t_1 > t_0$ is just the filtermatched at time $t_0$ with an additional delay of $t_1-t_0$. For thisreason, some people call the filter with impulse response $s(-t)$,(that is, the filter matched to $s(t)$ at $t=0$) the matched filter for $s(t)$ with theunderstanding that the exact time of match can be incorporated intothe discussion as and when needed. If $s(t) = 0$ for $t < 0$, then the matched filter is noncausal. With this, we can rephrase 1. as The matched filter for $s(t)$ produces a unique global maximumvalue $y(0) = \mathbb E$ at time $t=0$. Furthermore, $$y(t) = \int_{-\infty}^\infty s(t-\tau)s(-\tau)\,\mathrm d\tau= \int_{-\infty}^\infty s(\tau-t)s(\tau)\,\mathrm d\tau = R_s(t)$$is the autocorrelation function of the signal $s(t)$. It iswell-known, of course, that $R_s(t)$ is an even function of $t$with a unique peak at the origin. Note that the output of thefilter matched at time $t_0$ is just $R_s(t-t_0)$, the autocorrelationfunction delayed to peak at time $t_0$. No filter other than thematched filter for time $t_0$ can produce an output as large as $\mathbb E$ at $t_0$. However, for any $t_0$,it is possible to find filters thathave outputs that exceed $R_s(t_0)$ at $t_0$. Note that $R_s(t_0) < \mathbb E$. The transfer function of the matched filter is $H(f)=S^*(f)$, thecomplex conjugate of the spectrum of $S(f)$. Thus, $Y(f) = \mathfrak F[y(t)]= |S(f)|^2$.Think of this result as follows. Since $x^2 > x$ for $x > 1$ and $x^2< x$ for$0 < x < 1$, the matched filter has low gain at those frequencies where$S(f)$ is small, and high gain at those frequencies where $S(f)$ is large.Thus, the matched filter is reducing the weak spectral componentsand enhancing the strong spectral components in $S(f)$. (It is alsodoing phase compensation to adjust all the "sinusoids" so thatthey all peak at $t=0$). ------- But what about noise and SNR and stuff like that which is what the OPwas asking about? If the signal $s(t)$ plus additive white Gaussian noise withtwo-sided power spectral density $\frac{N_0}{2}$ is processedthrough a filter with impulse response $h(t)$, then the output noise process is a zero-mean stationary Gaussian process withautocorrelation function $\frac{N_0}{2}R_s(t)$. Thus, thevariance is$$\sigma^2 = \frac{N_0}{2} R_s(0) = \frac{N_0}{2}\int_{-\infty}^{\infty} |h(t)|^2\,\mathrm dt.$$It is important to note that the variance is the same regardlessof when we sample the filter output. So, what choice of $h(t)$will maximize the SNR $y(t_0)/\sigma$ at time $t_0$? Well, from theCauchy-Schwarz inequality, we have$$\text{SNR} = \frac{y(t_0)}{\sigma}= \frac{\int_{-\infty}^\infty s(t_0-t)h(t)\,\mathrm dt}{\sqrt{\frac{N_0}{2}\int_{-\infty}^\infty |h(t)|^2\,\mathrm dt}}\leq \frac{\sqrt{\int_{-\infty}^\infty |s(t_0-t)|^2 \,\mathrm dt}\sqrt{\int_{-\infty}^\infty |h(t)|^2\,\mathrm dt}}{\sqrt{\frac{N_0}{2}\int_{-\infty}^\infty |h(t)|^2\,\mathrm dt}} = \sqrt{\frac{2\mathbb E}{N_0}}$$with equality exactly when $h(t) = s(t_0-t)$, the filter that is matchedto $s(t)$ at time $t_0$!! Note that $\sigma^2 = \mathbb EN_0/2$. If we use this matched filter for our desired sample time, then at other times $t_1$, the SNR will be $y(t_1)/\sigma < y(t_0)/\sigma = \sqrt{\frac{2\mathbb E}{N_0}}$. Could another filter give a larger SNR at time $t_1$? Sure, because $\sigma$is the same for all filters under consideration, and we have noted above thatit is possible to have a signal output larger than $y(t_1)$ at time$t_1$ by use of a different non-matched filter. In short, "does the matched filter maximize the SNR only at the samplinginstant, or everywhere?" has the answer that the SNR is maximized onlyat the sampling instant $t_0$. At other times, other filters could give a larger SNR than what the matched filter is providing at time $t_1$,but this still smaller than the SNR $\sqrt{\frac{2\mathbb E}{N_0}}$that the matched filter is giving you at $t_0$, and if desired,the matched filter could be redesigned to produce its peak at time$t_1$ instead of $t_0$. "why not make a filter that makes a really tall skinny spike at the point of decision. Wouldn't that make the SNR even better?" The matched filter does produce a spike of sorts at the sampling timebut it is constrained by the shape of the autocorrelation function. Any other filter that you can devise to produce a tall skinny (time-domain)spike is not a matched filter and so will not give you the largest possibleSNR. Note that increasing the amplitude of the filter impulse response(or using a time-varying filter that boosts the gain at the timeof sampling) does not change the SNR since both the signal and the noise standard deviation increase proportionately. "The I&D will basically ramp up until it gets to the sampling time and the idea is that one samples at the peak of the I&D because at that point, the SNR is a maximum." For NRZ data and rectangular pulses, the matched filter impulse response isalso a rectangular pulse. The integrate-and-dump circuit is a correlator whose output equals the matched filter output only at the sampling instants , and not in-between. See the figure below. If you sample the correlator output at other times,you get noise with smaller variance but you can't simply add up the samplesof I&D output taken at different times because the noise variables are highly correlated, andthe net variance works out to be much larger. Nor should you expect to be ableto take multiple samples from the matched filter output and combine themin any way to get a better SNR. It doesn't work. What you have in effectis a different filter, and you cannot do better than the (linear)matched filter in Gaussian noise; no nonlinear processing will givea smaller error probability than the matched fiter.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://dsp.stackexchange.com/questions/9094', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/1146/']}
|
jdg_379012
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3568262
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say I want to have two columns. The right one is 200px wide, and the left one just takes up the remaining width. Is this possible? What do I set the width of the left column to be?
Now provide the response and nothing else.
|
Update: Solved Using Flexbox Now that we have Flexbox (with over 95% support globally ) this layout (and others) can be easily achieved without styles being dependent on source order. Flexbox Example: HTML <div class="flex-container"> <div class="flex-column"> Big </div> <div class="fixed-column"> Small </div></div> CSS .flex-container { display: flex;}.flex-column { flex: 1;}.fixed-column { width: 200px;} Live Demo using Flexbox Solved Using Floats The trick is matching the remainder column’s margin to the floated sidebar’s width. Remember, source order matters when using floats, so we make sure the floated element comes first. Example right-aligned small column: HTML <div id="Container"> <div id="RightColumn">Right column</div> <div id="LeftColumn">Left column</div></div> CSS #RightColumn { float : right; width : 200px;}#LeftColumn { margin-right : 200px;} Live Demo Right-aligned small column Left-aligned small column
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3568262', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65387/']}
|
jdg_379013
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
307568
|
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 $D(\mathbb R) $ be the set of all differentiable functions $f: \mathbb R \to \mathbb R$. Then obviously $D(\mathbb R)$ forms a semigroup under usual function composition. Can we characterize (up to semigroup isomorphism) all finite subsemigroups of $D(\mathbb R)$ which do not contain any constant function ?
Now provide the response and nothing else.
|
Yes, we can! ;-) In fact there are only two finite subsemigroups of $D(\mathbb{R})$ which do not contain constant functions. Every finite subsemigroup of $D(\mathbb{R})$ necessarily contains an idempotent $f$, i.e. a function $f$ such that $f \circ f = f$. Let us examine the properties of $f$. Let $A$ be the range of $f$. By continuity of $f$, $A$ is an interval. Since $f(f(x)) = f(x)$ for every $x \in \mathbb{R}$, we have $f(x) = x$ for $x \in A$. If $f$ is non-constant, then $A$ has non-empty interior. We claim that in this case $A = \mathbb{R}$. Suppose, contrary to this claim, that $A$ is bounded from above, and denote the right endpoint of $A$ by $b$. Then $f(b) = \lim_{x \to b^-} f(x) = \lim_{x \to b^-} x = b$, and so $b \in A$. Thus, $f$ attains a local maximum at $b$. Since $f$ is differentiable at $b$, we have $f'(b) = 0$. On the other hand, $f'_-(b) = \lim_{x \to b^-} f'(x) = 1$, a contradiction. We conclude that $A$ is not bounded from above. Similarly, $A$ is unbounded from below. Thus, either $f$ is constant or $f$ is the identity function. It follows that any finite subsemigroup of $D(\mathbb{R})$ contains either a constant function or the identity function. Suppose that $X$ is a finite subsemigroup of $D(\mathbb{R})$ with no constant function and $g \in X$. Then the subsemigroup of $X$ generated by $g$ contains an idempotent, and hence — the identity function. In other words, $g^{\circ n}$ is the identity function for some $n$. Todd Trimble already pointed out in his answer that necessarily $n = 1$ or $n = 2$, and if $n = 2$, then $g$ is decreasing. Here is a shorter variant of his argument that does not require differentiability: $g$ is invertible and continuous, and hence strictly monotone; $g \circ g$ is thus strictly increasing; if $g(g(x)) > x$ for some $x$, then $g^{\circ 2n}(x) > x$, a contradiction; similarly, if $g(g(x)) < x$ for some $x$, then $g^{\circ 2n}(x) < x$; therefore, $g(g(x)) = x$ for all $x$; if $g$ is increasing, then in a similar way $g(x) = x$ for all $x$. Finally, if $g, h \in X$ and none of them is the identity function, then both are decreasing, and so $g \circ h$ is an increasing function in $X$. Therefore, $g \circ h$ is the identity function, and consequently $g = h^-1 = h$. We have thus proved that that any discrete subsemigroup of $D(\mathbb{R})$ with no constant function contains the identity function and at most one strictly decreasing function $g$ such that $g = g^{-1}$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/307568', 'https://mathoverflow.net', 'https://mathoverflow.net/users/127387/']}
|
jdg_379014
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24457831
|
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 use the new CardView from Android L. I updated everything in the SDK manager, but I keep getting the following error: Failure [INSTALL_FAILED_OLDER_SDK] This is my build.gradle file: apply plugin: 'android'android { compileSdkVersion 'android-L' buildToolsVersion '20.0.0' defaultConfig { applicationId "www.thomascbeerten.com.nieuwetests" minSdkVersion 8 targetSdkVersion 20 versionCode 1 versionName "1.0" } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }}dependencies { // Support Libraries compile 'com.android.support:support-v4:19.1.0' compile 'com.android.support:appcompat-v7:19.1.0' compile 'com.android.support:gridlayout-v7:19.1.0' compile 'com.android.support:mediarouter-v7:19.1.0' // compile 'com.android.support:support-v13:19.1.0' compile 'com.android.support:recyclerview-v7:+'}
Now provide the response and nothing else.
|
Recently there was a post here regarding the L SDK's incompatibility with prior versions of Android. I've been digging in AOSP repositories for quite a few hours now, and determined that the tools behave this way because they are designed to treat preview platforms differently. If you compile against a preview SDK (android-L), the build tools will lock minSdkVersion and targetSdkVersion to that same API level. This results in the produced application being unable to be installed on devices running older releases of Android, even if your application isn't doing anything specific to L. To make matters worse, the new support libs (CardView, RecyclerView, Palette, etc.) are also locked into the L API level, even though--according to their repository names--they should work on API level 7 just fine (and they do!). See my Reddit post about this here , with a workaround.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24457831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3220953/']}
|
jdg_379015
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
46143
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am specifying path to my command in the file /etc/profile : export PATH=$PATH:/usr/app/cpn/bin My command is located in: $ which ydisplay /usr/app/cpn/bin/ydisplay So, when I performing "echo $PATH" output is looks like: $ echo $PATH...:/usr/app/cpn/bin And everything is OK, but when I am trying to launch my command via SSH I am getting error: $ ssh 127.0.0.1 ydisplay$ bash: ydisplay: command not found But the my path is still present: $ ssh 127.0.0.1 echo $PATH...:/usr/app/cpn/bin Please explain me why Bash unable to find ydisplay during SSH session and how to properly configurate SSH to avoid this issue. More over, if I specifying $PATH in local file .bashrc in the current user all works correctly. But I want to modify only one file instead specifying a lot of files for each user. This is why I am asking.
Now provide the response and nothing else.
|
tl;dr Running ssh 127.0.0.1 ydisplay sources ~/.bashrc rather than /etc/profile . Change your path in ~/.bashrc instead. details The only time /etc/profile is read is when your shell is a "login shell". From the Bash Reference Manual : When bash is invoked as a login shell, ... it first reads and executes commands from the file /etc/profile But when you run ssh 127.0.0.1 ydisplay , bash is not started as a login shell. Yet it does read a different startup file. The Bash Reference Manual says: when ... executed by ... sshd. ... it reads and executes commands from ~/.bashrc So you should put your PATH settings in ~/.bashrc . On most systems, ~/.bash_profile sources ~/.bashrc , so you can put your settings only in ~/.bashrc rather than putting them in both files. There's no standard way to change the setting for all users, but most systems have a /etc/bashrc , /etc/bash.bashrc , or similar. Failing that, set up pam_env and put the PATH setting in /etc/environment . See also: What's the conf file reading between login and non-login shell? Is there a ".bashrc" equivalent file read by all shells?
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/46143', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/21071/']}
|
jdg_379016
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6818683
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The are several sorting algorithms like inserstion sort, selection sort, bubble sort etc. that are often discussed in computer science textbooks. Given an array of integers or objects, are there built-in Java 6 language API that let me choose to apply a specfic sort algorithm to sort the array instead of me reinventing these wheels again? If not built into Java 6, are there open source libraries that prodivde this functionality and what are they?
Now provide the response and nothing else.
|
The Arrays.sort() methods use a quick sort in all primitive type arrays. The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. The Collections.sort() method uses a merge sort. This sort is also used in Arrays.sort(Object[]) and Arrays.sort(T[], Comparator<? super T>) . The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance. This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6818683', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/574122/']}
|
jdg_379017
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10299373
|
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 WCF service and have just created a DTO for a business object. My question is where to put the mapping between the two? A) In the DTO? public class PersonDTO{ [DataMember] public string Id { get; set; } [DataMember] public string Name { get; set; } public void CloneFrom(Person p) { Id = p.Id; Name = p.Name; } public void Populate(Person p) { p.Id = Id; p.Name = Name; }} or B) In the business object? public class Person{ public string Id { get; set; } public string Name { get; set; } public void CloneFrom(PersonDTO dto) { Id = dto.Id; Name = dto.Name; } public PersonDTO GetDTO() { return new PersonDTO() { Id = Id; Name = Name; } }} I like the separation of concerns in A (Business object has no knowledge of DTOs), but I prefer the encapsulation of B (no need to expose business object guts to DTO). Just wondered if there was a standard way?
Now provide the response and nothing else.
|
i'd think this calls for a separate class, as neither the BO nor the DTO should be concerned with their transformation into another class. I personally use the automapper library for object transformations. With simple transformations like in your example the mapping is done in a single line of code, complex transformations are also easy to set up. If you want to map yourself, you could still use extension methods to keep the mapping implementation separated from your DTO and BO classes.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10299373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/660536/']}
|
jdg_379018
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15212261
|
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 some POD variables are initialized by default, but others are not. (POD types include int , float , pointers, unions, arrays of POD types, structs of POD types, etc.) How does scope and storage class affect default initialization of POD types? Specifically, which of the following will be initialized implicitly: Local variables with automatic storage Static local variables Static global variables External variables Variables allocated with new POD members of a class (without explicit initialization in a constructor) I know there are existing questions relating to some of these situations, but none comprehensive (they only address specific situations).
Now provide the response and nothing else.
|
Local variables with automatic storage duration are not being initialized automatically. Since using uninitialized variables produces undefined behavior , it is a good practice to explicitly initialize your variables even when it's redundant. About POD types that are being zero-initialized, C++03 standard 3.6.2 Initialization of non-local objects states: §1 Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place. So it's guaranteed by standard that POD types with static storage duration (whatever their scope is) will be zero-initialized. POD members of a class (without explicit initialization in a constructor) This situation is described in 12.6.2 Initializing bases and members , that states (selected parts): If a given nonstatic data member or base class is not named by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer), then: — If the entity is a nonstatic data member ..., and the entity class is a non-POD class, the entity is default-initialized (8.5)... — Otherwise, the entity is not initialized ... After the call to a constructor for class X has completed, if a member of X is neither specified in the constructor’s mem-initializers, nor default-initialized, nor value-initialized, nor given a value during execution of the body of the constructor, the member has indeterminate value. Example: class C{public: C(int x, int z) : x(x), z(z) { } int x, y, z;};int main(void){ C* c = new C(1,3); std::cout << c->y; // value of y is undetermined !!!}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15212261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1428922/']}
|
jdg_379019
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15724120
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My intention is this. My client.html calls a php script check.php via ajax. I want check.php to check if another script task.php is already being run. If it is, I do nothing. If it is not, I need to run it in the background. I have an idea what I want to do, but am unsure how to do it. Part A. I know how to call check.php via ajax. Part B. In check.php I might need to run task.php. I think I need something like: $PID = shell_exec("php task.php > /dev/null & echo $!"); I think the "> /dev/null &" bit tells it to run in the background, but am unsure what the "$!" does. Part C. The $PID I need as a tag of the process. I need to write this number (or whatever) to a file in the same directory, and need to read it every call to check.php. I can't work out how to do that. Could someone give me a link of how to read/write a file with a single number in to the same directory? Part D. Then to check if the last launched task.php is still running I am going to use the function: function is_process_running($PID){ exec("ps $PID", $ProcessState); return(count($ProcessState) >= 2);} I think that is all the bits I need, but as you can see I am unsure on how to do a few of them.
Now provide the response and nothing else.
|
I would use an flock() based mechanism to make sure that task.php runs only once. Use a code like this: <?php$fd = fopen('lock.file', 'w+');// try to get an exclusive lock. LOCK_NB let the operation not blocking// if a process instance is already running. In this case, the else // block will being entered.if(flock($fd, LOCK_EX | LOCK_NB )) { // run your code sleep(10); // ... flock($fd, LOCK_UN);} else { echo 'already running';}fclose($fd); Also note that flock() is, as the PHP documentation points out, portable across all supported operating systems. !$ gives you the pid of the last executed program in bash. Like this: command &pid=$!echo pid Note that you will have to make sure your php code runs on a system with bash support. (Not windows) Update (after comment of opener). flock() will work on all operating systems (As I mentioned). The problem I see in your code when working with windows is the !$ (As I mentioned ;) .. To obtain the pid of the task.php you should use proc_open() to start task.php. I've prepared two example scripts: task.php $fd = fopen('lock.file', 'w+');// try to get an exclusive lock. LOCK_NB let the operation not blocking// if a process instance is already running. In this case, the else // block will being entered.if(flock($fd, LOCK_EX | LOCK_NB )) { // your task's code comes here sleep(10); // ... flock($fd, LOCK_UN); echo 'success'; $exitcode = 0;} else { echo 'already running'; // return 2 to let check.php know about that // task.php is already running $exitcode = 2; }fclose($fd);exit($exitcode); check.php $cmd = 'php task.php';$descriptorspec = array( 0 => array('pipe', 'r'), // STDIN 1 => array('pipe', 'w'), // STDOUT 2 => array('pipe', 'w') // STDERR);$pipes = array(); // will be set by proc_open()// start task.php$process = proc_open($cmd, $descriptorspec, $pipes);if(!is_resource($process)) { die('failed to start task.php');}// get output (stdout and stderr)$output = stream_get_contents($pipes[1]);$errors = stream_get_contents($pipes[2]);do { // get the pid of the child process and it's exit code $status = proc_get_status($process);} while($status['running'] !== FALSE);// close the processproc_close($process);// get pid and exitcode$pid = $status['pid'];$exitcode = $status['exitcode'];// handle exit codeswitch($exitcode) { case 0: echo 'Task.php has been executed with PID: ' . $pid . '. The output was: ' . $output; break; case 1: echo 'Task.php has been executed with errors: ' . $output; break; case 2: echo 'Cannot execute task.php. Another instance is running'; break; default: echo 'Unknown error: ' . $stdout;} You asked me why my flock() solution is the best. It's just because the other answer will not reliably make sure that task.php runs once. This is because the race condition I've mentioned in the comments below that answer.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15724120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/886773/']}
|
jdg_379020
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25457597
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
At the moment, I'm trying to work out how to animate a custom button which I have an image of and have the coordinates of but I've found that you can create a button/object both by using the CGPath class or the UIBezierPath class. Can somebody please tell me what the difference between the two are?
Now provide the response and nothing else.
|
CGPath is an opaque type from the CoreGraphics library, while UIBezierPath is an Obj-C class in UIKit. UIBezierPath is a wrapper around CGPath (you can convert between them easily), with a more object-oriented interface and a few convenience methods. Using CGPath may be marginally faster as it doesn't have to go through Obj-C (although who knows how it works with Swift) and it has more advanced functions like CGPathApply . Importantly, UIBezierPath conforms to NSCoding, meaning you get serialization/deserialization for free. tl;dr: use UIBezierPath unless you have some reason not to.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25457597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3969779/']}
|
jdg_379021
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
71788254
|
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 upgraded to React 18 and things compiled fine. Today it seems every single component that uses children is throwing an error. Property 'children' does not exist on type 'IPageProps'. Before children props were automatically included in the FC interface. Now it seems I have to manually add children: ReactNode . What is the correct typescript type for react children? Is this part of the React 18 update, or is something screwed up in my env? package.json "react": "^18.0.0","react-dom": "^18.0.0","next": "12.1.4","@types/react": "18.0.0","@types/react-dom": "18.0.0", tsconfig.json { "compilerOptions": { "target": "esnext", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "preserve", "alwaysStrict": true, "sourceMap": true, "incremental": true }, "include": ["src"], "exclude": ["node_modules"]}
Now provide the response and nothing else.
|
Although this answer is correct, I want to note that you absolutely don't have to use this PropsWithChildren helper. (It is primarily useful for the codemod , not manual usage.) Instead, I find it easier to define them manually. Before import * as React from 'react';type Props = {};const Component: React.FC<Props> = ({children}) => {...} After import * as React from 'react';type Props = { children?: React.ReactNode};const Component: React.FC<Props> = ({children}) => {...} That is all that's needed. Or you can stop using React.FC altogether. import * as React from 'react';type Props = { children?: React.ReactNode};function Component({children}: Props): React.ReactNode { ...} In React, children is a regular prop and is not something special. So you need to define it just like you define all the other props. The previous typings that hid it were wrong.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/71788254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1971279/']}
|
jdg_379022
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22593759
|
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 fiddling with this for a while but it won't work and I can't figure out why. Please help. Here is what I have: <html><head> <title>lala</title></head><body> <h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1> <div id="goy"></div> <script type="text/javascript"> function go(what) { document.getElementById("goy").innerHTML = what; } function clear() { document.getElementById("goy").innerHTML = ""; } </script></body></html> The mouseover works and displays the text in the div, but when I move the mouse out of the h1 tag, the text stays there and I don't know why, help would be appreciated.
Now provide the response and nothing else.
|
The problem appears to be that the global symbol clear is already in use and your function doesn't succeed in overriding it. If you change that name to something else (I used blah ), it works just fine: Live: Version using clear which fails | Version using blah which works <html><head> <title>lala</title></head><body> <h1 onmouseover="go('The dog is in its shed')" onmouseout="blah()">lalala</h1> <div id="goy"></div> <script type="text/javascript"> function go(what) { document.getElementById("goy").innerHTML = what; } function blah() { document.getElementById("goy").innerHTML = ""; } </script></body></html> This is a great illustration of the fundamental principal: Avoid global variables wherever possible. The global namespace in browsers is incredibly crowded, and when conflicts occur, you get weird bugs like this. A corollary to that is to not use old-style onxyz=... attributes to hook up event handlers, because they require globals. Instead, at least use code to hook things up: Live Copy <html><head> <title>lala</title></head><body> <h1 id="the-header">lalala</h1> <div id="goy"></div> <script type="text/javascript"> // Scoping function makes the declarations within // it *not* globals (function(){ var header = document.getElementById("the-header"); header.onmouseover = function() { go('The dog is in its shed'); }; header.onmouseout = clear; function go(what) { document.getElementById("goy").innerHTML = what; } function clear() { document.getElementById("goy").innerHTML = ""; } })(); </script></body></html> ...and even better, use DOM2's addEventListener (or attachEvent on IE8 and earlier) so you can have multiple handlers for an event on an element.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22593759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3451259/']}
|
jdg_379023
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45438671
|
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 problem:I have a list of integers: 7,0,2 If I sort the list using Collections.sort(list) the result is: 0,2,7 but I want to sort the list excluding the 0 from the sorting procedure so the output looks like this: 2,0,7 . Is it possible? Thanks in advance. EDIT: I've forgot to mention my 3 possible cases:1) list contains only one "0" and two numbers2) list contains two "0" and one number3) list contains three "0" and no numbers
Now provide the response and nothing else.
|
You can do it but not only with Collections.sort() Retrieve and store in a variable the index where the 0 Integer is : Remove the 0 from the List with List.remove(int) where int is the index. Sort the list with Collections.sort() Add 0 in the List at the stored index. In code, it gives : List<Integer> list = ...;int indexOf = list.indexOf(Integer.valueOf(0));list.remove(indexOf);Collections.sort(list);list.add(indexOf, Integer.valueOf(0)); Update after question edit to handle cases with more than one 0 in the List. I updated because this case is a little more complex to handle. As it removes more than one element, the index is not any longer the index of the original size. public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(7); list.add(0); list.add(2); list.add(9); list.add(0); list.add(1); list.add(0); list.add(4); Set<Integer> indexesOf = new HashSet<>(); int indexOf = -1; int shift = 0; while ((indexOf = list.indexOf(Integer.valueOf(0))) != -1) { indexesOf.add(indexOf + shift++); list.remove(indexOf); } Collections.sort(list); indexesOf.stream().forEach(index -> list.add(index, Integer.valueOf(0))); System.out.println(list);} Output : [1, 0, 2, 4, 0, 7, 0, 9]
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45438671', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8399806/']}
|
jdg_379024
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40832533
|
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 Macbook with OS X El Captain. I think that Python 2.7 comes preinstalled on it. However, I installed Python 3.5 too. When I started using Python 3, I read that if I want to install a package, I should type: pip3 install some_package Anyway, now when I use pip install some_package I get some_package installed for Python 3. I mean I can import it and use it without problems. Moreover, when I type just pip3 in the Terminal. I got this message about the usage: Usage: pip <command> [options] which is the same message I get when I type just pip . Does it mean that in previous versions, things were different, and now pip and pip3 can be used interchangeably? If so, and for the sake of argument, how can I install packages for Python 2 instead of Python 3?
Now provide the response and nothing else.
|
Your pip is a soft link to the same executable file path with pip3 .you can use the commands below to check where your pip and pip3 real paths are: $ ls -l `which pip`$ ls -l `which pip3` You may also use the commands below to know more details: $ pip show pip$ pip3 show pip When we install different versions of python, we may create such soft links to set default pip to some version. make different links for different versions. It is the same situation with python , python2 , python3 More information below if you're interested in how it happens in different cases: MacOS/Homebrew Fedora/CentOS Debian/Ubuntu
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/40832533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2282785/']}
|
jdg_379025
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10843563
|
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 reading the Reasoned Schemer . I have some intuition about how conde works. However, I can't find a formal definition of what conde / conda / condu / condi do. I'm aware of https://www.cs.indiana.edu/~webyrd/ but that seems to have examples rather than definitions. Is there a formal definition of conde , conda , condi , condu somewhere?
Now provide the response and nothing else.
|
In Prolog's terms, condA is "soft cut" a.k.a. *-> , where A *-> B ; C is like (A, B ; not(A), C) , only better ; whereas condU is "committed choice" , a combination of once and a soft cut so that (once(A) *-> B ; false) expresses (A, !, B) (with the cut inside): condA: A *-> B ; C % soft cut, % (A , B ; not(A) , C)condU: once(A) *-> B ; C % committed choice, % (A , !, B ; not(A) , C) (with ; meaning "or" and , meaning "and" , i.e. disjunction and conjunction of goals, respectively). In condA , if the goal A succeeds, all the solutions are passed through to the first clause B and no alternative clauses C are tried. In condU , once/1 allows its argument goal to succeed only once (keeps only one solution, if any). condE is a simple disjunction of conjunctions, and condI is a disjunction which alternates between the solutions of its constituents, interleaving the streams thereof. Here's an attempt at faithfully translating the book's code, w/out the logical variables and unification, into 18 lines of Haskell which is mostly a lazy Lisp with syntax . ( * ) See if this clarifies things: Sequential stream combination (" mplus " of the book): (1) [] ++: ys = ys (2) (x:xs) ++: ys = x : (xs ++: ys) Alternating stream combination (" mplusI "): (3) [] ++/ ys = ys (4) (x:xs) ++/ ys = x : (ys ++/ xs) Sequential feed (" bind "): (5) [] >>: g = [] (6) (x:xs) >>: g = g x ++: (xs >>: g) Alternating feed (" bindI "): (7) [] >>/ g = [] (8) (x:xs) >>/ g = g x ++/ (xs >>/ g) " OR " goal combination (" condE "): (9) (f ||: g) x = f x ++: g x "Alternating OR " goal combination (" condI "): (10) (f ||/ g) x = f x ++/ g x " AND " goal combination (" all "): (11) (f &&: g) x = f x >>: g "Alternating AND " goal combination (" allI " of the book): (12) (f &&/ g) x = f x >>/ g Special goals true and false (or "success" and "failure"): (13) true x = [x] -- a sigleton list with the same solution repackaged (14) false x = [] -- an empty list, meaning the solution is rejected And why are they called true and false ? Because for any goal g we have, e.g., (g &&: true) x = g x >>: true = g x >>: (\ x -> [x] ) = g x (false &&: g) x = false x >>: g = [] >>: g = [] = false x -- ... etc. Goals produce streams (possibly empty) of (possibly updated) solutions, given a (possibly partial) solution to a problem. Re-write rules for all are: (all) = true(all g1) = g1(all g1 g2 g3 ...) = (\x -> g1 x >>: (all g2 g3 ...)) = g1 &&: (g2 &&: (g3 &&: ... ))(allI g1 g2 g3 ...) = (\x -> g1 x >>/ (allI g2 g3 ...)) = g1 &&/ (g2 &&/ (g3 &&/ ... )) Re-write rules for condX are: (condX) = false(condX (else g1 g2 ...)) = (all g1 g2 ...) = g1 &&: (g2 &&: (...))(condX (g1 g2 ...)) = (all g1 g2 ...) = g1 &&: (g2 &&: (...))(condX (g1 g2 ...) (h1 h2 ...) ...) = (ifX g1 (all g2 ...) (ifX h1 (all h2 ...) (...) )) To arrive at the final condE and condI 's translation, there's no need to implement the book's ifE and ifI , since they reduce further to simple operator combinations, with all the operators considered to be right-associative : (condE (g1 g2 ...) (h1 h2 ...) ...) = (g1 &&: g2 &&: ... ) ||: (h1 &&: h2 &&: ...) ||: ...(condI (g1 g2 ...) (h1 h2 ...) ...) = (g1 &&: g2 &&: ... ) ||/ (h1 &&: h2 &&: ...) ||/ ... So there's no need for any special "syntax" in Haskell, plain binary infix operators suffice. Any combination can be used anywhere, with &&/ instead of &&: as needed. But on the other hand condI could also be implemented as a function to accept a collection (list, tree etc.) of goals to be fulfilled, that would use some smart strategy to pick of them one most likely or most needed etc, and not just simple binary alternation as in ||/ operator (or ifI of the book). Next, the book's condA can be modeled by two new operators, ~~> and ||~ , working together. We can use them in a natural way as in e.g. g1 ~~> g2 &&: ... ||~ h1 ~~> h2 &&: ... ||~ ... ||~ gelse which can intuitively be read as " IF g1 THEN g2 AND ... OR-ELSE IF h1 THEN ... OR-ELSE gelse ": " IF-THEN " goal combination is to produce a "try" goal which must be called with a failure-continuation goal: (15) (g ~~> h) f x = case g x of [] -> f x ; ys -> ys >>: h " OR-ELSE " goal combination of a try goal and a simple goal simply calls its try goal with a second, on-failure goal, so it's nothing more than a convenience syntax for automatic grouping of operands: (16) (g ||~ f) x = g f x With the " OR-ELSE " ||~ operator given less binding power than the " IF-THEN " ~~> operator and made right-associative too, and ~~> operator having still less binding power than &&: and the like, sensible grouping of the above example is automatically produced as (g1 ~~> (g2 &&: ...)) ||~ ( (h1 ~~> (h2 &&: ...)) ||~ (... ||~ gelse ...) ) Last goal in an ||~ chain must thus be a simple goal. That's no limitation really, since last clause of condA form is equivalent anyway to simple " AND "-combination of its goals (or simple false can be used just as well). That's all. We can even have more types of try goals, represented by different kinds of " IF " operators, if we want: use alternating feed in a successful clause (to model what could've been called condAI , if there were one in the book): (17) (g ~~>/ h) f x = case g x of [] -> f x ; ys -> ys >>/ h use the successful solution stream only once to produce the cut effect, to model condU : (18) (g ~~>! h) f x = case g x of [] -> f x ; (y:_) -> h y So that, finally, the re-write rules for condA and condU of the book are simply: (condA (g1 g2 ...) (h1 h2 ...) ...) = g1 ~~> g2 &&: ... ||~ h1 ~~> h2 &&: ... ||~ ... (condU (g1 g2 ...) (h1 h2 ...) ...) = g1 ~~>! g2 &&: ... ||~ h1 ~~>! h2 &&: ... ||~ ... ( * ) which is: simple juxtaposition is curried function application , f a b c =~= (((f a) b) c) =~= f(a, b, c) (\ a -> b ) is lambda function, (lambda (a) b) foo x = y is shortcut for foo = (\ x -> y ) a @@ b = y is shortcut for (@@) a b = y , definition of an infix operator @@ parentheses ( ) are just for grouping [] is the empty list, and : means cons -- both as a constructor ( lazy , as the whole language is lazy , i.e. call by need ), on the right of = in definitions; and as a destructuring pattern, on the left (or in pattern-matching case expressions).
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10843563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1383359/']}
|
jdg_379026
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9895924
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
More importantly, how do I fix it? It's as if backgrounding the app doesn't end the session.
Now provide the response and nothing else.
|
When your app goes into background mode it needs to tell the analytics to stop tracking. Application Delegate would have something like: -(void) applicationDidEnterBackground:(UIApplication*)application{[[GANTracker sharedTracker] stopTracker];} In google's Easy Tracker example, a view controller receives notifications when app state changes. Tracking is stopped when app goes into background (Around line 400). if ([application applicationState] == UIApplicationStateBackground) { if (self.state == EasyTrackerStateForeground) { // Transitioned from foreground to background. Generate the app stop // event, and stop the tracker. NSLog(@"Transitioned from foreground to background."); NSError *error = nil; if (![[GANTracker sharedTracker] trackEvent:@"" action:@"" label:@"" value:0 withError:&error]) { NSLog(@"Error tracking foreground event: %@", error); } // TODO(fmela): make this time period a constant. if (![[GANTracker sharedTracker] dispatchSynchronous:2.0]) { NSLog(@"Synchronous dispatch on background failed!"); } [[GANTracker sharedTracker] stopTracker]; } self.state = EasyTrackerStateBackground; }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9895924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1286610/']}
|
jdg_379027
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
109578
|
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 need to write the following (which is the result of a Solve command I ran in Mathematica ) in an academic journal paper: Root[-4 q2^2 - 4 q2^3 + (7 q2 + 19 q2^2) #1 - 17 q2 #1^2 + 2 #1^3 &, 1] I still don't have a good idea of what this Root function means. Can someone write this in an academically acceptable (journal paper-"plain math") format? Thanks for your help. I have quite a few of these expressions that I need to interpret and write up.
Now provide the response and nothing else.
|
TeXForm@ToRadicals@Root[-4 q2^2 - 4 q2^3 + (7 q2 + 19 q2^2) #1 - 17 q2 #1^2 + 2 ^3 &, 1] $$\frac{1}{6} \sqrt[3]{2222 \text{q2}^3-855 \text{q2}^2+3 \sqrt{3} \sqrt{-15633 \text{q2}^6+2190 \text{q2}^5-7225 \text{q2}^4+2744 \text{q2}^3}}-\frac{42 \text{q2}-175 \text{q2}^2}{6 \sqrt[3]{2222 \text{q2}^3-855 \text{q2}^2+3 \sqrt{3} \sqrt{-15633 \text{q2}^6+2190 \text{q2}^5-7225 \text{q2}^4+2744 \text{q2}^3}}}+\frac{17 \text{q2}}{6}$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/109578', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/31179/']}
|
jdg_379028
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23606554
|
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 Dashboard built in Ruby on Rails which fetches images from Webcams and serves them in jpg format. I have a refresh button on each image and would like to be able to refresh each image individually without refreshing the whole page. <% @shares.each do |camera| %> <div class="col-md-4 col-sm-6 col-xs-12 cam-box"> <a href="/cameras/<%= camera['id'] %>"> <div id="cam-name"><h5><%= camera['name'] %></h5></div> <img src="<%= camera['jpg'] %>" alt=""> <a href="#" id="cam-refresh" class="refresh"><span class="glyphicon glyphicon-refresh"></span></a> </div> </a> </div> <% end %> Does anyone know how I might achieve this with Jquery? Appreciate any suggestions.
Now provide the response and nothing else.
|
We do have ko.utils.arrayPushAll(array, valuesToPush) as a utility function that you can use. It is not available directly off of observableArrays though . If you add your pushAll to observableArrays , you would want to operate on the underlying array (this() in your case) and then call valueHasMutated() on the observableArray at the end. This will ensure that subscribers to the observableArray are only notified once with the end result rather than with each push. In KO core, it would need to call valueWillMutate() beforehand as well. The point was that I would not recommend using the code that you posted, as it will notify on every push, which can have a performance impact if you are pushing many items. In core, we might do something like: ko.observableArray.fn.pushAll = function(valuesToPush) { var underlyingArray = this(); this.valueWillMutate(); ko.utils.arrayPushAll(underlyingArray, valuesToPush); this.valueHasMutated(); return this; //optional}; The same discussion happened between John Papa and RP Niemeyer . The link can be found here . Hence, posted only useful tips as an answer here.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23606554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2549016/']}
|
jdg_379029
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14194148
|
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 customize the rendering of a form field in the edit page from sonata admin bundle to include an applet that uses the text content of a field. I know that I have to edit the configureFormFields function in the admin class, but I need to know 3 things: What is the syntax to provide a field form template Where to put the template file ( which directory ) What the template have to looks like.
Now provide the response and nothing else.
|
Found a solution What i have done is: Created a field type, lets call it myfieldType in myCompany\myBundle\Form\Type\myfieldType.php namespace myCompany\myBundle\Form\Type;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\FormBuilder;class myfieldType extends AbstractType{ public function getParent() { return 'text'; } public function getName() { return 'myfield'; }} Registered the Type in app/config/services.yml myCompany.myBundle.form.type.myfield: class: myCompany\myBundle\Form\Type\myfieldType tags: - { name: form.type, alias: myfield } In my myentityAdmin class, protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('myfieldname', 'myfield') ... } and public function getFormTheme() { return array('myCompanymyBundle:Admin:myfield_edit.html.twig');} and the template : {# src/mycompany/myBundle/Resources/views/Form/myfield_edit.html.twig #}{% block myfield_widget %} {% spaceless %} {{ block('textarea_widget') }} {% endspaceless %}{% endblock %} And now i can access the form field value by the twig variable "value" ! So easy... when you got it.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14194148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1254498/']}
|
jdg_379030
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42821330
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Restore original text from Keras’s imdb dataset I want to restore imdb’s original text from Keras’s imdb dataset. First, when I load Keras’s imdb dataset, it returned sequence of word index. >>> (X_train, y_train), (X_test, y_test) = imdb.load_data()>>> X_train[0][1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50, 670, 22665, 9, 35, 480, 284, 5, 150, 4, 172, 112, 167, 21631, 336, 385, 39, 4, 172, 4536, 1111, 17, 546, 38, 13, 447, 4, 192, 50, 16, 6, 147, 2025, 19, 14, 22, 4, 1920, 4613, 469, 4, 22, 71, 87, 12, 16, 43, 530, 38, 76, 15, 13, 1247, 4, 22, 17, 515, 17, 12, 16, 626, 18, 19193, 5, 62, 386, 12, 8, 316, 8, 106, 5, 4, 2223, 5244, 16, 480, 66, 3785, 33, 4, 130, 12, 16, 38, 619, 5, 25, 124, 51, 36, 135, 48, 25, 1415, 33, 6, 22, 12, 215, 28, 77, 52, 5, 14, 407, 16, 82, 10311, 8, 4, 107, 117, 5952, 15, 256, 4, 31050, 7, 3766, 5, 723, 36, 71, 43, 530, 476, 26, 400, 317, 46, 7, 4, 12118, 1029, 13, 104, 88, 4, 381, 15, 297, 98, 32, 2071, 56, 26, 141, 6, 194, 7486, 18, 4, 226, 22, 21, 134, 476, 26, 480, 5, 144, 30, 5535, 18, 51, 36, 28, 224, 92, 25, 104, 4, 226, 65, 16, 38, 1334, 88, 12, 16, 283, 5, 16, 4472, 113, 103, 32, 15, 16, 5345, 19, 178, 32] I found imdb.get_word_index method(), it returns word index dictionary like {‘create’: 984, ‘make’: 94,…}. For converting, I create index word dictionary. >>> word_index = imdb.get_word_index()>>> index_word = {v:k for k,v in word_index.items()} Then, I tried to restore original text like following. >>> ' '.join(index_word.get(w) for w in X_train[5])"the effort still been that usually makes for of finished sucking ended cbc's an because before if just though something know novel female i i slowly lot of above freshened with connect in of script their that out end his deceptively i i" I’m not good at English, but I know this sentence is something strange. Why is this happened? How can I restore original text?
Now provide the response and nothing else.
|
Your example is coming out as gibberish, it's much worse than just some missing stop words. If you re-read the docs for the start_char , oov_char , and index_from parameters of the [ keras.datasets.imdb.load_data ]( https://keras.io/datasets/#imdb-movie-reviews-sentiment-classification ) method they explain what is happening: start_char : int. The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character. oov_char : int. words that were cut out because of the num_words or skip_top limit will be replaced with this character. index_from : int. Index actual words with this index and higher. That dictionary you inverted assumes the word indices start from 1 . But the indices returned my keras have <START> and <UNKNOWN> as indexes 1 and 2 . (And it assumes you will use 0 for <PADDING> ). This works for me: import kerasNUM_WORDS=1000 # only use top 1000 wordsINDEX_FROM=3 # word index offsettrain,test = keras.datasets.imdb.load_data(num_words=NUM_WORDS, index_from=INDEX_FROM)train_x,train_y = traintest_x,test_y = testword_to_id = keras.datasets.imdb.get_word_index()word_to_id = {k:(v+INDEX_FROM) for k,v in word_to_id.items()}word_to_id["<PAD>"] = 0word_to_id["<START>"] = 1word_to_id["<UNK>"] = 2word_to_id["<UNUSED>"] = 3id_to_word = {value:key for key,value in word_to_id.items()}print(' '.join(id_to_word[id] for id in train_x[0] )) The punctuation is missing, but that's all: "<START> this film was just brilliant casting <UNK> <UNK> story direction <UNK> really <UNK> the part they played and you could just imagine being there robert <UNK> is an amazing actor ..."
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42821330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7233229/']}
|
jdg_379031
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
488369
|
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 Q, T and S are three points on an elliptic curve, such that Q+T = S. With knowing Q and S, can we compute T? In other word whether exists subtraction operation on elliptic curve, or not?
Now provide the response and nothing else.
|
One solution which I would consider more or less elegant is the following: $$B = \{x \in A \mid \exists y \in A: f(y) > f(x)\}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/488369', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/81683/']}
|
jdg_379032
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
90551
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
This principle claims that every true statement about a variety over the complex number field $\mathbb{C}$ is true for a variety over any algebraic closed field of characteristic 0. But what is it mean? Is there some "statement" not allowed in this principle? Is there an analog in char p>0? Is there reference about this topic? I tried to find some but in vain. Thanks:)
Now provide the response and nothing else.
|
The Lefschetz principle was formulated and illustrated the first time in: S. Lefschetz, Algebraic Geometry , Princeton University Press, 1953. The basic idea is that every equation over some algebraically closed field of characteristic $0$ only involves finitely many elements, which generate a subfield isomorphic to a subfield of $\mathbb{C}$. But as Seidenberg points out in A. Seidenberg, Comments on Lefschetz's principle , American American Monthly (65), No. 9, Nov. 1958, 685 - 690 Lefschetz has not given a rigorous proof and it is not clear at all if it holds when analytical methods over $\mathbb{C}$ are used. Tarski's classical result that the theory of algebraically closed fields of characteristic $0$ admits quantifier elimination and therefore all models are elementary equivalent is called the "Minor Lefschetz principle", because it does not apply to prominent examples such as Hilbert's Nullstellensatz. A precise formulation, with a short proof, which works in every characteristic, can be found here: Paul C. Eklof, Lefschetz's Principle and Local Functors , Proc. AMS (37), Nr. 2, Feb. 1973, online In the language of that paper, the principle states the following: Let $F$ be a functor from universal domains of characteristic $p$ ( = algebraically closed field of infinite transcendence degree over $\mathbb{F}_p$) to some category of many-sorted structures with embeddings, which satisfies the following finiteness condition: If $K \subseteq L$ is an extension, then every finite subset of $F(L)$ is already included in the image of a subextension of finite transcendence degree over $K$. Then, for all $K,L$, we have that $F(K)$ and $F(L)$ are elementary equivalent. For a specific statement one wants to prove using the Lefschetz princple, one can take $F(K)$ to be the collection of all "relevant algebraic geometry over $K$". A generalization is treated in: Gerhard Frey, Hans-Georg Rück, The strong Lefschetz Principle in Algebraic Geometry , manuscripta math. (55), 385 - 401 (1986)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/90551', 'https://mathoverflow.net', 'https://mathoverflow.net/users/15124/']}
|
jdg_379033
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
250908
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Given two (Euclidean or hyperbolic) triangles $ T = ABC $ and $ T' = A'B'C' $,the natural map is the one that sends $ A' \mapsto A $, $ B' \mapsto B $, $ C' \mapsto C $ and maps affinely each side of $T'$onto the corresponding side of $T$. We say that the triangle $ T' $ dominates the triangle $ T $ if the natural map is a short map (Lipschitz with constant $1$) with respect to the distance in the (Euclidean or hyperbolic) plane. My question is, given a triangle $T$ with side lengths $(a, b,c)$,is it true that the triangle $T'$ with side lengths $(a+\epsilon, b+\epsilon, c+\epsilon)$ dominates $T$ for all $\epsilon>0$ small enough? I can prove this statement for Euclidean triangles by some calculations involving the law of cosines, but I couldn't manage to dothe same in the hyperbolic plane.
Now provide the response and nothing else.
|
No, this is not true. Here is an indirect argument (if I made no mistake). If the statement would be true for $\epsilon > 0$ small enough, then it would be true for all $\epsilon > 0$ (since the maps commute, the set of "good" epsilons for a given $(a,b,c)$ is open; this set is also closed because the Lipschitz condition is closed). We will construct two triangles $(a,b,c)$ and $(a+M, b+M, c+M)$ for which the latter does not dominate the former. Take $a=b=1$ and $c=2$ (or slightly smaller if you need). Take points $A_1$ and $B_1$ on the sides $BC$ and $AC$ at distance $\frac13$ from $C$. The distance between $A_1$ and $B_1$ is $\frac23$. Now consider a triangle $(x, x, x+1)$ for a very large $x$. I claim that the distance between the corresponding points $A'_1$ and $B'_1$ tends to $0$ as $x$ tends to $\infty$. By the sine law in a right triangle we have$$\frac{\sinh \frac{A'_1B'_1}{2}}{\sinh\frac{x}{3}} = \sin\frac{\gamma'}{2} = \frac{\sinh\frac{x+1}2}{\sinh x}$$which implies that $\sinh\frac{A'_1B'_1}2$ goes down as $e^{-\frac{x}6}$. This means that somewhere inbetween there is an isosceles triangle for which the map is not $1$-Lipschitz even for small $\epsilon$...
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/250908', 'https://mathoverflow.net', 'https://mathoverflow.net/users/91134/']}
|
jdg_379034
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
699741
|
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 trying to set up a VPN tunnel using StrongSwan 5.1.2 between two Amazon AWS EC2 instances running Ubuntu 14.04.2 LTS. Prior to using StrongSwan, I used open(libre)swan on an Amazon RedHat AMI, which worked fine. For some reason I can't even get IKE to work here for StrongSwan. I triple checked my AWS configurations, and it all looks good, so it must be a problem with StrongSwan configuration. As you will see below, the error I am getting is "Error writing to socket: Invalid argument" . I have looked online and really can't find the solution to this. I am convinced my strongswan ipsec.conf is improperly configured. Here is what I am working with: Instance #1: N.Virginia - 10.198.0.164 with public EIP 54.X.X.XInstance #2: Oregon - 10.194.0.176 with public EIP 52.Y.Y.Y The (simple) topology is as follows: [ Instance #1 within N.Virginia VPC <-> Public internet <-> Instance #2 within Oregon VPC ] I verified that the following AWS configs are correct: Security groups permit allIP information is correctSrc/Dest disabled on both instancesACLs permit allroutes are present and correct (route to 10.x will point to that local instance in order to be routed out to the VPN tunnel) Below is the /etc/ipsec.conf (this is from Oregon, however it is the same on the N.Virginia instance except the left|right values are reversed) : config setup charondebug="dmn 2, mgr 2, ike 2, chd 2, job 2, cfg 2, knl 2, net 2, enc 2, lib 2"conn aws1oexternal-aws1nvexternal left=52.Y.Y.Y (EIP) leftsubnet=10.194.0.0/16 right=54.X.X.X (EIP) rightsubnet=10.198.0.0/16 auto=start authby=secret type=tunnel mobike=no dpdaction=restart Below is the /etc/ipsec.secrets *(reversed for other instance, obviously): 54.X.X.X 52.Y.Y.Y : PSK "Key_inserted_here" Below is the /etc/strongswan.conf: charon { load_modular = yes plugins { include strongswan.d/charon/*.conf }} Below is the /etc/sysctl.conf: net.ipv4.ip_forward=1net.ipv4.conf.all.accept_redirects = 0net.ipv4.conf.all.send_redirects = 0 Here is the debug output from /var/log/syslog It seems the problem here is "error writing to socket: Invalid argument; after everything I tried, I continue to get this same error : Jun 17 17:34:48 ip-10-198-0-164 charon: 13[IKE] retransmit 5 of request with message ID 0Jun 17 17:34:48 ip-10-198-0-164 charon: 13[NET] sending packet: from 54.X.X.X[500] to 52.Y.Y.Y[500] (1212 bytes)Jun 17 17:34:48 ip-10-198-0-164 charon: 03[JOB] next event in 75s 581ms, waiting]Jun 17 17:34:48 ip-10-198-0-164 charon: 16[NET] sending packet: from 54.X.X.X[500] to 52.Y.Y.Y[500]Jun 17 17:34:48 ip-10-198-0-164 charon: 13[MGR] checkin IKE_SA aws1vexternal-aws1oexternal[1]Jun 17 17:34:48 ip-10-198-0-164 charon: 13[MGR] check-in of IKE_SA successful.Jun 17 17:34:48 ip-10-198-0-164 charon: 16[NET] error writing to socket: Invalid argumentJun 17 17:36:04 ip-10-198-0-164 charon: 03[JOB] got event, queuing job for executionJun 17 17:36:04 ip-10-198-0-164 charon: 03[JOB] no events, waitingJun 17 17:36:04 ip-10-198-0-164 charon: 08[MGR] checkout IKE_SAJun 17 17:36:04 ip-10-198-0-164 charon: 08[MGR] IKE_SA aws1vexternal-aws1oexternal[1] successfully checked outJun 17 17:36:04 ip-10-198-0-164 charon: 08[IKE] giving up after 5 retransmitsJun 17 17:36:04 ip-10-198-0-164 charon: 08[IKE] establishing IKE_SA failed, peer not respondingJun 17 17:36:04 ip-10-198-0-164 charon: 08[MGR] checkin and destroy IKE_SA aws1vexternal-aws1oexternal[1]Jun 17 17:36:04 ip-10-198-0-164 charon: 08[IKE] IKE_SA aws1vexternal-aws1oexternal[1] state change: CONNECTING => DESTROYINGJun 17 17:36:04 ip-10-198-0-164 charon: 08[MGR] check-in and destroy of IKE_SA successful Below is what I have tried so far: 1) Verified layer 3 2) rebooted machines 3) Tried adding in leftid= 4) Tried doing ipsec update then ipsec restart 5) Tried adding nat_traversal=yes under confif setup (note that this shouldn't matter since ipsec statusall verified using IKEv2, which according to documentation automatically uses nat_traversal) 6) Tried omitting virtual_private <-- Was used according to AWS openswan documentation so I included it in strongswan config. 7) Tried disabling net.ipv4.conf.all.send_redirects = 0 and net.ipv4.conf.all.accept_redirects = 0 in /etc/sysctl.conf 8) Tried using private IP instead of EIPs. I no longer get the socket error, however obviously the two IPs can't communicate to each other to peer... 9) Tried adding this to strongswan.conf: load = aes des sha1 sha2 md5 gmp random nonce hmac stroke kernel-netlink socket-default updown 10) Tried using leftfirewall=yes, didn't work Please help! Thanks! EDIT #1: Michael's response cleared the original problem, however I have a new problem related to routing. Both VPN instances are unable to ping each other. Furthermore, when I try to ping from a random instance in either subnet, to either another random instance or the far end VPN instance, I get the following ping response: root@ip-10-194-0-80:~# ping 10.198.0.164PING 10.198.0.164 (10.198.0.164) 56(84) bytes of data.From 10.194.0.176: icmp_seq=1 Redirect Host(New nexthop: 10.194.0.176)From 10.194.0.176: icmp_seq=2 Redirect Host(New nexthop: 10.194.0.176)From 10.194.0.176: icmp_seq=3 Redirect Host(New nexthop: 10.194.0.176)From 10.194.0.176: icmp_seq=4 Redirect Host(New nexthop: 10.194.0.176) Obviously this must be a routing issue between the two VPN instances (most likely due to strongswan config or instance routing table) since the 10.194.0.80 host in the Oregon subnet is able to receive a response from the Oregon VPN instance. Route table + traceroute on instance: root@ip-10-194-0-80:~# netstat -rnKernel IP routing tableDestination Gateway Genmask Flags MSS Window irtt Iface0.0.0.0 10.194.0.1 0.0.0.0 UG 0 0 0 eth010.194.0.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0root@ip-10-194-0-80:~# traceroute 10.198.0.164traceroute to 10.198.0.164 (10.198.0.164), 30 hops max, 60 byte packets 1 10.194.0.176 (10.194.0.176) 0.441 ms 0.425 ms 0.409 ms^C When I was using openswan, it did not require me to make any manual modifications to each instance's routing table. Here is the Oregon VPN instance's routing table: root@ip-10-194-0-176:~# netstat -rnKernel IP routing tableDestination Gateway Genmask Flags MSS Window irtt Iface0.0.0.0 10.194.0.1 0.0.0.0 UG 0 0 0 eth010.194.0.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0 I'm a bit stumped. EDIT #2: Looks like routing between the VPN instances might not be the problem: /var/log/syslog shows packets being received from one VPN instance public IP to the other VPN instance Jun 23 19:57:49 ip-10-194-0-176 charon: 10[NET] received packet: from 54.X.X.X[4500] to 10.194.0.176[4500] (76 bytes) Looks like it is an issue related to Child Security Associations: aws1oexternal-aws1nvexternal: child: 10.194.0.0/16 === 10.198.0.0/16 TUNNEL, dpdaction=restartSecurity Associations (1 up, 0 **connecting**): /var/log/syslog: Jun 23 19:52:19 ip-10-194-0-176 charon: 02[IKE] failed to establish CHILD_SA, keeping IKE_SAJun 23 19:52:48 ip-10-194-0-176 charon: 11[IKE] queueing CHILD_CREATE taskJun 23 19:52:48 ip-10-194-0-176 charon: 11[IKE] activating CHILD_CREATE taskJun 23 19:52:48 ip-10-194-0-176 charon: 06[IKE] establishing CHILD_SA aws1oexternal-aws1nvexternalJun 23 19:52:48 ip-10-194-0-176 charon: 10[IKE] received FAILED_CP_REQUIRED notify, no CHILD_SA builtJun 23 19:52:48 ip-10-194-0-176 charon: 10[IKE] failed to establish CHILD_SA, keeping IKE_SAJun 23 19:52:49 ip-10-194-0-176 charon: 14[CFG] looking for a child config for 10.194.0.0/16 === 10.198.0.0/16 Jun 23 19:52:49 ip-10-194-0-176 charon: 14[CFG] found matching child config "aws1oexternal-aws1nvexternal" with prio 10Jun 23 19:52:49 ip-10-194-0-176 charon: 14[IKE] configuration payload negotiation failed, no CHILD_SA builtJun 23 19:52:49 ip-10-194-0-176 charon: 14[IKE] failed to establish CHILD_SA, keeping IKE_SA ***EDIT #3: Problem solved (uhh, actually see EDIT #4 below...)**** Problem fixed. 1) I did not properly follow Michael's config directions. I also configured a rightsourceip and leftsourceip together, thereby causing both instances to believe they were both initiators. I ensured that one was an initiator and one was a requestor; this fixed the IKE problem. 2) I figured out that I also had to explicitly set the esp parameter. Even though there is already a default (aes128-sha1,3des-sha1), the esp parameter still has to be set in order for the instance to know to use esp OR ah (but not both). I ended up using aes128-sha1-modp2048. Hope this posting helps the next linux newbie set this up!! Cheers! EDIT #4: Problem (not really) solved While troubleshooting a separate issue related to strongswan, I changed the "leftfirewall" parameter, tested, didn't fix my separate issue, then reverted back to the orig config beforehand (commented out leftfirewall). I then noticed that I now couldn't ping across the tunnel. After going crazy for hours trying to figure out what happened, I commented out the esp parameter to see what would happen: I CAN NOW PING ACROSS THE TUNNEL AGAIN! <- so, there is a possibility there are some ipsec ghosts running around playing tricks on me and that the esp parameter isn't really the fix for the TS_UNACCEPTABLE errors (although other resources online state the esp parameter is the fix...) EDIT #5: Problem fully solved I ended up moving everything into a test environment and starting from scratch. I installed from source using the latest version (5.3.2) rather than the older version that was in the Ubuntu repo (5.1.2). This cleared the problem I was having above, and verified layer 7 connectivity using netcat (great tool!!) between multiple subnets over the VPN tunnel. Also: It is NOT required to enable DNS hostnames for the VPC (as I was incorrectly led to believe by Amazon), FYI> Hope this all helps!!!!!! Additional edit 2/11/2017: As per JustEngland's request, copying the working configuration below (leaving out certain details in order to prevent identification in any way): Side A: # ipsec.conf - strongSwan IPsec configuration file# basic configurationconfig setup# Add connections here.conn %default ikelifetime= You choose; must match other side keylife= You choose; must match other side rekeymargin= You choose; must match other side keyingtries=1 keyexchange= You choose; must match other side authby=secret mobike=noconn side-a left=10.198.0.124 leftsubnet=10.198.0.0/16 leftid=54.y.y.y leftsourceip=10.198.0.124 right=52.x.x.x rightsubnet=10.194.0.0/16 auto=start type=tunnel# Add connections here.root@x:~# cat /etc/ipsec.secrets A.A.A.A B.B.B.B : PSK "Your Password" Side B: # ipsec.conf - strongSwan IPsec configuration file# basic configurationconfig setupconn %default ikelifetime= You choose; must match other side keylife= You choose; must match other side rekeymargin= You choose; must match other side keyingtries=1 keyexchange= You choose; must match other side authby=secret mobike=noconn side-b left=10.194.0.129 leftsubnet=10.194.0.0/16 leftid=52.x.x.x right=54.y.y.y rightsubnet=10.198.0.0/16 rightsourceip=10.198.0.124 auto=start type=tunnelroot@x:~# cat /etc/ipsec.secrets B.B.B.B A.A.A.A : PSK "Your Password"
Now provide the response and nothing else.
|
In VPC, the public IP address of an instance is never bound to the instance's stack, so you have to configure both the internal private address and the external public address. The invalid argument is presumably caused by trying to source traffic directly from the public IP address, which isn't known to your instance. left=10.10.10.10 # instance private IP of local systemleftsourceip=10.10.10.10 # instance private IP of local systemleftid=203.x.x.x # elastic IP of local systemleftsubnet=10.x.x.x/xxrightsubnet=10.x.x.x/xxright=198.x.x.x # elastic IP of remote system
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/699741', 'https://serverfault.com', 'https://serverfault.com/users/272326/']}
|
jdg_379035
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
69644
|
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
One of out clients is using a sub-network of 172.168.100.0/24 or
Now provide the response and nothing else.
|
They'll accidentally allow public IP traffic through ACLs and reduce the effectiveness of their perimeter security design. They'll also make parts of the real Internet inaccessible to themselves. The specific subnet you mention, 172.168.100.0/24 , is used by Oath. IIRC that's a division of Verizon that has to do with advertising. You should definitely help them fix this problem.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/69644', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/70465/']}
|
jdg_379036
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30757193
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to find out whether a character in a string is an emoji. For example, I have this character: let string = ""let character = Array(string)[0] I need to find out if that character is an emoji.
Now provide the response and nothing else.
|
What I stumbled upon is the difference between characters, unicode scalars and glyphs. For example, the glyph consists of 7 unicode scalars: Four emoji characters: In between each emoji is a special character, which works like character glue; see the specs for more info Another example, the glyph consists of 2 unicode scalars: The regular emoji: A skin tone modifier: Last one, the glyph 1️⃣ contains three unicode characters: The digit one : 1 The variation selector The Combining Enclosing Keycap : ⃣ So when rendering the characters, the resulting glyphs really matter. Swift 5.0 and above makes this process much easier and gets rid of some guesswork we needed to do. Unicode.Scalar 's new Property type helps is determine what we're dealing with.However, those properties only make sense when checking the other scalars within the glyph. This is why we'll be adding some convenience methods to the Character class to help us out. For more detail, I wrote an article explaining how this works . For Swift 5.0, this leaves you with the following result: extension Character { /// A simple emoji is one scalar and presented to the user as an Emoji var isSimpleEmoji: Bool { guard let firstScalar = unicodeScalars.first else { return false } return firstScalar.properties.isEmoji && firstScalar.value > 0x238C } /// Checks if the scalars will be merged into an emoji var isCombinedIntoEmoji: Bool { unicodeScalars.count > 1 && unicodeScalars.first?.properties.isEmoji ?? false } var isEmoji: Bool { isSimpleEmoji || isCombinedIntoEmoji }}extension String { var isSingleEmoji: Bool { count == 1 && containsEmoji } var containsEmoji: Bool { contains { $0.isEmoji } } var containsOnlyEmoji: Bool { !isEmpty && !contains { !$0.isEmoji } } var emojiString: String { emojis.map { String($0) }.reduce("", +) } var emojis: [Character] { filter { $0.isEmoji } } var emojiScalars: [UnicodeScalar] { filter { $0.isEmoji }.flatMap { $0.unicodeScalars } }} Which will give you the following results: "A̛͚̖".containsEmoji // false"3".containsEmoji // false"A̛͚̖▶️".unicodeScalars // [65, 795, 858, 790, 9654, 65039]"A̛͚̖▶️".emojiScalars // [9654, 65039]"3️⃣".isSingleEmoji // true"3️⃣".emojiScalars // [51, 65039, 8419]"".isSingleEmoji // true"♂️".isSingleEmoji // true"".isSingleEmoji // true"⏰".isSingleEmoji // true"".isSingleEmoji // true"".isSingleEmoji // true"".isSingleEmoji // true"".containsOnlyEmoji // true"".containsOnlyEmoji // true"Hello ".containsOnlyEmoji // false"Hello ".containsEmoji // true" Héllo ".emojiString // """".count // 1" Héllœ ".emojiScalars // [128107, 128104, 8205, 128105, 8205, 128103, 8205, 128103]" Héllœ ".emojis // ["", ""]" Héllœ ".emojis.count // 2"".isSingleEmoji // false"".containsOnlyEmoji // true For older Swift versions, check out this gist containing my old code.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/30757193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2876236/']}
|
jdg_379037
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50880917
|
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 get version installed chrome version using command prompt in windows? Tried, "C:\Program Files\Google\Chrome\Application\chrome.exe" -version "C:\Program Files\Google\Chrome\Application\chrome.exe" --version "C:\Program Files\Google\Chrome\Application\chrome.exe" -product-version "C:\Program Files\Google\Chrome\Application\chrome.exe" --product-version When i do that, a browser instance is opening. What flag should I be using to get the version. I am using Windows 7. Google Chrome version is 67.0.3396.87. Thanks in advance
Now provide the response and nothing else.
|
There's a bug filed about this: https://bugs.chromium.org/p/chromium/issues/detail?id=158372 Original Answer (but see the update below) What works for me is wmic datafile where name="C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" get Version /value It prints Version=67.0.3396.99 surrounded by some blank lines. There are some other suggestions in the bug comments, like querying the registry. Update Someone from the Chromium team posted this "totally unsupported" batch file in the bug comment thread: @ECHO OFF:: Look for machine-wide Chrome installs (stable, Beta, and Dev).:: Get the name, running version (if an update is pending relaunch), and:: installed version of each.FOR %%A IN ( {8A69D345-D564-463c-AFF1-A69D9E530F96}, {8237E44A-0054-442C-B6B6-EA0509993955}, {401C381F-E0DE-4B85-8BD8-3F3F14FBDA57}) DO ( reg query HKLM\Software\Google\Update\Clients\%%A /v name /reg:32 2> NUL reg query HKLM\Software\Google\Update\Clients\%%A /v opv /reg:32 2> NUL reg query HKLM\Software\Google\Update\Clients\%%A /v pv /reg:32 2> NUL):: Look for Chrome installs in the current user's %LOCALAPPDATA% directory:: (stable, Beta, Dev, and canary).:: Get the name, running version (if an update is pending relaunch), and:: installed version of each.FOR %%A IN ( {8A69D345-D564-463c-AFF1-A69D9E530F96}, {8237E44A-0054-442C-B6B6-EA0509993955}, {401C381F-E0DE-4B85-8BD8-3F3F14FBDA57}, {4ea16ac7-fd5a-47c3-875b-dbf4a2008c20}) DO ( reg query HKCU\Software\Google\Update\Clients\%%A /v name /reg:32 2> NUL reg query HKCU\Software\Google\Update\Clients\%%A /v opv /reg:32 2> NUL reg query HKCU\Software\Google\Update\Clients\%%A /v pv /reg:32 2> NUL) That should probably be seen as the right way to go for the time being.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50880917', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2414160/']}
|
jdg_379038
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3068189
|
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:
Consider the functión $u \in W^{1,p}(-1,1) $ , defined by $u(x)=|x|$ , we know its weak derivative is $$g(x)=\left \{ \begin{matrix} 1 & \text{if }x\in(0,1) \\ -1 & \text{if } x \in (-1,0) \end{matrix} \right..$$ By intregation by parts is straightforward verify this. But I want to prove that $g \notin W^{1,p}(-1,1)$ . If we suposse that $g$ has a weak derivative then exist a $h \in L^{p}(-1,1)$ , which satisfies $$\varphi(1)-\varphi(0)+\varphi(-1)-\varphi(0)=\int_{-1}^{1} h(t)\varphi(t)dt$$ for any $\varphi \in C_{c}^{1}(-1,1)$ . I tried to get a contradiction evaluating by concrete test functions like $\varphi(t)=t$ or $\varphi(t)=1$ but I don't get any interesting. Which kind functions would help me? or there is another aproach?
Now provide the response and nothing else.
|
To be blunt, it's typically not a matter of noticing a pattern, but proving the pattern that shows when it's enough. That's not to say pattern recognition is not helpful, because it absolutely is. It can cue you into where proving the pattern might lead, or what you might have to prove - all depending on the context. But the statement $$\tan^{-1} x = x - \frac{x^3}3 + \frac{ x^5 }5 - \frac{ x^7 }7 + \cdots = \sum_{k=0}^\infty \frac{(-1)^{k}}{2k+1} x^{2k+1}$$ means you would need to show that the factor controlling the sign, $(-1)^k$ , does indeed show up in the summation. You can't just say "oh I found the first few terms, the rest obviously follow the same pattern." I mean, they might, but there are examples of sequences that suddenly break from such a pattern. Maybe yours breaks from the pattern $1,000,$ or perhaps $100,000,000$ , or perhaps $10^{{10}^{100}}$ terms down the road. I mean, you have the right idea, sort of, you almost seem to be on the brink of realizing this very thing at the end of your post - that after finding however-many terms of the sequences, how do you know that the pattern doesn't change? And that's the thing - that's completely true, there's no reason, just finding $$x \;\;\; , \;\;\; - \frac{x^3}3 \;\;\; , \;\;\; \frac{ x^5 }5 \;\;\; , \;\;\; - \frac{ x^7 }7 \;\;\; , \;\;\; ...$$ that you should expect $x^9/9$ to come next. Finding a pattern isn't sufficient, you also have to verify - to prove - that pattern. I believe this post has a rough proof for the arctangent power series.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3068189', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/135689/']}
|
jdg_379039
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5292069
|
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 stored procedure I need to call several different times passing in different paramaters each time. I would like to collect the results as a single dataset. Is something like this possible ... exec MyStoredProcedure 1UNIONexec MyStoredProcedure 2UNIONexec MyStoredProcedure 3 I tried using the syntax above but got the error ... Incorrect syntax near the keyword 'UNION' The stored procedures I am dealing with are pretty complex and sort of a "black box" to me, so I cannot get into the definition of the stored procedure and change anything. Any suggestions on how to gather the results together? I am using SQL Server 2008 R2. Thanks for any help.
Now provide the response and nothing else.
|
You'd have to use a temp table like this. UNION is for SELECTs, not stored procs CREATE TABLE #foo (bar int ...)INSERT #fooexec MyStoredProcedure 1INSERT #fooexec MyStoredProcedure 2INSERT #fooexec MyStoredProcedure 3... And hope the stored procs don't have INSERT..EXEC.. already which can not be nested. Or multiple resultsets. Or several other breaking constructs
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5292069', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/287793/']}
|
jdg_379040
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.