INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to get all text files from one folder using Java? I need to read all ".txt" files from folder (user needs to select this folder). Please advise how to do it?
you can use `filenamefilter` class it is pretty simple usage public static void main(String[] args) throws IOException { File f = new File("c:\\mydirectory"); FilenameFilter textFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".txt"); } }; File[] files = f.listFiles(textFilter); for (File file : files) { if (file.isDirectory()) { System.out.print("directory:"); } else { System.out.print(" file:"); } System.out.println(file.getCanonicalPath()); } } just create an `filenamefilter` instance an override accept method how you want
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 6, "tags": "java, file" }
Transpose data in text file I have a text file in the format below: Name: John Age: 25 Location: CA Name: Mac Age: 24 Location: CA Name: Patrick Age: 25 Location: CA Name: Christian Age: 25 Location: CA I looking for help to transpose the data using either Perl or awk. Name Age Location John 25 CA Mac 24 CA Patrick 25 CA Christian 25 CA I would really appreciate if anyone can help me.
looking for this? kent$ awk -F'\n|: ' -v RS="" 'NR==1{print $1,$3,$5}{print $2,$4,$6}' file Name Age Location John 25 CA Mac 24 CA Patrick 25 CA Christian 25 CA if you want to let output look prettier, pipe the output to `|column -t` (values don't contain spaces) or use `printf` in awk. kent$ awk -F'\n|: ' -v RS="" 'NR==1{print $1,$3,$5}{print $2,$4,$6}' f|column -t Name Age Location John 25 CA Mac 24 CA Patrick 25 CA Christian 25 CA
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -3, "tags": "perl, awk" }
Which part of the plugin to change so the updater won't register the next version? I have made a change in WP qTip plugin so only a specific `a.something[title]` instead of `a[title]` is affected. It's just a small plugin, but if there is a new version and my client wll update this plugin the changes will be lost. My question is what in the plugin should I change so the update will be not possible and plugin not recognized? Will be changing the name enough? E.g. from: `Plugin Name: WP jQuery qTip` to som thing like: `Plugin Name: WP jQuery qTip - No Update` ? Or I need to make additional changes in the plugin too?
You should not modify Themes or Plugins that you don't control. Instead, use one of two options: 1. Patch the Theme/Plugin, and submit the patch to the developer 2. Fork the Theme/Plugin It sounds like you've opted for option #2. In that case, I would recommend changing both of the following: 1. Update the entire header phpDoc refs to your forked version of the Plugin 2. Change the directory name from `/wp-content/plugins/{plugin-name}`, to `/wp-content/plugins/{forked-plugin-name}` I believe the bare-minimum change needed is changing the `Plugin name` phpDoc, and the Plugin's directory name.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, updates" }
Pushing updates to a application built in Visual Studio I am considering building an application in Visual Studio 2010. This application will be distributed to dozens of users. As time passes, I will have to update the application. Is there a way that I can push updates to the users without having to rebuild the application, re-distribute the application to the users, have the users uninstall the original application, then install the new version? I imagine the solution as the user being notified of a new version upon start-up, and the user clicking "OK" (or some equivalent) and then the program will download the new version. Is there a way to do this in Visual Studio? Thanks!
ClickOnce is an option, but not necessarily the most popular. You can also roll-your-own solution, which really isn't that hard: * Create a URL on a web server which returns the latest version (as a JSON object, XML string, plain text, whatever). * Have your program query this URL at startup. * If the latest version doesn't match the current version, prompt the user and download the latest version from the web server, saving it to a temporary directory. * Invoke the downloaded installer. (If it's an msi, there are command line options for "silent install" without a user interface; other installer have similar features.) This approach has nothing to do with Visual Studio and could be used with any language / IDE.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "visual studio 2010, push, auto update" }
When I add a feature to a vector layer, all the features of the layer disappear Openlayers I'm working in a Geocoder tool that can put new features in a vector layer directly just pressing a button. When press the button all the features of the layer **disappear** in the map. The features still exists because I can get the length increased by one using after that: alert(vector.getSource().getFeatures().length) I did the following function as button click handler function addPoint(lng,lat) { var pp = new ol.geom.Point( [ ol.proj.transform([lng,lat], 'EPSG:4326', 'EPSG:3857'), ]); var featurething = new ol.Feature({ geometry: pp }); vector.getSource().addFeature(featurething); }
ol.proj.transform returns Array. so it means, var pp = new ol.geom.Point([[lng,lat]]); there's useless square brackets. remove them, then it works. var pp = new ol.geom.Point( ol.proj.transform([lng,lat], 'EPSG:4326', 'EPSG:3857') );
stackexchange-gis
{ "answer_score": 0, "question_score": 0, "tags": "openlayers, features" }
Memory problem in Ubuntu 8 server This is a chart of memory usage in my AWS instance of Ubuntu 8 server, which is configured as a LAMP server. I've had a problem with this server locking up about once a month, and looking at the memory chart, I can see the cache slowly taking over available memory. Will it stop at some point, or just keep growing until it locks up the server - in other words, is this normal? !alt text
Buffers and Cache look like they are doing what I would expect. Cache will continue to grow until 100% of your memory is being used. This is normal behavior as unused ram is wasted ram. Cache is released as other things need memory so this shouldn't force any low memory situation on any running applications. What makes you suspect that your problem is with memory? It looks like you have plenty of unused memory there.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "ubuntu, lamp, ubuntu 8.04" }
Android Studio Gradle - set module build variant I am setting up project that has a dependancy to one module, and I could successfully make APK file. All I did was adding > compile project(':ModuleName') However I am wondering if I can have module dependancy with build variance. So, _[Project: **debug** ]_ depends on _[Module: **debug** ]_, and _[Project: **release** ]_ depends on _[Module: **release** ]_ Thanks!
At the moment the Gradle toolchain only builds libraries in the release variant by default, regardless of what you choose as your application build type. There are some suggested work arounds to that problem but they are mostly involved in your build configuration rather than anything with the dependency include. The closest example I can think that is to what you want is to do the following; dependencies { flavor1Compile project(path: ':lib1', configuration: 'flavor1Release') flavor2Compile project(path: ':lib1', configuration: 'flavor2Release') } But this is achieved through build flavours rather than build variants.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 8, "tags": "android, build, module, gradle, variant" }
E-step of the stochastic approximation EM I am reading the paper: Convergence of a stochastic approximation version of the EM algorithm to implement this algorithm for a probability model I already have. In p. 3, the paper summarises the algorithm as follows. !enter image description here I am stuck at the E (or S) step in this algorithm. In a typical EM setup, one maximizes the integral $$Q(\theta)= \int \log p(x,y |\theta) p(x|y,\theta) dx$$ In here, this integral is estimated via the samples simulated from the posterior. I understand this. But, what I do not understand is: Do authors propose to 'update' the cost function? If so, how can we maximize the new $Q$? May be I am missing a very obvious thing and can not see how to implement this algorithm (I do not understand updating the 'cost'). Thanks in advance!
In an EM, $Q_k(\theta)$ is the result of the $k$th E step. It is not a classical cost function, but rather an approximation of the true target likelihood function, which you maximize in the M step. There proposed algorithm is simply an EM where the E step cannot be computed analytically so it is estimated using Monte Carlo methods. You can do the maximization in the M step using nay appropriate optimization scheme appropriate to the characteristics of Q. Say, analytically if Q permits it, or numerically if necessary. Note however, that as in any EM, you actually don't need to maximize Q, but rather just find a $theta$ that improves on the initial values.
stackexchange-stats
{ "answer_score": 1, "question_score": 2, "tags": "expectation maximization" }
ASP.NET how to access textbox within public method I am trying to access a TextBox within `GridView1` from a public method, however the value/string returned is null so a **null reference error is being created**. How I can access the TextBox because I really need the value `inside` to do something with it. C# code: protected void txtOut_TextChanged(object sender, EventArgs e) { string inside = ((TextBox)GridView1.FindControl("txtForeName")).Text.Trim(); }
You can use like this: GridViewRow row = (sender as Control).NamingContainer as GridViewRow; string inside = ((TextBox)row.FindControl("txtForeName")).Text.Trim();
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, asp.net, gridview" }
pandas groupby, difference between top and bottom group members Assume I have `df`: df = pd.DataFrame({'ID': ['a', 'b', 'b', 'b', 'c', 'c'], 'V1': [1,2,3,4,5,6], 'V2': [7,8,9,19,11,12]}) I want to create a new column `V3`, indicating the difference between `V2` for the "top" group member, and `V1` for the "bottom" group member. The result would look like: ID V1 V2 V3 0 a 1 7 6 1 b 2 8 4 2 b 3 9 4 3 b 4 19 4 4 c 5 11 5 5 c 6 12 5 I tried something like this, which doesn't work: df.groupby('ID').apply(lambda x: x.head(1).V2-x.tail(1).V1)
Use `GroupBy.transform` with `first` and `last` and subtract by `Series.sub`: df['V3'] = df.groupby('ID').V2.transform('first').sub(df.groupby('ID').V1.transform('last')) Your solution shoud be changed by selecting by positions and `Series.map`: s = df.groupby('ID').apply(lambda x: x.V2.iat[0]-x.V1.iat[-1]) df['V3'] = df['ID'].map(s) print (df) ID V1 V2 V3 0 a 1 7 6 1 b 2 8 4 2 b 3 9 4 3 b 4 19 4 4 c 5 11 5 5 c 6 12 5
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, pandas, dataframe, group by" }
similarity proof > Prove that if the vertical angle of a straight line which cuts the base, the rectangle contained by the segments of the base with the square on the line segment which bisects the angle and meeting at base > > i.e. , if $\angle ABC=\angle ACB$ i.e. $AB =AC$ and $AD$ is the angle bisector then prove that $AB\times AC=BD\times DC+AD^2$
![enter image description here]( Notice that by angle bisector theorem, $$\frac{AB}{AC}=\frac{BD}{DC}$$ Now,as $\frac{AB}{AC}=1,$ we have $BD=DC$. Also,by congruence,you can prove that,$\angle ADB=\angle ADC=90^0$. So,$$AB^2=AD^2+BD^2$$ $$\implies AB\times AB=BD\times BD+AD^2$$ As,$AB=AC$ and $BD=DC$(as $\triangle ABD\cong\triangle ACD$.) So, we can say,$ AB\times AC=BD\times DC+AD^2$ (Proved).
stackexchange-math
{ "answer_score": -1, "question_score": -3, "tags": "geometry" }
Counting non matching, shared digits between two numbers in Python I am trying to figure out a way to determine the total number of non-matching, common digits between two numbers in python. So far I can get the number of matching digits between the two numbers.The end goal is to have a function that takes two numbers ie 6621 and 6662 and return the numbers 2 for the number of matching digits and 1 for the number of non-matching shared digits. I have tried using nested while loops to do this, but the count is not always accurate depending on the numbers being compared. while i < n:#check 2. Nested while statements j = 0 while j < n: if g_list[i] == p_list[j] and j == i: x elif g_list[i] == p_list[j]: z += 1 print(g_list[i],p_list[j],z, i, j) j += 1 i += 1
You can count the number of occurrence of each digit in each number and take the minimum of those. This will get you the number of common digits, then you subtract the number of matching digits. def get_count_of_digit(number): l = [0 for i in range(10)] list_digit = str(number) for d in list_digit: l[int(d)] += 1 return l def number_of_common_digit(number1, number2): l1, l2 = [get_count_of_digit(n) for n in (number1, number2)] return sum([min(l1[i], l2[i]) for i in range(10)])
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python, python 3.x" }
Objective-C removing objects from NSArray containing indexpath I've an array which contains NSIndexPath and I want to remove all objects which have the same IndexPath.Row. My current code has some issues, not all the objects with same Row are removed. My code is: rowValue=(int)btn.tag; for (int i=0; i<[SingletonClass singleton].arraySubMenuItems.count; i++) { NSIndexPath * Path = [[SingletonClass singleton].arraySubMenuItems objectAtIndex:i]; int section = (int) Path.section; if (section == rowValue) { NSIndexPath *indexPath = [[SingletonClass singleton].arraySubMenuItems objectAtIndex:i]; [[SingletonClass singleton].arraySubMenuItems removeObjectAtIndex:i]; } }
You can remove objects like this rowValue=(int)btn.tag; NSMutableArray *arrTemp = [NSMutableArray new]; for (int i=0; i<[SingletonClass singleton].arraySubMenuItems.count; i++) { NSIndexPath * Path = [[SingletonClass singleton].arraySubMenuItems objectAtIndex:i]; int section = (int) Path.section; if (section == rowValue) { [arrTemp addObject:[[SingletonClass singleton].arraySubMenuItems objectAtIndex:i]]; } } [[SingletonClass singleton].arraySubMenuItems removeObjectsInArray:arrTemp];
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ios, objective c" }
How to properly craft a LineString CQL for WFS GET filter? A helper class I'm working on has to make an occasional requests to a GeoServer. These can be GET calls and I'd prefer them to be. These are filtered with CQL. Here is an example, which is returning the ol' `Could not parse CQL filter list` error. The programmatically constructed uri looks like this: service=WFS&version=1.1.0& request=GetFeature& typename="view:mydbview"& outputFormat=json& maxFeatures=500& cql_filter=INTERSECTS(geometry, LineString((-90 35,-80 35))) AND fieldname1 LIKE 'somevalue%' What I've checked: * `geometry` holds the geometry in `view:mydbview` * `fieldname1` does exist What am I missing? Willing to do my own homework but complex CQL/ECQL documentation is somewhat slender and I've not found a resource that shows explicitly how elements are to be appended to a URL request.
LineStrings only have one set of brackets, so INTERSECTS(geometry, LineString(-90 35,-80 35)) will work. If it was a MultiLineString you would need 2 sets.
stackexchange-gis
{ "answer_score": 2, "question_score": 0, "tags": "geoserver, wfs, cql" }
Keyboard similar to laptop keyboards for a desktop I want to use a keyboard that requires minimal effort pushing down with minimal (if any at all) space between keys. I like the new Apple keyboards, but I want something closer to the feel of a laptop keyboard with flat buttons (the keys on the Apple keyboards are still raised up a bit). Are there any that fit this description? I _want_ something touch-sensitive.
How about a laptop keyboard?
stackexchange-superuser
{ "answer_score": 2, "question_score": 2, "tags": "keyboard, ergonomics" }
org.eclipse.ui can't be resolved? Could you please tell me how to resolve that package import, I thought it is an element of SWT and I've already have SWT installed into Eclipse IDE. Why is it so bothersome? I guess I have to download some *.jar or *.zip files to add to my project as external library. Please give me a solution. Thank you! VipHaLong.
No, `org.eclipse.ui` is definitely not part of SWT (or vice versa, but it requires SWT). If you are creating an RCP plugin (if not, you probably shouldn't be using `org.eclipse.ui`), you need to open `plugin.xml` file, "Dependencies" tab, and add `org.eclipse.ui` to "Required plugins".
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "java, swt" }
How can I say that this model have been used by many people? How can I say that this model have been used by many people? Is this ok? > "it has been hugely used before"
Even though our president might say it that way, it is not idiomatic. _It has been widely used by others in the field._ _Many previous projects made use of this model._
stackexchange-english
{ "answer_score": 0, "question_score": 0, "tags": "sentence" }
Is there a way to make a map object repeat? Say if I have a map object: `map(lambda x: int(x), "123")`, but I want 6 items, I would expect `1,2,3,1,2,3` (Note I don't want it in list format, I would use next to get each item), but instead I just get a StopIteration error once I pull out 3 items. I do have a workaround but it's not as clean as I would like: def MakeMap(): return map(lambda x:int(x), "123") mapped=MakeMap() for i in range(6): try: print(next(mapped)) except StopIteration: mapped=MakeMap() print(next(mapped)) While this works, as stated above I would like it to be just as easy as: mapped=map(lambda x:int(x), "123") for i in range(6): print(next(mapped)) Is there anyway to do this?
`itertools.cycle` is the general way to (indefinitely) repeat any iterator's sequence. >>> from itertools import cycle >>> mapped = cycle(map(int, "123")) >>> for i in range(6): ... print(next(mapped)) 1 2 3 1 2 3 Do note the other change: `lambda x: int(x)` works, but is an expensive and obscure way to spell plain old `int`.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 1, "tags": "python" }
Animate a graphviz graph I'm exploring some graph algorithms, and would like to animate the graph change over time (e.g. when adding a heap node or balancing a tree). Is there a nice way to animate a sequence of `graphviz` graphs?
By now, there are two: * GraphAnim, which takes a graph and then a list of changes to it for the animations as source, and converts it into an animated GIF * d3-graphviz, which takes a list of fully fledged graph descriptions as source, converts each into an SVG, and then uses JavaScript (Vue.js) and d3 to create animations between them. though it is possible to have other workflows, like interactively generating subsequent graphs in the fly.
stackexchange-cstheory
{ "answer_score": 1, "question_score": 2, "tags": "graph theory" }
Can't open Talend Open Studio on ubuntu I am new to Talend Open studio. I am trying to open it but it is giving following warnings : > WARNING: An illegal reflective access operation has occurred > > WARNING: Illegal reflective access by org.eclipse.osgi.storage.FrameworkExtensionInstaller (file:/home/user/TOS_DI-20181026_1147-V7.1.1/plugins/org.eclipse.osgi_3.10.100.v20150521-1310.jar) to method java.net.URLClassLoader.addURL(java.net.URL) > > WARNING: Please consider reporting this to the maintainers of org.eclipse.osgi.storage.FrameworkExtensionInstaller > > WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations > > WARNING: All illegal access operations will be denied in a future release can anyone help me with this ? Please let me know if any infomration required by my side.
Looks like you're using a Java 9 or higher version. According to their docs they only support JDK8 (and recommend Azul Zulu)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, talend" }
$G_n(\mathbb{R}^{\infty})$ as a subspace $G_n(\mathbb{C}^{\infty})$ I'm trying to understand how $G_n(\mathbb{R}^{\infty})$ is a subspace of $G_n(\mathbb{C}^{\infty}).$ My issue is that the first is the set of $n$-planes over a real vector space, while the second is over a complex vector space, making it equivalent instead to oriented $2n$-planes, so how can the former be a subspace of the latter?
I think the embedding is given by tensoring with $\Bbb C$. We can identify $\Bbb C^\infty = \Bbb R^\infty \otimes_{\Bbb R} \Bbb C$. Under this identification, the map $\text{Gr}_n(\Bbb R^\infty) \to \text{Gr}_n(\Bbb C^\infty)$ is given by $V \mapsto V \otimes_{\Bbb R} \Bbb C \subset \Bbb R^\infty \otimes_{\Bbb R} \Bbb C$. This is clearly injective and it's not terribly hard to see that it's continuous, though a little more care must be taken (that I am not going to take) to see that it's an embedding.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "general topology" }
Wordpress: what is the coindtitional tag for custom taxonomies? I'm learning wordpress. In my archive.php I've several conditional tags such as : if ( is_category() ) { ... } elseif ( is_tag ) { ... } elseif ( is_month) { ... } and so on PROBLEM I can't find a conditional tag to recognize custom taxonomies. What's the conditional tag for a custom taxonomy named 'zones'?
Archive.php is basically a catch-all according to the template hierarchy. Your taxonomy page should be `taxonomy-zones.php`. The function you are asking about is `is_tax()`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "wordpress" }
C# learning resources for PHP developers I am a PHP developer however I'm looking widen my skill set. Can anyone recommend some good resources? (Online would be awesome but not necessary :) ) What are the biggest differences? Any help is appreciated.
I think the main difference is that C# is usually compiled (in a windows platform), whereas PHP is usually interpreted. C# is closer to Java in syntax, and is much more strongly typed than PHP (which is loose, weakly typed - you don't have to declare variables, etc). If you're looking for great tutorials on C# I would personally look for books, since fundamentally valuable beginner-to-savvy instructions are more nicely consolidated in them than online. You can look at this post on SitePoint.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c#, php, .net" }
How can I allow a literal dot in a Perl regular expression? I use this condition to check if the value is alphanumeric values: $value =~ /^[a-zA-Z0-9]+$/ How can I modify this regex to account for a possible dot `.` in the value without accepting any other special characters?
$value =~ /^[a-zA-Z0-9.]+$/
stackexchange-stackoverflow
{ "answer_score": 25, "question_score": 16, "tags": "regex, perl" }
query in Sql with JDBC In my table, I have taken capacity in this form. `capacity DECL(3,0) UNSIGNED Is it correct??I am not sure if the above method is correct to do it in this way? if I have to do it with PreparedStatement, how would it work?
First of all your SQL query is incorrect. SELECT max(f.capacity)-COALESCE(SUM(r.num_seats),0) AS seats_avail FROM flights f, reservations r WHERE f.flight_no="CSC585" AND r.flight_no=f.flight_no AND r.departure_date="2010-05-31"; Java code will looks like String sql = " SELECT max(f.capacity)-COALESCE(SUM(r.num_seats),0) AS seats_avail FROM flights f, reservations r WHERE f.flight_no=? AND r.flight_no=f.flight_no AND r.departure_date=?"; final PreparedStatement stmt = connectionHolder.prepareStatement(sql); stmt.setString(1, "CSC585"); stmt.setString(2, "2010-05-31"); ResulSet rs = stmt.executeQuery(); while ( rs.next() ) { String seats = rs.getString("seats_avail"); System.out.println(seats ); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "sql, mysql, jdbc" }
Heroku Won't Run "Rake" Commands !enter image description here This literally just happened, and won't go away -- anyone had any similar experiences or a fix? Many thanks!
You need to use `heroku run` to run your rake commands but don't do it with assets:precompile. That happens already when you deploy. If you need to precompile your assets, do it locally, commit the compiled files and deploy to heroku.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "ruby on rails, heroku, ruby on rails 4, rake" }
How to override attribute from embedded column is superclass I'm trying to override a property of an embedded column existing in the superclass of an entity. My entities look like this: @Embeddable public class Key { @Column private String a, @Column private String b } @MappedSuperclass public abstract class Superclass { @EmbeddedId private Key key; } @Entity @Table(name = "my_entity") @AttributeOverride(name = "b", column = @Column(name="renamed_b")) public class MyEntity extends Superclass { } I have tried using AttributeOverride on MyEntity, but it doesn't do anything. It would work if I would move the AttributeOverride annotation on the embedded field, but I cannot modify the superclass. Is there any solution?
Look, read documentation carefully: > To override mappings at multiple levels of embedding, a dot (".") notation form must be used in the name element to indicate an attribute within an embedded attribute. The name `"b"` is incorrect. You should use `"key.b"` @Entity @Table(name = "my_entity") @AttributeOverride(name = "key.b", column = @Column(name="renamed_b")) public class MyEntity extends Superclass }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, hibernate" }
Proving that there is no invertible matrix with zero row sums using determinants I have the following question which I know I should use the **determinant** to solve. Here it is: > Determine if there exists an invertible $3\times3$ matrix $A$ such that $$\begin{align*} a_{11}+a_{12}+a_{13}&=0 \\\ a_{21}+a_{22}+a_{23}&=0 \\\ a_{31}+a_{32}+a_{33}&=0 \end{align*}$$ I know that the answer is no, that there is no such matrix, but I’d like to know how to solve this question with **determinants**.
The determinant is invariant under adding single multiples of one column to another. So using this we can add Column $2$ to Column $1$. Then add Column $3$ to Column $1$. This results in a column of zeroes. Hence, the determinant of $A$ is $0$ so it cannot be invertible.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "linear algebra, matrices, determinant, inverse" }
How to select count of particular rows in Oracle? I am writing a query like this... select consumer_name,count(select * from consumer where product='TTT') from consumer; I want filtered count... What will be perfect query for this?
Maybe something like this: select consumer_name, ( SELECT COUNT(*) FROM consumer AS tbl WHERE tbl.product='TTT' ) from consumer;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, database, oracle" }
Confusion about a definition in Bourbaki Algebra I am currently reading Bourbaki Algebra and in section 2 of chapter one they define when two ordered sequences are similar as this: Two ordered sequence $(x_i)_{i \in I}$ and $(y_k)_{k \in K}$ are similar if there exists an **ordered set isomorphism** $f$ of $I$ onto $K$ such that $y_{f(i)} = x_i$ for all $i \in I$. What do they mean by ordered set isomorphism? Do they mean that the function is an ordered set? If so why do they go on and endow the function with an ordered relation? *Note: Definition of ordered sequence $(x_i)_{i \in I}$ is a finite family of elements of $E$ whose index $I$ is totally ordered set.
Asserting that $f$ is an ordered set isomorphism means that $f$ is a bijection such that both $f$ and $f^{-1}$ preserve the order (that is $x\leqslant y\implies f(x)\leqslant f(y)$).
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "abstract algebra, sequences and series, elementary set theory, order theory" }
Git: Undoing rewrite of history? I have a problem with the following situation: * several commits are pushed to a remote (our codereview system) * developer has rewritten history (edited some commit during a rebase) locally * when attempting to push again, codereview does not accept it (as this change can already haved passed review) How can I 'reset' a -single- commit to what is in this remote? The modified commit is not always HEAD, so I cannot simply do 'git reset --hard HEAD^ && git pull'. edit: Preferably the diff between the two versions are created as a new commit, but it is not really a necessity.
Check the reflog with: git reflog Then pick the HEAD that corresponds to the commit of your choice, e.g. git reset --hard HEAD@{5} would reset your branch to the point HEAD pointed at five commits ago.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "git, rebase" }
How to use a specific path to write/read data to firestore in flutter I wanted to use dynamic paths selected by the user in my app to access/write data to my db. Sort of like a file path that the user can type, Eg: "users/mike/age". Using this string, I need to fetch as well as write data to the path in the db. Is there any way this is possible??
Kind of strange, but you could split the string then refactor with firebase path. String pathStr = 'users/mike/age'; List<String> list = pathStr.split('/'); //now we have a list with the fields. var ref; switch (list.length) { case 0: break; case 1: ref = FirebaseFirestore.instance.collection(list[0]); break; case 2: ref = FirebaseFirestore.instance.collection(list[0]).doc(list[1]); break; case 3: ref = FirebaseFirestore.instance.collection(list[0]).doc(list[1]).collection(list[2]); break; case 4: ref = FirebaseFirestore.instance.collection(list[0]).doc(list[1]).collection(list[2]).doc(list[3]); break; default: ref = null; } //Do whatevar with the ref path.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "flutter, firebase, google cloud firestore" }
Using natural identifiers (like an e-mail address) Is there a particular reason why you wouldn't use a natural identifier like an e-mail address? Currently I use Java's UUID class to create unique identifiers but for some objects they have a natural key - like a user and their e-mail address. It would make more sense (and make my code cleaner) if I used their e-mail address but I wondered if there was any particular reason you shouldnt? Thanks **UPDATE** I am using MongoDB in this particular case.
Natural identifiers are often not constant. For example, I've updated my email address a few times over the past 20 or so years, yet I'm still the same person. It _is_ reasonable to have an index on the email address column though; after all, people don't change them very often…
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "database" }
How to make these triangles into quads I have these triangles I need to make into quads, I'm confused how to achieve this. ![enter image description here](
Not sure what you mean by "triangles", there's only one, the rest showing are quads (and two n-gons). That having been said, this is one of the standard ways to change a tri like that to a quad: ![enter image description here]( That won't be the best topology for all circumstances, but without anything else to go on? That's how I'd do it. If you wanted all-quads: ![enter image description here]( That makes two E-poles or 5-poles, indicated by the green arrows. Another potential all-quads solution would be: ![enter image description here](
stackexchange-blender
{ "answer_score": 8, "question_score": 5, "tags": "topology" }
delete a submitted changelist from perforce history I accidentally submitted a wrong changelist to my perforce server. I then backed out that changelist using the "backout changelist" option. But, these two changes appear in the history of all those affected files that they were once deleted and then added back again. I want to be able to delete the history from perforce server of these two changelists. Is it possible. Can it be done via some Perforce administrator command. EDIT: I have seen `p4 change -d -f` which can delete a changelist but this requires to use p4 obliterate on the files which were there in the changelist. Does this mean that I have to obliterate all the files which were affected by the changelist. This doesnt seem a viable solution for me as I do not want to delete those files. Should I only obliterate those specific two revisions of the files due to the two submitted changelists?
Your perforce administrator could call `p4 obliterate` to completely wipe out files, revisions and history. But I'd strongly advise not to do so. It's a perfectly normal thing to rollback files/changes and to see the history of it. In case you still decide to use `p4 obliterate` make sure you call it without the "-y" option first (preview) and then (if the output of what perforce says will happen is ok) call the same command with the "-y" option (to actually perform the obliterate). If you call `p4 obliterate` with a file revision (e.g. `p4 obliterate //depot/dir/file#5`) then only the changes and history of that revision will be removed leaving all previous revisions and history intact. You can also obliterate a revision range.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 8, "tags": "perforce, changelist" }
Powershell to get template name site is using I have a site collection `http:/SC/` under which I have a site `http:/SC/site`. Can you provide powershell to check which template `http:/SC/site` is using?
You mean like this? $web = Get-SPWeb http:/SC/site $web.WebTemplate + " " + $web.WebTemplateId $web.close()
stackexchange-sharepoint
{ "answer_score": 18, "question_score": 10, "tags": "powershell" }
How to parse JSON data without key names into a Java class structure? I successfully followed the example Simple Spring code to parse JSON into a Java class structure using Jackson. Now i am looking for a hint how to do the same for JSON data without key names, e.g. { "10869918": { "BRANCH": "Dienstleistungen", "SECTOR": "Diverse" }, "12254991": { "BRANCH": "Luft- und Raumfahrtindustrie", "SECTOR": "Logistik" }, "12302743": { "BRANCH": "Touristik und Freizeit", "SECTOR": "Medien/Freizeit" } }
I doubt this is possible with a POJO-JSON mapper. You could use libraries like json-simple to parse the JSON string into Java objects (which basically are maps and lists) and access values like `"10869918"` by reading the keys of those maps.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, json, jackson, anonymous types, class structure" }
Springsource Tool Suite UML plugin Is there an open-source "UML Modeling" plugin for Spring source Tool Suite? I tried installing UML2 plugin provided for Eclipse but it doesn't seem to work. After some googling, I found Object Aid which isn't licensed open source software! Is there any other plugin available? Regards Surekha
UMLet works fine, but it can be used to make diagrams from scratch. It does not create class diagrams from java classes though!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 4, "tags": "spring, eclipse plugin, uml" }
NSPredicate interpreting a keyPath instead of a property I have a `Core Data` database of `Recipes`. Each `Recipe` has an `ingredients` relationship (many to many), so my `XYZRecipe` object has a `ingredients` property that points to an `NSSet` of `XYZIngredients`. I want an `NSPredicate` to select all the `Recipes` that have more than 5 `ingredients` and tried this: NSPredicate *p = [NSPredicate predicateWithFormat:@"ingredients.count > 5"]; This fails, and complains that the class `XYZIngredient` is not key value compliant for `count`. Clearly `"ingredients.count"` is being interpreted as a `keyPath` instead of returning the `ingredients` property of each recipe. Is there a way around this?
It should be possible to solve that problem on KVC side and on Core Data side: KVC: @"ingredients.@count > 5" Should deliver the count of ingredients as the result of the key path. Core Data: @"ingredients[SIZE] > 5"
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "objective c, core data, nspredicate" }
Curl error: Operation timed out I have the following fatal error when trying to use Curl: PHP Fatal error: Uncaught HTTP_Request2_MessageException: Curl error: Operation timed out after 30000 milliseconds with 0 bytes received in /usr/share/php/HTTP/Request2/Adapter/Curl.php on line 200 Exception trace Function Location 0 HTTP_Request2_Adapter_Curl::wrapCurlError('Resource id #12') /usr/share/php/HTTP/Request2/Adapter/Curl.php:200 1 HTTP_Request2_Adapter_Curl->sendRequest(Object(HTTP_Request2)) /usr/share/php/HTTP/Request2.php:959< in /usr/share/php/HTTP/Request2/Adapter/Curl.php on line 172 However, I can't see how to best debug it. There's no reference to any line of code I've written, only the `HTTP_Request2` and `Curl` modules. What's the best approach to try and resolve this?
Your curl gets timed out. Probably the url you are trying that requires more that 30 seconds. If you are running the script through browser, then set the `set_time_limit` to zero for infinite seconds. set_time_limit(0); Increase the curl's operation time limit using this option `CURLOPT_TIMEOUT` curl_setopt($ch, CURLOPT_TIMEOUT,500); // 500 seconds It can also happen for infinite redirection from the server. To halt this try to run the script with follow location disabled. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
stackexchange-stackoverflow
{ "answer_score": 44, "question_score": 20, "tags": "php, curl" }
Ansible: How to recursively set directory and file permissions In ansible, I can do this: file: dest=/foo/bar/somedir owner=root group=apache mode=0775 recurse=yes And it recursively sets the owner, group, and permissions to 0775 on all directories and files in that path. But I want to set directories to 0775, and files to 0664. Is there some way to make ansible do this?
file: dest=/foo/bar/somedir owner=root group=apache mode=u=rwX,g=rX,o=rX recurse=yes will set directories to 755, and files to 644.
stackexchange-superuser
{ "answer_score": 83, "question_score": 83, "tags": "file permissions, ansible" }
How to view contents of an array while debugging in Code Blocks? This is probably a silly question and i am posting this Post-Googling, The question is, > `How do i view the contents of an array while debugging, Provided the Breakpoint is in function not Main?` I am using code::blocks 13.12 version and i set a break point in my sample simple c++ code, and i want to observe how the contents of the array change with the code but **all i see is the the address of the array under watch window,** It is however displaying the values of other integer variables correctly, !enter image description here a is an array I forgot to mention that i am tracking the array in a function and not in main,and i am aware that main passes the address of the array to the function being called(by reference i meant) I am relatively new to codeblocks, Am i missing some setting or something?
i am using 12.11. I select the array variable suppose a, choose "watch a" in the right button down menu, and I can see the values in the array a.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 8, "tags": "c++, arrays, debugging, codeblocks" }
Why are there so many formats for local IP address? If I enter the following command in CMD prompt... netstat -ano I get a list of active connections as expected. What confuses me is that there are many different formats for my "Local Address"... Proto Local Address Foreign Address State PID TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 656 TCP 208.80.154.224:13 0.0.0.0:0 LISTENING 4 TCP 127.0.0.1:2559 0.0.0.0:0 LISTENING 8628 TCP [::]:135 [::]:0 LISTENING 656 UDP [::1]:1900 *:* 4512 For a particular connection, what determines which format is used for my "Local Address"? i.e. why is 0.0.0.0 displayed for some connections and [::] displayed for other connections, and so on?
netstat shows which ip adresses and ports are being listened on, because a program requested this. 0.0.0.0 means: any IP4 address. 208... is your public ip address that is being listed on. 127.0.0.1 is your local ip address, also known as local host, which would indicate that the program needs to open a port, but only does this so it can connect to itself. 192. (or whatever your network ip address would be) is for LAN connections only. :: is an IP v6 address which means: it listens to any ip v6 address, similar as 0.0.0.0 ::1 is ipv6's version of local host, similar to 127.0.0.1 meaning that its only used for communication to itself. The PID is the program that initiated the command. You can find this number in the task manager under processes.
stackexchange-superuser
{ "answer_score": 2, "question_score": 0, "tags": "networking, ip" }
What are ways to solve Memory Leaks in C# I'm learning C#. From what I know, you have to set things up correctly to have the garbage collector actually delete everything as it should be. I'm looking for wisdom learned over the years from you, the intelligent. I'm coming from a C++ background and am VERY used to code-smells and development patterns. I want to learn what code-smells are like in C#. Give me advice! What are the best ways to get things deleted? How can you figure out when you have "memory leaks"? * * * Edit: I am trying to develop a punch-list of "stuff to always do for memory management" * * * Thanks, so much.
C#, the .NET Framework uses Managed Memory and everything (but allocated unmanaged resources) is garbage collected. It is safe to assume that managed types are always garbage collected. That includes `arrays`, `classes` and `structures`. Feel free to do `int[] stuff = new int[32];` and forget about it. If you open a file, database connection, or any other unmanaged resource in a class, implement the IDisposable interface and in your Dispose method de-allocate the unmanaged resource. Any class which implements IDisposable should be explicitly closed, or used in a (I think cool) Using block like; using (StreamReader reader = new StreamReader("myfile.txt")) { ... your code here } Here .NET will dispose reader when out of the { } scope.
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 10, "tags": "c#, .net, memory leaks, garbage collection" }
Statements regarding relations in R Suppose $\rho$ is a relation on $R$. I want to verify whether the following statements are true. Looks simple but proving them seems to be difficult for me. * $\rho\circ\rho$ is a subset of $\rho$ * $\rho\circ\rho=\rho$ implies $\rho=i_{D(\rho)}$ ($D(\rho)$ being the domain of $\rho$) * $\rho=\rho^{-1}$ implies $\rho=i_{D(\rho)}$ I believe the second point is false considering the counter example constant function but I need help with the other statements.
All of them are false. For the first, let $\rho = \\{(a,b),\,(b,c)\\}$ For the second, let $\rho = \\{(1,1),\,(3,3),\,(1,3),\,(3,1)\\}$ For the third, let $\rho = \\{(0,1),\,(1,0)\\}$
stackexchange-math
{ "answer_score": 2, "question_score": -2, "tags": "elementary set theory, relations" }
Update table from itself, but only top result So if we have a table with the following: Id INT EventDate DATETIME NextDate DATETIME UserId INT I want to update the next date value from the same table and set the `NextDate` value to the date of the next entry related to that user. Below is the basic query, but I'm not sure how to tell it to update it from the next occurring `EventDate` UPDATE EVENTS SET NextDate = n.EventDate FROM EVENTS AS n WHERE EVENTS.UserId = n.UserId
I would use the `lead()` function (available in SQL Server 2012+): with toupdate as ( select e.*, lead(eventdate) over (partition by userid order by eventdate) as next_eventdate from e ) update toupdate set nextdate = next_eventdate; Note: this should be much more efficient than alternative methods using joins, correlated subqueries, or `apply`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jquery, sql, sql server, tsql, sql update" }
How to automate a table that holds deletions? So as I have it now, I have a table called Registrant that holds everything that is live. If a user deletes a record, it moves the row to the RegistrantDelete table. The problem is, if I make any edits to the Registrant table (IE a new column) then I have to also make the same edits in the RegistrantDelete table. Is there some easy way to automate this deletion table to be the same setup as the original table?
You could do this with a DDL trigger. But James' comment of doing "soft deletes" is how I would handle this, personally.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, sql server, database" }
Intervals of Convex and Concave function > Find the intervals where the function is convex and concave. $$f (x) = e^{2x} - 2e^x$$ I tried differentiating twice, and my answer is: concave when $x < \ln (1/2)$ and convex when $x > \ln (1/2)$. However the key says the other way around...
$f'(x) = 2e^{2x} - 2e^x \to f''(x) = 4e^{2x} - 2e^x$. $f$ is concave if $f''(x) < 0$, and is convex if $f''(x) > 0$. $f''(x) < 0 \iff 2e^x\left(2e^x - 1\right)<0 \iff 2e^x - 1 < 0 \iff e^x < \dfrac{1}{2} \iff x < \ln\left(\dfrac{1}{2}\right)=-\ln 2$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "calculus, derivatives, exponential function" }
If the probability of current flowing in circuit is known, how can I know the probability that a certain bulb will work? Here the schema is very important:![enter image description here]( The probability that a bulb will work is 0,5. The probability that the current will flow in circuit is 0,3984375. What is the probability that the bulb C will work. It is clear from the schema, that in order for current to flow $e$ or $f$ or $(a \lor b) \land c \land d$ must work. So if it is known that current flows it is $1/3$ chance that the $(a \lor b) \land c \land d$ works. But I don't know where to go from here.
In my answer to your previous question, we found that $$p(w)=\frac{51}{128}$$ where $w$ is the event "the current flows" in the given circuit. By using the same approach, if $c$ works then $$p((a\lor b)\land c\land d)=\left(1-\left(\frac{1}{2}\right)^2\right)\cdot 1\cdot \frac{1}{2}=\frac{3}{8},$$ and therefore $$p(w|c)=\frac{1}{2}\cdot\left(1-\left(1-\frac{3}{8}\right)\cdot \left(1-\frac{1}{2}\right)\cdot \left(1-\frac{1}{2}\right)\right)=\frac{1}{2}\cdot\left(1-\frac{5}{32}\right)=\frac{27}{64}.$$ Hence, it follows that $$p(c|w)=\frac{p(c)\cdot p(w|c)}{p(w)}=\frac{\frac{1}{2}\cdot \frac{27}{64}}{\frac{51}{128}}=\frac{27}{51}\approx0.529$$ which is a bit greater then $p(c)=0.5$.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "probability, independence" }
How does OpenCV function Grab work in Windows? I am trying to understand the low-level functionality of the OpenCV function grab, in particular I want to understand what OS functions it calls in windows. I am having a hard time tracking down what actually happens in the source code, I went to the videoio source code but it doesn't have any windows specific calls in it. Can someone explain or link me to the functions OpenCV actually calls when interacting with USB cameras on USB machines?
just look at those files, < < opencv uses Windows MediaCapture Class <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "windows, opencv" }
RecyclerView добавление как удалить\изменить\добавить один пункт списка, не перезагружая список У меня есть `RecyclerView`. Мне нужно реализовать удаление, изменение и добавление по пункту списка (просто `TextView`). Если с изменением все понятно — просто получаю и изменяю `View`, то как можно удалить и добавить только один пункт, не перезагружая весь список?
1. Добавьте/удалите элемент в/из список(-ка) данных, отображаемых адаптером. 2. Вызовите `notifyItemInserted(int positionOfInsertedElement);`/`notifyItemRemoved(int positionOfRemovedElement);` метод адаптера.
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "android" }
Add an output to a non built-in MatLab function I have downloaded a non built-in MatLab function, on MatLab file exchange. This function is "struct2table" (for MatLab Version >2013 this function is implemented as a built-in, unfortunately my MatLab version is 2012). With this function I would like to create an output on my workspace that could be usable afterwards. Unfortunately the code I have downloaded (on < ), is not able to produce any workspace output. Does anyone as an idea about how to change this function in order to produce an output in the workspace?
# Modifying Function To make the function `struct2table` output something you need to change the line function struct2table(varargin) to function [output1, output2, ...] = struct2table(varargin) without the `...`. _They are present just to show you can have multiple outputs._ The names `output1`, `output2` and so on should be the same as the variables you want to retrieve from the function. For example it could be `formatString` or `fprintfArgs`. # Calling Function Then when you call `struct2table` you can retrieve only the first output argument with output1 = struct2table(...) or more of the output arguments with [output1, output2, ...] = struct2table(...)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "matlab, struct, output" }
Making minimum number of partitions of a set Let us consider a set in which every element has an ordered pair of natural number (x,y)( Each pair is distinct) associated with it. Let us define a partition of a set to be consisting of elements such that one of the numbers from the pair (i.e either x or y is same throughout the partition ) . We have to partition the set into minimum number of components such that union of all the components is the set itself. How can we find the minimum number of components into which set can be partitioned.
If either all x or all y values in the set are distinct, you are done. Otherwise: 1. Construct a bipartite graph with vertices in A representing the values of x and vertices in B representing the values of y. 2. Each edge represents the ordered pair. You need to find the minimum vertex cover for a bipartite graph. This can be done by Konig's theorem, Wikipedia gives a good explanation of the algorithm.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "combinatorics, elementary set theory, graph theory, algorithms" }
Beta testing issue in iTunes connect When build uploading to testflight its working fine. Facing issue when app sharing to users by beta testing. Please check the issue in the bellow attachment. ![enter image description here](
I got the solution last comment from below attached link. I hope it helpful to you friends. <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios, itunes, testflight, applepay, beta testing" }
Is there an "exists" function for jQuery? How can I check the existence of an element in jQuery? The current code that I have is this: if ($(selector).length > 0) { // Do something } Is there a more elegant way to approach this? Perhaps a plugin or a function?
In JavaScript, everything is 'truthy' or 'falsy', and for numbers `0` means `false`, everything else `true`. So you could write: if ($(selector).length) You don't need that `>0` part.
stackexchange-stackoverflow
{ "answer_score": 2743, "question_score": 3104, "tags": "javascript, jquery" }
How to extract only two fields using Regular Expression In TCL I am writing the regular expression for below output: Output args is packet-filter 0 identifier 0 direction bidirectional network-ip 10.7.98.231/32 ue-port-start 0 ue-port-end 0 nw-port-start 0 nw-port-end 0 protocol 1 precedence 0 packet-filter 1 identifier 1 direction uplink network-ip 10.7.98.231/32 ue-port-start 0 ue-port-end 0 nw-port-start 0 nw-port-end 0 protocol 1 precedence 0 Output of my Regular Expression : `regexp -all -inline {direction\s+(\S+)} $args` is {direction bidirectional} bidirectional {direction uplink} uplink I need to extract the direction value which is `bidirectional` and `uplink` Any suggestion ?
For the current case, where the captured substrings are chunks of non-whitespace text, you may re-build the output checking if each item has length set to `1`: set results [regexp -all -inline {direction\s+(\S+)} $args] set res {} foreach item $results { if {[llength $item] == 1} { lappend res $item } } Then, `$res` will only hold `bidirectional` and `uplink`. See the Tcl demo. For a more generic case, you may use set res {} foreach {whole capture1} $results { lappend res $capture1 } See this Tcl demo You may add more `captureX` arguments to accommodate all the capturing group values returned by your regex.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "regex, networking, tcl" }
How to add specific value in column in in every row in dataframe here i am trying add (EA) in every record for column 1 is it possible to save value in column 1 like 1.0 Each(EA) followed by 0.0 / 0.001 (EA)... df_1 Out[46]: 0 1 0 Unit of Measure Each (EA) 1 Conversion 1.0 Each 2 Net/Gross Weight (lbs) 0.0 / 0.001 3 Volume (cubic ft) 0.0 4 Shipping Dimensions (inch) L x W x H 0.589 x 0.589 x 0.589 5 GTIN NaN
Use: df['1'].apply(lambda x: str(x) + '(EA)' if '(EA)' not in str(x) else x) if the name of column not is a `str` then use: df[1].apply(lambda x: str(x) + '(EA)' if '(EA)' not in str(x) else x)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, pandas" }
Symfony 1.4 preUpdate method never firing I've got the following model class: class ContractDetails extends BaseContractDetails { public function updateContractDetailsByConId($conId, $key, $value) { $q = Doctrine_Query::create() ->update('ContractDetails'); if ($value === null) { $q->set($key, 'NULL'); } else { $q->set($key, '?', $value); } $q->where('cd_con_id = ?', $conId) ->execute(); return $q; } public function preUpdate($values) { $test = "test"; } } What I want is to run some code before the "updateContractDetailsByConId" method row is updated. From my investigations I should be able to use the built in hooks i.e. preUpdate But the preUpdate method is never running. Any ideas why not?
You need to hook to the DQL Callbacks when you update from a DQL query. See documentation here for more info. in your code, you need to update the `preUpdate` for public function preDqlUpdate($values) { $test = "test"; } Don't forget, as mentioned in the documentation that you need to implicitly turn the DQL callbacks on. In your ProjectConfiguration.class.php file, add: public function configureDoctrine(Doctrine_Manager $manager) { $manager->setAttribute(Doctrine::ATTR_USE_DQL_CALLBACKS, true); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, doctrine, symfony 1.4" }
Column names of a CTE in SQL Server I know it is possible to **_SELECT_** , from _sys.columns_ and from _tempdb.sys.columns_ the names of the columns of a specific table. Can the same be done from a **CTE**? with SampleCTE as ( Select 'Tom' as Name ,'Bombadill' as Surname ,99999 as Age ,'Withywindle' as Address ) is there any way to know that the columns of this CTE are **Name,Surname,Age** and **Address** , without resorting to dumping the CTE result to a temporary table and reading the columns from there? Thanks!
Here is a "dynamic" approach without actually using Dynamic SQL. Unpivot (dynamic or not) would be more performant **Example** with SampleCTE as ( Select 'Tom' as Name ,'Bombadill' as Surname ,99999 as Age ,'Withywindle' as Address ) Select C.* From SampleCTE A Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData) Cross Apply ( Select Item = a.value('local-name(.)','varchar(100)') ,Value = a.value('.','varchar(max)') From B.XMLData.nodes('/row') as C1(n) Cross Apply C1.n.nodes('./@*') as C2(a) Where a.value('local-name(.)','varchar(100)') not in ('ID','ExcludeOtherCol') ) C **Returns** Item Value Name Tom Surname Bombadill Age 99999 Address Withywindle
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "sql, sql server, common table expression" }
Why are my windows scrolling together? I have two windows open on the same buffer and I want to edit two parts of the same file at the same time. I can't because the windows are scrolling together. I have `noscrollbind` set so I am confused by this. What else could be causing this? If I start a new session then the problem goes away. I'd prefer not to have to close my session because I have memorized all the buffer numbers.
As suggested by Christian Brabandt in the comments, this was caused by the `'cursorbind'` setting. `:help 'cursorbind'`: > When this option is set, as the cursor in the current window moves other cursorbound windows (windows that also have this option set) move their cursors to the corresponding line and column. This option is useful for viewing the differences between two versions of a file (see 'diff'); in diff mode, inserted and deleted lines (though not characters within a line) are taken into account.
stackexchange-vi
{ "answer_score": 9, "question_score": 14, "tags": "gvim, scrolling, plugin fugitive" }
Нужна запятая между однородными членами предложения? Сегодня и элитарная, и народная культуры сохранили своих почитателей.
_Сегодня и элитарная, и народная культуры сохранили своих почитателей._ Запятая ставится, если однородные члены связаны повторяющимся союзом И. Исключение (отсутствие запятой) возможно при близком единстве однородных членов. В данном случае такого единства нет. Розенталь: < 2. При двух однородных членах предложения, соединенных повторяющимся союзом и, запятая не ставится, если образуется тесное смысловое единство (обычно такие однородные члены не имеют при себе пояснительных слов): Кругом было и светло и зелено (Т.); Он носил и лето и зиму старую жокейскую кепку (Пауст.); Прибрежная полоса, пересечённая мысами, уходила и в ту и в другую сторону (Сем.); Он был и весел и печален в одно и то же время.
stackexchange-rus
{ "answer_score": 3, "question_score": 2, "tags": "однородные члены" }
Update post meta - Custom field does not match meta-key I am trying to update my acf with `update-post-meta`: //ga_analytics_settings update_post_meta($my_post, 'ganalytics_settings', serialize($ganalytics_settings)); `$ganalytics_settings` is an array, which I would like to store `serialized` within the field. ![enter image description here]( However, I get the following condition is not met(taken from meta.php): function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') { global $wpdb; if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) ) { return false; //I am getting here in, but I do not know why. } Any suggestions what I might do wrong? I appreciate your reply!
Arrays are serialized by default, so just do update_post_meta($my_post, 'ganalytics_settings', $ganalytics_settings); < > $meta_value (mixed) (required) The new value of the custom field. A passed array will be serialized into a string.(this should be raw as opposed to sanitized for database queries) Default: None Also, make sure that `$my_post` is post ID, not the post object. And, if you want to update ACF field, you should use it's `update_field` function. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, advanced custom fields, post meta" }
Python 3 does not split strings when encoded Here is the snippet: for eachLine in content.splitlines(True): entity = str(eachLine.encode("utf-8"))[1:] splitResa = entity.split('\t') print(entity) print(splitResa) Basically I am getting this result: '<!ENTITY DOCUMENT_STATUS\t\t\t\t\t"draft">\n' ['\'<!ENTITY DOCUMENT_STATUS\\t\\t\\t\\t\\t"draft">\\n\''] however in IDLE it all works fine: >>> '<!ENTITY DOCUMENT_STATUS\t\t\t\t\t"draft">\n'.split('\t') ['<!ENTITY DOCUMENT_STATUS', '', '', '', '', '"draft">\n'] Couldn't figure out why. I've also tried answers here: splitting a string based on tab in the file But it still does the same behaviour. What is the issue here?
Looks like `eachLine` is a raw string. >>> r'<!ENTITY DOCUMENT_STATUS\t\t\t\t\t"draft">\n'.split('\t') ['<!ENTITY DOCUMENT_STATUS\\t\\t\\t\\t\\t"draft">\\n'] So, you should either split that with a raw `\t` (`r'\t'`), like this >>> r'<!ENTITY DOCUMENT_STATUS\t\t\t\t\t"draft">\n'.split(r'\t') ['<!ENTITY DOCUMENT_STATUS', '', '', '', '', '"draft">\\n'] or with properly escaped `\t` (`'\\t'`), like this >>> r'<!ENTITY DOCUMENT_STATUS\t\t\t\t\t"draft">\n'.split('\\t') ['<!ENTITY DOCUMENT_STATUS', '', '', '', '', '"draft">\\n']
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, string, python 3.x, split" }
How to write a voltage in phasor form (using a reference-voltage) **I have the following problem:** Consider two voltages described by > v1 = 325 sin(wt+10º) V > v2 = 326 sin(wt+130º) V Write v2 in _Phasor Form_ using v1 as reference... **My Question is:** I understand that the angle will be 120º, but what will the voltage be? Below is a drawing of how I am imagining it to be from a trigonometric point of view, but maybe this is the wrong way to look at the problem? ![enter image description here](
> Write v2 in Phasor Form using v1 as reference... To find it without drawing phasors you just add/subtract \$\theta °\$ to/from **all** of your phasors where \$\theta °\$ is the angle that when added/subtracted from your reference phasor will make it \$0°\$. In your case you can subtract \$10°\$ from each phasor (thus making \$v_1\$ your reference). Making \$v_1\$ the _reference_ means you adjust its angle to \$0°\$. When you do this, the entire phasor diagram rotates with \$v_1\$ until \$v_1\$ is at the \$0°\$ position. For example, below on the left are two arbitrary phasors \$V_X\$ and \$V_Y\$. On the right I have made \$V_X\$ the reference and put it at position \$0°\$. ![enter image description here]( What really matters with phasors is their **position relative to each other**. Rotating the whole group around does not change their relationship to each other. Further, you can use whatever angle you want as the reference. Some folks use \$90°\$ so it is whatever you prefer.
stackexchange-electronics
{ "answer_score": 2, "question_score": 0, "tags": "power electronics, electromagnetism" }
Starting a forever process in a Jenkins build step? I'm running a shell command at the end of a Jenkins deployment to restart a forever script: npm install && forever stop app.js && forever start -a -l /var/log/forever.log app.js When I run that as a user jenkins everything works fine and the console output from the build history also tells me that the forever script is running. However, the process stops right after the deployment is finished and the forever process is stopped. What causes this behavior and how can I fix it?
Jenkins kills all process spawn by the job. This can be disabled by setting the `BUILD_ID` environment variable to something else: export BUILD_ID=dontKillMe see < for details
stackexchange-serverfault
{ "answer_score": 29, "question_score": 18, "tags": "deployment, node.js, jenkins" }
Whats the best way to compile a jsp project on linux? I am doing some web apps development with apache Tomcat in Linux platform, I usually compile my web pages by running them, tracking error through TomCat's logs. Each time I am making a modification I am reloading the project throuh TomCat manager. for the beans I am compiling them and making a new war file. I wonder how are other developers compiling their jsp files? I need some feedbacks.. Thanks,
As I understand, your biggest pain is having to reload the project every time. In our project, we deal with this problem in the following way: * when doing development, simply copy the JSP files over to `tomcat/webapps/yourapp/WEB-INF/...`. Tomcat will detect the files have changed and JSPs will be dynamically compiled. The obvious benefit is that there's no need to redeploy the app. * when done with development, check in the code. * continuous integration server has the option to precompile all JSPs so if by any chance you left an error, you will get notified. If you don't have continuous integration, you can simply create a script that checks out the source code every night and attempts to statically compile the JSPs. If you need more information on static compilation, check out Jasper documentation.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "jsp, tomcat" }
Trying to navigate to page location when selecting option from select options dropdown so I have a select box like this with more elements being loaded in of course. <select class="cherry-dropdown"> <option class="cherryOption" value="#cherry_'.$rownum.'">'.$name.'</option> </select> And. I'm trying to use javascript to take me to the appropriate page location based off the value attribute in the option. $('.cherry-dropdown').click(function(){ console.log("yes"); $('.cherryOption').click(function(){ console.log("maybe"); window.location=$(this).val(); }); }); I'm getting yes from the first console.log (opening the select box to reveal the options). But when I click an option I'm not getting the maybe console.log, and thus the window.location part isn't working as well. What am I doing wrong here...
You only actually need one event listener here, if you target the select menu itself (.cherry-dropdown) and listen for a `change` event instead of `click`, and then by passing the event as a argument to access it's value. $(".cherry-dropdown").change(function (e) { console.log(e.target.value); //Returns the selected options value window.location = $(this).val(); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript" }
Computing a linear recurrence relation in modular arithmetic If we have a linear recurrence relation: $$F_{i+k} = c_0 F_{i} + c_1 F_{i+1} + \dots + c_{k-1} F_{i+k-1}$$ we can easily find an analytic formula for $F_i$ via the characteristic polynomial and initial conditions. However, how would one compute $F_i \mod m$? It is easy to see that $F_i \mod m$ must be periodic with period no larger than $m^k$, but I'm not sure it's even meaningful to solve the characteristic polynomial in the ring mod $m$. Specifically, with $F_i$ defined as $$F_{i+2} = F_{i+1} + 3F_i$$ $$F_0 = F_1 = 1$$ it is asked to compute $F_{30000} \mod 31$ without the help of a calculator. Is it possible to do without brute-forcing the sequence period by evaluating first $31^2$ terms by hand?
$F_n \equiv t^n \mod m$ is a solution if $t$ is a root of the characteristic polynomial mod $m$. In this case ($m = 31$, characteristic polynomial $p(x) = x^2 - x - 3$) the characteristic polynomial has no root in the field $\mathbb F_{31}$, so you go to an extension field where you get your two roots. Alternatively, you might try computing some terms, and notice that $F_{8} \equiv F_{9} \equiv 12 \mod 31$. What does that tell you about $F_{8n}$?
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "modular arithmetic, recurrence relations" }
Piping parts of a file to a command that requires multiple inputs Often when doing some things in my Unix shell, I would like to pipe a part of one file to a particular command, such as: cut -f1 file1 | perl -pe 's/foo/bar/' I like this because it means I don't have to have a whole other file just for column 1 of `file1`. Though, I run into problems when I want to do a command that takes in multiple sets of input such as `join` . I wish I could do something like: join (cut -f1 file1) (cut -f1 file2) Is there some way to do this nicely without creating unnecessary files?
Perhaps this: join <(cut -f1 file1) <(cut -f1 file2) That assumes you're using `bash` as a shell, though...
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "unix, pipe" }
Mysql NOW() and PHP time()? I am salting users' passwords with a mysql column which has the type timestamp and default is CURRENT TIMESTAMP. Both of my timezones for mysql and php are identical. My problem is this, $q = $dbc -> prepare("INSERT INTO accounts (password) VALUES (?)"); $q -> execute(array(hash('sha512', 'somestaticsalt' . $_POST['password'] . time()))); Now as you can see I have to hash with PHP's time function and on the mysql side it is a default timestamp. Somewhere there must be an overlap because where users' are entering correct information it is still failing to match the hashed password in the database. I have tried inserting time() into the joined column but it returns at 1970. Also I do not want to save the timestamp as an INT as this isn't the correct thing to do, so what is your thoughts?
Your salt really should be random. A small improvement on your code (you could do a lot better, like use bcrypt or at least some stretching on sha512): $salt = md5(time() . 'some-other-static-salt'); //more random than time() along. $q = $dbc -> prepare("INSERT INTO accounts (password, salt) VALUES (?, ?)"); $q -> execute(array(hash('sha512', 'somestaticsalt' . $_POST['password'] . $salt), $salt)); Now you're no longer depending on CURRENT_TIMESTAMP returning the same thing as time(), and you've got a better salt. EDIT: if you insist on doing it your way, look at what mysql returns for that timestamp column. I bet it looks like "Y-m-d H:i:s" and not like a unix timestamp. Of course, you should have been able to figure that out yourself. Assuming that's true, wrap it in strtotime and you might have some success.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "php, mysql, time" }
How to enter value on textbox using php and get it by javascript I want to be able to have a text box on a page where php writes into and javascript read from I saw this solution How can I set the value of a textbox through PHP? use it and I manage to write the value on the textbox using this command <input type=\"text\" name=\"txtFromPHP\" value=\"" .$row['id'] . "\"> but when I access the textbox usng this var str = document.getElementById('txtFromPHP').value; I get error document.getElementById("txtFromPHP") is null Just maybe it's relevant, my html page where textbox is placed is a modified version of Ajax Database example found at < Thanks
You need to set the element ID as follows <input type=\"text\" id=\"txtFromPHP\" name=\"txtFromPHP\" value=\"" .$row['id'] . "\"> In your example you only set the name of the element `txtFromPHP` and did not set an ID
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, getelementbyid" }
Hyperlink vs Button Searching for input about UI design patterns regarding the use of hyperlinks vs buttons. A screen in a web application should/could have a mix of buttons and hyperlinks on it. It seems that the 'look' is the major governing factor as to which is used, but I want something more logical than that. Does anyone know of any hard and fast rules about when to use each one? Do you have guidelines of your own that you'd like to share? Thanks.
Links go places. Buttons send data places. In a nutshell, if you have form data, have a button. Otherwise, don't.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "design patterns, user interface" }
Excel Array Functionality for Cross Check I have 2 columns in my Excel File. First column is called Planned Q and has values separated by Comma. The second column is called Current Q and it has only one value. As per below screen, I want to check if any of A2 value is in B2 value it should find/call a MATCH otherwise it is Mis-Match. How can I perform this task? ![enter image description here]( Thank you for your help!
Use SEARCH: =IF(ISNUMBER(SEARCH(B2,A2)),"Match","Mis-Match")
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "arrays, excel, excel formula, cross reference" }
Why does this MVC action return a 404 response in IE11 I have written an mvc action that works in Chrome and Firefox but not in IE11. Using IE11 it returns a 404 response code. Controller: [HttpDelete] public ActionResult DeleteAction(int ActionID) { return Json(_Logic.DeleteAction(ActionID), JsonRequestBehavior.DenyGet); } Calling JS: Ajax_Proxy.DeleteAction = function (_actionID, successCallback, failureCallback) { return $.ajax({ type: "DELETE", datatype: 'json', url: "/root/someurl/DeleteAction?ActionId=" + _actionID, contentType: 'application/json; charset=utf-8', success: function (data) { successCallback(_actionID, data); }, error: function (data) { failureCallback(data); }, }); }; The Url I am accessing is correct, as it works in other browsers. Has anyone seen this before?
Beacuse you say that it works in Chrome and Firefox I assume you enabled `PUT/Delete` methods on the IIS? If yes, I think this may be problem that some IE browsers doesn't support `type: "DELETE"` in Ajax calls. Maybe you are using compability mode to IE8 or something like that? This problem was already mentioned on SO here: Problem with jQuery.ajax with 'delete' method in ie maybe you just discover that IE11 also doesn't support `DELETE`. Another one good discusion Are the PUT, DELETE, HEAD, etc methods available in most web browsers?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ajax, asp.net mvc, routes" }
jQuery using the .delay() method in an .each() loop With the following code I want the li elements to fade in one by one, but the all fade in together: $('li').each(function () { $(this).delay(1000).fadeIn(1000); }); Can anyone explain why they do not fade in one by one?
The `.delay` call doesn't stop the loop from carrying on immediately, so all of the delays and animations will start (pretty much) at once. The most trivial solution is to stagger the delay by the current index number: $('li').each(function(index) { $(this).delay(1000 * index).fadeIn(1000); }); A better solution would use a pseudo-recursive loop and the "completion callback" of the animation to trigger the next iteration: var els = $('li').get(); (function loop() { if (els.length) { var el = els.shift(); $(el).fadeIn(1000, loop); } })(); This method is generally preferable because it ensures that the next fade-in cannot possibly start until the previous has finished, and also avoids creating multiple parallel delay / fade queues (one per element) since the 2nd animation isn't queued until the first has finished.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jquery" }
How to better position ios app in search results? You can download it here: As you can see I have a lot of positive votes (726) and almost 5.0 average;) ![enter image description here]( The question is why am I displayed to the user behind the apps that have significantly worse number of votes and worst average. ![enter image description here]( What can I do to improve position of my app?
You can try to optimize the metadata about your app (such as the subtitle, keywords, etc). Besides that and the good average rating you have, your ranking is also determined by factors such as the number of downloads, the amount of sales, how long time the app is used for, update frequency and click-through rate.
stackexchange-apple
{ "answer_score": 2, "question_score": -1, "tags": "applications, ios appstore" }
Why does the lower f-stop in my camera makes the photo darker? I have a nikon d5100 camera with 35mm/f 1.8 lens. I'm not sure what's going wrong with my camera but my photo with larger f-stop numbers is brighter than the photo with smaller f-stop numbers (the ISO and the shutter speed remain the same). Isn't that the photo supposed to be darker on bigger f-stops? Edit: I'm clearly understood with how aperture works. Just transferred the file into the computer and I have only realized that it was my fault for activating the "AUTO ISO sensitivity control" that messed up the shutter speed and the ISO for the photo I have taken. ![Auto ISO sensitivity control in my camera]( This is the link that I have referred to: < My camera is working fine after turning off it. Thank you to everyone who has given an effort in solving my problem.
> ... my photo with larger f-stop numbers is brighter than the photo with smaller f-stop numbers (the ISO and the shutter speed remain the same). Since you refer to "f-stop numbers", it appears you know how F-numbers and aperture size are related to each other. You also appear to understand the effect that changing F-numbers _should_ have on the image. When ISO and shutter speed are kept constant, it's normally expected that increasing the F-number reduces exposure, which causes the image to become darker. This is opposite what you describe. Brighter images taken with smaller aperture sizes _could_ be explained by: * Changes in scene lighting. * Settings that alter the processing of images, such as **Active-D Lighting**. The following page has sample images that show how Active-D Lighting affects the brightness of images: * Nikonites: Active D-Lighting For the D5100 * Changes to shutter speed and ISO. However, you state they did not change in your case.
stackexchange-photo
{ "answer_score": 3, "question_score": 1, "tags": "aperture" }
MySQL trigger doesn't work on table insert Maybe I'm just being dense but hopefully someone can help. I am trying to add a trigger for a DateCreated column, which fires when a row is added. When I try to add I get > Can't update table 'products' in stored function/trigger because it is already used by statement which invoked this stored function/trigger I realize from this answer that it is because MySQL won't let me trigger after the insert because of a recursive loop, but my trigger has the update BEFORE and I'm using NEW. what am I missing out my trigger? Also, if I wanted to do a DateModified what would I have to alter? trigger CREATE TRIGGER `DateCreatedTriggerTS` BEFORE INSERT ON `products` FOR EACH ROW UPDATE products SET DateEntered = NOW( ) WHERE ProductID = NEW.ProductID
Is ProductID a unique key in this products table? If so, your UPDATE is basically updating only the row that spawned the trigger, right? So it's simpler to do this: CREATE TRIGGER `DateCreatedTriggerTS` BEFORE INSERT ON `products` FOR EACH ROW SET NEW.DateEntered = NOW( ); That will change the value of the DateEntered column only in the row that spawned the trigger.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "mysql, triggers" }
Is there a way to produce an "evaluate at" vertical bar that resizes properly in display formulae? There are two examples of what I am talking about in this equation: $$\displaystyle \left.\mathrm{d}\Phi\left(v\right)\right|_{p}\equiv\left.v^{\mu}\frac{\partial\Phi^{\lambda}}{\partial x^{\mu}}\frac{\partial}{\partial y^{\lambda}}\right|_{\Phi\left(p\right)}.$$ They are the vertical bars that inform the reader what value is used for evaluation of the preceding expressions. When I try to produce such a result, the bar resizes inappropriately. I want this this for text and display equations, not form input. Is there a way to accomplish what I am asking for?
Perhaps you can use an input alias? For example: CurrentValue[EvaluationNotebook[], InputAliases] = { "at" -> SubscriptBox[ RowBox[{ "\[SelectionPlaceholder]", StyleBox["\[RightBracketingBar]", FontFamily->"Times"] }], "\[Placeholder]" ] }; And here is an animation producing your desired formula: ![enter image description here]( _(note that I modified the style sheet to adjust the`ScriptLevel`, `FontSize` and `FontFamily` of inline cells)_
stackexchange-mathematica
{ "answer_score": 1, "question_score": 3, "tags": "formatting, display" }
Grails Many to Many Association Querying I have a many to many relationship. class Post { String title static hasMany = [tags:Tag] } class Tag { static hasMany = [posts:Post] } I would like to get a list of posts for a tag that have some other criteria (like a sort order, partial title match, etc). Do I _have_ to use the grails criteria to achieve this? Or is there some way to do something like this: Post.findAllByTitleLikeAndTagsContains("partial title", aTag)
I don't think dynamic finders will allow you to get into one to many or many to many associations - you have to do a criteria or go the HQL query route. You can only query by one to one association, not by one to many. (see section 5.4.1 Dynamic Finders.html))
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "grails, associations, querying" }
What is this nested bracket notation? The following is an excerpt from K. Varga's paper, _Precise solution of few-body problems with stochastic variational method on correlated Gaussian basis_ : > ...The function $θ_{LM_L}(\mathbf{x})$ in Eq. (2), which represents the angular part of the wave function, is a generalization of $\mathcal{Y}$ and can be chosen as a vector-coupled product of solid spherical harmonics of the Jacobi coordinates $$ θ_{LM_L}(\mathbf{x}) = [[[\mathcal{Y}_{l_1}(\mathbf{x}_1) \mathcal{Y}_{l_2}(\mathbf{x}_2)]_{L_{12}} \mathcal{Y}_{l_3}(\mathbf{x}_3)]_{L_{123}}, \ldots]_{LM_L}.\tag{5} $$ Each relative motion has a definite angular momentum... What is the RHS of the above equation? I've never seen this nested-bracket notation before, and as far as I can tell, it isn't defined in the paper. My first guess would be something like a commutator $$[A, B] = AB - BA$$ but that doesn't explain the subscripts on the closing brackets.
This is pretty niche notation, and it is indeed not defined in the paper, but the name **"vector-coupled product"** does seem to be used by a few people beyond Varga and Suzuki. In essence, $$ [\mathcal Y_{l_1}(\mathbf x_1)\mathcal Y_{l_2}(\mathbf x_2)]_{LM} $$ is a coupled wavefunction with total angular momentum $L$ that's made up of the single-particle wavefunctions $\mathcal Y_{l_1}(\mathbf x_1)$ and $\mathcal Y_{l_2}(\mathbf x_2)$, which have angular momentum $l_1$ and $l_2$ respectively. This means that you need to couple them via Clebsch-Gordan coefficients as usual. Thus, the product above is given by $$ [\mathcal Y_{l_1}(\mathbf x_1)\mathcal Y_{l_2}(\mathbf x_2)]_{LM} = \sum_{m_1,m_2} l_1m_1,l_2m_2|LM \mathcal Y_{l_1m_1}(\mathbf x_1)\mathcal Y_{l_2m_2}(\mathbf x_2) $$ where the sum is over all permissible magnetic quantum numbers for the individual particles.
stackexchange-physics
{ "answer_score": 1, "question_score": 2, "tags": "quantum mechanics, angular momentum, computational physics, notation, commutator" }
Write SQLite DB from PHP i have a following scenario that i have a products, categories and subcategories in mysql i want to create the SQLite DB so what i do first I create the XML and and then parse the xml and create Database its has problem i getting that i get too much error in xml because data are too complicated and special characters in the database so is it any possiblity to write direct SQLite DB or some SQL Script which runs in sqlite.. please tell me.. Thanks.
I recently discovered a great ORM layer called RedBean - < You can attach it to all kinds of RDMS, even Sqlite. I suggest it because it can create table structures on-the-fly, without writing CREATE TABLE...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "php, mysql, xml, sqlite" }
stopPropagation() for only one element So right now, I am using hammer.js to bind some touch controls to an element on the page. By swiping to the right on an element, it will add the class of disabled. If any item has a class of disabled, I want to, essentially, "unbind" the doubletap and the swiperight events ONLY for that element that has the class disabled. Does anyone know if this is possible? $('.row').hammer({ prevent_default: false, drag_vertical: false }).bind('doubletap swiperight', function(e) { var $this = $(this) if (e.type == "doubletap") { confirm("Do You Want To Edit Med?") } else if (e.type == "swiperight") { $this.removeClass('yHighlight'); $this.addClass('gHighlight disabled'); $this.css('opacity','.5') } });
You can simply check from inside your event handler if the element that triggered the event has that class; if it does, then return without doing anything. .bind('doubletap swiperight', function(e) { var $this = $(this); // ADDED CODE if ($this.hasClass("disabled")) { e.stopPropagation(); return; } if (e.type == "doubletap") { confirm("Do You Want To Edit Med?") } else if (e.type == "swiperight") { $this.removeClass('yHighlight'); $this.addClass('gHighlight disabled'); $this.css('opacity','.5') } });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, events, types, element, bind" }
Extracting the space between polygons I have a GeoJSON file and I was able to extract the space where there are some obstacles, e.g., forest. ![enter image description here]( import geopandas as gpd import matplotlib.pyplot as plt import geopandas as gpd from shapely.ops import cascaded_union gdf = gpd.read_file('/home/jovyan/work/Export3.geojson') wood_poly = [] for polygon, model_type in zip(gdf["geometry"], gdf["natural"]): if(model_type == "wood"): wood_poly.append(polygon) fig2 = plt.figure(2, dpi=90) ax2 = fig2.add_subplot(111) wood_cascade = cascaded_union(wood_poly) wood = gpd.GeoSeries(wood_cascade) wood.plot(ax=ax2, color = 'red') wood.boundary.plot(color="black", edgecolor='k', linewidth = 2, ax=ax2) plt.show() **Problem:** Now I want to separate out the free space, i.e., space which is shown in white colour. Any idea how to do it?
Try unary_union to dissolve all obstacles to a big multipolygon. Then create a rectangle around the multipolygon and difference: import geopandas as gpd df = gpd.read_file(r'C:\GIS\data\tempdata\my.shp') multipolygon = df.geometry.unary_union envelope = multipolygon.envelope diff = envelope.difference(multipolygon) ![enter image description here](
stackexchange-gis
{ "answer_score": 5, "question_score": 2, "tags": "python, geojson, geometry, geopandas" }
Can I generate Rails SECRET_KEY_BASE without Ruby? I'm wondering if there is a way to generate a Rails SECRET_KEY_BASE variable without having Ruby installed? All answers on SO I've seen point to using the SecureRandom library in Ruby. This is fine, but my situation is a bit chicken and egg - I want to generate a file with a SECRET_KEY_BASE _before_ I've built a Docker image with my Rails app. The base VM that the container runs in doesn't have Ruby installed. It's Ubuntu 16.04 server and I'd install as little extra as possible (preferably just Docker!). It has Perl and OpenSSL installed. Could any of these be used?
OK, I found out - using OpenSSL: `openssl rand -hex 64`
stackexchange-stackoverflow
{ "answer_score": 29, "question_score": 10, "tags": "ruby on rails 5, secret key" }
I need to find second element with the same automationid by Xpath I'm struggling with finding by Xpath. My problem is that the software that I'm testing has one specific function where I need to scan two components (is it called two-step scan) and there are two textboxes without the name and with the same Automationid. So I need to find the second one I tried this but it does not work. [FindsBy(How = How.Xpath, Using = "//*[@AutomationId='ScanTextBox'][1]")] public IWebElement ScanTextBox1; [FindsBy(How = How.Xpath, Using = "//*[@AutomationId='ScanTextBox'][2]")] public IWebElement ScanTextBox2; I'm using winium and I'm testing WPF application.
You really need to use a `FindsBy`? We are unable to create a correct XPath to a FindsBy to these buttons without the html. This way, I only can provide you another solution, and update my awnser when the html code be provided. You can use `FindElement`, the plural one, that is able to return both. After, you select the desired button by index. A example method able to do it: public IWebElement GetScanTextBox(int index) { return Driver .FindElements(By.XPath("//*[@AutomationId='ScanTextBox']")) .ElementAt(index); } public void UsageExample() { var buttonOne = GetScanTextBox(0); var buttonTwo = GetScanTextBox(1); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, wpf, selenium, testing, xpath" }
Multiple Tags on a UIImageView? Is it possible to have more than one tag associated with a UIImageView ? Cheers, Martin
The tag serves solely to identify a view within your application. It's kind of like the `id` attribute in an HTML element; it doesn't make sense to have more than one of them attached to a single view. Use your own data structures to map tags to multiple "things" if you need to.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "iphone, objective c, uiimageview" }
Is there a generic way to access objects in UFT My task is to check the value of data from the global data sheet within different UIs, each of them having lots of data. My idea was to do this in a generic way. I create a array with the objects name, which corresponds with the name of the data sheet column And then I just compare the content Browser("").Page("").GENERIC_TYPE(label).GetROProperty("value") = datasheet.GetParameter(label) Is there such a Generic Type that works for WebEdit and WebList?
You can use `WebElement` and this is generic as all elements on the page are web elements. If you are reading the objects from OR, then you might have to update the element type to WebElement and it's tidious (if you are dealing with multiple objects). So the alternative way is using the below approach. Browser("").Page("").WebElement("xpath:=//*[@common_attribute=" + element_attribute_value + "]").GetROProperty("value") = datasheet.GetParameter(label)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "hp uft" }
Where is the pseudo-distributed template for HBase? The HBase documentation asks me to Copy the pseudo-distributed suggested configuration file cp conf/hbase-site.xml{.pseudo-distributed.template,} But there is no such file! cp: cannot stat `conf/hbase-site.xml.pseudo-distributed.template': No such file or directory Where can I find that template?
It's missing. You can find it in packages that came before to 0.9. See the bug tracker entry
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "configuration, hbase" }
How to set value of age textbox by using javascript/jquery I have <input type="text" name="age" value="" enabled="false">` paired with a `<input type="date" name="birthdate"> I want to set the age text box value as the difference of the present date and the date the user has inputted to automatically get the date using either javascript or jquery
If you are using 'vanilla' JS. Then you can parse the date which has been inputted in the DOB. function setAge(e){ var bday = new Date(Date.parse(e.target.value)); var today = new Date() document.getElementsByName('age')[0].value = today.getFullYear() - bday.getFullYear(); } You can setup an onchange event for the birthday input. <input type="date" name="birthdate" onchange="setAge(event)"> Fiddle: < Hope that helps!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "javascript, jquery" }
Proving $|f(x)|$ $\le \| x\|\| f\|$ , where f is a continuous linear functional I am self studying Functional Analysis and came across this proposition. Suppose, $f$ is a continuous linear functional defined on a Normed Linear space $V$, then $$|f(x)| \le \| x\|\| f\|$$ I don't get how this inequality is derived, I know $f : V \to \mathbb{R}$ is a continuous linear map So, we have $\| f(x)\| \le \| f\|\| x\|$ Now, are we assuming the norm on $\mathbb{R}$ to be the usual $l^1$ norm in this case?
This is a direct proof: Let $f:V \to W$ be a continuous linear map between normed spaces $V,W$, i.e. $$ \forall \varepsilon > 0 :\exists \delta>0 :\forall x \in V:(\|x\| < \delta \implies\|f(x)\| < \varepsilon). $$ It follows that for every preassigned $\varepsilon$ and as long as $ 0 <\|x\| < \delta(\varepsilon)$ we have $$ \|f(x)\| < \varepsilon \implies \frac{\|f(x)\|}{\|x\|} < \frac{\varepsilon}{\|x\|}. $$ Now we can take the infimum on RHS of the last inequality $$ \frac{\|f(x)\|}{\|x\|} \le \inf_{0 < \|x\| < \delta(\varepsilon)} \left\\{ \frac{\varepsilon}{\|x\|} \right\\} = \frac{\varepsilon}{\delta(\varepsilon)}=:\alpha(\varepsilon) < \infty, $$ since $\delta(\varepsilon) > 0$. Thus we proved, since the RHS of the last inequality doesn't depend on $\|x\|$, that $$ \exists\alpha \ge 0 :\forall x \in V: \|f(x)\| \le\alpha \|x\| $$ which is boundedness of $f$. The infimum of all these $\alpha(\varepsilon)$ is the norm $\|f\|$ of $f$.
stackexchange-math
{ "answer_score": -2, "question_score": 2, "tags": "functional analysis" }
Is it wrong to use a laptop with the lid closed? Recently I decided to use my laptop with an external monitor and I always use it closed-lid and enjoy. :) The question is: Is it wrong to use a laptop closed-lid? I mean problems like overheating or anything else? Also, I use it without the battery. Can it cause any damage or problems?
If your hardware manufacturer offers a dock peripheral for your laptop, you can rest assured it's considered normal use for your device. If you're still concerned about overheating, I would recommend using an open source temperature monitoring utility to put your mind at ease.
stackexchange-superuser
{ "answer_score": 41, "question_score": 54, "tags": "laptop, display, battery, battery life, lid" }
inserting Item's ID into query string Dear guys! I have list view and for each item there is a button. What I'm trying to do is: When user clicks the button he should be re directed to a page with a pair of Key/Vale of specified item in the new pages query string. like: http:/newpage.aspx?ID=123456&...
try this <asp:LinkButton ID="lnkView" runat="server" PostBackUrl='<%# string.Format("Pages/User/vFullSpecs.aspx?vID={0}", Eval("vID")) %>'>View Form</asp:LinkButton>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, asp.net" }
Importing strings from a file, into a list, using python I have a txt file, with these contents: a,b c,d e,f g,h i,j k,l And i am putting them into a list, using these lines: keywords=[] solutions=[] for i in file: keywords.append((i.split(","))[0]) solutions.append(((i.split(","))[1])) but when I print() the solutions, here is what it displays: ['b\n', 'd\n', 'f\n', 'h\n', 'j\n', 'l'] How do I make it, so that the \n-s are removed from the ends of the first 5 elements, bu the last element is left unaltered, using as few lines as possible.
You need to `string.strip()` the whitespace/new-line characters from the string after reading it to remove the `\n`: keywords=[] solutions=[] for i_raw in file: i = i_raw.strip() # <-- removes extraneous spaces from start/end of string keywords.append((i.split(","))[0]) solutions.append(((i.split(","))[1]))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, list" }
How to unset session in <script> tag? is it possible to unset a `$_session` in the `<script>` tag?? i have this script (for the checkout), and after it pop up, and clicked "ok" it will clear my cart using `unset($_SESSION['cart'])`; how can i do that? thanks. echo "<script> alert('Thank You For Ordering! We will Keep in Touch!');window.location='cart.php';</script>";
Im not sure if you can do that, but you can do like this. echo "<script> alert('Thank You For Ordering! We will Keep in Touch!'); window.location='unset.php';</script>"; your `unset.php` <?php unset($_SESSION['session index']); header('Location: cart.php'); ?>
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "javascript, php" }
how to display a string from a rest webservice in windows forms? how can display a string from a rest webservice in windows forms my xml looks like this: <string>whatever</string> How can you display that in a textbox in win forms? If I try string uri = string.Format("etc/{0}/{1} Sad.Text, Happy.Text"); XDocument xDoc = XDocument.Load(uri); string mystring = xDoc.Element("String").Value; textBox1.Text = mystring; You get an object reference error?
XML elements are case-sensitive. Try, string mystring = xDoc.Element("string").Value; * * * A better way to solve the problem is to not use XML to return a simple string. The media type `text/plain` is designed to do that. If you are using Microsoft's ASP.NET Web API just return return new HttpResponseMessage() { Content = new StringContent("etc/{0}/{1} Sad.Text, Happy.Text") }; and on the client (using this < do, var httpClient = new HttpClient(); textBox1.Text = httpClient.GetAsync(uri).Result.Content.ReadAsString();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, string, wcf, web services, rest" }
Can javascript execution from address bar cause any harm to client's machine? Given the fact that modern browsers these days prohibit JavaScript from having access to any resources on the client's machine, does JavaScript execution from the address bar pose any threat at all to the client's machine (the machine the browser is running on)?
That JavaScript executed from the address bar will run in the context of the website displayed in that tab. This means complete access to that website and it could change how the website looks and behaves from the point of view of the user. This attack is called self XSS and can cause harm to the user and indirectly to the machine. A reputable website can ask the user to download and install a malicious piece of executable code by pretending, for example, that it needs a Flash update. To get a nice visual example of this, manually type `javascript:` in your address bar and then paste this: `z=document.createElement("script");z.src=" document.body.appendChild(z);` If you don't trust me, do it in the address bar of a website you are not logged in. Most browsers have realised this vulnerability and attempt to limit the impact by cutting out `javascript:` when pasting `javascript:some_js_code` in the address bar. But it is still possible to manually write it and execute it.
stackexchange-security
{ "answer_score": 29, "question_score": 22, "tags": "web browser, javascript, url" }
Sort Spark Dataframe with two columns in different order Let's say, I have a table like this: A,B 2,6 1,2 1,3 1,5 2,3 I want to sort it with ascending order for column `A` but within that I want to sort it in descending order of column `B`, like this: A,B 1,5 1,3 1,2 2,6 2,3 I have tried to use `orderBy("A", desc("B"))` but it gives an error. How should I write the query using dataframe in Spark 2.0?
Use Column method desc, as shown below: val df = Seq( (2,6), (1,2), (1,3), (1,5), (2,3) ).toDF("A", "B") df.orderBy($"A", $"B".desc).show // +---+---+ // | A| B| // +---+---+ // | 1| 5| // | 1| 3| // | 1| 2| // | 2| 6| // | 2| 3| // +---+---+
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 6, "tags": "scala, sorting, apache spark, dataframe, apache spark sql" }
CSS if statement question What is the syntax if I want to load a css file in my website with if statement. Situation is like this. If ie6 I will load ie6_style.css and if ie7, mozilla, or new browsers, I will load style.css
<link rel="stylesheet" type="text/css" href="style.css"> <!--[if IE 6]> <link rel="stylesheet" type="text/css" href="ie6_style.css"> <![endif]-->
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 3, "tags": "css" }
Why does 慢 mean "supercilious; rude"? I have lived in China and Taiwan for at least 20 years. I have always known that means "slow". But I never knew until today — and could never have guessed that — also means "supercilious"! How are these meanings related? Why does mean both? | ---|--- adj. | slow; dilatory; supercilious; rude adv. | slowly; gradually v. | treat rudely; postpone; defer <
does have the meanings "supercilious" and "rude", when used with the following words - () **** , **** (), **** (), and **** (). There are many examples in the old works, such as: * **** ——· * **** ——· * **** —— < "Supercilious" and "rude" are extended interpretations of , because one's "slowness" in many circumstances can, rightfully or wrongfully, draws negative perceptions from others. For example, * you don't promptly respond/react to others in a conversation, you could be criticized as supercilious and rude (,). * You let customers wait for service too long, you could be criticized as committing an offense by ignoring the customer (). Hope now you can see the link between the varies meaning of .
stackexchange-chinese
{ "answer_score": 4, "question_score": 0, "tags": "meaning" }