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 | 2050850 |
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 very simple MATLAB question. What is the easiest way to find the point of intersection between two vectors. I am not familiar with the various MATLAB functions -- it seems like there should be one for this. For example, if I have one vector from (0,0) to (6,6) and another vector from (0,6) to (6,0), I need to determine that they intersect at (3,3).
Now provide the response and nothing else.
| One solution is to use the equations derived in this tutorial for finding the intersection point of two lines in 2-D ( update: this is an internet archive link since the site no longer exists). You can first create two matrices: one to hold the x coordinates of the line endpoints and one to hold the y coordinates. x = [0 0; 6 6]; %# Starting points in first row, ending points in second rowy = [0 6; 6 0]; The equations from the above source can then be coded up as follows: dx = diff(x); %# Take the differences down each columndy = diff(y);den = dx(1)*dy(2)-dy(1)*dx(2); %# Precompute the denominatorua = (dx(2)*(y(1)-y(3))-dy(2)*(x(1)-x(3)))/den;ub = (dx(1)*(y(1)-y(3))-dy(1)*(x(1)-x(3)))/den; And you can now compute the intersection point of the two lines: xi = x(1)+ua*dx(1);yi = y(1)+ua*dy(1); For the example in the question, the above code gives xi = 3 and yi = 3 , as expected. If you want to check that the intersection point lies between the endpoints of the lines (i.e. they are finite line segments ), you just have to check that the values ua and ub both lie between 0 and 1: isInSegment = all(([ua ub] >= 0) & ([ua ub] <= 1)); A couple more points from the tutorial I linked to above: If the denominator den is 0 then the two lines are parallel. If the denominator and numerator for the equations for ua and ub are 0 then the two lines are coincident. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2050850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/132433/']} | jdg_76541 |
stackexchange | llm_judgeable_groundtruth_similarity | 2136204 |
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:
Evaluate $$\int_{0}^{2\pi}\frac{1}{2-\cos^2(x)} dx$$ For this problem I tried using residue theorem to find the value of the integral but the computation seems rather messy. Is there a better way to find the integral? Thanks.
Now provide the response and nothing else.
| I would do it like this$$I=\int_0^{2\pi} \frac1{2-\cos^2(x)} = \int_0^{2\pi} \frac2{3-\cos(2x)} = \int_0^{\pi} \frac4{3-\cos(2x)}.$$We then introduce $z=e^{2ix}$ and obtain$$ I= \oint_{|z|=1} \frac{dz}{2i z} \frac{4}{3 -(z+z^{-1})/2}= \oint_{|z|=1} \frac{4i}{1-6 z +z^2}.$$ There is a single pole at $z^*= 3-2\sqrt{2}$ inside the unit circle. The second pole is at $z_2= 3+2\sqrt{2}$ with $z^2-6z+1=(z-z^*)(z-z_2)$. Using the residue theorem, we obtain$$I= -8\pi \mathop{\rm Res}_{z=z^*} \frac{1}{(z-z^*)(z-z_2)}= -\frac{8\pi}{z^*-z_2} =\sqrt{2}\pi.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2136204', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/244917/']} | jdg_76542 |
stackexchange | llm_judgeable_groundtruth_similarity | 7651 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
We had an incident where some of our managers were given passwords for the people they supervise using a particular company website. Ostensibly it was done so the managers could check in on the users and see that they're doing what they've been directed to do with this third party website. When I found out that a list of the passwords were printed out and given to the managers, I immediately thought that the passwords on the commercial website weren't being stored in a secure fashion and warned users that they should immediately change any passwords that nearly matched their "throwaway" accounts; I'm also afraid that, being typical humans, there are a number of people that used the same password on that site that they use with our internal password system so they didn't need to remember more than one password. I was also shocked that the users weren't warned that their passwords would be distributed to other people/supervisors. I went to the website in question and clicked on their privacy policy link; it returned a 404 error. Was I being paranoid? What are the chances that the commercial website is storing theirpasswords in the clear if a manager is able to retrieve aplaintext list of passwords?
Now provide the response and nothing else.
| No, you're not paranoid. The chances are pretty high that passwords are stored as plaintext in the database (it's the most obvious explanation). Some estimations say that 30% of websites store (or have stored) their users' passwords in plaintext. Examples include Reddit.com or RockYou.com. It's typically only after a serious breach occurs that the password storage procedures are put to the test. Often sites that store passwords in plaintext will offer you a possibility to resend you the old password once you forgot it. That pretty much proves this insecure practice. There is a possibility that the passwords are stored encrypted and were decrypted for the report, but it's a rare practice. Even if the passwords are encrypted there will always be a problem of key storage as the application most likely would need access to the decryption key for authenticating its users. Of course the proper thing to do for the application is to salt and hash the passwords . | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/7651', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/5208/']} | jdg_76543 |
stackexchange | llm_judgeable_groundtruth_similarity | 346356 |
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 want to add both timestamp and file list to the log. Currently, I can only get one. The following command to can track the updated file list but it does not add timestamp. rsync -avz --progress --delete /web/path/public_html/ $newhost:/web/path/public_html >> /var/log/rsync.log sent 2345743 bytes received 43205 bytes 530877.33 bytes/sectotal size is 14828110173 speedup is 6206.96sending incremental file listerror_log 5740980 100% 36.98MB/s 0:00:00 (xfer#1, to-check=1405/1524)sent 2344322 bytes received 51694 bytes 684576.00 bytes/sectotal size is 14828115593 speedup is 6188.65 The following command can add timestamp to the log, but it doesn't tell which files were updated. rsync -avz --progress --delete /web/path/public_html/ $newhost:/web/path/public_html --log-file=/var/log/rsync1.log --log-file-format="%t\n" 2012/01/03 17:30:05 [10505] Total transferred file size: 6170062 bytes2012/01/03 17:30:05 [10505] Literal data: 5470 bytes2012/01/03 17:30:05 [10505] Matched data: 6164592 bytes2012/01/03 17:30:05 [10505] File list size: 23332822012/01/03 17:30:05 [10505] File list generation time: 0.002 seconds2012/01/03 17:30:05 [10505] File list transfer time: 0.000 seconds2012/01/03 17:30:05 [10505] Total bytes sent: 23454352012/01/03 17:30:05 [10505] Total bytes received: 286282012/01/03 17:30:05 [10505] sent 2345435 bytes received 28628 bytes 527569.56 bytes/sec2012/01/03 17:30:05 [10505] total size is 14828121798 speedup is 6245.88
Now provide the response and nothing else.
| From rsyncd.conf(5): "The default log format is "%o %h [%a] %m (%u) %f %l", and a "%t [%p] " is always prefixed when using the "log file" parameter." 2012/01/04 03:19:12 [1461] building file list2012/01/04 03:19:12 [1461] .d..t...... ./2012/01/04 03:19:14 [1461] >f+++++++++ file1.pdf2012/01/04 03:19:14 [1461] >f+++++++++ file2.pdf2012/01/04 03:19:14 [1461] >f+++++++++ file3.pdf2012/01/04 03:19:14 [1461] sent 40892313 bytes received 72 bytes 16356954.00 bytes/sec2012/01/04 03:19:14 [1461] total size is 81997177 speedup is 2.01 I believe this is what you want? Try your command without the --log-format option, and read the manual page for rsyncd.conf and search for "log format" to see what options you have to customize the logfile. Another option I often use in my rsync scripts is to add date before/after the rsync, like: date >> /var/log/rsync.logrsync -avz --progress --delete /src /dst >> /var/log/rsync.logdate >> /var/log/rsync.log And a third and final option would be to put your rsync command within a bash loop to prefix each line with the date. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/346356', 'https://serverfault.com', 'https://serverfault.com/users/26731/']} | jdg_76544 |
stackexchange | llm_judgeable_groundtruth_similarity | 18786230 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an application that starts with a database pre-populated. I want to update the application, inserting new tables and copying the new database pre-populated.When updating the application, if I put the version of the database to 2, it creates new tables, but does not copy the new database. But if I keep to version 1, the application stops with an error. The database is in the assets folder and use this code to copy in the first time: public class DataBaseHelper<E> extends OrmLiteSqliteOpenHelper { private static String DB_PATH = "/data/data/com.teste/databases/"; private static String DB_NAME = "teste.db"; private static int DB_VERSION = 1; private SQLiteDatabase myDataBase; Context context; public DataBaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); this.context = context; try { createDataBase(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { } else { this.getReadableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } } } private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { } if (checkDB != null) { checkDB.close(); } return checkDB != null ? true : false; } private void copyDataBase() throws IOException { InputStream myInput = context.getAssets().open(DB_NAME); String outFileName = DB_PATH + DB_NAME; OutputStream myOutput = new FileOutputStream(outFileName); byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.flush(); myOutput.close(); myInput.close(); } public void openDataBase() throws SQLException { String myPath = DB_PATH + DB_NAME; myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } @Override public void onCreate(SQLiteDatabase db, ConnectionSource src) { try { TableUtils.createTable(src, Table1.class); TableUtils.createTable(src, Table2.class); TableUtils.createTable(src, Table3.class); } catch (Exception e) { e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase db, ConnectionSource src, int oldVersion, int newVersion) { try { TableUtils.dropTable(src, Table1.class, true); TableUtils.dropTable(src, Table2.class, true); TableUtils.dropTable(src, Table3.class, true); onCreate(db, src); } catch (Exception e) { e.printStackTrace(); } } @Override public synchronized void close() { if (myDataBase != null) myDataBase.close(); super.close(); }} Now, I have one more table to insert, and I'm using this code: public class DataBaseHelper<E> extends OrmLiteSqliteOpenHelper {private static String DB_PATH = "/data/data/com.teste/databases/";private static String DB_NAME = "teste.db";private static int DB_VERSION = 2;private SQLiteDatabase myDataBase;Context context;public DataBaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); this.context = context; try { createDataBase(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}public void createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { } else { this.getReadableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } }}private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { } if (checkDB != null) { checkDB.close(); } return checkDB != null ? true : false;}private void copyDataBase() throws IOException { InputStream myInput = context.getAssets().open(DB_NAME); String outFileName = DB_PATH + DB_NAME; OutputStream myOutput = new FileOutputStream(outFileName); byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.flush(); myOutput.close(); myInput.close();}public void openDataBase() throws SQLException { String myPath = DB_PATH + DB_NAME; myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);}@Overridepublic void onCreate(SQLiteDatabase db, ConnectionSource src) { try { TableUtils.createTable(src, Table1.class); TableUtils.createTable(src, Table2.class); TableUtils.createTable(src, Table3.class); TableUtils.createTable(src, Table4.class); } catch (Exception e) { e.printStackTrace(); }}@Overridepublic void onUpgrade(SQLiteDatabase db, ConnectionSource src, int oldVersion, int newVersion) { try { TableUtils.dropTable(src, Table1.class, true); TableUtils.dropTable(src, Table2.class, true); TableUtils.dropTable(src, Table3.class, true); TableUtils.dropTable(src, Table4.class, true); onCreate(db, src); } catch (Exception e) { e.printStackTrace(); }}@Overridepublic synchronized void close() { if (myDataBase != null) myDataBase.close(); super.close();}} EDIT 2: I call copyDatabase in onUpgrade and the DB is not copied. See: TableUtils.createTable(src, Linhas.class);TableUtils.createTable(src, Horarios.class);TableUtils.createTable(src, Itinerarios.class);TableUtils.createTable(src, Utils.class);copyDataBase(); Any help? EDIT 3: I noticed that when we change the version of the database upgrade using the method and copied the database from asset folder, the data do not appear because the version of the database that this folder assets be less than the current version. Is there a way to copy when the new database pre-populated, change the version of it?
Now provide the response and nothing else.
| You can't observe an array for changes. ReactiveCocoa uses key-value observation. Which, as the name suggests, only observes changes to keyed attributes (dictionary members, properties, etc.). What you can do is observe an array property for changes: @interface Blah : NSObject@property (copy, readonly) NSArray *arrayProperty;@end// later...Blah *blah = [Blah new];[RACObserve(blah, arrayProperty) subscribeNext:^(NSArray *wholeArray){}]; If you want to know which objects where inserted/removed then you have two options. You could work it out by storing each array and comparing each with the previous. This is simplest but will perform badly with very large arrays. AFAIK, ReactiveCocoa does not have built-in operations to do this. Or you could implement KVO collection accessors and ensure that changes to the array are made using mutableArrayValueForKey: . This avoids creating a new array whenever any changes are made, and also notifies observers of changes made to the proxy array returned by mutableArrayValueForKey: . Observing change info with ReactiveCocoa is slightly more involved: RACSignal *changeSignal = [blah rac_valuesAndChangesForKeyPath:@keypath(blah, arrayProperty) options: NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld observer:nil];[changeSignal subscribeNext:^(RACTuple *x){ NSArray *wholeArray = x.first; NSDictionary *changeDictionary = x.second;}]; The change dictionary tells you what kind of change was made to the array, which objects were inserted/removed, and the indexes of the inserted/removed objects. It is documented at: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSKeyValueObserving_Protocol/Reference/Reference.html | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18786230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2087208/']} | jdg_76545 |
stackexchange | llm_judgeable_groundtruth_similarity | 45713887 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
dict1 = {a: 5, b: 7}dict2 = {a: 3, c: 1}result {a:8, b:7, c:1} How can I get the result?
Now provide the response and nothing else.
| this is a one-liner that would do just that: dict1 = {'a': 5, 'b': 7}dict2 = {'a': 3, 'c': 1}result = {key: dict1.get(key, 0) + dict2.get(key, 0) for key in set(dict1) | set(dict2)}# {'c': 1, 'b': 7, 'a': 8} note that set(dict1) | set(dict2) is the set of the keys of both your dictionaries. and dict1.get(key, 0) returns dict1[key] if the key exists, 0 otherwise. this works on a more recent python version: {k: dict1.get(k, 0) + dict2.get(k, 0) for k in dict1.keys() | dict2.keys()} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45713887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8450773/']} | jdg_76546 |
stackexchange | llm_judgeable_groundtruth_similarity | 57531781 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been going through a lot of similar posts but I am not able to understand the reason here. I had the whole code working. I only added the following code later: import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}import com.fasterxml.jackson.module.scala.DefaultScalaModuleimport com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapperdef toJson(value: Map[Symbol, Any]): String = { toJson(value map { case (k,v) => k.name -> v})}def toJson(value: Any): String = { mapper.writeValueAsString(value)}def toMap[V](json:String)(implicit m: Manifest[V]): Map[String, Any] = fromJson[Map[String,Any]](json)def fromJson[T](json: String)(implicit m : Manifest[T]): T = { mapper.readValue[T](json)}val mapper = new ObjectMapper() with ScalaObjectMappermapper.registerModule(DefaultScalaModule)mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) and now when i execute the following writestream cell in notebook: data.writeStream .option("checkpointLocation", _checkpointLocation) .format("avro") .partitionBy("Date", "Hour") .option("path", _containerPath) .start() I am getting this error: org.apache.spark.SparkException: Job aborted. at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:196) Caused by: org.apache.spark.SparkException: Task not serializable at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:403) Caused by: java.io.NotSerializableException: com.fasterxml.jackson.module.paranamer.shaded.CachingParanamerSerialization stack: - object not serializable (class: com.fasterxml.jackson.module.paranamer.shaded.CachingParanamer, value: com.fasterxml.jackson.module.paranamer.shaded.CachingParanamer@660424b3) - field (class: com.fasterxml.jackson.module.paranamer.ParanamerAnnotationIntrospector, name: _paranamer, type: interface com.fasterxml.jackson.module.paranamer.shaded.Paranamer) Can anyone help me understand what could be going wrong here?Thanks!
Now provide the response and nothing else.
| Short answer: packages collect related classes, and correspond roughly to directories; while modules are a much higher level and correspond to projects and/or compiler runs. Longer answer: In Java and Kotlin, classes are arranged into packages. They're set using the package directive at the top of each file. (In Java, this corresponds exactly to the directory structure in which they're stored; that's common in Kotlin too, though not strictly required.) They provide a way of grouping related classes: you can refer to classes (and top-level functions and fields) in the same package directly, while all other classes need to be import ed, or their fully-qualified names ( package . package … class ) used. And in the most recent versions of Java, you can ‘seal’ a package, which means no-one else can add classes to it later on. Modules, on the other hand, are new to Kotlin. They are a much higher-level concept, collecting together all the classes in a program or library. (Some IDEs and tools call this a ‘project’ or ‘source set’.) All the files in a module must be compiled together, and the results are usually collected into a .jar (or .war) file. A big system might consist of a handful of modules, but each of those could contain many tens of packages. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57531781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3868051/']} | jdg_76547 |
stackexchange | llm_judgeable_groundtruth_similarity | 6196896 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can someone explain me when it comes to binary search we say the running time complexity is O(log n) ? I searched it in Google and got the below, "The number of times that you can halve the search space is the same as log 2 n". I know we do halve until we find the search key in the data structure, but why we have to consider it as log 2 n ? I understand that e x is exponential growth and so the log 2 n is the binary decay. But I am unable to interpret the binary search in terms of my logarithm definition understanding.
Now provide the response and nothing else.
| Think of it like this: If you can afford to half something m times, (i.e., you can afford to spend time proportional to m ), then how large array can you afford to search? Obviously arrays of size 2 m , right? So if you can search an array of size n = 2 m , then the time it takes is proportional to m , and solving m for n look like this: n = 2 m log 2 (n) = log 2 (2 m ) log 2 (n) = m Put another way: Performing a binary search on an array of size n = 2 m takes time proportional to m , or equivalently, proportional to log 2 (n) . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6196896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/540798/']} | jdg_76548 |
stackexchange | llm_judgeable_groundtruth_similarity | 155075 |
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:
Sun's light appear to travel as parallel beams towards earth $_1$. Sun produces electromagnetic radiations through pp chain and other reactions in Photosphere $_2$. I don't see whether these reactions send photons in that neatly arranged parallel rays, or else any other effects make the rays have such parallel beautiful motion. So what makes Sun's light travel as parallel beams towards earth? Links : A very good news for those who wants to desperately know the answer. I have replaced the word "ray" with "beam", as both have difference in their meaning. I have extracted a small passage from the webpage Light beam - Wikipedia : A light beam or beam of light is a directional projection of light energy radiating from a light source. Sunlight forms a light beam (a sunbeam) when filtered through media such as clouds, foliage, or windows. If the passage is saying truth, we are only left with the question, how clouds (the question is concerned with this) form beams? Reference: $_1$ Crepuscular rays-Wikipedia $_2$ Sun-Wikipedia
Now provide the response and nothing else.
| Close to the surface of the Sun, the light it emits is not in parallel beams at all. It sends photons out in pretty much every direction at random, like this: But the Sun is far away from Earth. Most of those photons don't reach the Earth because they're heading in the wrong direction. Only those photons that happen to be heading toward the Earth actually get there - and the photons that are heading to the Earth are all heading in more or less the same direction. So the photons that actually reach the Earth are all travelling in more or less parallel directions. Below I've drawn the photons that reach the Earth in red, and the other photons in grey. You can see that the red ones are more or less parallel. (In reality, the Earth is further away than that, so the photons are more parallel than in the diagram.) To answer your last question: sunbeams are formed when a gap in the clouds lets some light through, like this: Photons from the Sun are always travelling in more or less the same direction, because they all came from the Sun, but it's easier to notice this when the light is concentrated in one particular place like this. Finally, we have to explain why you're able to see the beam at all. This is just because some of the photons in the beam collide with particles in the atmosphere, which scatter them in all directions, and some of these scattered photons happen to hit your eye. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/155075', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/29762/']} | jdg_76549 |
stackexchange | llm_judgeable_groundtruth_similarity | 12744542 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I use JavaFX 2.1 and I created GUI using FXML, in the controller of this GUI I added myTextField.requestFocus(); . But I always get the focus in the other control.
Now provide the response and nothing else.
| At the time of initialize() controls are not yet ready to handle focus. You can try next trick: @Overridepublic void initialize(URL url, ResourceBundle rb) { Platform.runLater(new Runnable() { @Override public void run() { tf.requestFocus(); } });} For tricky complex applications (like Pavel_K has in the comments) you may want to repeat this routine several times and call method line next one: private void requestFocusOrDieTrying(Node node) { Platform.runLater(() -> { if (!node.isFocused()) { node.requestFocus(); requestFocusOrDieTrying(node); } });} Note this is the undocumented approach and it may be wise to add a limit for repetitions to avoid endless loop if something changed or broke in future Java releases. Better to lose focus than a whole app. :) Example with the described threshold: @Overridepublic void requestFocus() { requestFocus( getNode(), 3 );}private void requestFocus( final Node node, final int max ) { if( max > 0 ) { runLater( () -> { if( !node.isFocused() ) { node.requestFocus(); requestFocus( node, max - 1 ); } } ); }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12744542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1246145/']} | jdg_76550 |
stackexchange | llm_judgeable_groundtruth_similarity | 3102266 |
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:
$\displaystyle f(x) = \lim_{n \to \infty} ((\cos x )^n + (\sin x)^n))^{1/n}$ . Then $\int _0 ^{\pi /2} f(x)\,dx$ is? I proceeded by attempting to solve the limit first as the integral for the function with the powers is very difficult to solve but even using l'hospital twice (after taking log) I am not able to resolve the limit. How do I proceed?
Now provide the response and nothing else.
| $$f(x)=\lim_{n\rightarrow \infty}\bigg((\cos x)^n+(\sin x)^n\bigg)^{\frac{1}{n}}$$ $$=\left\{\begin{matrix}\lim_{n\rightarrow \infty}\cos x\bigg[(\tan x)^n+1\bigg]^{\frac{1}{n}}=\cos x\;, \displaystyle x\in \bigg(0,\frac{\pi}{4}\bigg) & \\\\lim_{n\rightarrow \infty}\sin x\bigg[(\cot x)^n+1\bigg]^{\frac{1}{n}}=\sin x\;, \displaystyle x\in \bigg(\frac{\pi}{4},\frac{\pi}{2}\bigg) & \end{matrix}\right.$$ $$\int^{\frac{\pi}{2}}_{0}f(x)dx = \int^{\frac{\pi}{4}}_{0}\cos xdx +\int^{\frac{\pi}{2}}_{\frac{\pi}{4}}\sin xdx$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3102266', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_76551 |
stackexchange | llm_judgeable_groundtruth_similarity | 318748 |
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'm trying to repair a small electronic door bell. I was wondering what is the name and purpose of the white box component ? It seems to be just a wire with some white body around. Is it a resistor or a fuse? My guess is that 4W22R means 4 watts 22 ohms but I'm not sure. How can I test that component is still working ? AFAIK the ground (the black wire) goes through the 400V capacitor first, then it has to go through that white component before going to the bridge rectifier. EDIT : I found out the issue : the zener diode is dead and acts like a wire (it's always closed). Because of this, the main 400V capacitor is never charging and don't provide power to the rest of the circuit.I disoldered the diode and tried to put 5.0V directly between the solder joints using a external power supply, it works again !Thanks Marko Buršič for pointing out the zener diode.
Now provide the response and nothing else.
| I was wondering what is the name and purpose of the white box component ? It seems to be just a wire with some white body around. Is it a resistor or a fuse ? It's a resistor, perhaps wirewound. Look at the PCB where that component is soldered. Its component designator will probably be a number prefixed by "R". In combination with that capacitor C25 , this is a " capacitive dropper " from the incoming mains voltage. You can read more about that type of power supply in this previous question and elsewhere. My guess is that 4W22R means 4 watts 22 ohms Yes. How can I test that component is still working ? With power completely removed and the capacitors on the PCB discharged , you could try measuring its resistance with a DMM and see if you get a sensible result. Since I expect it to be in series with C25 and no other components in parallel with it, then you should measure 22 ohms +/- 10% 5% The lack of discolouring gives us no indication of overheating (although doesn't disprove that it has occurred). | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/318748', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/9865/']} | jdg_76552 |
stackexchange | llm_judgeable_groundtruth_similarity | 25257 |
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:
When I design something or going to add a fuse to place where fuse isn't used now, should I prefer slow or fast fuse? I understand that this depends on situation, but I'd like to hear what do you prefer if there are no special circumstances. To be more specific, I am going to use a 20x5mm 250 Volt glass fuse. I know how much current the circuit takes, so it is not problem to choose a fuse with the right current I need. But should I take slow, or fast? If I understand it correctly, the slow fuse is more tolerant to shocks during power-on of the device. For example today I think of a fluorescent lamp ballast in my kitchen which is a weird chinese unfused circuit and fuse addition seems to a be good idea. Since there can be a higher current moment during start of fluorescent lamps, a slow fuse possibly allows me to use a lower Amp one. On the other hand, if I use a fast fuse, I can safely use a higher Amp one and still it will react sooner in the case of short circuit. A higher Amp fuse also has much smaller resistance. So for example I personally would prefer 1 or 2 Amp fast fuse instead of .150 Amp slow fuse for that kitchen lamp. Is this a good idea, do you agree with me? (The kitchen lamp is a real example, but it's just an example. I'd prefer to know if you prefer slow or fast fuses. I mean classic replaceable 20x5mm glass fuses / 250 Volt.)
Now provide the response and nothing else.
| Note the very very (lfe savingly) important aspect of HRC = "High rupture capacity" fuses, discussed at the end. You have done a fairly good job of summarising both the reasons and the dilemmas involved. Fast blow are used where possible, where the fuse can be sized such that typical faults will always cause it to blow but nuisance blowing is rare. Suh situations have little or no startup surges or large occasional current excursions. Slow blow are used where large short term transients are known to occur and if sizing of the fuse to accommodate the transients will result in inadequate protectionm against typical faults. Where neither fast or slow blow fuses offer adequate protection (transients are very high but faults may be relatively low compared to maximum usual) then a cicuit breaker can be used, whose characteristics can be mapped accurately to a desired time/current profile. Fast blow is the "more ideal" where possible. Circuit current is well defined within known limits, Start up transients are not so large compared to typical current that allowing for them is going to cause problems. Fault currents are liable to be much much larger normal operate current and much larger than expected transients. Slow blow is a compromise that allows protection while accommodating expected transient behaviour. Startup or other transients may occur which cause much higher than average currents but for short periods. Sizing a fast-blow fuse to allow the transients would result in a fuse which may not provide protection during some expected fault conditions. The ideal may be both a fast and slow blow fuse in series (very unusual and possibly also illegal for regulatory reasons) or a circuit breaker with a well defined current versus time "envelope". Regulatory requirements often make it clear which sort of fuse must be used. ________________________- HRC / High Rupture capacity. ** The life saver!!!** In some situations fault conditions can develop which can result in fault currents vastly in excess of the normal operating current and so high that massive destruction to property or loss of life may occur. An excellent example is a multimeter intended or measuring AC mains voltages of 230 VAC or higher. A meter measuring nominal 230 VAC mains voltages may easily be exposed to over 330 VDC peak, and transients on the waveform may cause much higher voltages to occur. A domestic range/stove/oven may be supplied with two phases with phase to phase voltages of 400 VAC or approaching 600 VDC peak to peak. In either case above, if these voltages break down circuitry in the meter, an arc may occur followed rapidly by carbonisation of components, PCB, nearby case etc and a relatively low resistance across mains short may occur. The mains may then be supplying a high energy load vastly in excess of what is expected or designed - at least kilowatts with ease and tens of kilowatts in some cases. The onset of arc formation and generation of heat can be so rapid as to cause an explosion of th equipment with debris being ejected violently and with electric shock hazard also increasing. Standing in the gap to this happening is "the fuse". Edit: Actually, the fuses in multimeters are used to protect the current measuring circuitry. The voltage measurement stuff is protected by MOVS and PTCs. If the fuse is able to blow and stay functionally blown when such a fault occurs the meter etc 'just stops working". if the fuse holder arcs and the PCB carbonises or the fuse otherwise fails to interrupt current, then the above scenario can occur. And does. People have died due to this scenario and will die in future An answer is the use of an HRC fuse which is designed to "rupture" in suh a way that a damaging arc does not form and the circuit is cleanly broken. HRC fuses are usually ceramic bodied, usually white. Not all white or ceramic fuses are HRC. Not all HRC fuses are white or ceramic.Image below shows fuses said by makers to be HRC. note that one is glass bodied. ( From here .) Many HRC fuse images and links here . Test equipment intended for AC mains use will usually specify HRC fuses. DO NOT SUBSTITUTE inferior types. I have only ever had one meter fail under high voltage high energy conditions. That was on a 1000 VDC range with a 1200 ior so VDC transmitting power supply being measured. Very impressive. A good lesson. Long long ago. Cheap multimeters often have their high end ACV ranges marked "not for mains use" or similar. That's why. If you use them on mains you usually won't die. But if you do, you won't be able to say that you weren't warned. Remember that before you can't !!! | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/25257', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/7575/']} | jdg_76553 |
stackexchange | llm_judgeable_groundtruth_similarity | 27798862 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to deploy both Debug and Release builds to my device at the same time. I can do this if I manually change the package name in the manifest before I build, e.g. change <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.package"> to <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.packageDEBUG"> However, I'd like to do this automatically when I'm building the solution. If I do a Debug build, it'll build with package="my.packageDEBUG" in the manifest. Is this possible, and if so, how?
Now provide the response and nothing else.
| You'll need to create a custom Pre-Build Event for your project. Right-click on your project and select Properties... Then click on Build Events and add this to the Pre-build event textbox: PowerShell -File "$(SolutionDir)Update-PackageName.ps1" $(ProjectDir) $(ConfigurationName) Copy the following PowerShell script and save it in your solution folder as Update-PackageName.ps1 param ([string] $ProjectDir, [string] $ConfigurationName)Write-Host "ProjectDir: $ProjectDir"Write-Host "ConfigurationName: $ConfigurationName"$ManifestPath = $ProjectDir + "Properties\AndroidManifest.xml"Write-Host "ManifestPath: $ManifestPath"[xml] $xdoc = Get-Content $ManifestPath$package = $xdoc.manifest.packageIf ($ConfigurationName -eq "Release" -and $package.EndsWith("DEBUG")) { $package = $package.Replace("DEBUG", "") }If ($ConfigurationName -eq "Debug" -and -not $package.EndsWith("DEBUG")) { $package = $package + "DEBUG" }If ($package -ne $xdoc.manifest.package) { $xdoc.manifest.package = $package $xdoc.Save($ManifestPath) Write-Host "AndroidManifest.xml package name updated to $package"} Good luck! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27798862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/181771/']} | jdg_76554 |
stackexchange | llm_judgeable_groundtruth_similarity | 19039 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there any way to avoid the tidal locking of a planet orbiting a red dwarf in the habitable zone? For example, could a planet with a 90° obliquity and large moon avoid such a situation?
Now provide the response and nothing else.
| Leconte et al. (2015) suggested that the presence of an atmosphere could prevent or at least slow tidal locking. The star should exert two separate torques: one on the atmosphere and one on the solid body of the planet:$$T_a=-\frac{3}{2}K_ab_a(2\omega-2n),\quad T_g=-\frac{3}{2}K_gb_g(2\omega-2n)$$where$$K_a\equiv\frac{3M_*R_p^3}{5\bar{\rho}a^3},\quad K_g\equiv\frac{GM_*R_p^5}{a^6}$$for stellar mass $M_*$, planetary radius $R_p$, mean density $\rho$, semi-major axis $a$, mean motion $n$, rotation rate $\omega$, and response to torques $b_a$ and $b_g$. The two torques could be equal, and assuming that the atmosphere transfers some angular momentum to the surface of the planet, this could prevent tidal locking. There are several equilibria at which this could occur: | {} | {'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/19039', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/14829/']} | jdg_76555 |
stackexchange | llm_judgeable_groundtruth_similarity | 45183642 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to create an initialize task that will run before all other task when I execute it. task A { println "Task A"}task initializer { println "initialized"} If I execute gradle -q A , the output will be: >initialized>Task A Now if i'll add: task B { println "Task B"} Execute gradle -q B , and I get: >initialized>Task B So it doesn't matter which task I execute, it always get "initialized" first.
Now provide the response and nothing else.
| You can make every Task who's name is NOT 'initializer' depend on the 'initializer' task. Eg: task initializer { doLast { println "initializer" }}task task1() { doLast { println "task1" }}// make every other task depend on 'initializer'// matching() and all() are "live" so any tasks declared after this line will also depend on 'initializer'tasks.matching { it.name != 'initializer' }.all { Task task -> task.dependsOn initializer}task task2() { doLast { println "task2" }} Or you could add a BuildListener (or use one of the convenience methods eg: Gradle.buildStarted(...) ) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45183642', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5843514/']} | jdg_76556 |
stackexchange | llm_judgeable_groundtruth_similarity | 109559 |
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 want to start my minecraft server when someone tries to connect to it on port 25565. I have a plugin for the server which shuts it down after x amount of minutes without players online. With a shell script I created a loop that starts the server when it shuts down: #!/bin/bashwhile truedo # run server java -Xms2048M -Xmx2048M -Djava.awt.headless=true -jar "craftbukkit.jar" # server shut down # run MCSignOnDoor java -jar MCSignOnDoor.jar --sentrymode -m "Gone Fishin' Back in Five Minutes!" # McSignOnDoor shut down # stop loop if error code is not 12 # so only restart the server when the program ended because of a packet if [ "$?" -ne "12" ]; then break fidone McSignOnDoor was a java program someone made that emulates an active server, and exits as soon as someone pings it on port 25565 with exit code 12. Sadly, this does not work since a protocol update, so I'm looking for an alternative. Is there a way to wait until it receives a packet on port 25565 (or any other port) and then continue the script?
Now provide the response and nothing else.
| There's a service that's already included with Linux that provides this feature, it's called xinetd . Red Hat maintains pretty good documentation on their website, titled: 2.6.4. xinetd Configuration Files . The service xinetd allows you to setup a master service that will listen on specific ports, and then launch other applications when connections are made on said ports. excerpt from xinetd man page xinetd performs the same function as inetd: it starts programs that provide Internet services. Instead of having such servers started at system initialization time, and be dormant until a connection request arrives, xinetd is the only daemon process started and it listens on all service ports for the services listed in its configuration file. When a request comes in, xinetd starts the appropriate server. Because of the way it operates, xinetd (as well as inetd) is also referred to as a super-server. NOTE: If it isn't installed you can install it, the package is typically called xinetd . Once it's installed you place configuration files under this directory, /etc/xinetd.d . For example, let's create a service called minecraft . # /etc/xinetd.d/minecraftservice minecraft{ disable = no type = UNLISTED socket_type = stream protocol = tcp wait = no server = /path/to/minecraft/server bind = <ip of minecraft server> port = 25565 user = root} With the above file in place you can then manually start xinetd to check things out. $ sudo service xinetd start Now when you attempt to connect to your system via port 25565 the minecraft server should start up and you should be able to access it. You might need to adjust the user = .. line to whatever user ultimately owns the server. To make this persistent you can use whatever mechanism your distro uses to start services automatically during boot-up. References Port Forwarding with xinetd xinetd man page xinetd.conf man page | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/109559', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/56506/']} | jdg_76557 |
stackexchange | llm_judgeable_groundtruth_similarity | 18116 |
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'm building a playing card dealing machine and I would like to get some advice in regards how I should do with my image processing. The card will be scanned and depending on the suit and rank of the card it will be place in 1 out of 4 slots. The best way I believe (Which does not have to be the right one..) is to use a FPGA chip for the image recognition. A FPGA chip seem to be very affordable for the speed but I have no experience with this. So here is a few questions. Is FPGA to way to go or should I look into a different solution? (Low price and energy consumption is two important factors for me) Is it best for example to read the corner of the card and read the suit and rank individually(4 suits and 13 ranks) or just compare against the 52 cards right off? I really want the solution simple so I can for example easily use different layouts of decks. Hope I'm making some sense here! Thanks,Stefan
Now provide the response and nothing else.
| For this kind of application I would rather think of a DSP solution. You'll probably find image processing code easier for DSP than for FPGA. Sure, you can run a soft DSP on the FPGA, but I wonder what the FPGA's added value would be. It seems you don't need extensive peripherals around the DSP which would justify a great amount of gates. Just connect your camera to an A-to-D converter and let the DSP do the rest. Analog Devices has this image processing toolbox for its Blackfin DSP . Analog has several DSP lines . I would look for a DSP development kit targeted at image processing. | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/18116', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/5153/']} | jdg_76558 |
stackexchange | llm_judgeable_groundtruth_similarity | 1462 |
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:
what is the relation between mass density $\rho$ and pressure $P$ for a perfect fluid ?
Now provide the response and nothing else.
| There is no restriction. The simplest choice is $P = \kappa \rho$, where $\kappa$ is a real constant, and that is often used to get simple results. $\kappa=0$ is dust, $\kappa=-1$ is cosmological constant, and $\kappa=\frac{1}{3}$ is a gas of photons. A proper analysis also needs an equation describing the flow of internal energy and its relationship to temperature. As a concrete example, note that $PV=NkT$ can be rewritten as $P = \frac{N}{V}kT = \frac{\rho}{m_{p}}kT$, where $m_{p}$ is the mass of the particle making up the ideal gas. Thus, if the fluid is held at a constant temperature, we get $\kappa = \frac{kT}{m_{p}}$. If the fluid is not at a constant temperature, we need to use the First Law of Thermodynamics and knowledge of the process (isoentropic, adiabatic, etc) the system is undergoing to get a relationship between the density and pressure. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/1462', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/540/']} | jdg_76559 |
stackexchange | llm_judgeable_groundtruth_similarity | 8162257 |
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 define a block that I'll use to pass the the each method of multiple ranges. Rather than redefining the block on each range, I'd like to create a lamba, and pass the lambda as such: count = 0procedure = lambda {|v| map[count+=1]=v}("A".."K").each procedure("M".."N").each procedure("P".."Z").each procedure However, I get the following error: ArgumentError: wrong number of arguments(1 for 0) from code.rb:23:in `each' Any ideas what's going on here?
Now provide the response and nothing else.
| Tack an ampersand ( & ) onto the argument, for example: ("A".."K").each &procedure This signifies that you're passing it as the special block parameter of the method. Otherwise it's interpreted as a normal argument. It also mirrors they way you'd capture and access the block parameter inside the method itself: # the & here signifies that the special block parameter should be captured# into the variable `procedure`def some_func(foo, bar, &procedure) procedure.call(foo, bar)endsome_func(2, 3) {|a, b| a * b }=> 6 | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8162257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/879034/']} | jdg_76560 |
stackexchange | llm_judgeable_groundtruth_similarity | 22632236 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Having the function definition: void f(int) { } I want to define: int a; but if the function definition changes to: void f(double) { } the variable definition must become: double a; that is, the type of "a" must be the same of the first argument of the "f" function.I need something like the following: decltype_of_argument<f, 0> a; Is it possible in C++?
Now provide the response and nothing else.
| You can get the type by template metaprogramming: template <class F> struct ArgType;template <class R, class T> struct ArgType<R(*)(T)> { typedef T type;}; void f(int) {}#include <type_traits>#include <iostream>int main() { // To prove std::cout << std::is_same< ArgType<decltype(&f)>::type, int >::value << '\n'; // To use ArgType<decltype(&f)>::type a;} Depending on where you want to use it you'd need to specialize this litte template for other callable entities such as member function poitners, functions with more arguments, functors etc. There are more sophisitcated approaches in the Boost libraries, see e.g. https://stackoverflow.com/a/15645459/1838266 Caveat: all these utilities work only if the name of the function/callable is unambiguously mapped to one single function signature. If a function is overloaded or if a functor has more than one operator() , the right function/operator has to be picked by explicitly casting to the right signature, which makes finding out part of the signature via the template pretty useless. This applies in a certain way to templates as well, although getting the signature of an explicitly secialized callable might still be useful, e.g.: template <unsigned N, class F> struct ArgType; //somewhat more sophisitcated template <class T> void f(int, T);ArgType<0, decltype(&f<double>)> //int - ArgType has it's use hereArgType<1, decltype(&f<double>)> //double - here it's useless... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22632236', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3459257/']} | jdg_76561 |
stackexchange | llm_judgeable_groundtruth_similarity | 621652 |
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 the following question. Suppose I have a formal power series $f(x)=\sum\limits_{i=0}^\infty c_ix^i$ with real coefficients. Suppose that all the derivatives $f'(1),f''(1),\dots,f^{(n)}(1),\dots$ of $f(x)$ at the point $x=1$ are zero. What can I say about the coefficients $c_i$? I want to say that they all must be zero, but when I try to write down the system of equations, I get infinite systems, and each equation involves infinitely many variables. Is there a nice way to solve this problem? Thank you!
Now provide the response and nothing else.
| A "formal power series" can't be evaluated at $x=1$, just $x=0$. If you mean that $\sum_{i=0}^\infty c_i x^i$ is the Maclaurin series of a function $f(x)$ which is analytic in a connected open set $D$ that contains both $0$ and $1$, thenindeed all the coefficients are $0$, because $f$ is constant on $D$. On the other hand, you might consider $f(x) = \exp(-1/(x-1)^2)$ with $f(1) = 0$, which is analytic on ${\mathbb C} \backslash \{1\}$ and $C^\infty$ on $\mathbb R$, with all derivatives $0$ at $x=1$. Its Maclaurin series is $$ e^{-1} - 2 e^{-1} x - e^{-1} x^2 + \dfrac{2}{3} e^{-1} x^3 + \ldots$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/621652', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/113232/']} | jdg_76562 |
stackexchange | llm_judgeable_groundtruth_similarity | 56435 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The Freudenthal suspension theorem states in particular that the map $$\pi_{n+k}(S^n)\to\pi_{n+k+1}(S^{n+1})$$ is an isomorphism for $n\geq k+2$ . My question is: What is the intuition behind the proof of the Freudenthal suspension theorem?
Now provide the response and nothing else.
| There are two proofs I particularly like: A Morse-theoretic proof, probably due to Bott, can be found in Milnors book. Idea: consider the space of all paths on $S^n$ from the north to the south pole, which is homotopy equivalent to $\Omega s^n$. There is the energy function on this space. One does Morse theory: critical points correspond to geodesics (they are not non-degenerate, but Bott proved that a good deal of Morse theory works nevertheless). The set of absolute minima is the space of minimal geodesics connecting the poles. This is homeomorphic to $S^{n-1}$. All other critical points have index at least (rouhgly) $2n$. Therefore, the inclusion of the set of absolute minima into the whole space is $2n$-connected. A spectral sequence proof (see Kirk, Davis, Lectures on Algebraic topology). Consider the homology Leray-Serre spectral sequence of the path-loop fibration $\Omega S^n \to PS^n \to S^n$. The total space $P S^n$ is contractible. Look at the shape of the spectral sequence; you'll see that for $k \leq 2n$ (again, only a rough estimate), all differentials out of the $E_{k,0}$-slot are zero, except of the last one, which gives an isomorphism $H_k (S^n)=E_{k,0}^{2} \to E_{0,k-1}^{2} = H_{k-1} (\Omega S^n)$. It is credible (but nontrivial to prove, this uses the transgression theorem) that this isomorphism is the same as the composition $H_k (S^n) \cong H_{k-1} (S^{n-1}) \to H_{k-1} (\Omega S^n)$ of the suspension isomorphism and the natural map $S^{n-1} \to \Omega S^n$.Thus the natural map is a homology isomorphism in a range of degrees, and by the Hurewicz theorem, this holds for homotopy groups as well. | {} | {'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/56435', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4676/']} | jdg_76563 |
stackexchange | llm_judgeable_groundtruth_similarity | 65985554 |
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 have an icon with a number on top in the left corner of a div container, to the right of this number and icon is an image. On the desktop this looks fine, separated accordingly but on the mobile devices, the image on the right appears over the icon and text on the left. HTML looks like this: <div class="col-1"> <div class="wrap-image"> <a th:rowNumber="${status.count}" th:href="@{'/basket/remove/' + ${product.id}}"> <img src="images/bin.png" height="60"> <span z-index: 10;>[[${status.count}]]</span> </a> </div> </div> <div class="col-3"> <img th:src="@{${product.mainImagePath}}" class="img-fluid" /> </div> css: .wrap-image { position: relative; width: min-content;}.wrap-image span { position: absolute; top: 1px; left: 20px;} Device: device device2 PC: desktop Image and text if they were more in the corner ,it might not happen but the sizing for the main image is not correct either for a mobile device, but not sure how to change it.
Now provide the response and nothing else.
| You need to use global selector inside your local selector in CSS-modules. For example, if you have HTML: <div className={classes.someCSSMoludesClass}> <div className="some-global-class"> content </div></div> for rewriting global class "some-global-class" you need to make this inside your CSS-module: .someCSSModulesClass { :global(.some-global-class) { %your properties% }} Don't forget to use selector inside :global. I had the same problem, but in swiper slider, and resolved it like this.Maybe you have to write this class in the component that is above | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65985554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15116847/']} | jdg_76564 |
stackexchange | llm_judgeable_groundtruth_similarity | 8066850 |
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 good reason why the type of Prelude.read is read :: Read a => String -> a rather than returning a Maybe value? read :: Read a => String -> Maybe a Since the string might fail to be parseable Haskell, wouldn't the latter be be more natural? Or even an Either String a , where Left would contain the original string if it didn't parse, and Right the result if it did? Edit: I'm not trying to get others to write a corresponding wrapper for me. Just seeking reassurance that it's safe to do so.
Now provide the response and nothing else.
| Edit : As of GHC 7.6, readMaybe is available in the Text.Read module in the base package, along with readEither : http://hackage.haskell.org/packages/archive/base/latest/doc/html/Text-Read.html#v:readMaybe Great question! The type of read itself isn't changing anytime soon because that would break lots of things. However, there should be a maybeRead function. Why isn't there? The answer is "inertia". There was a discussion in '08 which got derailed by a discussion over "fail." The good news is that folks were sufficiently convinced to start moving away from fail in the libraries. The bad news is that the proposal got lost in the shuffle. There should be such a function, although one is easy to write (and there are zillions of very similar versions floating around many codebases). See also this discussion . Personally, I use the version from the safe package . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8066850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1015905/']} | jdg_76565 |
stackexchange | llm_judgeable_groundtruth_similarity | 4420219 |
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 calling a method on super supported in the implementation of an Objective-C block? When I was calling a method on super an EXC_BAD_ACCESS error would be thrown but as soon as I changed those calls from [super methodToCall] to [self methodToCall] and let the message move up the responder chain it worked fine. There is no implementation of -methodToCall in the instance of the class that the block exists in, but there is one in the superclass (that is, the class that self inherits from). I'm just curious to learn the details as to why calling a method on super inside the implementation of a block was a problem in the first place (technically) so I can avoid it in the future. I have a suspicion it is related to how the variables are captured in the block and something about the stack and the heap, but I really have no concrete idea. Note: the block implementation code is called up to a few seconds after the block is stored in a property, the property uses copy so I don't think it's a problem with the block's lifecycle, that all looks to be fine. Also, this was only crashing on the iPhone device (3G) but was working without crashing in the iPhone Simulator. Results in EXC_BAD_ACCESS : [self retrieveItemsForId:idString completionHandler:^(NSError *error) { if (!error) { [super didRetrieveItems]; } else { [super errorRetrievingItems]; }}]; Works perfect, implementations of -didRetrieveItems and -errorRetrievingItems are in the super-class. [self retrieveItemsForId:idString completionHandler:^(NSError *error) { if (!error) { [self didRetrieveItems]; } else { [self errorRetrievingItems]; }}];
Now provide the response and nothing else.
| Technically, this is an issue with the Objective-C runtime, and the underlying mechanics of how calls to super actually work. Basically, they capture both the object which is the recipient of the message ( self in all cases) and the class which implements the specific version of the method (the superclass of the class in which the method implementation occurs). Because a lot of the preparation for such a message send happens at compile-time, not runtime, I wouldn't be surprised if it interacted badly with blocks. I would check to see if self is still valid when the message is about to be sent. Normally, any objects referenced in a block are automatically retained. Since super works a bit differently, it might mean that self is not getting retained like one would expect. One easy way to check this would be to use the calls to super as originally written, and simply leak the object referred to as self , and see if it works. If this turns out to be the problem, you might have to insert a dummy reference to self within the block to get that automatic memory management. In the strictest sense, however, I'm not sure you can depend on this working forever and always. Although blocks can capture the current runtime state, it doesn't really make sense (from an OOP perspective) for them to break encapsulation and invoke superclass implementations, since the hierarchical level at which methods are implemented should be opaque to any external calling code. I would try to find another solution which doesn't depend on the inheritance hierarchy. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4420219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4055451/']} | jdg_76566 |
stackexchange | llm_judgeable_groundtruth_similarity | 4169714 |
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 attempting to call startActivity(myIntent) from the click of a menu button but my application crashes at that point. The same startActivity call works fine from a regular button click, so, I assume the menu button is missing information about the context? Or maybe I'm totally off the mark here. So... what's the correct way to have a menu item take me to a specific Activity? I've revised my code based on the initial set of advice. Still crashing in the same place. The debugger doesn't enter the exception clause, the app just dies. [EDITED WITH CODE SNIPPET] public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) { // Handle item selection try{ switch (item.getItemId()) { case R.id.menuItemLang: startActivity(new Intent("com.my.project.SETTINGS")); return true; default: return super.onOptionsItemSelected(item); } }catch(Exception e){ log(e); }}
Now provide the response and nothing else.
| First option You have to override onOptionsItemSelected method in your Activity, which is called when user clicks on the item in Options menu. In the method you can check what item has been clicked. @Overridepublic boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_item1: Intent intent = new Intent(this, ActivityForItemOne.class); this.startActivity(intent); break; case R.id.menu_item2: // another startActivity, this is for item with id "menu_item2" break; default: return super.onOptionsItemSelected(item); } return true;} There is also onContextItemSelected method which works similary, but for Context menu (I'm not sure, what menu you mean). More information at http://developer.android.com/guide/topics/ui/menus.html EDIT: Second option I think the first option is easier, but from your code I see, that you want to start activity as an action (because of String parameter in Intent constructor). To do this, you need to specify an action in your AndroidManifest.xml. So, if I would start activity ActivityForItemOne (from previous example) the <application> element in AndroidManifest.xml would look like this: <application ...> ... <activity android:label="Activity For First Item" android:name=".ActivityForItemOne"> <intent-filter> <action android:name="my.app.ITEMONE" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity></application> And the Intent will be: Intent intent = new Intent("my.app.ITEMONE"); The my.app. is package of your application. It's not necessary to use your application package, but it's recommended for uniqueness of actions. More information at: Class Intent - Action and Category constants Action element Intents and Intent Filters Hope this solve your problem. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4169714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59947/']} | jdg_76567 |
stackexchange | llm_judgeable_groundtruth_similarity | 2854 |
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:
Is the music industry, and perhaps the entertainment industry, being ruined by piracy (or otherwise losing a substantial amount of money?) For example, the record label EMI has blamed piracy for the loss of about 2,000 jobs and a slump in revenue. However, is it just a scapegoat for poor financial performance? Have any independent studies been conducted to see if their claims are true?
Now provide the response and nothing else.
| As one can imagine, many studies have been conducted regarding the relationship between the rise of P2P networks and the drop of CD sales. I have looked at several papers, some come to the conclusion that file sharing actually contributed to more CDs being bought, others attribute atleast some part of the decline of CD sales to file sharing. What some studies also suggest is, that music sales have shifted some what from the majors to smaller labels. In THE EFFECT OF INTERNET PIRACY ON CD SALES: CROSS-SECTION EVIDENCE , 2004, CESIfo: [...] we find that music downloading could have caused a 10% reduction in CD sales worldwide in 2001. [...] The story for 2002 is different, at least for the US, as the number of people downloading music has only slightly increased. As a matter of fact, our estimates imply a 2% loss in CD sales due to music downloads, a small number compared to the observed 9% drop in 2002 in the US. But the paper also points out, that the music industry could benefit: Besides, there are reasons to believe that the music industry might actually benefit from digital distribution. Indeed, numerous surveys (documented in Peitz and Waelbroeck 2003b) highlight the potential sampling role of digital copies. [...] As a result, labels may benefit from file-sharing because, as Peitz and Waelbroeck (2003c) have argued, they may be able to save on marketing and promotion costs, by letting consumers search for their most preferred music. In [The Impact of Digital File Sharing on the Music Industry: An Empirical Analysis] (http://www.bepress.com/bejeap/topics/vol6/iss1/art18/), 2005, Nicholls State University: Music industry representatives argue that the practice decreases CD sales, while supporters of file-sharing allege the practice could actually increase sales. Using household-level data from the Consumer Expenditure Survey, we find support for the claim that file-sharing has decreased sales. In Music Sales in the Age of File Sharing : For younger people, Internet access predicts a decrease in sales. For older people, Internet access predicts an increase in sales. The overall effect of Internet access is positive -- the magnitude of the Internet effect is larger in the older age groups, and the older age groups represent a greater proportion of the population. This strongly suggests that file sharing is not the cause of the recent decline in the record industry Even if the RIAA’s lawsuits against file sharers successfully deter people from sharing music over P2P networks, I would not expect to see a short term increase in sales. If the older demographic is more responsive to the threat of legal action than the younger demographic, the lawsuits would even tend to decrease sales in the short run In File Sharing and International Sales of Copyrighted Music: An Empirical Analysis with a Panel of Countries : I find that countries with higher internet and broadband penetration have suffered higher drops in music sales, suggesting that music downloads may explain at least part of the recent reduction in sales. In The Impact of Music Downloads and P2P File-Sharing on the Purchase of Music: A Study for Industry Canada : In the aggregate, we are unable to discover any direct relationship between P2P filesharing and CD purchases in Canada. The analysis of the entire Canadian population does not uncover either a positive or negative relationship between the number of files downloaded from P2P networks and CDs purchased. That is, we find no direct evidence to suggest that the net effect of P2P file-sharing on CD purchasing is either positive or negative for Canada as a whole. However, our analysis of the Canadian P2P file-sharing subpopulation suggests that there is a strong positive relationship between P2P file-sharing and CD purchasing. That is, among Canadians actually engaged in it, P2P file-sharing increases CD purchasing. We estimate that the effect of one additional P2P download per month is to increase music purchasing by 0.44 CDs per year. | {} | {'log_upvote_score': 5, 'links': ['https://skeptics.stackexchange.com/questions/2854', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/1626/']} | jdg_76568 |
stackexchange | llm_judgeable_groundtruth_similarity | 40720 |
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:
Assume I start an X server manually from a virtual console /dev/tty1 with xinit or startx , with the line id:3:initdefault: set in /etc/inittab . The X server gets run and put on another virtual console, normally being /dev/tty7 . After some time I decide to lock the screen with xscreensaver --lock and leave my computer. To unlock the screen one would have to know my user's password. If someone now decides to kill the running X server, he or she would be returned to the shell running at /dev/tty1 and pretty much have access to my computer. Typically, the X server can be killed with Ctrl+Alt+Backspace or switching to the initial console and SIGTERM the running process with ^C . This is trivial to do - which means there must be trivial ways to prevent it from happening. I'm using vlock to lock my virtual console /dev/tty1 to prevent this: $ xinit && vlock || vlock When the X server now returns, gracefully && or not || , the console will be locked. This may not be the optimal solution.I've read this thread and this wiki article, explaining different solutions. What other methods are there to prevent this kind of access to virtual consoles from X sessions? Is the above method safe enough? How do you prevent this on your system? I'm not going to use a display manager.
Now provide the response and nothing else.
| You can prevent console switches from Xorg by adding the Option"DontVTSwitch" "yes" to your Xorg config file. To prevent Ctrl + Alt + Backspace you have toadd the DontZap option to your Xorg config file. Of course this will not completely prevent access to the console. If X terminates for some reason, e.g. problem with a driver the attacker will still have access to your console. You can also use exec startx instead of startx which will replaces bash with startx, this means even if someone is able to abort X they won't be able to access your console. You can also use a display manager like lightdm , kdm , gdm , or xdm so you won't need an existing shell session to start a x session. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/40720', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']} | jdg_76569 |
stackexchange | llm_judgeable_groundtruth_similarity | 32898667 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Having a bit of an issue with LEFT JOIN in a Mysqli statement. I have two tables, one that has single entries for various events. The second table has all the images for that event. What I want to get: I want to get a single return for the last 8 events with an image count for that event and the last image uploaded for the event. The problem: A simple LEFT JOIN would be great for this, however that's a hitch... sometimes there's multiple days for these events. So the one thing that connects the two tables together is the FOLDER field. But, the can also differ if there's more than one day. This makes match up the event to the images a bit tougher. Visual example: Table: Events Title Folder Days Added-------------------------------------------Event1 2015-EventA 1 20151001Event2 2015-EventB 2 20150901Event3 2015-EventC 3 20150801 Table: Images File Folder Date---------------------------------------imgA1.jpg 2015-EventA 20150930imgA2.jpg 2015-EventA 20151001imgB1.jpg 2015-EventB-1 20150910imgB2.jpg 2015-EventB-2 20150901imgC1.jpg 2015-EventC-1 20150910imgC2.jpg 2015-EventC-2 20151001imgC3.jpg 2015-EventC-2 20150930imgC4.jpg 2015-EventC-3 20150927 Result I'm looking for (remember it's picking the last uploaded image for that event): Title Folder Days File IMGCount IMGFolder------------------------------------------------------------------------Event 1 2015-EventA 1 imgA2.jpg 2 2015-EventAEvent 2 2015-EventB 2 imgB1.jpg 2 2015-EventB-1 Event 3 2015-EventC 3 imgC2.jpg 4 2015-EventC-2 What I've tried: SELECT t1.*, t2.IMGCount, t2.File, T2.Folder AS IMGFolder FROM Events as t1 LEFT JOIN (select count(File) AS IMGCount, Folder, File FROM Images GROUP BY Folder ORDER BY Date DESC LIMIT 8)AS t2on t1.Folder LIKE t2.FolderOR t1.Folder LIKE t2.Folder || '-1'OR t1.Folder LIKE t2.Folder || '-2'OR t1.Folder LIKE t2.Folder || '-3'OR t1.Folder LIKE t2.Folder || '-4' ORDER BY Added DESC LIMIT 8 This ALMOST works... but the Event table repeats the first Event's information for all the matches... so I get this which has correct Image table info, but repeated Event: Title Folder Days File IMGCount IMGFolder------------------------------------------------------------------------Event 1 2015-EventA 1 imgA2.jpg 2 2015-EventAEvent 1 2015-EventA 1 imgB1.jpg 2 2015-EventB-1 Event 1 2015-EventA 1 imgC2.jpg 4 2015-EventC-2 What am I doing wrong?
Now provide the response and nothing else.
| As mentioned in the comments, there is a difference between the version of the Maven Ant tasks used in Eclipse versus the one used on the command line. Eclipse seems to be using a newer version of this library in which the method DependenciesTask.setPathType(String) exists whereas the command line is relying on an older version. You may be able to get more information on which version of the Ant tasks Eclipse is using by checking the preferences page. Try navigating to Window -> Preferences -> Ant -> Runtime and see Classpath tab for external libraries. On the other hand, from the output of the Ant build: [echo] Executing maven build on Developer machine (other machine)parsing buildfile jar:file:/C:/Apps/ANT/apache-ant-1.9.5/lib/maven-artifact-ant-2.0.4-dep.jar!/org/apache/maven/artifact/ant/antlib.xml with URI = jar:file:/C:/Apps/ANT/apache-ant-1.9.5/lib/maven-artifact-ant-2.0.4-dep.jar!/org/apache/maven/artifact/ant/antlib.xml from a zip file the command line is obviously using version 2.0.4 which is located in the lib folder of the Ant home directory. Checking this page , the latest version is 2.1.3 which does contain the missing method. So it would make sense to update the version in the Ant lib directory to be the latest one (check the download link on the project page). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32898667', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4438742/']} | jdg_76570 |
stackexchange | llm_judgeable_groundtruth_similarity | 59554 |
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 other words, is there an algebraic proof showing that $\sum_{k=0}^{N} {N\choose k} = 2^N$? I've been trying to do it some some time now, but I can't seem to figure it out.
Now provide the response and nothing else.
| An algebraic proof: Expand $(1+x)^n$ using binomial theorem which gives $$(1+x)^n={n\choose 0}x^0 + {n\choose 1}x^1 + {n\choose 2}x^2 + {n\choose 3}x^3 + \cdots + {n\choose n}x^n$$ set $x = 1$ hence, $$(1+1)^n={n\choose 0}1^0 + {n\choose 1}1^1 + {n\choose 2}1^2 + {n\choose 3}1^3 + \cdots + {n\choose n}1^n$$ $$\Rightarrow 2^n={n\choose 0} + {n\choose 1} + {n\choose 2} + {n\choose 3} + \cdots + {n\choose n}$$ $$\Rightarrow 2^n=\sum_{k=0}^{n} {n\choose k}$$ QED! | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/59554', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8616/']} | jdg_76571 |
stackexchange | llm_judgeable_groundtruth_similarity | 24258784 |
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 getting "webView:didFailLoadWithError -1004: Could not connect to the server" error while accepting google plus authentication before getting profile data. These code was working properly before. Now i am facing these error. No idea why i am not able to connect.Please help me to get rid of these error.Below is my code for integrating google plus in Phonegap (3.4.0) for ios. var googleapi = { //alert('ready'); authorize: function(options) { var deferred = $.Deferred(); //Build the OAuth consent page URL var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({ client_id: options.client_id, redirect_uri: options.redirect_uri, response_type: 'code', scope: options.scope }); //Open the OAuth consent page in the InAppBrowser var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=yes'); $(authWindow).on(' ', function(e) { var url = e.originalEvent.url; var code = /\?code=(.+)$/.exec(url); var error = /\?error=(.+)$/.exec(url); if (code || error) { //Always close the browser when match is found authWindow.close(); } if (code) { //Exchange the authorization code for an access token $.post('https://accounts.google.com/o/oauth2/token', { code: code[1], client_id: options.client_id, client_secret: options.client_secret, redirect_uri: options.redirect_uri, grant_type: 'authorization_code' }).done(function(data) { deferred.resolve(data); $("#loginStatus").html('Name: ' + data.given_name); }).fail(function(response) { deferred.reject(response.responseJSON); }); } else if (error) { //The user denied access to the app deferred.reject({ error: error[1] }); } }); return deferred.promise(); } }; var accessToken; function callGoogle() { alert('starting'); googleapi.authorize({ client_id: 'CLIENT_ID', client_secret: 'CLIENT_SECRET', redirect_uri: 'http://localhost', scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email' }).done(function(data) { accessToken=data.access_token; alert(accessToken); // $loginStatus.html('Access Token: ' + data.access_token); console.log(data.access_token); getDataProfile(); });}function getDataProfile(){ var term=null; //accessToken=null; //alert("getting user data="+accessToken); $.ajax({ url:'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='+accessToken, type:'GET', data:term, dataType:'json', error:function(jqXHR,text_status,strError){ }, success:function(data) { var item; var dat=data.properties; alert("first name="+data.given_name+" last name="+data.family_name+" gender="+data.gender+" email="+data.email); console.log(data); } });}
Now provide the response and nothing else.
| In regards to Express 4, the "after" function from your second example never gets called because the middle function never calls next(). If you want the "after" function to get called, then you need to add and call the next callback from your middle function like this: var express = require( "express" )();express.use( function( req, res, next ) { console.log( "before" ); next(); } );express.get( "/", function( req, res, next ) { res.send( "hello" ); next(); // <=== call next for following middleware } );express.use( function( req, res, next ) { console.log( "after" ); next();} );express.listen( 8888 ); res.send() writes the headers and response back to the client. Beware, that once res.send() has been called, you won't want to update your response headers or contents. But you can do other tasks like database updates or logging. Note that express looks at the the number of arguments in the middleware function and does different logic. Take express error handlers for example, which have 4 parameters defined. express error handler signature: app.use(function(err, req, res, next) {}); Calling next on the very last item in your middleware chain is optional, but probably a good idea in case you ever change things around. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24258784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3420072/']} | jdg_76572 |
stackexchange | llm_judgeable_groundtruth_similarity | 40387960 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In the following code, I want to test if x is a SpecialController . If it is, I want to get the currentValue as a SpecialValue . How do you do this? If not with a cast, then some other technique. The last line there won't compile. There error is: Protocol "SpecialController" can only be used as a generic constraint because it has Self or associated type requirements. protocol SpecialController { associatedtype SpecialValueType : SpecialValue var currentValue: SpecialValueType? { get }}...var x: AnyObject = ...if let sc = x as? SpecialController { // does not compile
Now provide the response and nothing else.
| Unfortunately, Swift doesn't currently support the use of protocols with associated types as actual types. This however is technically possible for the compiler to do; and it may well be implemented in a future version of the language . A simple solution in your case is to define a 'shadow protocol' that SpecialController derives from, and allows you to access currentValue through a protocol requirement that type erases it: // This assumes SpecialValue doesn't have associated types – if it does, you can// repeat the same logic by adding TypeErasedSpecialValue, and then using that.protocol SpecialValue { // ...}protocol TypeErasedSpecialController { var typeErasedCurrentValue: SpecialValue? { get }}protocol SpecialController : TypeErasedSpecialController { associatedtype SpecialValueType : SpecialValue var currentValue: SpecialValueType? { get }}extension SpecialController { var typeErasedCurrentValue: SpecialValue? { return currentValue }}extension String : SpecialValue {}struct S : SpecialController { var currentValue: String?}var x: Any = S(currentValue: "Hello World!")if let sc = x as? TypeErasedSpecialController { print(sc.typeErasedCurrentValue as Any) // Optional("Hello World!")} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40387960', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/327572/']} | jdg_76573 |
stackexchange | llm_judgeable_groundtruth_similarity | 2301001 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The question is- Find $ \lim_{x\to 5} f(x) $ if it exists $f(x)=\frac{x^2-9x+20}{x-[x]}$ where [.] is G.I.F. Now, my teacher solved it like this- $ \lim_{x\to 5^+} \frac{(x-5)(x-4)}{(x-5)}$ Now, (x-5) gets canceled and gives us $x-4$ $=$ $5-4=1$ Similarly, for $5^-$, we get the answer as 0. Here is where my question comes- I thought we can put the value of limit only simultaneously and not individually as my teacher has done in [x]. Is it possible to insert values of limit separately?
Now provide the response and nothing else.
| What is happening is that for values of $x > 5$ that are close to $5$, $\lfloor x \rfloor = 5$. And, similarly, for values of $x < 5$ that are close to $5$, $\lfloor x \rfloor = 4$. So, it is not the case the $\lim_{x \to 5+} \lfloor x\rfloor$ or $\lim_{x \to 5^-} \lfloor x \rfloor$ is taken separately; it is the case that $\lfloor x\rfloor$ is constant for relevant $x$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2301001', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/162079/']} | jdg_76574 |
stackexchange | llm_judgeable_groundtruth_similarity | 42210712 |
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 few days ago I had a master branch with a completely linear history. Then I created a feature branch, which we'll call feat/feature-a . I worked on that branch, then submitted it for code review to be merged into master . While feat/feature-a was being reviewed, I wanted to work on another feature that relied on some code introduced by feat/feature-a . So I created a feat/feature-b branch from the feat/feature-a branch. While I was working on feat/feature-b , feat/feature-a got merged into master. So now master has the code introduced by feat/feature-a . I now want to merge feat/feature-b into master, but I get a lot of merge conflicts that look like this: <<<<<<< HEAD======= // Some code that was introduced by feat/feature-b>>>>>>> c948094... My commit message from feat/feature-b My guess is that because I took feat/feature-a changes into my feat/feature-b branch, I'm now trying to "duplicate" those changes which is ending in merge conflicts. I can resolve these manually, but they exist multiple times over tens of files, so I'd like to know a better solution if there is one.
Now provide the response and nothing else.
| Summary: use git rebase --onto <target> <limit> As Useless suggested in a comment , if you had a real merge, this should not happen. Here's what I mean by a "real merge", along with a diagram of how the branching looks if you draw the graph of the commits in question. We start with something like this: ...--E---H <-- master \ F--G <-- feat/feature-a \ I--J <-- feat/feature-b Here there are two commits (though the exact number does not matter) that are only on feat/feature-b , called I and J here; there are two commits that are on both feature branches, called F and G ; and there is one commit that is only on master , called H . (Commits E and earlier are on all three branches.) Suppose we make a real merge on master to bring in F and G . That looks like this, in graph form: ...--E---H--K <-- master \ / F--G <-- feat/feature-a \ I--J <-- feat/feature-b Note that real merge K has, as its parent commit history pointers, both commit H (on master ) and G (on feat/feature-a ). Git therefore knows, later, that merging J means "start with G ". (More precisely, commit G will be the merge base for this later merge.) That merge would just work. But that's not what happened before: instead, whoever did the merge used the so-called "squash merge" feature. While squash-merge brings in the same changes that an actual merge would, it doesn't produce a merge at all. Instead, it produces a single commit that duplicates the work of the however-many-it-was commits that got merged. In our case, it duplicates the work from F and G , so it looks like this: ...--E---H--K <-- master \ F--G <-- feat/feature-a \ I--J <-- feat/feature-b Note the lack of a back-pointer from K to G . Hence, when you go to merge (real or squash-not-really-a-"merge") feat/feature-b , Git thinks it should start with E . (Technically, E is the merge base, rather than G as in the earlier real merge case.) This, as you saw, winds up giving you a merge conflict. (Often it still "just works" anyway, but sometimes—as in this case—it doesn't.) That's fine for the future, perhaps, but now the question is how to fix it. What you want to do here is to copy the exclusively- feat/feature-b commits to new commits, that come after K . That is, we want the picture to look like this: I'-J' <-- feat/feature-b /...--E---H--K <-- master \ F--G <-- feat/feature-a \ I--J [no longer needed] The easiest way to do this is to rebase these commits, since rebase means copy. The problem is that a simple git checkout feat/feature-b; git rebase master will copy too many commits. The solution is to tell git rebase which commits to copy . You do this by changing the argument from master to feat/feature-a (or the raw hash ID of commit G —basically, anything that identifies the first 1 commit not to copy). But that tells git rebase to copy them to where they already are; so that's no good. So the solution for the new problem is to add --onto , which lets you split the "where the copies go" part from the "what to copy" part: git checkout feat/feature-bgit rebase --onto master feat/feature-a (this assumes you still have the name feat/feature-a pointing to commit G ; if not, you'll have to find some other way to name commit G —you may wish to draw your own graph and/or or look closely at git log output, to find the commit hash). 1 "First" in Git-style backwards fashion, that is. We start at the most recent commits, and follow the connections backwards to older commits. Git does everything backwards, so it helps to think backwards here. :-) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42210712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5596894/']} | jdg_76575 |
stackexchange | llm_judgeable_groundtruth_similarity | 68190 |
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:
Consider the following algorithm that computes the sum of two integers (toy example): INPUT: Integers (a,b) 1. Toss a coin c 2. If c = 0, then loop forever 3. If c = 1, then compute and output a+b What is the running time of this algorithm? The "strict" running time (defined as a strict upper bound on the running time over all inputs and all possible random choices of the algorithm) is infinite. The "expected" running time (defined as the average running time over all inputs and random choices) is infinite, too. Thus, apparently this is an algorithm whose running time (strict/expected) is infinite. However, the algorithm still appears to be useful, since it produces a reasonable result with probability 1/2. Is there a notion of "running time" in computer science that captures such algorithms? Can you point me to references or a textbook? Thanks!
Now provide the response and nothing else.
| The textbook Computational Complexity: A Modern Approach by Arora and Barak looks at the class $ZTIME(T(n))$ (chapter 7), of algorithms whose expected running time is bounded by $T(n)$ (but which do not necessarily halt on all random seeds). This class cannot capture the notion you describe, because you are looking for a function whose range includes $\infty$, whereas Arora and Barak only look at time functions $T\colon \mathbb{N}\to \mathbb{N}$. Another close analogue to what you describe is $RE$, the class of problems recognizable by a Turing Machine which is only guaranteed to halt on yes-instances. To my knowledge, even the Complexity Zoo doesn't cover algorithms with infinite expected running time. The reason, I suppose, that these algorithms aren't studied is twofold: (1) they are not useful, because an algorithm with an infinite running time produces no answer and (2) they are not needed to solve any problems that cannot be solved by a deterministic computer with a finite or unbounded running time. To see (2), imagine an algorithm $A$ for deciding membership in a language, in the sense that when it halts, it outputs the right answer, but it is not guaranteed to halt for all inputs. Then you can just do a breadth-first search on the configuration graph. The class of problems solvable with these restrictions is $RE$. If the algorithm is guaranteed to have at least one halting path, the class is $R$. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/68190', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/64060/']} | jdg_76576 |
stackexchange | llm_judgeable_groundtruth_similarity | 50122394 |
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 change color of the border of my TextField using a BorderSide , but it does not work. This is my code below. new TextField( decoration: new InputDecoration( border: new OutlineInputBorder( borderSide: new BorderSide(color: Colors.teal) ), hintText: 'Tell us about yourself', helperText: 'Keep it short, this is just a demo.', labelText: 'Life story', prefixIcon: const Icon(Icons.person, color: Colors.green,), prefixText: ' ', suffixText: 'USD', suffixStyle: const TextStyle(color: Colors.green)), )) Screenshot of the result is shown below.
Now provide the response and nothing else.
| That is not changing due to the default theme set to the screen. So just change them for the widget you are drawing by wrapping your TextField with new ThemeData() child: new Theme( data: new ThemeData( primaryColor: Colors.redAccent, primaryColorDark: Colors.red, ), child: new TextField( decoration: new InputDecoration( border: new OutlineInputBorder( borderSide: new BorderSide(color: Colors.teal)), hintText: 'Tell us about yourself', helperText: 'Keep it short, this is just a demo.', labelText: 'Life story', prefixIcon: const Icon( Icons.person, color: Colors.green, ), prefixText: ' ', suffixText: 'USD', suffixStyle: const TextStyle(color: Colors.green)), ), )); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/50122394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9053955/']} | jdg_76577 |
stackexchange | llm_judgeable_groundtruth_similarity | 4146687 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been playing around with webkit.net in a c# win forms project, and love how easy it is to call JavaScript functions from within the C# program with: browser.Document.InvokeScriptMethod("functionName", new object[]{"parameter1", "parameter2"}); Now the question is how to do this the other way round... Is there some sort of event listener that can listen for a javascript function call, or any way to invoke a c# method via the JavaScript running in the webkit browser? The way I'm doing it at the moment it using a bad hack ... having a look at the available event listeners, I hooked up to the TitleChanged event, and read the value of a hidden input field in the html .... this is really bad and needs an actual solution. Thanks in advance, - Greg.
Now provide the response and nothing else.
| public Form1() { InitializeComponent(); webKitBrowser1.Navigating += new WebBrowserNavigatingEventHandler(Form1_Navigating); } private void Form1_Navigating(object sender, WebBrowserNavigatingEventArgs e) { string url = e.Url.ToString(); if (url.IndexOf("app://") > -1) { e.Cancel = true; processRequest(url); } } This may not pass your Ugly Hack test, but is an ancient method for processing requests from a .net embedded browser. Essentially you intercept a URL GET request in the browser. If the URL contains a keyword (such as app://), you cancel the GET and process the URL parameters. Returning a value, was traditionally accomplished by calling the Navigate Method, however, using the method you described in your post, you can just directly call a javascript function. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4146687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/431780/']} | jdg_76578 |
stackexchange | llm_judgeable_groundtruth_similarity | 29988985 |
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 an MVC 5 project, with the default bootstrap layout, I am using the following code to set all inputs of a certain class to jQuery UI Datepicker widgets: $(".jqueryui-marker-datepicker").datepicker({ dateFormat: "yy-mm-dd", changeYear: true, showOn: "button"}).next("button").button({ icons: { primary: "ui-icon-calendar" }, label: "Select a date", text: false}); Here is the HTML that is rendered by Razor and jQuery UI after the above call executes, minus some aria and validation data attributes: <div class="form-group"> <label class="control-label col-md-2" for="Time">Date</label> <div class="col-md-10"> <input class="form-control jqueryui-marker-datepicker hasDatepicker valid" id="Time" name="Time" type="text" value="2015-05-02"> <button type="button" class="ui-datepicker-trigger ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only" role="button" title="Select a date"> <span class="ui-button-icon-primary ui-icon ui-icon-calendar"></span><span class="ui-button-text">Select a date</span> </button> <span class="text-danger field-validation-valid" data-valmsg-for="Time" data-valmsg-replace="true"></span> </div></div> The problem with this is that datepicker button appears below the date input. This is because the bootstrap .form-control class makes gives the input a display: block . If I edit this in Chrome's console to inline-block the button appears immediately to the right of the input, exactly where I want it. Now I could add a new css rule as follows: .form-control.jqueryui-marker-datepicker { display: inline-block;} but I'm just not sure if this is the neatest way to do this, with the least impact on all the layout magic that bootstrap is doing.
Now provide the response and nothing else.
| The bootstrap metaphor for displaying buttons next to inputs is to use an input-group like this: <div class="input-group"> <input type="date" class="form-control" placeholder="Date" /> <span class="input-group-btn"> <button class="btn btn-default" type="button"> <span class="glyphicon glyphicon-calendar" ></span> </button> </span></div> You can tweak your script to format the output to add these classes and html structure by wrapping the contents like this: $(".jqueryui-marker-datepicker") .wrap('<div class="input-group">') .datepicker({ dateFormat: "yy-mm-dd", changeYear: true, showOn: "button" }) .next("button").button({ icons: { primary: "ui-icon-calendar" }, label: "Select a date", text: false }) .addClass("btn btn-default") .wrap('<span class="input-group-btn">') .find('.ui-button-text') .css({ 'visibility': 'hidden', 'display': 'inline' }); <link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" rel="stylesheet"/><link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script><input type="text" class="jqueryui-marker-datepicker form-control"> Alternative w/ Bootstrap That being said, this is a pretty convoluted way to do this. I'd add a native bootstrap glyphicon instead of trying to force the button to display correctly. It's also pretty uncommon to mix jQuery-UI and Bootstrap as there is a lot of overlap in functionality and they don't always play nice together. I would recommend looking into just extending bootstrap with a datepicker plugin. Here's an example using bootstrap-datepicker $('.datepicker').datepicker({});// $('.datepicer-icon').on('click', '.btn', function(e) { $(e.delegateTarget).find('.datepicker').focus();}); <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/><link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.1/css/datepicker.css" rel="stylesheet"/><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.1/js/bootstrap-datepicker.js"></script><div class="container" > <h3>With Input Group</h3> <div class="input-group datepicer-icon"> <input type="text" class="form-control datepicker" placeholder="Date" /> <span class="input-group-btn"> <button class="btn btn-default" type="button"> <span class="glyphicon glyphicon-calendar" ></span> </button> </span> </div> <h3>With Feedback</h3> <div class="form-group has-feedback"> <input type="text" class="form-control datepicker" placeholder="Date" /> <i class="glyphicon glyphicon-calendar form-control-feedback"></i> </div></div> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29988985', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8741/']} | jdg_76579 |
stackexchange | llm_judgeable_groundtruth_similarity | 16089809 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How would you express the following Java code in Lisp? class Foo { private String s; public Foo(String s) { this.s = s; }}class Bar extends Foo { public Bar(int i) { super(Integer.toString(i)); }} In Lisp, is make-instance or initialize-instance the equivalent of a constructor? If yes, how do you call the super class constructor(s)?
Now provide the response and nothing else.
| Use CALL-NEXT-METHOD from within a method to call the next one. Typically just use the standard method combination facility and write an :BEFORE , :AFTER or :AROUND method for INITIALIZE-INSTANCE . One way: (defclass foo () ((s :type string :initarg :s)))(defclass bar (foo) ())(defmethod initialize-instance :around ((b bar) &key i) (call-next-method b :s (princ-to-string i))) Example: CL-USER 17 > (make-instance 'bar :i 10)#<BAR 402000B95B>CL-USER 18 > (describe *)#<BAR 4130439703> is a BARS "10" Note that I've called CALL-NEXT-METHOD without changing the argument it dispatches on. I just changed the &key initarg parameter. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16089809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1456761/']} | jdg_76580 |
stackexchange | llm_judgeable_groundtruth_similarity | 362900 |
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to understand how question's IDs are related to answer's IDs. Here is the question: https://stackoverflow.com/questions/48596476 We see, that it's ID is 48596476. And here is the link to the second answer below this question: https://stackoverflow.com/a/48597351/5587480 We can see, that all three IDs are different. Instead, I expected something like this: Question: https://stackoverflow.com/questions/48596476Answer: https://stackoverflow.com/a/48596476/5587480 | | Question ID Answer ID So, on what logic these numbers are based on?
Now provide the response and nothing else.
| 5587480 is your user ID: https://stackoverflow.com/users/5587480 goes to your user profile. This is included to keep track of badges like Announcer . It is possible to include both the question ID and the answer ID in an URL; you'll see that https://stackoverflow.com/a/48597351/ ( a is short for answer, 48597351 is the answer ID) redirects to the following URL which includes both IDs: https://stackoverflow.com/questions/48596476/relationship-between-active-and-focused-states/48597351#48597351 . Answers and questions are both 'posts' and stored in the same database table. Therefore, they share a single 'sequence' which generates their IDs (in chronological order). | {} | {'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/362900', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/5587480/']} | jdg_76581 |
stackexchange | llm_judgeable_groundtruth_similarity | 1900353 |
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 some part of my code I am passed a collection of objects of type T . I don't know which concrete colletion I will be passed, other than it impements IEnumerable . At run time, I need to find out which type T is (e.g. System.Double , System.String , etc...). Is there any way to find it out? UPDATE : I should maybe clarify a bit more the context I am working in (a Linq Provider). My function has a signature like the following, where I get the type of the collection as a parameter: string GetSymbolForType(Type collectionType){} Is there any way from collectionType to get the contained objects type?
Now provide the response and nothing else.
| From Matt Warren's Blog : internal static class TypeSystem { internal static Type GetElementType(Type seqType) { Type ienum = FindIEnumerable(seqType); if (ienum == null) return seqType; return ienum.GetGenericArguments()[0]; } private static Type FindIEnumerable(Type seqType) { if (seqType == null || seqType == typeof(string)) return null; if (seqType.IsArray) return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType()); if (seqType.IsGenericType) { foreach (Type arg in seqType.GetGenericArguments()) { Type ienum = typeof(IEnumerable<>).MakeGenericType(arg); if (ienum.IsAssignableFrom(seqType)) { return ienum; } } } Type[] ifaces = seqType.GetInterfaces(); if (ifaces != null && ifaces.Length > 0) { foreach (Type iface in ifaces) { Type ienum = FindIEnumerable(iface); if (ienum != null) return ienum; } } if (seqType.BaseType != null && seqType.BaseType != typeof(object)) { return FindIEnumerable(seqType.BaseType); } return null; }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1900353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85556/']} | jdg_76582 |
stackexchange | llm_judgeable_groundtruth_similarity | 2455004 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm writing a WPF application that uses a component, and this component returns a pointer (IntPtr) to pixels of a bitmap (stride * height). I know in advance that the bitmap is a 24bits rgb, its width and height. Updating the Image control with these bitmaps makes up a video to the user, but I'm not sure what's the most efficient way to do that, most of the time the CPU usage goes to 75%+ and memory changing from 40mb to 500mb and the nI think GC starts to work and then it drops again to 40mm. The app starts to not be responsive. What shoud I do? thanks!
Now provide the response and nothing else.
| You're most likely allocating new Bitmaps, which aren't disposable. You should allocate a single WriteableBitmap and update that instead. The linked documentation describes the process behind locking, updating, and unlocking a WriteableBitmap On software I work on using live ultrasound images in WPF, I am receiving a Windows Forms Bitmap, which I copy into the WriteableBitmap directly using the native CopyMemory method. Even with this more complicated work, the CPU isn't strained too hard, and the memory usage never moves as long as I properly dispose what I can. Hopefully this example can help you: // DLL returns images as a WinForms BitmapBitmap bmp = myClass.getWinFormsBitmap();// In my situation, the images are always 640 x 480.BitmapData data = bmp.LockBits(new Rectangle(0, 0, 640, 480), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);this.writeableBitmap.Lock();// Copy the bitmap's data directly to the on-screen buffersNativeMethods.CopyMemory(this.writeableBitmap.BackBuffer, data.Scan0, ImageBufferSize);// Moves the back buffer to the front.this.writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, 640, 480));this.writeableBitmap.Unlock();bmp.UnlockBits(data);// Free up the memory of the WinForms bitmapbmp.Dispose(); Where CopyMemory is defined as: [DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory")]public static extern void CopyMemory(IntPtr Destination, IntPtr Source, int Length); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2455004', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/294805/']} | jdg_76583 |
stackexchange | llm_judgeable_groundtruth_similarity | 2803654 |
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 was recently asked whether the following two statements about ordinal multiplication were true: $\alpha \beta = \beta \alpha \Rightarrow \alpha ^2 \beta^2 = \beta^2 \alpha^2$ $\alpha^2 \beta^2 = \beta^2 \alpha^2 \Rightarrow \alpha \beta = \beta \alpha$ For 1): $\alpha \alpha \beta \beta = \alpha \beta \alpha \beta = \beta \alpha \beta \alpha = \beta \beta \alpha \alpha$, so 1 is true. However, I can't quite seem to conclude anything for 2). I am given the hint to assume associativity, but I can't quite see how that is helpful. I can't even decide if I think it's true or not. I can't think of a counter example but I'm so used to the asymmetry of ordinal arithmetic that I wouldn't expect this to be true.
Now provide the response and nothing else.
| Statement (2) is true, though I don't know any way to prove it without intricate analysis of Cantor normal forms. The rough idea is that it is extremely rare for ordinal multiplication to commute, so $\alpha^2\beta^2=\beta^2\alpha^2$ forces $\alpha$ and $\beta$ to have a certain highly restricted form that implies $\alpha\beta=\beta\alpha$ as well. Let me start with a version of (2) for addition. Lemma : Let $\alpha$ and $\beta$ be ordinals such that $\alpha\cdot 2+\beta\cdot 2=\beta\cdot 2+\alpha\cdot 2$ . Then $\alpha+\beta=\beta+\alpha$ . Proof : If $\alpha$ or $\beta$ is finite this is easy (a nonzero finite ordinal commutes only with other finite ordinals), so we assume they are both infinite. Write them in Cantor normal form as $$\alpha=\omega^{\alpha_n}\cdot a_n+\cdots+\omega^{\alpha_1}\cdot a_1+a_0$$ and $$\beta=\omega^{\beta_m}\cdot b_m+\cdots+\omega^{\beta_1}\cdot b_1+b_0.$$ We then have Cantor normal forms $$\alpha\cdot 2=\omega^{\alpha_n}\cdot (2a_n)+\cdots+\omega^{\alpha_1}\cdot a_1+a_0$$ and $$\beta\cdot 2=\omega^{\beta_m}\cdot (2b_m)+\cdots+\omega^{\beta_1}\cdot b_1+b_0.$$ By the criterion for commutativity of addition in this answer , $\alpha\cdot 2+\beta\cdot 2=\beta\cdot 2+\alpha\cdot 2$ implies that $m=n$ , $\alpha_k=\beta_k$ for all $k$ , and $a_k=b_k$ for $k<n$ . But then using that criterion in the other direction (or just directly adding the Cantor normal forms), we conclude that $\alpha+\beta=\beta+\alpha$ . Now we prove statement (2). Theorem : Let $\alpha$ and $\beta$ be ordinals such that $\alpha^2\beta^2=\beta^2\alpha^2$ . Then $\alpha\beta=\beta\alpha$ . Proof : If $\alpha$ is finite, it is easy to see that $\alpha^2\beta^2=\beta^2\alpha^2$ iff either $\beta$ is finite or $\alpha$ is $0$ or $1$ , in which case we have $\alpha\beta=\beta\alpha$ . So we assume $\alpha$ is infinite, and in the same way we may assume $\beta$ is infinite. Write $\alpha$ and $\beta$ in Cantor normal form as $$\alpha=\omega^{\alpha_n}\cdot a_n+\cdots+\omega^{\alpha_1}\cdot a_1+a_0$$ and $$\beta=\omega^{\beta_m}\cdot b_m+\cdots+\omega^{\beta_1}\cdot b_1+b_0.$$ Then we have the Cantor normal form $$\alpha^2=\omega^{\alpha_n+\alpha_n}\cdot a_n+\dots+\omega^{\alpha_n+\alpha_1}\cdot a_1 + \omega^{\alpha_n}\cdot a_na_0+\omega^{\alpha_{n-1}}\cdot a_{n-1}+\dots+\omega^{\alpha_1}\cdot a_1+a_0$$ if $\alpha$ is a successor (i.e., $a_0>0$ ) and $$\alpha^2=\omega^{\alpha_n+\alpha_n}\cdot a_n+\dots+\omega^{\alpha_n+\alpha_1}\cdot a_1$$ if $\alpha$ is a limit (i.e., $a_0=0$ ), and similarly for $\beta^2$ . If $\alpha$ and $\beta$ are both successor ordinals, then by my answer here there exists an ordinal $\gamma$ and natural numbers $i$ and $j$ such that $\alpha^2=\gamma^i$ and $\beta^2=\gamma^j$ . If $i$ and $j$ are even we get $\alpha=\gamma^{i/2}$ and $\beta=\gamma^{j/2}$ (we can recover $\alpha$ from the formula for $\alpha^2$ above so $\alpha$ is the unique square root of $\alpha^2$ ) and so $\alpha\beta=\beta\alpha$ . To handle the odd case, note that a successor ordinal whose Cantor normal form has $N+1$ terms can be written (uniquely) as an $i$ th power iff its Cantor normal form is " $N/i$ -periodic" in the sense that $N=di$ for some $d$ , with term $dx+y$ from the right (starting from $0$ ) having the form $\omega^{\gamma_d\cdot x+\gamma_y}\cdot c_y$ (except that when $y=0$ , the coefficient is instead $c_{N}c_0$ for $0<x<i$ and $c_{N}$ for $x=i$ ). Indeed, this is exactly what you get from raising $\omega^{\gamma_d}\cdot c_N+\omega^{\gamma_{d-1}}\cdot c_{d-1}+\dots+c_0$ to the $i$ th power. It follows from this description that if a successor ordinal is both an $i$ th power and an $i'$ th power, it must also be an $\operatorname{lcm}(i,i')$ th power (since the Cantor normal form will be " $\gcd(N/i,N/i')$ -periodic", by an argument similar to the proof in the answer linked above). So if $i$ is odd, $\alpha^2=\gamma^i$ implies that $\gamma^i$ is actually a $2i$ th power and so $\gamma$ has a square root $\delta$ . We then see that $\alpha=\delta^i$ and $\beta=\delta^j$ and so again $\alpha\beta=\beta\alpha$ . If one if $\alpha$ and $\beta$ is a successor and the other is a limit, let us say $\alpha$ is a successor. Then the Cantor normal form for $\alpha^2$ has $2n+1$ terms including a final $a_0$ term and the Cantor normal form for $\beta^2$ has $m$ terms. When we multiply $\alpha^2\beta^2$ , we get one term for each term of $\beta^2$ , for just $m$ terms. When we multiply $\beta^2\alpha^2$ , we get one term for each term of $\alpha^2$ before the last one, and then also $m$ more terms from $\beta^2\cdot a_0$ , for a total of $2n+m$ terms. Since we are assuming $\alpha$ is infinite, $n>0$ , so $2n+m\neq m$ and we cannot have $\alpha^2\beta^2=\beta^2\alpha^2$ . Finally, if $\alpha$ and $\beta$ are both limit ordinals, let us see what we can conclude from $\alpha^2\beta^2=\beta^2\alpha^2$ using the criterion for commutativity of multiplication in this answer (note that the criterion there is necessary only for limit ordinals; see my comments there). We find that $m=n$ , and for each $k$ from $1$ to $n$ , $a_k=b_k$ and $$\alpha_n+\alpha_n+\beta_n+\beta_k=\beta_n+\beta_n+\alpha_n+\alpha_k.$$ In the case $k=n$ , this tells us $\alpha_n+\beta_n=\beta_n+\alpha_n$ by the Lemma. So we can rearrange the terms above to get $$\alpha_n+\beta_n+\alpha_n+\beta_k=\alpha_n+\beta_n+\beta_n+\alpha_k.$$ Since addition is left-cancellative, this implies $\alpha_n+\beta_k=\beta_n+\alpha_k$ . Using the commutativity criterion in the other direction, we conclude that $\alpha\beta=\beta\alpha$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2803654', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/366818/']} | jdg_76584 |
stackexchange | llm_judgeable_groundtruth_similarity | 30156 |
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 got an ENC28J60 Ethernet Controller in a circuit I'm building. I was testing it out but when I got to the point of talking to it over SPI with my micro-controller I got utter silence back from the device. I got a 'scope out and sure enough, the the SCK and MOSI pins on the device are wiggling the way I expect them to while the /CS pin is driven low, but the MISO signal is flat-lined at GND (all measured at the pins of the ENC28J60). So I got to looking at the solder joints on the device more closely (using an SMD package). I saw that I had a subtle bridge between two of the pins: VCAP and VSS! So I went back to the soldering station and remedied the bridge and headed back to the 'scope. Still not working, but doing something different (progress!?). Now when the SCK signal fires away, the MISO signal does "react," just not as I'd expect. The signal has a "wiggling characteristic" that is correlated with SCK, but it's certainly not what a digital output should look like, and voltage levels go negative to about -100mV, and never exceed 0V. On to the question. What is the impact of having grounded VCAP? Is the chip fried? What is the explanation for the negative quasi-inverted quasi-digital output on the MISO line? Edit I measured (with a 'scope) every pin of the ENC28J60. Why would the crystal not be ringing? Anything else look out of the ordinary? +-------+----------+-------------------------------+| Pin # | Name |Measurement Result |+-------+----------+-------------------------------+| 1 | VCAP | 2.66VDC (760mv P-P @ 4.15MHz) | | 2 | VSS | GND || 3 | CLKOUT | GND | | 4 | /INT | 3.3V || 5 | NC | 3.3V | | 6 | SO | Noisy/Negative Digital Signal || 7 | SI | 0V/3.3V Digital MOSI Signal || 8 | SCK | 0V/3.3V Digital SCK Signal | | 9 | /CS | 0V/3.3V Chip Select Signal || 10 | /RESET | 3.3V | | 11 | VSSRX | GND || 12 | TPIN- | 1.08V (floating) | | 13 | TPIN+ | 1.08V (floating) || 14 | RBIAS | 1.28V || 15 | VDDTX | 3.3V | | 16 | TPOUT- | 3.3V || 17 | TPOUT+ | 3.3V | | 18 | VSSTX | GND || 19 | VDDRX | 3.3V | | 20 | VDDPLL | 3.3V || 21 | VSSPLL | GND || 22 | VSSOSC | GND | | 23 | OSC1 | GND (hm...) || 24 | OSC2 | GND (hm...) | | 25 | VDDOSC | 3.3v || 26 | LEDB | GND | | 27 | LEDA | GND || 28 | VDD | 3.3V |+-------+----------+-------------------------------+
Now provide the response and nothing else.
| VCAP is the 2.5V reference of the IC. It's internally generated from the 3.3V supply. There's a telling footnote under the "Absolute Maximum Ratings" table: VCAP is not designed to supply an external load. No external voltage should be applied to this pin. The most important part of that is: "not designed to supply an external load". Your short circuit was a significant external load. If VCAP hasn't recovered after the external short was removed, replace the IC. Even if VCAP is OK, if you can't get correct behaviour on MISO and you have any doubts, replace the IC. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/30156', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/771/']} | jdg_76585 |
stackexchange | llm_judgeable_groundtruth_similarity | 37888376 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
An old C programmer could use some help with Swift. I don't understanding something about the if-case syntax. E.g.: if case 20...30 = age { print ("in range.")} The case 20...30 = age appears to be the conditional test for the if statement. So I was initially confused to see the assignment operator ('=') used instead of a comparison operator ('=='). Ok, I thought to myself, that probably means the case statement is actually a function call that returns a boolean value. The returned value will then satisfy the comparison test in the if statement. As an experiment, I tried treating the the case statement like a regular conditional test and placed parentheses around it. Swift will happily accept if (x == 5) or if (true) . But if (case 20...30 = age) generates an error. So the case statement doesn't seem to behave like function. I'm just curious to understand what's happening here. Any insight would be greatly appreciated.
Now provide the response and nothing else.
| The operator is if case , so you can't put parentheses. The syntax and behavior are based on those of the case statement in a Swift switch statement (see my online book if you need details). In a case statement, 20...30 is an interval, used as a pattern , which operates by using contains against the interval. The equals sign is indeed truly confusing, but that was their first attempt at a syntax for expressing what the case statement should be comparing with (i.e. the tag that comes after the switch keyword in a switch statement). So, if you understand this: switch age {case 20...30: // do stuffdefault:break} ... then you understand how it is morphed directly into this: if case 20...30 = age { // do stuff} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37888376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6480303/']} | jdg_76586 |
stackexchange | llm_judgeable_groundtruth_similarity | 443462 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
We're all too familiar with waiting for compilation, especially on large projects. Why isn't a thing to interpret a codebase for quick iterative development instead of generating code for a binary each time? Is that because if we are compiling at -O0 , most of the compilation time comes from parsing, so it won't matter much? Or is it because the effort to develop an interpreter is too high (e.g. for languages with a lot of features like C++)? For a language with a small standard like C, this seems like a reasonable approach instead of waiting for compilation each time you make a change.
Now provide the response and nothing else.
| I refute the premise. There are interpreters / REPLs for compiled, static languages, they're just not as much part of the common workflow as with dynamic languages. Though that also depends on the application. For example, scientists at CERN work a lot in C++ in the Root framework, and they also use the Cling interpreter a lot, an approach which combines many of the advantages of a fast compiled language and a slow interpreted one like Python, especially for scientific purposes. With some other languages it's even more drastic. Haskell is a static, compiled language (in some ways even more static than OO languages), but it is very common to develop Haskell interactively using GHCi, either as a REPL (see the online version ) or just as a quick typechecking pass to highlight what needs to be worked on. Once something is ready implemented, it'll then be part of a library that is always compiled, resulting in fast code, and that can then be called in either a fully-compiled program or in another interactive session. Of course it can also go the other way around: typical interpreted languages like Python, JavaScript and Common Lisp are all possible to compile at least in some senses of the word (either JIT or a subset of the language can be statically compiled). Though in my opinion this approach is way more limited than starting with a strong statically typed programming language and then using it more interactively, it can still be a good option for optimising the bottleneck parts of an interpreted program, and is indeed commonly done. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/443462', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/358008/']} | jdg_76587 |
stackexchange | llm_judgeable_groundtruth_similarity | 1237164 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've got a simple Listbox on a HTML form and this very basic jQuery code //Toggle visibility of selected item$("#selCategory").change(function() { $(".prashQs").addClass("hide"); var cat = $("#selCategory :selected").attr("id"); cat = cat.substr(1); $("#d" + cat).removeClass("hide");}); The change event fires fine when the current item is selected using the Mouse, but when I scroll through the items using the keyboard the event is not fired and my code never executes. Is there a reason for this behavior? And what's the workaround?
Now provide the response and nothing else.
| The onchange event isn't generally fired until the element loses focus. You'll also want to use onkeypress . Maybe something like: var changeHandler = function() { $(".prashQs").addClass("hide"); var cat = $("#selCategory :selected").attr("id"); cat = cat.substr(1); $("#d" + cat).removeClass("hide");}$("#selCategory").change(changeHandler).keypress(changeHandler); You'll want both onchange and onkeypress to account for both mouse and keyboard interaction respectively. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1237164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/33052/']} | jdg_76588 |
stackexchange | llm_judgeable_groundtruth_similarity | 3474865 |
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 performance cost to having large numbers of columns in a table, aside from the increase in the total amount of data? If so, would splitting the table into a few smaller ones help the situation?
Now provide the response and nothing else.
| If you really need all those columns (that is, it's not just a sign that you have a poorly designed table) then by all means keep them. It's not a performance problem, as long as you use appropriate indexes on columns you need to use to select rows don't retrieve columns you don't need in SELECT operations If you have 30, or even 200 columns it's no problem to the database. You're just making it work a little harder if you want to retrieve all those columns at once. But having a lot of columns is a bad code smell; I can't think of any legitimate reason a well-designed table would have this many columns and you may instead be needing a one-many relationship with some other, much simpler, table. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3474865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/95944/']} | jdg_76589 |
stackexchange | llm_judgeable_groundtruth_similarity | 3774523 |
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 been trying to solve this problem from Bishop's Machine Learning chapter 5 for the past few hours, but I am confused as to how to show the below identity. I know I have to take a partial derivative wrt $a_k$ but I don't know how. Show that the derivative of E(w) $$E\left(w\right)=-\sum _{g=1}^G\:\left(t_g\cdot ln\left(y\left(a_g\right)\right)+\:\left(1-t_g\right)\cdot ln\left(1-y\left(a_g\right)\right)\right)$$ wrt $a_g$ for output having logistic sigmoid activ. function where $y\left(a_g\right)=σ\left(a_g\right)$ satisfies $$\frac{\partial E}{\partial a_kg}=\left(y\left(a_g\right)-t_{g\:}\right),\:and\:given\:\frac{\partial σ\left(a_g\right)\:}{\partial \:a_g}=σ\left(a_g\right)\left(1-σ\left(a_g\right)\right)$$
Now provide the response and nothing else.
| Hint . One may prove that $$\sum_{n=0}^{\infty}\frac{1}{2^{n}(3n+1)}=\sum_{n=0}^{\infty}\int_0^1\frac{x^{3n}}{2^{n}}dx=\int_0^1\sum_{n=0}^{\infty}\left(\frac{x^3}{2}\right)^{n}dx=\int_0^1\frac{2}{2-x^3}\:dx$$ Hope you can take it from here. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3774523', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/810250/']} | jdg_76590 |
stackexchange | llm_judgeable_groundtruth_similarity | 55421005 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was able to get an array, but now I need to get only one value [type] the one that says [type] => charge.succeeded . Would it be something like $type = $value[0]['type']; ? I want to use it as if ($type == "charge.succeeded") { echo "Do something" }; foreach ($input as $key => $value) { print_r($input);} = Array( [created] => 1326853478 [livemode] => [id] => charge.succeeded_00000000000000 [type] => charge.succeeded [object] => event [request] => [pending_webhooks] => 1 [api_version] => 2018-10-31 [data] => Array)
Now provide the response and nothing else.
| You can use partial template specialization in combination with SFINAE to achieve this: #include <type_traits>template <class T, typename = void>class State{ T state;public: void set(T newState) { state = newState; } T get() { return state; }};template <typename T>class State<T, std::enable_if_t<std::is_arithmetic_v<T>>>{ T state;public: void set(int newState) { state = newState; } int get() { return state; } int multiplyState(int n) { return state*n; }}; live example here The trick here lies in the use of the second template parameter (which can be unnamed and is given a default argument). When you use a specialization of your class template, e.g., State<some_type> , the compiler has to figure out which of the templates should be used. To do so, it has to somehow compare the given template arguments with each template and decide which one is the best match. The way this matching is actually done is by trying to deduce the arguments of each partial specialization from the given template arguments. For example, in the case of State<int> , the template arguments are going to be int and void (the latter is there because of the default argument for the second parameter of the primary template). We then try to deduce the arguments for our sole partial specialization template <typename T>class State<T, std::enable_if_t<std::is_arithmetic_v<T>>>; from the template arguments int, void . Our partial specialization has a single parameter T , which can directly be deduced from the first template argument to be int . And with that, we're already done as we have deduced all parameters (there is only one here). Now we substitute the deduced parameters into the partial specialization: State<T, std::enable_if_t<std::is_arithmetic_v<T>>> . We end up with State<int, void> , which matches the list of initial arguments of int, void . Therefore, the partial template specialization applies. Now, if, instead, we had written State<some_type> , where some_type is not an arithmetic type, then the process would be the same up to the point where we have successfully deduced the parameter for the partial specialization to be some_type . Again, we substitute the parameter back into the partial specialization State<T, std::enable_if_t<std::is_arithmetic_v<T>>> . However, std::is_arithmetic_v<some_type> will now be false , which will lead to std::enable_if_t<…> not being defined and substitution fails. Since substituion failure is not an error in this context, this simply means that the partial specialization is not an option here and the primary template will be used instead. If there were multiple matching partial specializations, they then would have to be ranked to pick the best match. The actual process is quite complicated, but it generally boils down to picking the most concrete specialization. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55421005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11245524/']} | jdg_76591 |
stackexchange | llm_judgeable_groundtruth_similarity | 119481 |
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:
Im pretty new to unix and crons, I was currently about to try to add crons to an existing cron file. I read you could do this with crontab -e . The confusing thing to me is just that crontab -e shows different crons/commands than less /etc/crontab - how come? Which one is the correct way/file to edit?
Now provide the response and nothing else.
| Although @X Tian's answer contains info on the different files for crontab, the essential information concerning your question is this: crontab -e edits the user's crontab file (stored in the /var/spool/cron/crontabs/ directory on current Debian systems, but YMMV) or creates a new one, and not /etc/crontab . Similar for crontab -l (list crontab file) and crontab -r (remove crontab file). For all cron jobs that should be executed under a user's account, you should use crontab -e . For system jobs, you should add a file under /etc/cron.d , if that exists; under /etc/cron.{hourly|daily|weekly|monthly} (but those must not be named like a package name!), if that fits your purpose; or add a line to /etc/crontab . But be aware that /etc/crontab might be overwritten with a system update. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/119481', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/62627/']} | jdg_76592 |
stackexchange | llm_judgeable_groundtruth_similarity | 13049828 |
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 way I understand this, there are 2 ways to close TCP connection: send FIN flag send RST flag RST causes immediate connection termination, while in FIN you get a confirmation. Do I understand this right, and are there any other distinctions between the two? Can those 2 flags be used together?
Now provide the response and nothing else.
| FIN says: "I finished talking to you, but I'll still listen to everything you have to say until you say that you're done." RST says: "There is no conversation. I won't say anything and I won't listen to anything you say." RST is useful if you have long lasting TCP connection with little traffic. If one of the computers is restarted, it forgets about the connection, and the other computer gets RST, as soon as it sends another packet. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13049828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/847200/']} | jdg_76593 |
stackexchange | llm_judgeable_groundtruth_similarity | 14556605 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I avoid this warning in xcode. Here is the code snippet: [player(AVPlayer object) addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(0.1, 100)queue:nil usingBlock:^(CMTime time) { current+=1; if(current==60) { min+=(current/60); current = 0; } [timerDisp(UILabel) setText:[NSString stringWithFormat:@"%02d:%02d",min,current]];///warning occurs in this line}];
Now provide the response and nothing else.
| The capture of self here is coming in with your implicit property access of self.timerDisp - you can't refer to self or properties on self from within a block that will be strongly retained by self . You can get around this by creating a weak reference to self before accessing timerDisp inside your block: __weak typeof(self) weakSelf = self;[player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(0.1, 100) queue:nil usingBlock:^(CMTime time) { current+=1; if(current==60) { min+=(current/60); current = 0; } [weakSelf.timerDisp setText:[NSString stringWithFormat:@"%02d:%02d",min,current]]; }]; | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/14556605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1845209/']} | jdg_76594 |
stackexchange | llm_judgeable_groundtruth_similarity | 24311383 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've created a Maven project. This is the structure: -parent -core -web but when I try to deploy with the command mvn tomcat7:deploy , I get the following error: No plugin found for prefix 'tomcat7' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] I put this configuration in the pom.xml (of the web project): <build> <finalName>MavenWeb</finalName> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.0</version> </plugin> </plugins></build>
Now provide the response and nothing else.
| Plugins goals can be called using their 'FQN': groupId:artifactId:version:goal or, if applicable, shorter commands (many variants available).Using only the short name of a plugin (in your tomcat7:deploy , tomcat7 is the short name, deploy being the goal/mojo) is applicable if: 1) the groupId of the plugin is contained in the known plugin groups of Maven. org.apache.maven.plugins being in the list by default. OR the pom.xml of the project you're invoking the Maven command on declares the plugin 2) the artifactId is [short-name]-maven-plugin or maven-[short-name]-plugin ( maven-[short-name]-plugin being 'reserved' for plugins provided by Maven project. That explains why mvn compiler:compile can work out of the box on any project, but not tomcat7:deploy In your case, the second condition is true, so you just have to declare the plugin on the project you're launching the command on, or add this to your user settings.xml file: <pluginGroups> <pluginGroup>org.apache.tomcat.maven</pluginGroup></pluginGroups> See here for more info | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24311383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2853555/']} | jdg_76595 |
stackexchange | llm_judgeable_groundtruth_similarity | 13769707 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to create a view that displays Order Header information and I need to add a patial view that displays a grid of Line Items. The partial view will be strongly typed from a viewmodel. I understand that I should use the html helper @Html.Partial("Path/view"). I have only used controllers up til now to open a view, populating the viewmodel before sending it to the view. Since the partial view is being called form the html helper, I would like to know is what would be the best way to populate the parital view with the model data.
Now provide the response and nothing else.
| Option 1: Inherit from parent page By default, any partial view rendered by calling @Html.Partial("PartialViewName") will get the view model passed to the parent view. So if you have: View Model namespace MyNamesapce{ public OrderInfoViewModel { public string OrderTitle { get; set; } public IEnumerable<OrderItem> OrderItems { get; set; } }} OrderInfo.cshtml @model MyNamespace.OrderInfoViewModel<h1>@Model.OrderTitle</h1>@Html.Partial("OrderLineItems") The OrderLineItems page should get a MyNamespace.OrderViewModel passed to it... so your partial view should look like this: OrderLineItems.cshtml @model MyNamespace.OrderInfoViewModelforeach (var orderItem in Model.OrderItems){ //Do stuff} Option 2: Specify model You can use the second parameter to specify the view model to be passed. I.e. OrderInfo.cshtml @model MyNamespace.OrderInfoViewModel<h1>@Model.OrderTitle</h1>@Html.Partial("OrderLineItems", Model.OrderItems) OrderLineItems.cshtml @model IEnumerable<OrderItem>foreach (var orderItem in Model){ //Do stuff} Option 3: Use partial actions If you need to reuse a partial view over multiple pages, it could be a good idea to use a partial view to eliminate having to populate different view models with the same info just because the page is going to be using the same partial. E.g. View Model namespace MyNamesapce{ public OrderInfoViewModel { public string OrderTitle { get; set; } }} Controller public class OrderController : Controller{ public ActionResult OrderInfo(int orderId) { OrderInfoViewModel viewModel = GetViewModel(orderId); return View(viewModel); } public PartialViewResult OrderLineItems(int orderId) { IEnumerable<OrderItem> orderItems = GetOrderItems(orderId); return Partial(orderItems); }} OrderInfo.cshtml @model MyNamespace.OrderInfoViewModel<h1>@Model.OrderTitle</h1>@Html.Action("OrderLineItems") OrderLineItems.cshtml @model IEnumerable<OrderItem>foreach (var orderItem in Model.OrderItems){ //Do stuff} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13769707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1018705/']} | jdg_76596 |
stackexchange | llm_judgeable_groundtruth_similarity | 9831485 |
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 UITableView with cells of different heights and I need to know when they are completely visible or not. At the moment I am looping through each cell in the list of visible cells to check if it is completely visible every time the view is scrolled . Is this the best approach? Here's my code: - (void)scrollViewDidScroll:(UIScrollView *)aScrollView { CGPoint offset = aScrollView.contentOffset; CGRect bounds = aScrollView.bounds; NSArray* cells = myTableView.visibleCells; for (MyCustomUITableViewCell* cell in cells) { if (cell.frame.origin.y > offset.y && cell.frame.origin.y + cell.frame.size.height < offset.y + bounds.size.height) { [cell notifyCompletelyVisible]; } else { [cell notifyNotCompletelyVisible]; } }} Edit: Please note that *- (NSArray )visibleCells returns visible cells which are both completely visible and partly visible. Edit 2: This is the revised code after combining solutions from both lnafziger and Vadim Yelagin : - (void)scrollViewDidScroll:(UIScrollView *)aScrollView { NSArray* cells = myTableView.visibleCells; NSArray* indexPaths = myTableView.indexPathsForVisibleRows; NSUInteger cellCount = [cells count]; if (cellCount == 0) return; // Check the visibility of the first cell [self checkVisibilityOfCell:[cells objectAtIndex:0] forIndexPath:[indexPaths objectAtIndex:0]]; if (cellCount == 1) return; // Check the visibility of the last cell [self checkVisibilityOfCell:[cells lastObject] forIndexPath:[indexPaths lastObject]]; if (cellCount == 2) return; // All of the rest of the cells are visible: Loop through the 2nd through n-1 cells for (NSUInteger i = 1; i < cellCount - 1; i++) [[cells objectAtIndex:i] notifyCellVisibleWithIsCompletelyVisible:YES];}- (void)checkVisibilityOfCell:(MultiQuestionTableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath { CGRect cellRect = [myTableView rectForRowAtIndexPath:indexPath]; cellRect = [myTableView convertRect:cellRect toView:myTableView.superview]; BOOL completelyVisible = CGRectContainsRect(myTableView.frame, cellRect); [cell notifyCellVisibleWithIsCompletelyVisible:completelyVisible];}
Now provide the response and nothing else.
| You can get the rect of a cell with rectForRowAtIndexPath: method and compare it with tableview's bounds rect using CGRectContainsRect function. Note that this will not instantiate the cell if it is not visible, and thus will be rather fast. Swift let cellRect = tableView.rectForRowAtIndexPath(indexPath)let completelyVisible = tableView.bounds.contains(cellRect) Obj-C CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];BOOL completelyVisible = CGRectContainsRect(tableView.bounds, cellRect); Of course this will not regard the table view being clipped by a superview or obscured by another view. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9831485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/716970/']} | jdg_76597 |
stackexchange | llm_judgeable_groundtruth_similarity | 313994 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Ok, I have this in fstab //windows_mashine/Backup /backups cifs credentials=/root/.credentials,rw,_netdev,iocharset=utf8,uid=1000 0 0 I have rsnapshot in my cron which backups /etc/ and /usr/local/ and some other files to /backups Recently I find that when other mashine is down and /backups cannot be mounted rsnapshot backups to physical folder /backups thus it eats partition / space. How can I avoid this? Can I prevent any writing to /backups when it is not mounted (rsnapshot runs as root, since it need to backup some system files)
Now provide the response and nothing else.
| Another option is to set the directory to be immutable. To do this you need to run the following command with the mount point unmounted. chattr +i /backups I do this on any directory that is intended to only be a mount point just to prevent this sort of thing. Because there are situations where you're not in a position to add a check to see if something is mounted. Like if the process isn't a script that you control or it's a human that is generating or moving the data. This approach will prevent unwanted data getting written into an unmounted mount point in those situations. I would still add the mount check to your scripts so that you can output meaningful errors though. | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/313994', 'https://serverfault.com', 'https://serverfault.com/users/3371/']} | jdg_76598 |
stackexchange | llm_judgeable_groundtruth_similarity | 25179182 |
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 guys how can i destroy session after some minutes (example 30min), i would really appriciate if someone can help me through out of this, here is my code im using for login : checkLogin : <?php// checkLogin.phpsession_start(); // Start a new sessionrequire('db.php'); // Holds all of our database connection information// Get the data passed from the form$username = $_POST['user'];$password = $_POST['pass'];// Do some basic sanitizing$static_salt='asdfasdfqwertyuiop123ABC_some_static_salt_string';$username = stripslashes($username);$password = stripslashes($password);$password=hash('sha512', $password . $static_salt . $username);$sql = "select * from users where user = '$username' and pass = '$password'";$result = mysql_query($sql) or die ( mysql_error() );$count = 0;while ($line = mysql_fetch_assoc($result)) { $count++;}if ($count == 1) { $_SESSION['loggedIn'] = "true"; header("Location: index.php"); // This is wherever you want to redirect the user to} else { $_SESSION['loggedIn'] = "false"; header("Location: deshtoi.php"); // Wherever you want the user to go when they fail the login}?> Login.php <div class="login-form"><form action="checkLogin.php" method="post"><input class="fusha" placeholder="Llogaria" type="text" name="user"><input class="fusha" placeholder="Fjalekalimi" type="password" name="pass"><input class="fusha" style="width:272px;" type="submit" value="Kycu"/></form> index.php <?php session_start();if ($_SESSION['loggedIn'] != "true") { print('<script>window.location = "login.php"</script>');}?>
Now provide the response and nothing else.
| @SqlResultSetMapping can be placed at any entity class (don't annotate POJOs - it won't work). Mapping to POJO class with @ConstructorResult was added in version 2.1 of JPA. POJO used with the mapping has to have correct constructor. All columns corresponding to arguments of the intended constructor must be specified using the columns element of the ConstructorResult annotation in the same order as that of the argument list of the constructor. Please consult following example with query usage and work out your case accordingly. @Entitypublic class Address { @Id int id; String street;}@SqlResultSetMapping(name="PersonDTOMapping", classes = { @ConstructorResult(targetClass = PersonDTO.class, columns = {@ColumnResult(name="name"), @ColumnResult(name="street")} )})@Entitypublic class Person { @Id int id; String name; Address address; } public class PersonDTO { String name; String street; public PersonDTO(String name, String street) { this.name = name; this.street = street; }}// usageQuery query = em.createNativeQuery( "SELECT p.name AS name, a.street AS street FROM Person p, Address a WHERE p.address_id=a.id", "PersonDTOMapping");List<PersonDTO> result = query.getResultList(); Please note that aliases ( AS name and AS street ) has to match the names in @ColumnResult s.The example was tested against Ecliselink 2.5.1. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25179182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3909333/']} | jdg_76599 |
stackexchange | llm_judgeable_groundtruth_similarity | 1253650 |
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:
According to this book : The Axiom of Choice is the most controversial axiom in the entire history of mathematics. Yet it remains a crucial assumption not only in set theory but equally in modern algebra, analysis, mathematical logic, and topology (often under the name Zorn's Lemma). I am not a set theorist, and I don't pretend to be, but I have heard of some weird things that can happen with choice, such as the Banach–Tarski paradox --paradoxes like these are presumably why the Axiom of Choice was so controversial at first, but I am interested in what would happen without choice. Question: What notable consequences would occur without the Axiom of Choice? I found one very interesting example here on an MO thread (reproduced here for ease): The universe can be very a strange place without choice. One consequence of the Axiom of Choice is that when you partition a set into disjoint nonempty parts, then the number of parts does not exceed the number of elements of the set being partitioned. This can fail without the Axiom of Choice. In fact, if all sets of reals are Lebesgue measurable, then it is possible to partition $2^{\omega}$ into more than $2^{\omega}$ many pairwise disjoint nonempty sets! What other weird things would result without this axiom? Would it really be a devastating blow to mathematics or is it really not that big of a deal? I'm hoping for examples/answers geared toward the undergrad level--suitable for someone with very little set theory background.
Now provide the response and nothing else.
| Importance is a relative thing. For a computer scientist, or an applied mathematician, or a combinatorialist working with finite sets the axiom of choice might be the least important axiom in mathematics. As instances involving only finite sets will never require the axiom of choice. We can see the axiom of choice budding importance when you reach to infinite objects. The axiom is needed to ascertain that countable union of countable sets are countable, it is needed to ensure that every two algebraic closures of $\Bbb Q$ are isomorphic, it is needed to ensure that $\Bbb R$ is not the countable union of countable sets, it is needed to ensure that every filter can be extended to an ultrafilter and as a consequence it gives us Hahn-Banach theorem, the compactness theorem for logic. The axiom of choice is needed to ensure that every vector space has a [Hamel] basis. It is needed to ensure that every commutative ring with a unit has a maximal ideal. The axiom is needed to make sure that cardinal arithmetic is going along as planned. That the Lowenheim-Skolem theorems hold. Wherever infinite sets play a role, the axiom of choice is needed to make sure that the formulation of the theorem is simple, and that it is relevant to sets we deem important. Sets like the real numbers, like $\ell_\infty$, sets which are uncountable. What weird results can happen without the axiom of choice? Pretty much anything, if it needs the axiom of choice in a substantial way, it means that it can fail without the axiom of choice. But there is a usual reminder here. The failure of the axiom of choice is just as non-constructive as the axiom itself, and that means that just saying that the axiom of choice has failed spectacularly doesn't mean that this failure happens in sets which interest the "working mathematician", or even "the working set theorist". So let me list a few failures of the axiom of choice which occur at the level of the real numbers, which is what we really seem to think is bizarre. The real numbers can be a countable union of countable sets. This means that most analysis goes out the window, as the usual definition of Borel/Lebesgue measures trivializes. Things can be remedied by working with Borel codes, but everything becomes much harder to manage. $\Bbb Q$ has two non-isomorphic algebraic closures. We can prove that the usual algebraic closure always exists, or at least there is always a canonical algebraic closure to $\Bbb Q$. But it turns out that there can be a non-canonical as well, and they can be non-isomorphic. Every ultrafilter on $\Bbb N$ is principal. This means that definitions using ultraproducts and ultralimits (e.g. in the definition of the hyperreal numbers) do not go through; it also means that $\Bbb R$ cannot be well-ordered. Every set of reals can have the Baire property (it is equivalent to an open set up to a meager set). This might not seem like much, but it is in fact a big deal. This implies, at least in the presence of dependent choice (a strengthening of countable choice), that every linear operator between a Banach space and a normed space is continuous. In particular, every linear functional from a Banach space to $\Bbb R$ is continuous, and every functional from $\Bbb R$ to $\Bbb Q$ is continuous. So the reals have no Hamel basis over $\Bbb Q$ and $\ell_2$ is isomorphic to its algebraic dual, which is just its usual topological dual. It also means that $(\ell_\infty/c_0)^*=\{0\}$. I'd be remiss if I didn't mention the axiom of determinacy. This axiom implies a lot of structure in the land of sets of reals; although this structure is much more complex and strange than we are used to with the axiom of choice. It implies the measurability and other regularity properties of sets of reals, and its consistency strength is higher than all the aforementioned failures, but let's not get into that. $\Bbb Q$ might not be injective (as an abelian group). In fact, the assertion that every divisible group is injective implies the axiom of choice. And it is consistent that there are no injective groups, in particular $\Bbb Q$ might not be injective. There might be an infinite Dedekind-finite subset of $\Bbb R$. This means that a lot of definitions go out the window, e.g. continuity by sequences is not equivalent to continuity by $\varepsilon$-$\delta$ when talking about a continuous function at some $x$. It means that there is a tree on whose nodes are real numbers, its height $\omega$, and it is without maximal nodes, but without infinite branches either. More specifically to the previous one, we can arrange that this set cannot be endowed with a group structure on its own, contradicting the theorem (which is equivalent to full choice) that every non-empty set can be endowed with a group structure. It is entirely possible that $\Bbb R$ is the union of two disjoint sets, each of strictly smaller cardinality. You heard me. This list can go on and on and on. So let me stop here. And let me point out that there are many other failures which can happen which may interest "Mathematician Joe", because they prevent nice formulation of theorems. It's no longer "every commutative ring with unity has a maximal ideal" but rather "every well-orderable commutative ring with unity has a maximal ideal"; and similar additions which force us to restrict to smaller classes of objects, and since there might be commutative rings which are not well-orderable, but still have maximal ideals, this theorem is not satisfying either. So is the axiom of choice important? To modern mathematics, which deals with infinite objects, the answer is yes. How is it important? It is important by bringing some order to infinite sets and getting them at least a little bit under control. | {} | {'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/1253650', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/191378/']} | jdg_76600 |
stackexchange | llm_judgeable_groundtruth_similarity | 16634875 |
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 new to MySql(3hours under my belt),just finished reading PHP & MYSQL for dummies 4th Edition and i'm currently to create a database that contains information about shops for practice. The database i'm trying to create contains information about a list of stores.Each store will contain some basic information about the store,the industry(E.g Clothes, Food) the store is operating in, as well as their inventory. While i currently have a table containing the store's name,description(which can be a short write up and/or a URL to the store's website), and a store ID(Which serves as the primary key) create table Merchant(MerchantID SERIAL,Industry ENUM("Retail","Dining","Entertainment"),Name VARCHAR(1000) NOT NULL,Description VARCHAR(1000),PRIMARY KEY(MerchantID)) Each store will then have multiple categories for what they are selling, and each categories will have multiple items.Would i be right in saying that what i am looking at is a One(Store) to Many(Categories) table linked to a One(Category) to Many(Items) table? The reason being that although the first table(Store to Categories) has a One to Many R/S, the second table(Category to Item) also has a One to Many, and NOT a Many to Many R/S as i am only looking at a singular category which contains multiple items in it. Table for Categories: Create table Categories(CategoryID SERIAL references MerchantID,Category VARCHAR(50) NOT NULL,PRIMARY KEY(CategoryID)) Table for Items: Create table Items(ItemID Serial references CategoryID,Item VARCHAR(50) NOT NULL,PRIMARY KEY(ItemID)) Is the code above correct? Or do i have to enter all the Primary Keys that are one level above. E.g: Create table Item(MerchantID SERIAL,CategoryID SERIAL,ItemID SERIAL,Item VARCHAR(50),PRIMARY KEY(MerchantID,CategoryID,ItemID)) Furthermore, is there any difference between having VARCHAR(50) and VARCHAR(1000) seeing as MYSQL would automatically get rid of all the unused space?Also, is there any way to further optimise the database for performance etc.?
Now provide the response and nothing else.
| Edit After researching this problem a bit more it appears Visual Studio doesn't support Markup as HTML for rdlc reports until Visual Studio 2010. So if upgrading is an option, then you can do what you want. Otherwise you could always just strip out the HTML tags like so: On the Report menu, click Report Properties... and select the Code tab. Enter the following code: Function StripHTMLTags(ByVal text as String) AS String Return System.Text.RegularExpressions.Regex.Replace(text, "<(.|\n)*?>", "")End Function Now in your cell use the following expression: =Code.StripHTMLTags(Fields!MyField.Value) Original answer follows: Leaving aside that you should separate data from presentation, you can render using HTML tags in Reporting Services, its just not very intuitive to find: Left click the field you want to display so that the <Expr> tag is highlighted Right click the highlighted <Expr> tag and choose Placeholder Properties... On the General tab, select the HTML- Interpret HTML tags as style radio button Only a limited number of tags are supported however. This article on MSDN tells your more. Screenshots: | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16634875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2249197/']} | jdg_76601 |
stackexchange | llm_judgeable_groundtruth_similarity | 1618997 |
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 was trying to help a friend solve this and I am really troubled.The task was to show that $$\int_0^1x^t(1-x)^{s-t}dx=\frac{t!(s-t)!}{(s+1)!}$$ using the Gamma distribution properties. What I did was initially to try and show that is $$\frac{t!(s-t)!}{(s+1)!}$$ this times the cumulative fuction of a Gamma multiplying/dividing the right things. What I could not think of is how to appear the exponential that I need in order to create the cumulative. Am I wrong? How can I prove this? Also Gamma integrates from zero to infinity and in this case $$x\in (0,1)$$. I am trying to use the formula: $$\text{Gamma}(\alpha,\lambda)\implies\frac{{\lambda}^{\alpha}}{\Gamma(\alpha)}\cdot x^{\alpha-1}e^{-\lambda x}$$
Now provide the response and nothing else.
| Take the logarithm of each side, base $100$. Since the $\log$ function is monotonically increasing, this preserves the ordering. $\log_{100}(100^{300})$ is clearly $300$. Meanwhile, $$\log_{100}300! = \log_{100}1 + \log_{100}2 + \dotsb + \log_{100}300 = \sum_{n=1}^{300} \log_{100}n .$$ We can try using integrals to approximate this series. Since, again, $\log$ is monotonically increasing, we have: $$\sum_{n=1}^{300} \log_{100}n \geq \int_{1}^{300} \log_{100}x\, dx = \dfrac{1}{\ln 100} \int_{1}^{300} \ln x\, dx = \dfrac{1}{\ln 100} \left[x \ln x - x \right]^{300}_1 = \dfrac{300\ln 300 - 299}{\ln 100} = 306.64... > 300.$$ This implies that $300! \geq 100^{300}.$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1618997', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/292472/']} | jdg_76602 |
stackexchange | llm_judgeable_groundtruth_similarity | 27951570 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was given a library with generic data objects in it, Projects, Tables, Rows and Fields. In my program I have a single Project called Building, its Table 1 contains "Units", and Field 1 of Table 1 is "Unitname". So what I did was... Public Class Unit Private myRow As Row Public Sub New(ByRef R as Row) myRow = Row End Sub Public Function Unitname() as String Return myRow.Fields(1) End Function ... etc ...End Class That doesn't look so bad does it? But I don't have Unit objects loaded, I have Rows. So then I also have to make a another class... Public Class Building Private myProj as Project... Public Function Units() As List(Of Unit) Dim ans as New List(Of Unit) For Each R In myProj.Tables(1).Rows ans.Add(new Unit(R)) Next Return ans ' or I could use myProj.Tables(1).Rows.ConvertTo(Of Unit) End Function ...etc... And of course I have to make the list of Buildings so I can get to the list of Units, and the dozens of other lists and accessors, turning into thousands of lines of code who's only purpose is to make one set of objects that points to another. It works, and I know shipping is a feature. But what I really want to do is make a Unit that looks like... Public Class Unit Inherits Row ...End Class Then I would "reverse cast" the List(Of Row) into a List(Of Unit). This would not only eliminate a lot of code, it would eliminate dangling pointers, reduce memory a whole lot, and eliminate a set-up set that might take some time. Theoretically possible, there's no difference except code, but I don't see a way to do it in VB.Net. In Obj-C this is called swizzling (and/or extensions), and I think Java has a similar concept. I suspect that ADO.Net has to do something like this? Is there some sort of "wrap this in that" functionality I'm missing?
Now provide the response and nothing else.
| I am assuming Basic authentication here. $cred = Get-CredentialInvoke-WebRequest -Uri 'https://whatever' -Credential $cred You can get your credential through other means ( Import-Clixml , etc.), but it does have to be a [PSCredential] object. Edit based on comments: GitHub is breaking RFC as they explain in the link you provided : The API supports Basic Authentication as defined in RFC2617 with a few slight differences. The main difference is that the RFC requires unauthenticated requests to be answered with 401 Unauthorized responses. In many places, this would disclose the existence of user data. Instead, the GitHub API responds with 404 Not Found. This may cause problems for HTTP libraries that assume a 401 Unauthorized response. The solution is to manually craft the Authorization header. Powershell's Invoke-WebRequest does to my knowledge wait for a 401 response before sending the credentials, and since GitHub never provides one, your credentials will never be sent. Manually build the headers Instead you'll have to create the basic auth headers yourself. Basic authentication takes a string that consists of the username and password separated by a colon user:pass and then sends the Base64 encoded result of that. Code like this should work: $user = 'user'$pass = 'pass'$pair = "$($user):$($pass)"$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))$basicAuthValue = "Basic $encodedCreds"$Headers = @{ Authorization = $basicAuthValue}Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers You could combine some of the string concatenation but I wanted to break it out to make it clearer. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/27951570', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1469457/']} | jdg_76603 |
stackexchange | llm_judgeable_groundtruth_similarity | 759572 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
While re-partitioning a Server 2003 R2 domain controller, we accidentally deleted the partition that held the Active Directory database folder ( D:\AD\Data ). The D:\ was a partition on a disk shared with C:\ . We eliminated the D:\ drive not realizing that it housed the Active Directory data folder. We have no other domain controllers and no backups of this Active Directory data. Is there any chance of restoring the AD?
Now provide the response and nothing else.
| If you just deleted the partition and did not create a new partition, it is likely possible to recover. First things first - pull the drive, put it in a Linux box and do a raw clone. The first rule of data recovery is that you do your work on a clone, not the original. Now on the clone run a linux tool called testdisk . If the filesystem hasn't been obliterated this should re-create the partition table entry and allow it to be accessed again. If you did create a new partition, or if testdisk can't find the filesystem then your chances of successful recovery are much lower. You might want to consider talking to data recovery specialists at this point. | {} | {'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/759572', 'https://serverfault.com', 'https://serverfault.com/users/212457/']} | jdg_76604 |
stackexchange | llm_judgeable_groundtruth_similarity | 49835791 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
def on_entry_click_text(event): if(speech_text.get('1.0', END) == 'Click and Say...'):#<-not working speech_text.delete('1.0',END) # delete all the text in the entry speech_text.insert(END,'') #Insert blank for user input speech_text.config(fg = 'black')winchat=Tk()speech_text=Text(winchat)speech_text.bind("<FocusOut>",on_focusout_text)speech_text.insert(END,'Click and Say...')speech_text.pack() i have set the value of the text field 'Click and Say...' and want when ever the user clicks the text box data clears out.
Now provide the response and nothing else.
| The reason your code is not working is because client.run is blocking, meaning that nothing after it will execute. This means your loop will never be reached. To get around this, use client.loop.create_task . The github of discord.py has an example of a background task, found here . You should be able to use this as reference. Currently the task posts a message to the given channel every minute, but you can easily modify it to wait for a specific action. New discord.py versions import discordimport asyncioclient = discord.Client()async def my_background_task(): await client.wait_until_ready() counter = 0 channel = client.get_channel(id=123456789) # replace with channel_id while not client.is_closed(): counter += 1 await channel.send(counter) await asyncio.sleep(60) # task runs every 60 [email protected] def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------')client.loop.create_task(my_background_task())client.run('token') Older discord.py versions import discordimport asyncioclient = discord.Client()async def my_background_task(): await client.wait_until_ready() counter = 0 channel = discord.Object(id='channel_id_here') while not client.is_closed: counter += 1 await client.send_message(channel, counter) await asyncio.sleep(60) # task runs every 60 [email protected] def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------')client.loop.create_task(my_background_task())client.run('token') | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49835791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9646811/']} | jdg_76605 |
stackexchange | llm_judgeable_groundtruth_similarity | 482 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have occasionally heard people talk about quantum algorithms and about states and the ability to consider multiple possibilities at once, but I have never managed to get someone to explain the computational model behind this. To be clear, I am not asking about how quantum computers are physically constructed, but rather how to view them from a computational point of view.
Now provide the response and nothing else.
| I'll echo Martin Schwartz's recommendation of Nielsen & Chaung as the standard reference; there are many others as well. Research in the field prefers to consider uniform families of quantum circuits, which (ironically) are directed acyclic networks describing how the state of one or more registers transforms with time, in a way similar to classical boolean circuits. If you wish to learn more, I recommend learning in terms of this model. I would like to give some qualitative answers to complement Martin's response. Quantum computation does not actually consider "multiple possibilities at once" --- or more precisely, whether or not you consider them to consider multiple possibilities at once is a matter of your choice of interpretation of quantum mechanics , i.e. a philosophical choice which has no bearing on the ability or predictions of the computational model. ("Considering multiple possibilities at once" corresponds to the "many worlds interpretation" of QM.) At the very least, one can say that a quantum computer considers multiple possibilities at the same time only to the extent that a randomized computation using coin-flips considers multiple possibilities at the same time. This is because: Quantum states are generalizations of "the usual" probability distributions --- with some simple but important differences. A probability distribution can be represented as a non-negative real vector whose entries sum to 1: that is, a unit vector in the ℓ 1 norm. Probabilistic computations must map ℓ 1 -unit vectors to other such vectors, and so they are described by stochastic maps. One can describe quantum computation in a similar way, except using ℓ 2 -unit vectors over ℂ (not restricted to be real or non-negative); transformations are by those maps which preserve the ℓ 2 -norm, i.e. unitary operations. This difference is not trivial, of course, nor does it explain yet what the coefficients of the quantum state vectors mean . But it may help to explain what is going on with Hilbert spaces and tensor products in quantum computation: to wit, exactly the same things as happen in probabilistic computation. The configuration space of a random bit is a vector in ℝ + 2 (where ℝ + are the non-negative reals); but because random bits can be correlated, we combine the configuration spaces of one or more random bits by taking the tensor product. So the configuration space of two random bits is ℝ + 2 ⊗ ℝ + 2 ≅ ℝ + 4 , or the fully-general space of probability distributions over the four distinct two-bit strings. An operation A on the first of these random bits which does not act on the second is represented by the operator A ⊗ I 2 . And so on. The same constructions apply to quantum bits; and we can consider quantum registers over sets of distinguishable elements the same way we consider probability distributions over such sets, again using ℓ 2 -norm vectors over ℂ. This description actually describes the "pure" quantum states --- the ones for which you can in principle transform in an information-preserving way to a delta-distribution over the bit-string 00...0 (or more precisely, to a state arbitrarily close to this in the ℓ 2 norm). On top of the quantum-randomness (of which I have not yet mentioned anything explicit), you can consider vanilla-convexity-randomness corresponding to probabilistic mixtures of quantum states: these are represented by density operators , which can be represented by positive definite matrices with trace 1 (again generalizing "classical" probability distributions, which may be represented by the special case of positive diagonal matrices with trace 1). What is important about this is that, while quantum states are often described as being "exponentially large", this is because they are usually described using the same mathematical structures as probability distributions; why probability distributions are not described as "exponentially large" in the same way is unclear (but ultimately unimportant). The difficulty of simulating quantum states come from this fact, together with the fact that the complex coefficients of these ℓ 2 -distributions (or the complex off-diagonal terms of the density operators, if you prefer) may cancel in a way that probabilities cannot, rendering estimation of them more difficult. Entanglement is just another form of correlation. For probabilistic computation on e.g. boolean strings, the only "pure" states (which can be mapped by information-preserving transformations to a delta-peaked distribution on 000...0) are the "standard basis" of delta-peaked distributions on the different boolean strings. Thus, this basis of ℝ + 2 n is distinguished. But there is no such distinguished basis in quantum mechanics, as far as we can tell --- this is clearest for quantum bits (look up spin 1/2 particles, if you want to know why). As a consequence, there are more information-preserving transformations than just the permutations: a continuous group of them, in fact. This allows would-be quantum computers to transform states in ways which are not possible for probabilistic computers, possibly obtaining an asymptotic advantage over them. But what about entanglement, which many people find mysterious, and claim to be the cause of the speed-up of quantum computers over classical? "Entanglement" here is really just a form of correlation: just as two random variables are correlated if their distribution is a convex combination of more than one product distribution (with different marginals on each variable), two "quantum variables" are entangled if their distribution is a linear combination (with unit ℓ 2 -norm) of two valid product distributions; it is the same concept under a different norm, and plays a similar role in communication tasks. (For example: "quantum teleportation" in quantum communication corresponds to encoding and decoding a message using a one-time pad classically.) This is a form of correlation which is more general than just classically correlated bits; but the only way to show this is that the correlations encoded in the entangled state apply to more than just one privileged basis . In a manner of speaking, entanglement is a consequence of the absence of a privileged basis. People like to invoke entanglement as the key element of quantum computation, but this simply doesn't seem to hold water: there have been results showing that entanglement is not quantitatively important for Shor's algorithm to factor large integers, and that indeed a quantum system can have too much entanglement to be useful for a computation. In fact, everywhere that I am aware of that entanglement plays an important role in a quantum protocol is essentially one of communication (where correlations would be expected to play an important role for a classical protocol). At this point, I begin wading into the domain of personal opinion, so I'll stop here. But hopefully, these remarks might de-mystify some of what is obscure about quantum computation and how it is described. | {} | {'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/482', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/450/']} | jdg_76606 |
stackexchange | llm_judgeable_groundtruth_similarity | 9778505 |
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 found numerous sources that cite the Facebook app as an example of a Hybrid App. I understand the term Hybrid App is broadly defined as any smartphone app that wraps a WebView in a native application. There are mobile phone development frameworks (PhoneGap, Appcelerator, etc) that enable developers to build apps using their existing web dev skills (HTML5, Javascript, CSS) while providing access to core phone features (camera, address book, etc). Therefore, since Facebook is a hybrid app that accesses the phone's core features like Push Notifications and camera I'm curious: Is the Facebook app built using a mobile development framework?
Now provide the response and nothing else.
| Your broad definition of a hybrid app might be a little too broad. An entire app running in a webview is a sufficient but not necessary condition for a hybrid app. You might imagine this as a spectrum: Pure native Facebook Appcelerator PhoneGap HTML5 |---------------|--------------|-------------|-----------| PhoneGap apps, for example, are as you mentioned: "apps that wrap a WebView in a native application." However, Appcelerator apps are also hybrid apps, yet they do not necessarily need to contain a webview component. They are hybrid because their UI are native, yet parts of their logic runs on Javascript. Facebook is definitely not built in PhoneGap. Creating its sliding menu in HTML5 without any performance hitches is close to impossible with current webviews. There are telltale signs that Facebook is not built in Appcelerator either. In my experience, Appcelerator apps tend to have huge file sizes because of the Titanium libraries that are included. Facebook should be a lot bigger than its current size if it were built in Appcelerator. Facebook has the resources to build its own native apps, so it doesn't require a framework for the usual reasons (development speed, ease of coding). Lastly, and perhaps the best reason I would say Facebook isn't built using a (publicly available) framework is that if it were, that framework would be either 1) happily announcing it to the world, or 2) bought over by Facebook. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9778505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/690431/']} | jdg_76607 |
stackexchange | llm_judgeable_groundtruth_similarity | 220400 |
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 $X$ be some smooth scheme over $\mathbf C$ equipped with an action of $\mu_n$ (the group of $n$th roots of unity). The étale cohomology groups of X are therefore equipped with an action of $\mu_n$. Now, let's suppose that the action of $\mu_n$ on $X$ extends to an action of $\mathbf G_m$.Then, the analytic space $X(\mathbf C)$ is equipped with an action of $\mu_n$ which extends to an action og $\mathbf C^\times$. As $\mathbf C^\times$ is connected, one concludes that the action of $\mu_n$ on the singular cohomology of $X(\mathbf C)$ is trivial (the multiplication by each element $\xi\in \mu_n$ is homotopic to the identity). Going backwards to étale cohomology, using a comparison theorem between étale and singular cohomology, one concludes that the action of $\mu_n$ on the étale cohomology of $X$ is trivial. Is there a direct proof that the action on the étale cohomology groups is trivial without having to refer to the topological case?
Now provide the response and nothing else.
| Smoothness of $X$ is not needed (neither for the comparison isomorphism nor for the result in question). Let $X$ be any quasi-separated scheme over a separably closed field $k$, equipped with an action by a connected $k$-group scheme $G$ of finite type. Let $n > 0$ be an integer not divisible by the characteristic of $k$ and choose an integer $i \ge 0$. Then we want to show that the action of $G(k)$ on ${\rm{H}}^i(X, \mathbf{Z}/(n))$ is trivial (using etale cohomology here). [The hypothesis on $n$ is necessary because if $n = p = {\rm{char}}(k)>0$ and $X = {\rm{Spec}}(A)$ is affine then the effect of $G(k)$ on ${\rm{H}}^1(X, \mathbf{Z}/(p)) = A/\wp(A)$ (with $\wp(f) = f^p-f$) is the induced action from the $G(k)$-action on $A = \Gamma(X,O_X)$, and this is generally nontrivial (e.g., $X = G = \mathbf{A}^1_k$ with the translation action corresponding to $c.f(t) = f(t+c)$ on global functions (for $c \in G(k)$).] By a spectral sequence argument using a covering by quasi-compact $G$-stable open subsets we may reduce to the case when $X$ is quasi-compact (and quasi-separated).It is harmless to make the radiciel extension from $k$ to its algebraic closure ("topological invariance" of etale cohomology), so we may assume that the separably closed $k$ is even algebraically closed. We may then replace $G$ with $G_{\rm{red}}$ so that $G$ is smooth. Let $f:G \times X \rightarrow G$ be the projection map. The hypothesis on $n$ and smoothness of $G$ allow us to apply the smooth base change theorem to conclude that $\mathscr{F} = {\rm{R}}^if_{\ast}(\mathbf{Z}/(n))$ is the constant sheaf on $G$ attached to ${\rm{H}}^i(X,\mathbf{Z}/(n))$.Consider the action automorphism $$\alpha: G \times X \simeq G \times X$$defined by $(g,x) \mapsto (g, gx)$. This commutes with $f$, and so induces an automorphism $[\alpha]$ of $\mathscr{F}$ on $G$. The effect on the stalk at $g \in G(k)$ is the $g$-action on ${\rm{H}}^i(X, \mathbf{Z}/(n))$ that we want to be trivial. But $\mathscr{F}$ is a constant sheaf on a connected scheme, so the effect on $\mathscr{F}$ of any automorphism is uniquely determined by the effect on a single stalk. Looking on the stalk at $g=1$ thereby shows that $[\alpha]$ is the identity automorphism. Now pass to the effect of $[\alpha]$ on the stalk at any $g \in G(k)$ to conclude. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/220400', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5239/']} | jdg_76608 |
stackexchange | llm_judgeable_groundtruth_similarity | 312059 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a file as below. ~PAR1~This is Par1 line 1This is Par1 line 2Par Finished~PAR2~This is Par2 line 1This is Par2 line 2Par Finished If I pass PAR1 , I should get all lines between PAR1 and Par Finished line. How can I get it? I was looking into awk and sed and couldn't find any options.
Now provide the response and nothing else.
| If you want the header and footer line then it's pretty simple with sed eg sed -n "/^~PAR1~$/,/Par Finished/p" This is simple to use with a variable START=PAR1sed -n "/^~$START~$/,/Par Finished/p" We can also make the last line to be a variable START=PAR1END="Par Finished"sed -n "/^~$START~$/,/$END/p" The result looks like: ~PAR1~This is Par1 line 1This is Par1 line 2Par Finished Now if you don't want the start/end lines and you don't want the blank line then it's a little more complicated. There may be better ways, but this works for me: sed -n "/^~$START~$/,/$END/ { /^~$START~$/d ; /$END/d ; /^$/d ; p }" The result of this is This is Par1 line 1This is Par1 line 2 | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/312059', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/191661/']} | jdg_76609 |
stackexchange | llm_judgeable_groundtruth_similarity | 3916089 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two lists, I want both of them to be sortable and want to be able to copy (drag) items from list1 to list2 and vice versa. http://jqueryui.com/demos/sortable/#connect-lists Is what I want, but the items are moved, not copied.I did a few experiments with draggables and droppables, but I can't get to to work keeping them sortable. For example: http://jsfiddle.net/tunafish/dvXmf/
Now provide the response and nothing else.
| OK here is my app; two lists of images, sortable and you can copy over from the connected list. If an item already exists in the target it's disabled. Hopefully useful to someone... JSFiffle here: http://jsfiddle.net/tunafish/VBG5V/ CSS: .page { width: 410px; padding: 20px; margin: 0 auto; background: darkgray; }.album { list-style: none; overflow: hidden; width: 410px; margin: 0; padding: 0; padding-top: 5px; background: gray; } .listing { margin-bottom: 10px; }.album li { float: left; outline: none; width: 120px; height: 80px; margin: 0 0 5px 5px; padding: 5px; background: #222222; }li.placeholder { background: lightgray; } JS: $("ul, li").disableSelection();$(".album, .favorites").sortable({ connectWith: ".album, .favorites", placeholder: "placeholder", forcePlaceholderSize: true, revert: 300, helper: "clone", stop: uiStop, receive: uiReceive, over: uiOver});$(".album li").mousedown(mStart);var iSender, iTarget, iIndex, iId, iSrc, iCopy;var overCount = 0;/* everything starts here */function mStart() { // remove any remaining .copy classes $(iSender + " li").removeClass("copy"); // set vars if ($(this).parent().hasClass("listing")) { iSender = ".listing"; iTarget = ".favorites"; } else { iSender = ".favorites"; iTarget = ".listing"; } iIndex = $(this).index(); iId = $(this).attr("id"); iSrc = $(this).find("img").attr("src"); iCopy = $(iTarget + " li img[src*='" + iSrc + "']").length > 0; // boolean, true if there is allready a copy in the target list // disable target if item is allready in there if (iCopy) { $(iTarget).css("opacity","0.5").sortable("disable"); }}/* when sorting has stopped */function uiStop(event, ui) { // enable target $(iTarget).css("opacity","1.0").sortable("enable"); // reset item vars iSender = iTarget = iIndex = iId = iSrc = iCopy = undefined; overCount = 0; // reinit mousedown, live() did not work to disable $(".album li").mousedown(mStart);}/* rolling over the receiver - over, out, over etc. */function uiOver(event, ui) { // only if item in not allready in the target if (!iCopy) { // counter for over/out (numbers even/uneven) overCount++; // if even [over], clone to original index in sender, show and fadein (sortables hides it) if (overCount%2) { if (iIndex == 0) { ui.item.clone().addClass("copy").attr("id", iId).prependTo(iSender).fadeIn("slow"); } else { ui.item.clone().addClass("copy").attr("id", iId).insertAfter(iSender + " li:eq(" + iIndex + ")").fadeIn("slow"); } } // else uneven [out], remove copies else { $(iSender + " li.copy").remove(); } } // else whoooooo}/* list transfers, fix ID's here */function uiReceive(event, ui) { (iTarget == ".favorites") ? liPrefix = "fli-" : liPrefix = "lli-"; // set ID with index for each matched element $(iTarget + " li").each(function(index) { $(this).attr("id", liPrefix + (index + 1)); // id's start from 1 });} HTML: <div class="page"> <div class="container"> <h2>Photo Album</h2> <ul class="listing album"> <li id="li-1"><img src="tn/001.jpg" /></li> <li id="li-2"><img src="tn/002.jpg" /></li> <li id="li-3"><img src="tn/003.jpg" /></li> <li id="li-4"><img src="tn/004.jpg" /></li> <li id="li-5"><img src="tn/005.jpg" /></li> </ul> </div> <div style="clear:both;"></div> <div class="container"> <h2>Favorites</h2> <ul class="favorites album"> <li id="fli-1"><img src="tn/001.jpg" /></li> <li id="fli-2"><img src="tn/002.jpg" /></li> <li id="fli-3"><img src="tn/010.jpg" /></li> </ul> </div></div> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3916089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238898/']} | jdg_76610 |
stackexchange | llm_judgeable_groundtruth_similarity | 3648712 |
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 believe that we are all know that setUp (@Before) will execute before any test method and tearDown(@After) will execute after test method. Also we know that Junit will create one instance of Test per test method . my question is that can we just move setUp method content to class Constructor and remove setUp method? is there any specific reason to keep setUp method?
Now provide the response and nothing else.
| This (old) JUnit best practices article puts it like this: Do not use the test-case constructor to set up a test case Setting up a test case in the constructor is not a good idea. Consider: public class SomeTest extends TestCase public SomeTest (String testName) { super (testName); // Perform test set-up }} Imagine that while performing the setup, the setup code throws an IllegalStateException . In response, JUnit would throw an AssertionFailedError , indicating that the test case could not be instantiated. Here is an example of the resulting stack trace: junit.framework.AssertionFailedError: Cannot instantiate test case: test1 at junit.framework.Assert.fail(Assert.java:143) at junit.framework.TestSuite.runTest(TestSuite.java:178) at junit.framework.TestCase.runBare(TestCase.java:129) at junit.framework.TestResult.protect(TestResult.java:100) at junit.framework.TestResult.runProtected(TestResult.java:117) at junit.framework.TestResult.run(TestResult.java:103) at junit.framework.TestCase.run(TestCase.java:120) at junit.framework.TestSuite.run(TestSuite.java, Compiled Code) at junit.ui.TestRunner2.run(TestRunner.java:429) This stack trace proves rather uninformative; it only indicates that the test case could not be instantiated. It doesn't detail the original error's location or place of origin. This lack of information makes it hard to deduce the exception's underlying cause. Instead of setting up the data in the constructor, perform test setup by overriding setUp() . Any exception thrown within setUp() is reported correctly. Compare this stack trace with the previous example: java.lang.IllegalStateException: Oops at bp.DTC.setUp(DTC.java:34) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult.protect(TestResult.java:100) at junit.framework.TestResult.runProtected(TestResult.java:117) at junit.framework.TestResult.run(TestResult.java:103) ... This stack trace is much more informative; it shows which exception was thrown ( IllegalStateException ) and from where. That makes it far easier to explain the test setup's failure. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3648712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/393786/']} | jdg_76611 |
stackexchange | llm_judgeable_groundtruth_similarity | 34910370 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using Guzzle (v6.1.1) in PHP to make a POST request to a server. It works fine. I am adding some logging functions to log what was sent and received and I can't figure out how to get the data that Guzzle sent to the server. I can get the response just fine, but how do I get the sent data? (Which would be the JSON string.) Here is the relevant portion of my code: $client = new GuzzleHttp\Client(['base_uri' => $serviceUrlPayments ]); try { $response = $client->request('POST', 'Charge', [ 'auth' => [$securenetId, $secureKey], 'json' => [ "amount" => $amount, "paymentVaultToken" => array( "customerId" => $customerId, "paymentMethodId" => $token, "publicKey" => $publicKey ), "extendedInformation" => array( "typeOfGoods" => $typeOfGoods, "userDefinedFields" => $udfs, "notes" => $Notes ), 'developerApplication'=> $developerApplication ] ]); } catch (ServerErrorResponseException $e) { echo (string) $e->getResponse()->getBody(); } echo $response->getBody(); // THIS CORRECTLY SHOWS THE SERVER RESPONSE echo $client->getBody(); // This doesn't work echo $client->request->getBody(); // nor does this Any help would be appreciated. I did try to look in Guzzle sourcecode for a function similar to getBody() that would work with the request, but I'm not a PHP expert so I didn't come up with anything helpful. I also searched Google a lot but found only people talking about getting the response back from the server, which I have no trouble with.
Now provide the response and nothing else.
| You can do this work by creating a Middleware . use GuzzleHttp\Client;use GuzzleHttp\HandlerStack;use GuzzleHttp\Middleware;use Psr\Http\Message\RequestInterface;$stack = HandlerStack::create();// my middleware$stack->push(Middleware::mapRequest(function (RequestInterface $request) { $contentsRequest = (string) $request->getBody(); //var_dump($contentsRequest); return $request;}));$client = new Client([ 'base_uri' => 'http://www.example.com/api/', 'handler' => $stack]);$response = $client->request('POST', 'itemupdate', [ 'auth' => [$username, $password], 'json' => [ "key" => "value", "key2" => "value", ]]); This, however, is triggered before to receive the response. You may want to do something like this: $stack->push(function (callable $handler) { return function (RequestInterface $request, array $options) use ($handler) { return $handler($request, $options)->then( function ($response) use ($request) { // work here $contentsRequest = (string) $request->getBody(); //var_dump($contentsRequest); return $response; } ); };}); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34910370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5735139/']} | jdg_76612 |
stackexchange | llm_judgeable_groundtruth_similarity | 29946512 |
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 new to RxJS and FRP in general. I had the idea of converting an existing promise chain in my ExpressJS application to be an observable for practice. I am aware that this probably isn't the best example but maybe someone can help shed some light. What I'm trying to do : I have two promises - prom1 and prom2 I want prom1 to run before prom2 If prom1 sends a reject(err), I want to cancel prom2 before it starts. I want the error message prom1 returns to be available to the onError method on the observer. var prom1 = new Promise(function(resolve, reject) { if (true) { reject('reason'); } resolve(true);});var prom2 = new Promise(function(resolve, reject) { resolve(true);});// What do I do here? This is what I've tried so far...var source1 = Rx.Observable.fromPromise(prom1);var source2 = source1.flatMap(Rx.Observable.fromPromise(prom2));var subscription = source2.subscribe( function (result) { console.log('Next: ' + result); }, // I want my error 'reason' to be made available here function (err) { console.log('Error: ' + err); }, function () { console.log('Completed'); });
Now provide the response and nothing else.
| If I understood what you are trying to do - you need to create two deferred observables from functions that return promises and concat them: var shouldFail = false;function action1() { return new Promise(function (resolve, reject) { console.log('start action1'); if (shouldFail) { reject('reason'); } resolve(true); });}function action2() { return new Promise(function (resolve, reject) { console.log('start action2'); resolve(true); });}var source1 = Rx.Observable.defer(action1);var source2 = Rx.Observable.defer(action2);var combination = Rx.Observable.concat(source1, source2);var logObserver = Rx.Observer.create(function (result) { console.log('Next: ' + result);},function (err) { console.log('Error: ' + err);},function () { console.log('Completed');}); then for normal case: combination.subscribe(logObserver);// start action1// Next: true// start action2// Next: true// Completed And case where fisrt promise fails: shouldFail = true;combination.subscribe(logObserver);// start action1// Error: reason http://jsfiddle.net/cL37tgva/ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29946512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1396575/']} | jdg_76613 |
stackexchange | llm_judgeable_groundtruth_similarity | 30825535 |
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 list (python): [[item1],[item2],[item3],[/],[item4],[item5],[item6],[/]...] I want to separate these into chunks and the elements that will go into each chunk are the elements before the separator "/". So my chunks would look like: chunk1 = [[item1],[item2],[item3]]chunk2 = [[item4],[item5],[item6]] I've tried and tried, but nothing efficient came to mind. Tried looping through it with a for and and if element[x] == '/' then get some positions. It's very dirty and doesn't properly work. Any help would be appreciated.
Now provide the response and nothing else.
| The usual approach for collecting contiguous chunks is to use itertools.groupby , for example: >>> from itertools import groupby>>> blist = ['item1', 'item2', 'item3', '/', 'item4', 'item5', 'item6', '/']>>> chunks = (list(g) for k,g in groupby(blist, key=lambda x: x != '/') if k)>>> for chunk in chunks:... print(chunk)... ['item1', 'item2', 'item3']['item4', 'item5', 'item6'] (Your representation of your list [item1],[item2],[item3],[/], makes it look like each of your elements in the list is actually a list, in which case the same approach will work, you simply need to compare against ['/'] or whatever your separator is.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30825535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3630268/']} | jdg_76614 |
stackexchange | llm_judgeable_groundtruth_similarity | 164988 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a shell script which uses find -print0 to save a list of files to be processed into a temporary file. As part of the logging I'd like to output the number of files found, and so I need a way to get that count. If the -print0 option weren't being used for safety I could use wc -l to get the count.
Now provide the response and nothing else.
| Some options: tr -cd '\0' | wc -ctr '\n\0' '\0\n' | wc -l # Generic approach for processing NUL-terminated # records with line-based utilities (that support # NUL characters in their lines like GNU ones).grep -cz '^' # GNU grepsed -nz '$=' # recent GNU sed, no output for empty inputawk -v RS='\0' 'END{print NR}' # not all awk implementations Note that for an input that contains data after the last NUL character (or non-empty input with no NUL characters), the tr approaches will always count the number of NUL characters, but the awk / sed / grep approaches will count an extra record for those extra bytes. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/164988', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/26360/']} | jdg_76615 |
stackexchange | llm_judgeable_groundtruth_similarity | 848636 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried to list all properties of an Objective-C class like described in the Objective-C 2.0 Runtime Programming Guide : id LenderClass = objc_getClass("UIView");unsigned int outCount, i;objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount);for (i = 0; i < outCount; i++) { objc_property_t property = properties[i]; fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));} But this lists only three properties: userInteractionEnabled Tc,GisUserInteractionEnabledlayer T@"CALayer",R,&,V_layertag Ti,V_tag Looking at the header file for UIView.h those are the three properties directly declared in the class. The other UIView properties are added through categories. How do I get all properties of a class, including those coming from categories? I tried this with the iPhone simulator (iPhone SDK 2.2.1), btw. (in case this is important).
Now provide the response and nothing else.
| Based on my tests here, properties from categories will show up when using class_copyPropertyList . It looks as though the properties you're seeing on UIView are only described as properties in the public headers, not actually declared as such when building the UIKit itself. Probably they adopted the property syntax to make the creation of the public headers a little quicker. For reference, here's my test project: #import <Foundation/Foundation.h>#import <objc/runtime.h>@interface TestClass : NSObject{ NSString * str1; NSString * str2;}@property (nonatomic, copy) NSString * str1;@end@interface TestClass (TestCategory)@property (nonatomic, copy) NSString * str2;@end@implementation TestClass@synthesize str1;@end@implementation TestClass (TestCategory)// have to actually *implement* these functions, can't use @synthesize for category-based properties- (NSString *) str2{ return ( str2 );}- (void) setStr2: (NSString *) newStr{ [str2 release]; str2 = [newStr copy];}@endint main (int argc, const char * argv[]){ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList([TestClass class], &outCount); for (i = 0; i < outCount; i++) { objc_property_t property = properties[i]; fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property)); } [pool drain]; return 0;} And here's the output: str2 T@"NSString",Cstr1 T@"NSString",C,Vstr1 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/848636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85539/']} | jdg_76616 |
stackexchange | llm_judgeable_groundtruth_similarity | 10897230 |
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 intercept all route changes with Sammy to first check if there is a pending action. I have done this using the sammy.before API and I return false to cancel the route. This keeps the user on the 'page' but it still changes the hash in the browsers address bar and adds the route to the browsers' history. If I cancel the route, I dont want it in the address bar nor history, but instead I expect the address to stay the same. Currently, to get around this I can either call window.history.back (yuk) to go back to the original spot in the history or sammy.redirect. Both of which are less than ideal. Is there a way to make sammy truly cancel the route so it stays on the current route/page, leaves the address bar as is, and does not add to the history? If not, is there another routing library that will do this? sammy.before(/.*/, function () { // Can cancel the route if this returns false var response = routeMediator.canLeave();if (!isRedirecting && !response.val) { isRedirecting = true; // Keep hash url the same in address bar window.history.back(); //this.redirect('#/SpecificPreviousPage'); }else { isRedirecting = false;}return response.val;});
Now provide the response and nothing else.
| In case someone else hits this, here is where I ended up. I decided to use the context.setLocation feature of sammy to handle resetting the route. sammy.before(/.*/, function () { // Can cancel the route if this returns false var context = this, response = routeMediator.canLeave(); if (!isRedirecting && !response.val) { isRedirecting = true; toastr.warning(response.message); // toastr displays the message // Keep hash url the same in address bar context.app.setLocation(currentHash); } else { isRedirecting = false; currentHash = context.app.getLocation(); } return response.val;}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10897230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13375/']} | jdg_76617 |
stackexchange | llm_judgeable_groundtruth_similarity | 3795490 |
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 a bit confused from File::Find documentation... What is the equivalent to $ find my_dir -maxdepth 2 -name "*.txt" ?
Now provide the response and nothing else.
| Personally, I prefer File::Find::Rule as this doesn't need you to create callback routines. use strict;use Data::Dumper;use File::Find::Rule;my $dir = shift;my $level = shift // 2;my @files = File::Find::Rule->file() ->name("*.txt") ->maxdepth($level) ->in($dir);print Dumper(\@files); Or alternatively create an iterator: my $ffr_obj = File::Find::Rule->file() ->name("*.txt") ->maxdepth($level) ->start($dir);while (my $file = $ffr_obj->match()){ print "$file\n"} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3795490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/377031/']} | jdg_76618 |
stackexchange | llm_judgeable_groundtruth_similarity | 47756 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
In Strøm's (no relation) paper "The Homotopy Category is a Homotopy Category" he provesthat the category of unpointed topological spaces, with Hurewicz fibrations and ordinary cofibrations and homotopy equivalences, is a model category. Then he has a fairly long section on the pointed case, and his results are not as good: he restricts to well-pointed spaces, and doesn't get all the model category axioms. But if $\mathcal{M}$ is a model category, then for any object $A\in \mathcal{M}$, the category $A \downarrow \mathcal{M}$ inherits a model category structure in perfectly straightforward way. Since$\mathbf{Top}_* = * \downarrow \mathbf{Top}$, we get a model structure right away. So: what is going on here? Did he simply miss an easy extension to the pointed case?Is it possible that the natural model structure on $* \downarrow \mathbf{Top}$ is not the onehe wants (i.e., the received cofibrations, fibrations or weak equivalences differ somehow from pointed cofibrations, fibrations and pointed homotopy equivalences)?
Now provide the response and nothing else.
| You must allow the weak equivalences to be unpointed homotopy equivalences. These become honest pointed homotopy equivalences between fibrant-cofibrant objects by the generalized whitehead theorem. Strøm's mistake, I think, was that he didn't realize that unbased $Top$ with his model structure has the very special property that all objects are fibrant-cofibrant. This is not the case for based spaces, however (all objects are fibrant but not cofibrant). The cofibrant objects are precisely the nondegenerately based spaces. By restricting to nondegenerately based spaces, he restricted himself to working in the category of cofibrant objects of the actual model category $*\downarrow Top$ equipped with the relative Strøm model structure. It shouldn't be too surprising that this subcategory does not admit a (compatible) model structure. (Proof that all objects in Strøm's model structure on $Top$ are fibrant-cofibrant): Lemma: A Hurewicz fibration $A\to B$ has the RLP with respect to every inclusion of a space $X$ into its cylinder $X\times I$. When $B$ is the terminal object, let $X\times I\to X$ be the map killing the cylinder. Then we get a lift to $X\times I$ of any map $X\to A$ by composing $X\times I\to X\to A$. Lemma: A closed Hurewicz cofibration is a closed inclusion $A\hookrightarrow B$ such that $A\times I \coprod_{A\times \{0\}} B\times \{0\}\hookrightarrow B\times I$ has the LLP with respect to any map $Y\to *$. When $A$ is empty, this reduces to finding an extension of a map $B\to Y$ to a homotopy extending this, but again, this is immediately possible by composition with the trivial homotopy $B\times I\to B$. The theorem of Strøm is that there exists a model structure on Top with $C$ = closed hurewicz cofibrations $W$ = homotopy equivalences $F$ = hurewicz fibrations From which it follows that all objects are fibrant-cofibrant. (Source of definitions: Dwyer-Spalinski example 3.6) | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/47756', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3634/']} | jdg_76619 |
stackexchange | llm_judgeable_groundtruth_similarity | 64626 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some FASTQ files in two datasets which are sequences from 16Srna region. The first dataset is amplicons form V4 region and the second is V3-V4 region. However all the reads are 250 nucleotides long, whereas one region is strictly included in the other. So what is the biological meaning of the length? I'm expecting reads to have the same length as the sequenced/amplified region. I don't know the size of the regions but one is obviously longer than the other. Thank you(I thought it was better to ask here rather than on bioinformatics.stackexchange.com)
Now provide the response and nothing else.
| The read length has absolutely nothing to do with what you are sequencing. It is a characteristic of the sequencing technology you use. NGS sequencing techniques typically produce this sort of short read you're seeing. The read length does not change because you are sequencing a longer molecule. You would still get ~250nt reads even if you were sequencing an entire genome. Your reads are something like this ( image source ): So the vast majority of your 250nt are overlapping and cover slightly different parts of your target sequence. This is one of the reasons why NGS analysis is not trivial. The first step in any NGS analysis is to assemble your reads into a bam file that covers your target region. If you need help on doing that, come on over to http://bioinformatics.stackexchange.com . | {} | {'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/64626', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/35284/']} | jdg_76620 |
stackexchange | llm_judgeable_groundtruth_similarity | 2071847 |
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 asking because I believe the following question: Evaluate $66^e$ was a part of a non-calculator exam that permitted decimal approximations. (Only 3 decimal places were needed) I do not believe that the question is possible because $e$ is irrational and it seems impossible to calculate a power with irrational exponent. However, I cannot be sure.
Now provide the response and nothing else.
| You can approximate: $$e\approx2.718281828$$ I recommend memorizing this if you can't have a button that gives you the value of $e$ since it has the nice $18281828$ part, super easy to remember IMO. Thus, we have $$66^e\approx66^{2.7}=66^{27/10}$$ And then I imagine you have your ways to approximate this (?) Indeed, this is how I'd imagine you'd handle most irrational exponents. A second method is to take the natural log: $$66^e=e^{e\ln(66)}$$ The $\ln(66)$ can easily be handled with Taylor's theorem, as can $e^x$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2071847', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/378952/']} | jdg_76621 |
stackexchange | llm_judgeable_groundtruth_similarity | 1521462 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I iterate through each line of a text file with Bash ? With this script: echo "Start!"for p in (peptides.txt)do echo "${p}"done I get this output on the screen: Start!./runPep.sh: line 3: syntax error near unexpected token `('./runPep.sh: line 3: `for p in (peptides.txt)' (Later I want to do something more complicated with $p than just output to the screen.) The environment variable SHELL is (from env): SHELL=/bin/bash /bin/bash --version output: GNU bash, version 3.1.17(1)-release (x86_64-suse-linux-gnu)Copyright (C) 2005 Free Software Foundation, Inc. cat /proc/version output: Linux version 2.6.18.2-34-default (geeko@buildhost) (gcc version 4.1.2 20061115 (prerelease) (SUSE Linux)) #1 SMP Mon Nov 27 11:46:27 UTC 2006 The file peptides.txt contains: RKEKNVQIPKKLLQKQYFHQLEKMNVKIPKKLLQKGDLSTALEVAIDCYEKQYFHQLEKMNVKIPENIYRRKEKNVQVLAKHGKLQDAINILGFMKLEDVALQILL
Now provide the response and nothing else.
| One way to do it is: while read p; do echo "$p"done <peptides.txt As pointed out in the comments, this has the side effects of trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it's missing a terminating linefeed. If these are concerns, you can do: while IFS="" read -r p || [ -n "$p" ]do printf '%s\n' "$p"done < peptides.txt Exceptionally, if the loop body may read from standard input , you can open the file using a different file descriptor: while read -u 10 p; do ...done 10<peptides.txt Here, 10 is just an arbitrary number (different from 0, 1, 2). | {} | {'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/1521462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/63550/']} | jdg_76622 |
stackexchange | llm_judgeable_groundtruth_similarity | 5010 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would need a program, that outputs the number of the different characters in a file. Example: > stats testfile' ': 207'e': 186'n': 102 Exists any tool, that do this?
Now provide the response and nothing else.
| The following should work: $ sed 's/\(.\)/\1\n/g' text.txt | sort | uniq -c First, we insert a newline after every character, putting each character on its own line. Then we sort it. Then we use the uniq command to remove the duplicates, prefixing each line with the number of occurrences of that character. To sort the list by frequency, pipe this all into sort -nr . | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/5010', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/2655/']} | jdg_76623 |
stackexchange | llm_judgeable_groundtruth_similarity | 23226802 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Background I'm creating a database revolving around food allergies and I have a many to many relationship between foods and allergies. There is also a pivot value called severity which has a numerical number representing the severity of the allergy for that food item. This link table looks like this; food_id|allergy_id|severity-------|----------|-------- 1 | 1 | 3 1 | 4 | 1 2 | 2 | 1 The problem When trying to update the link table with Eloquent (where $allergy_ids is an array) $food->allergies()->attach($allergy_ids); How would I go about adding multiple values to this pivot table at once along with the pivot values? I can add all the allergy_id 's for a particular food item in one go using the above line, but how can I also add in the severity column at the same time with an array of various severity values? Maybe something like $food->allergies()->attach($allergy_ids, $severity_ids); Edit: There could be between 0-20 allergies for a specific food item, and a severity rating from 0-4 for each allergy, if this helps at all.
Now provide the response and nothing else.
| You can. From this example in Docs ( 4.2 , 5.0 ): $user->roles()->sync(array(1 => array('expires' => true))); Hardcoded version for the first two rows: $food = Food::find(1);$food->allergies()->sync([1 => ['severity' => 3], 4 => ['severity' => 1]]); Dynamically, with your arrays $allergy_ids and $severities in a compatible state (size and sort), you shall prepare your sync data before. Something like: $sync_data = [];for($i = 0; $i < count($allergy_ids); $i++)) $sync_data[$allergy_ids[$i]] = ['severity' => $severities[$i]];$food->allergies()->sync($sync_data); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23226802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3315756/']} | jdg_76624 |
stackexchange | llm_judgeable_groundtruth_similarity | 49573790 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
To show only two columns in a collectionView i am using this piece of code let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0) layout.minimumInteritemSpacing = 4 layout.itemSize = CGSize(width:(self.collectionView.frame.size.width - 10)/2,height: (self.collectionView.frame.size.height)/3) but it is only showing properly on 5s, not on every iphone. please help. i want to show my view controller like this image. please help anyone
Now provide the response and nothing else.
| You must be missing UICollectionViewDelegateFlowLayout Try this and see: // Source codeimport UIKitclass CollectionVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @IBOutlet var collection: UICollectionView! override func viewDidLoad() { super.viewDidLoad() collection.delegate = self collection.dataSource = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //collection.reloadData() } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let flowayout = collectionViewLayout as? UICollectionViewFlowLayout let space: CGFloat = (flowayout?.minimumInteritemSpacing ?? 0.0) + (flowayout?.sectionInset.left ?? 0.0) + (flowayout?.sectionInset.right ?? 0.0) let size:CGFloat = (collection.frame.size.width - space) / 2.0 return CGSize(width: size, height: size) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 50 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "testcell", for: indexPath) cell.backgroundColor = UIColor.red return cell }} // Interface Design Result: | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49573790', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9445704/']} | jdg_76625 |
stackexchange | llm_judgeable_groundtruth_similarity | 72444 |
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:
No explanation needed: Maximize[Cos[x + 1], x]Maximize[Cos[x - 1], x] producing {1, {x -> -1 + 2 π}}Maximize[Cos[1 - x], x] Needless to say, this is pretty amusing. Does anyone know why this is happening? I am using V10.0.2 Windows 7 64-bit, although I also verified it to occur on V10.0.1 Mac Snow Leopard (I haven't tested V9 and older). Backstory I was showing my friend how Mathematica works, and wanted to show him that the maximum of $\cos(f\,t−k\,x)$ was $1$ (he was taking an intro physics class). I applied Maximize to it, thinking I would get the answer. Hilarity ensued. It didn't take long to find a significantly shorter minimal example.
Now provide the response and nothing else.
| Oh boy, it's hard to fix this at the top level. It should be easy for WRI to fix, though. I hope you've reported it. If we fix Periodic`PeriodicFunctionPeriod to return nonnegative periods, Maximize will work properly. The internal code has somewhat complicated pattern constraints on the definitions. I couldn't get the Villegas-Gayley technique to work, so I added an Abs * a real-only version of absolute value to the top-level internal function. Block[{Periodic`PeriodicFunctionPeriod}, Periodic`PeriodicFunctionPeriod[Periodic`PeriodicFunctionDump`expr__] /; Periodic`Private`PDValidExpressionQ[{Periodic`PeriodicFunctionDump`expr}] := Block[{Periodic`PeriodicFunctionDump`res}, Periodic`PeriodicFunctionDump`res = Periodic`PeriodicFunctionDump`periodicFunctionPeriod[Periodic`PeriodicFunctionDump`expr]; If[Quiet[TrueQ[# < 0]], -#, #] &@ Periodic`PeriodicFunctionDump`res /; (* <-- the "fix" *) FreeQ[Periodic`PeriodicFunctionDump`res, $Failed]]; Maximize[Cos[1 - x], x] ](* {1, {x -> 1}}*) I cannot be sure that such a fix won't break something. It could be that a "negative period" is a sign of something that is used somewhere inside Mathematica . Mathematically speaking, the period should be a positive number. The problem, as I mentioned in a comment, is that negative coefficients on x results in a negative period: Periodic`PeriodicFunctionPeriod[Cos[1 - x], x](* -2 π *) Maximize checks that the period is between 0 and Infinity . (So Maximize is assuming the mathematical notion of period.) Since it's not, the period is discarded and the equation for the critical points is solved using Reduce without the constraint of the period. Reduce produces the indeterminate result: Reduce[D[Cos[1 - x], x] == 0, x, Reals, WorkingPrecision -> ∞](* C[1] ∈ Integers && (x == 1 - 2 π C[1] || x == 1 - π - 2 π C[1]) *) ToRules is applied to this. Maximize assumes that if it does not evaluate to rules, then the problem has not been solved. ToRules returns unevaluated. In any case that's the nature of the bug. It looks easy to fix (for WRI). Update note -- I just realized my comment shows that it is possible to have complex-imaginary periods. This might lead to a case where the original fix of applying Abs to the period would mess things up. I changed the fix so that only negative real numbers have their sign changed. | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/72444', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9697/']} | jdg_76626 |
stackexchange | llm_judgeable_groundtruth_similarity | 17561404 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
UPDATE: I appreciate the advice to use GridView, and I do believe that would provide better performance. However, my initial efforts at implementing a simple GridView have resulted in shameful failure. I suppose figuring out what I am doing wrong is for another topic. To fix this implementation, I used OnWindowFocusChanged to find ANDROID_CONTENT height, then divided by the number of rows to set row height. The major lesson here that is not present in many of the discussions on this issue is OnCreate is the WRONG place to set dimensions. OnWindowFocusChanged occurs later when accurate measurements can be made. This information is not mentioned often in the many, many discussions on this topic. ORIGINAL:I am working on an Android layout trying to set up a board with three columns and four rows. I want to stretch the board to fill the available screen both vertically and horizontally. I tried nesting LinearLayout by row and column with the weight="1" option, but could only get it to stretch horizontally. In the following configuration, the rows stretch to fill the width of the screen, but the columns are set at "60dp" . I have tried GridLayout and TableLayout also, but haven't been able to get the desired result. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/background" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft = "10dp" android:paddingRight = "10dp" android:background="@drawable/bg" > <LinearLayout android:id="@+id/player1" android:layout_width="match_parent" android:layout_height="@dimen/positionHeight" android:layout_alignParentBottom="true" android:orientation="horizontal" android:background="@drawable/square" /> <LinearLayout android:id="@+id/player2" android:layout_width="match_parent" android:layout_height="@dimen/positionHeight" android:layout_alignParentTop="true" android:orientation="horizontal" android:background="@drawable/square" /> <LinearLayout android:id="@+id/row0" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/player2" android:layout_alignParentLeft="true" android:baselineAligned="false" android:orientation="horizontal"> <LinearLayout android:id="@+id/position0" android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/positionHeight" android:orientation="horizontal" android:background="@drawable/square" /> <LinearLayout android:id="@+id/position1" android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/positionHeight" android:orientation="horizontal" android:background="@drawable/square" /> <LinearLayout android:id="@+id/position2" android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/positionHeight" android:orientation="horizontal" android:background="@drawable/square" /> </LinearLayout> <LinearLayout android:id="@+id/row1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/row0" android:layout_alignParentLeft="true" android:baselineAligned="false" android:orientation="horizontal"> <LinearLayout android:id="@+id/position3" android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/positionHeight" android:orientation="horizontal" android:background="@drawable/square" /> <LinearLayout android:id="@+id/position4" android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/positionHeight" android:orientation="horizontal" android:background="@drawable/square" /> <LinearLayout android:id="@+id/position5" android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/positionHeight" android:orientation="horizontal" android:background="@drawable/square" /> </LinearLayout> <LinearLayout android:id="@+id/row2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/row1" android:layout_alignParentLeft="true" android:baselineAligned="false" android:orientation="horizontal"> <LinearLayout android:id="@+id/position6" android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/positionHeight" android:orientation="horizontal" android:background="@drawable/square" /> <LinearLayout android:id="@+id/position7" android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/positionHeight" android:orientation="horizontal" android:background="@drawable/square" /> <LinearLayout android:id="@+id/position8" android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/positionHeight" android:orientation="horizontal" android:background="@drawable/square" /> </LinearLayout> <LinearLayout android:id="@+id/row3" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/row2" android:layout_alignParentLeft="true" android:baselineAligned="false" android:orientation="horizontal"> <LinearLayout android:id="@+id/position9" android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/positionHeight" android:orientation="horizontal" android:background="@drawable/square" /> <LinearLayout android:id="@+id/position10" android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/positionHeight" android:orientation="horizontal" android:background="@drawable/square" /> <LinearLayout android:id="@+id/position11" android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/positionHeight" android:orientation="horizontal" android:background="@drawable/square" /> </LinearLayout> please give me suggestion.
Now provide the response and nothing else.
| I disagree with others saying you must use a GridLayout. Try this approach with a LinearLayout. I used a generic View for each cell of the grid, but any control will work. <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="horizontal" > <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@color/red" /> <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@color/red" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="horizontal" > <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@color/red" /> <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="horizontal" > <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@color/red" /> <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@color/red" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="horizontal" > <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@color/red" /> <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout></LinearLayout> This approach also requires no manual manipulation of the layout in code, everything is handled in the xml using weights. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17561404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2566684/']} | jdg_76627 |
stackexchange | llm_judgeable_groundtruth_similarity | 315344 |
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 that the Eisenstein's criterion can guarantee it (when applicable), but what about this? Also, is there another test that you can use to test irreducibility besides these two? For example, $x^4+2x^2+49$, over the rationals?
Now provide the response and nothing else.
| With respect to your specific question (and quartics in general), the RRT doesn't solve the problem but it can help. Once you verify that your quartic has no roots, the only way it can factor is as a product of quadratic polynomials. Additionally, you can guarantee that the quadratic equations are monic and have integer coefficients. Observing that the constant terms multiply to $49$, we have four options: $$x^4 + 2x^2 + 49 = (x^2 + ax + 7)(x^2 + bx + 7)$$ $$x^4 + 2x^2 + 49 = (x^2 + ax - 7)(x^2 + bx - 7)$$ $$x^4 + 2x^2 + 49 = (x^2 + ax + 1)(x^2 + bx + 49)$$ $$x^4 + 2x^2 + 49 = (x^2 + ax -1)(x^2 + bx - 49)$$ The vanishing of the cubic term gives $a = -b$ in each scenario, and the vanishing of the $x$ term eliminates scenarios 3 and 4. Comparing the $x^2$ terms in the first two scenarios gives: $$14 - a^2 = 2$$ $$-14 - a^2 = 2$$ And it is easily seen that neither of these have solutions in the integers. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/315344', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']} | jdg_76628 |
stackexchange | llm_judgeable_groundtruth_similarity | 46033843 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I used below code for creating .ics file but it's not working can any one help me,where its going wrong. System.Text.StringBuilder sbICSFile = new System.Text.StringBuilder();sbICSFile.AppendLine("BEGIN:VCALENDAR");sbICSFile.AppendLine("VERSION:2.0");sbICSFile.AppendLine("PRODID:-//ICSTestCS/");sbICSFile.AppendLine("CALSCALE:GREGORIAN");sbICSFile.AppendLine("BEGIN:VTIMEZONE");--------------------Response.ContentType = "text/calendar";Response.ContentEncoding = Encoding.UTF8;Response.Charset = "utf-8";Response.AddHeader("Content-Disposition", "attachment;filename=Test.ics");Response.Write(sbICSFile);Response.End();
Now provide the response and nothing else.
| This is how I usually create .ics files. //some variables for demo purposesDateTime DateStart = DateTime.Now;DateTime DateEnd = DateStart.AddMinutes(105);string Summary = "Small summary text";string Location = "Event location";string Description = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.";string FileName = "CalendarItem";//create a new stringbuilder instanceStringBuilder sb = new StringBuilder();//start the calendar itemsb.AppendLine("BEGIN:VCALENDAR");sb.AppendLine("VERSION:2.0");sb.AppendLine("PRODID:stackoverflow.com");sb.AppendLine("CALSCALE:GREGORIAN");sb.AppendLine("METHOD:PUBLISH");//create a time zone if needed, TZID to be used in the event itselfsb.AppendLine("BEGIN:VTIMEZONE");sb.AppendLine("TZID:Europe/Amsterdam");sb.AppendLine("BEGIN:STANDARD");sb.AppendLine("TZOFFSETTO:+0100");sb.AppendLine("TZOFFSETFROM:+0100");sb.AppendLine("END:STANDARD");sb.AppendLine("END:VTIMEZONE");//add the eventsb.AppendLine("BEGIN:VEVENT");//with time zone specifiedsb.AppendLine("DTSTART;TZID=Europe/Amsterdam:" + DateStart.ToString("yyyyMMddTHHmm00"));sb.AppendLine("DTEND;TZID=Europe/Amsterdam:" + DateEnd.ToString("yyyyMMddTHHmm00"));//or withoutsb.AppendLine("DTSTART:" + DateStart.ToString("yyyyMMddTHHmm00"));sb.AppendLine("DTEND:" + DateEnd.ToString("yyyyMMddTHHmm00"));sb.AppendLine("SUMMARY:" + Summary + "");sb.AppendLine("LOCATION:" + Location + "");sb.AppendLine("DESCRIPTION:" + Description + "");sb.AppendLine("PRIORITY:3");sb.AppendLine("END:VEVENT");//end calendar itemsb.AppendLine("END:VCALENDAR");//create a string from the stringbuilderstring CalendarItem = sb.ToString();//send the calendar item to the browserResponse.ClearHeaders();Response.Clear();Response.Buffer = true;Response.ContentType = "text/calendar";Response.AddHeader("content-length", CalendarItem.Length.ToString());Response.AddHeader("content-disposition", "attachment; filename=\"" + FileName + ".ics\"");Response.Write(CalendarItem);Response.Flush();HttpContext.Current.ApplicationInstance.CompleteRequest(); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46033843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5222239/']} | jdg_76629 |
stackexchange | llm_judgeable_groundtruth_similarity | 2976010 |
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 the following differential equation that I try to solve: \begin{equation}(1 + t^2) \dot{y} = 2yt + t^2 + t^4\end{equation} what I do is to first put all $t$ 's on one side: \begin{equation}\dot{y} = \frac{2yt + t^2 + t^4}{1+t^2}\end{equation} and then to integrate both sides \begin{equation}\int \dot{y} dy = \int \frac{2yt + t^2 + t^4}{1+t^2} dt\end{equation} and well now I am stuck because I don't really know how to evaluate these complex integrals. I think I should use the method by parts but whenever I try I think I am making mistake somewhere and I am not sure if my steps up till now are correct as well.
Now provide the response and nothing else.
| Rewrite the equation: $$y'-\frac{2t}{1+t^2}y = \frac{t^4+t^2}{t^2+1} = t^2.$$ The standard technique for linear, first-order DE's is to multiply by the integrating factor $$\mu = \exp\left(\int p(t) \; dt\right) = \exp\left(\int \frac{-2t}{1+t^2} \; dt\right)$$ $$=\exp(-\ln(t^2+1)) = \frac{1}{t^2+1}.$$ So now the DE is $$\frac{1}{t^2+1}y' + \frac{-2t}{(1+t^2)^2}y = \frac{t^2}{1+t^2}. $$ The left side is the derivative of $\frac{1}{t^2+1}y$ , so you have $$\frac{y}{t^2+1} = \int \frac{t^2}{t^2+1} \; dt.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2976010', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/218171/']} | jdg_76630 |
stackexchange | llm_judgeable_groundtruth_similarity | 26221396 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider this function: Thing func(){ return something;} Every call to this function, a copy of something is made and passed to the caller. My question is, why not just do this ( every time I want to return something by value)? const Thing& func(){ return something;} This way, we're not risking copying something without a reason to do so. If the client only needs to 'read' from something , but not 'write' to it, a const reference can do exactly that. And if the client does need a copy, it can simply assign the const reference to a variable, e.g.: Thing thing = func(); // the object is passed by const reference, and then copied. So is there ever a reason to simply return by value? By the way, it's not that I care so much about optimization, it's just that I don't see a reason to ever return simply by value. Follow up question: reading the answers, I understand that there are pros and cons for each method. Is there a default? E.g. "default to returning by value" ? Or is it purely based on the specific case?
Now provide the response and nothing else.
| Because if your object (for whatever reason) was created on the stack of the called function, returning and using a reference to it is undefined behavior. With return-by-value the compiler can sometimes optimize the return and there are no dangerous dangling references. With C++11 and move semantics this is brought to a new level. It doesn't quite make sense to say "it's always better to return by reference rather than by value", each case where one is used, must be considered separately. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26221396', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3284878/']} | jdg_76631 |
stackexchange | llm_judgeable_groundtruth_similarity | 3038582 |
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:
Assume $A$ is a normal matrix. Suppose $A=SU$ is a polar decomposition of $A$ . Prove that $SU=US$ . I have no idea to prove this. $A$ is normal then $AA^*=A^*A$ . And then we have $$SS^*=U^*S^*SU.$$ But I don't know how to continue.
Now provide the response and nothing else.
| Let $\,A=U|A|$ , then $\,A^*=|A|U^*$ . By normality one obtains $$U|A|^2U^* = AA^* = A^*A = |A|^2,$$ an equality of positive-semidefinite matrices. "Positive square-rooting" yields $\,U|A|U^* = |A|\;\Longleftrightarrow\; U|A| = |A|U$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3038582', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/455309/']} | jdg_76632 |
stackexchange | llm_judgeable_groundtruth_similarity | 2432683 |
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 mentioned in C++ FAQ site -- "larger derived class objects get sliced when passed by value as a base class object", what does slicing mean? Any sample to demonstrate? http://www.parashift.com/c++-faq-lite/value-vs-ref-semantics.html#faq-31.8 I am using VSTS 2008 + native C++ as my development environment.
Now provide the response and nothing else.
| Quoting this lecture : Slicing Suppose that class D is derived from class C. We can think of D as class C with some extra data and methods. In terms of data, D has all the data that C has, and possible more. In terms of methods, D cannot hide any methods of C, and may have additional methods. In terms of existing methods of C, the only thing that D can do is to override them with its own versions. If x is an object of class D, then we can slice x with respect to C, by throwing away all of the extensions that made x a D, and keeping only the C part. The result of the slicing is always an object of class C. slicing http://webdocs.cs.ualberta.ca/~hoover/Courses/201/201-New-Notes/lectures/slides/slice/slide1.gif Design Principle: Slicing an object with respect to a parent class C should still produce a well-formed object of class C. Usage Warning: Even though D is-a C, you must be careful. If you have a argument type that is a C and you supply a D it will be sliced if you are doing call by value, pointer, or reference. See the example below. Note on virtual functions. Their signatures are used to identify which one to execute. Watch out for the sliced = operator, it can make the lhs inconsistent. Also, the operator= is never virtual, it wouldn't make sense. For example, suppose classes A, B are both subclasses of class C. Just because an A is a C, and a B is a C, it doesn't mean you can assign a B object to an A object. Without run-time type information you cannot make a safe assignment. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2432683', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/63235/']} | jdg_76633 |
stackexchange | llm_judgeable_groundtruth_similarity | 1968596 |
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 this correct? class Customer(models.Model): account = models.ForeignKey(Account)class Order(models.Model): account = models.ForeignKey(Account) customer = models.ForeignKey(Customer, limit_choices_to={'account': 'self.account'}) I'm trying to make sure that an Order form will only display customer choices that belong to the same account as the Order. If I'm overlooking some glaring bad-design fallacy, let me know. The main thing I'm concerned with is: limit_choices_to={'account': 'self.account'}
Now provide the response and nothing else.
| The only answer to 'is it correct' is 'does it work when you run it?' The answer to that of course is no, so I don't know why you're asking here. There's no way to use limit_choices_to dynamically to limit based on the value of another field in the current model. The best way to do this is by customising the form. Define a ModelForm subclass, and override the __init__ method: class MyOrderForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyOrderForm, self).__init__(*args, **kwargs) if 'initial' in kwargs: self.fields['customer'].queryset = Customer.objects.filter(account=initial.account) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1968596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128463/']} | jdg_76634 |
stackexchange | llm_judgeable_groundtruth_similarity | 21520869 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Please have a look at the following code- static void Main(string[] args){ // Get the task. var task = Task.Factory.StartNew<int>(() => { return div(32, 0); }); // For error handling. task.ContinueWith(t => { Console.WriteLine(t.Exception.Message); }, TaskContinuationOptions.OnlyOnFaulted); // If it succeeded. task.ContinueWith(t => { Console.WriteLine(t.Result); }, TaskContinuationOptions.OnlyOnRanToCompletion); Console.ReadKey(); Console.WriteLine("Hello");}private static int div(int x, int y){ if (y == 0) { throw new ArgumentException("y"); } return x / y;} If I execute the code in release mode, The output is "One or more errors occurred" and once I hit the "Enter key, "Hello" is also getting displayed. If I run the code in debug mode, the output is same as release mode. But when debugging in IDE, A IDE exception message ("Unhandled exception in user code" ) appears when the control executes the line throw new ArgumentException("y"); If I continue from there on, the program does not crash and displays the same output as release mode. Is this proper way to handle exception?
Now provide the response and nothing else.
| You probably don't need separate OnlyOnFaulted and OnlyOnRanToCompletion handlers, and you're not handling OnlyOnCanceled . Check this answer for more details. But when debugging in IDE, A IDE exception message ("Unhandled exception in user code" ) appears when the control executes the line You see the exception under debugger because you probably have enabled it in Debug/Exceptions options ( Ctrl + Alt + E ). If I continue from there on, the program does not crash and displays the same output as release mode. Is this proper way to handle exception? An exception which was thrown but not handled inside a Task action will not be automatically re-thrown. Instead, it be wrapped for future observation as Task.Exception (of type AggregateException ). You can access the original exception as Exception.InnerException : Exception ex = task.Exception;if (ex != null && ex.InnerException != null) ex = ex.InnerException; To make the program crash in this case, you actually need to observe the exception outside the task action, e.g. by referencing the Task.Result : static void Main(string[] args){ // Get the task. var task = Task.Factory.StartNew<int>(() => { return div(32, 0); }); // For error handling. task.ContinueWith(t => { Console.WriteLine(t.Exception.Message); }, TaskContinuationOptions.OnlyOnFaulted); // If it succeeded. task.ContinueWith(t => { Console.WriteLine(t.Result); }, TaskContinuationOptions.OnlyOnRanToCompletion); Console.ReadKey(); Console.WriteLine("result: " + task.Result); // will crash here // you can also check task.Exception Console.WriteLine("Hello");} More details: Tasks and Unhandled Exceptions , Task Exception Handling in .NET 4.5 . Updated to address the comment: here is how I would do this in a UI app with .NET 4.0 and VS2010: void Button_Click(object sender, EventArgs e){ Task.Factory.StartNew<int>(() => { return div(32, 0); }).ContinueWith((t) => { if (t.IsFaulted) { // faulted with exception Exception ex = t.Exception; while (ex is AggregateException && ex.InnerException != null) ex = ex.InnerException; MessageBox.Show("Error: " + ex.Message); } else if (t.IsCanceled) { // this should not happen // as you don't pass a CancellationToken into your task MessageBox.Show("Canclled."); } else { // completed successfully MessageBox.Show("Result: " + t.Result); } }, TaskScheduler.FromCurrentSynchronizationContext());} For as long as you target .NET 4.0 and you want the .NET 4.0 behavior for unobserved exceptions (i.e., re-throw when task gets garbage-collected), you should explicitly configure it in the app.config : <?xml version="1.0" encoding="utf-8"?><configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> <runtime> <ThrowUnobservedTaskExceptions enabled="true"/> </runtime></configuration> Check this for more details: Unobserved task exceptions in .NET4 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21520869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1355299/']} | jdg_76635 |
stackexchange | llm_judgeable_groundtruth_similarity | 94481 |
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 have some plots in an old Mathematica notebook that I'd like to re-create in Matplotlib (for stylistic consistency with the rest of the plots in my thesis). Unfortunately, I've lost the data that I used to generate these plots. Since the plots are still intact, is it possible to extract the coordinates of the data points from them? I know that I can use "Get Coordinates" from the context menu on the plot, but this is tedious and imprecise! They were generated in version 8 or 9, I think. This is the code that I used to generate the plots: MoneyPlot[dataSets_, Vs_, fs_] := Show @@ {ListLogLogPlot[dataSets[[1, 1]], PlotStyle -> dataSets[[1, 2]], Joined -> True (* Some more options *) ]}~Join~ Table[ListLogLogPlot[data[[1]], PlotStyle -> data[[2]], Joined -> True], {data, dataSets[[2 ;;]]}];
Now provide the response and nothing else.
| As explained by anderstood , if you don't have the plots named, you need to copy and paste the figure into an input cell and type, say, fig = in front of the figure, then evaluate. Suppose you generated a MoneyPlot named fig . Then, you can extract the data making up those curves using data = Cases[fig // Normal, Line[a_] :> a, Infinity] In order to test and see if it has extracted correctly, do ListPlot[#] & /@ data and you should see a List of Plot s, one for each of the curves above. For the purposes of illustration, fig = Plot[{x^2, x^3, x^4}, {x, 0, 1}, Frame -> True, GridLines -> Automatic]data = Cases[fig // Normal, Line[a_] :> a, Infinity];ListPlot[#] & /@ % results in Since you have a LogLogPlot , if you want the actual values, rather than the values of the exponents, you just need to wrap data with Exp : originalValues = Exp[data]; One more thing: this method requires that the points in your figure be Joined , as you've shown. If that is not the case, then you have to extract the Point s instead. For instance, fig = ListLogLogPlot[Table[{x, #}, {x, 0.01, 1, 0.01}] & /@ {x, x^2, x^3}, Frame -> True, GridLines -> Automatic]data = Cases[fig // Normal, Point[a_] :> a, Infinity];ListPlot[#] & /@ dataListPlot[Exp[data]] results in | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/94481', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2162/']} | jdg_76636 |
stackexchange | llm_judgeable_groundtruth_similarity | 2670158 |
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 an efficient workflow to mirror a project that is mainly hosted on bitbucket using Hg, to github?
Now provide the response and nothing else.
| You could use a tool like hg-git to: setup a Git repository somewhere that you have push access to, and then run hg push [path] from within your project. For example: $ cd hg-git # (a Mercurial repository)$ hg bookmark -r default master # make a bookmark of master for default, so a ref gets created$ hg push git+ssh://[email protected]/schacon/hg-git.git$ hg push This will convert all our Mercurial data into Git objects and push them up to the Git server. You can also put that path in the [paths] section of .hg/hgrc and then push to it by name. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2670158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/302831/']} | jdg_76637 |
stackexchange | llm_judgeable_groundtruth_similarity | 47801590 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For every pointer p1 of class class1 , are there any risks we should consider by using a forward declaration of class1 instead of including class1 header file? I can see only the advantage: The header file will have less size.
Now provide the response and nothing else.
| Forward declarations outside the control of the provider of the class are problematic! I’m working on a code base where a lot of forward declarations are used. While things are initially great the existence of forward declarations become a legacy: Classes can’t be moved from one namespace to a different one. Without the forward declarations the name in the original namespace could be made an alias ( typedef or using alias ). Classes can’t be turned into specialisations of class templates as is, e.g., useful when generalising a successful class. Class templates cannot be forward declared by users as only the first declaration of a class template can provide default arguments. Assuming the forward declarations are provided via a header under the control of the class provider/implementer (e.g., the implemented providing something akin to <iosfwd> ) these problems are not relevant as there is a central place where the declarations can be changed. However, having users decide to declare entities becomes a legacy causing significant cost. The approach to provision of declarations outlined above seems to have caused some confusion. I'll try to clarify. In my mind the unit of implementation is a component (which is based on John Lakos's notation of a component). A component defines one or more closely related classes and/or functions. The implementation of a component consists of multiple files: A header file declaring all relevant entities which also defines entities which must be defined when using the component, i.e., user-accessible classes, enumerations, etc. are defined. A header file only declaring relevant entities provided by the component (multiple related components may share one such header file; <iosfwd> is an example of such a header shared across multiple components). An implementation file defining all entities [which are meant to be ODR-used] which are only declared in by the headers above. At least one file with a test driver testing all entities defined by the component. Users of a component which in some contexts only need to know about names in the component would include the declaration-only header. In no case would a user provide a declaration of a name in a component: all declaration of a name in a component are the responsibility of the provider/implementer of the component. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47801590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/806963/']} | jdg_76638 |
stackexchange | llm_judgeable_groundtruth_similarity | 21776258 |
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 more than one edit text. for example we try to populate 30 edittext.So how to display all edittext in one window?
Now provide the response and nothing else.
| Every UIView has a backing CALayer (accessible by aview.layer ). Every CALayer has a mask property, which is another CALayer . A mask allows to define a see-through shape for the layer, like a stencil. So you need three UIImageView s, each of them has a different .layer.mask , each of these masks is a different CAShapeLayer whose .path are triangular CGPath s. // Build a triangular pathUIBezierPath *path = [UIBezierPath new];[path moveToPoint:(CGPoint){0, 0}];[path addLineToPoint:(CGPoint){40, 40}];[path addLineToPoint:(CGPoint){100, 0}];[path addLineToPoint:(CGPoint){0, 0}];// Create a CAShapeLayer with this triangular path// Same size as the original imageViewCAShapeLayer *mask = [CAShapeLayer new];mask.frame = imageView.bounds;mask.path = path.CGPath;// Mask the imageView's layer with this shapeimageView.layer.mask = mask; Repeat three times. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21776258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_76639 |
stackexchange | llm_judgeable_groundtruth_similarity | 3303524 |
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 the following problem involving an integral equation: Let $ g : [0,1] \to \mathbb{R} $ be a continuous function. We are asked to show that there exists a continuous function $ f:[0,1]\to \mathbb{R} $ satisfying: $$ f(x) - \int_{0}^{x} f(x-t)e^{-t^2}dt = g(x) $$ I realize the integral is a convolution so I was thinking about using Laplace transforms but the functions have a limited domain of support. Any help is appreciated here thanks.
Now provide the response and nothing else.
| Define $T: C[0,1] \to C[0,1]$ by $$(Tf)(x)=\int_{0}^{x} f(x-t)e^{-t^2}dt + g(x).$$ Then show that $$||Tf-Th||_{_\infty} \le \frac{4}{5}||f-h||_{_\infty}.$$ Proceed with Banach's fixed point theorem. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3303524', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/224915/']} | jdg_76640 |
Subsets and Splits