_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d3901
train
Try this guide: https://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx It will guide you trough the configuration of a Many To Many relationship, using EF6 Code First and Fluent Api
unknown
d3902
train
JVCL passes the application handle to 'hwndParent' parameter of IDSObjectPicker.InvokeDialog, hence the dialog is owned (not like 'owner' as in VCL, but more like popup parent) by the application window. Then you can enurate windows to find out the ones owned by the application window and post them a close command. procedure CloseOpenForms(const AComponent: TComponent); function CloseOwnedWindows(wnd: HWND; lParam: LPARAM): BOOL; stdcall; begin Result := TRUE; if (GetWindow(wnd, GW_OWNER) = HWND(lParam)) and (not IsVCLControl(wnd)) then begin if not IsWindowEnabled(wnd) then // has a modal dialog of its own EnumWindows(@CloseOwnedWindows, wnd); SendMessage(wnd, WM_CLOSE, 0, 0); end; end; procedure CloseOpenFormsRecursive(const RecComponent: TComponent); var i: Integer; begin for i := 0 to pred(RecComponent.ComponentCount) do begin CloseOpenFormsRecursive(RecComponent.Components[i]); if RecComponent.Components[i] is TForm then begin TForm(RecComponent.Components[i]).OnCloseQuery := nil; TForm(RecComponent.Components[i]).Close; end; end; end; begin EnumWindows(@CloseOwnedWindows, Application.Handle); CloseOpenFormsRecursive(AComponent) end;
unknown
d3903
train
It is not clear what exactly you are asking here. The code that you presented already supports assignment. Just do it and at will work (or at least it should compile). It makes absolutely no difference which side of the assignment operator your overloaded [] is used on. It will work in exactly the same way on left-hand side (LHS) as it does on the right-hand side (RHS) of the assignment (or as an operand of <<, as in your original post). Your [] returns a reference to an Object, and then the actual assignment is handled by the assignment operator of your Object type, meaning that the [] itself is not really involved in the actual assignment. The real question here is how you want your [] to act in certain special cases. What is going to happen if your key is not present in the table? Reference to what Object is your lookup going to return in this case? It is impossibe to figure out from what you posted. I see it returns a reference, so returning NULL is out of question. Does it insert a new, empty Object for the given key? If so, then you don't have to do anything. Your [] is already perfectly ready to be used on the LHS of the assigment. (This is how [] in std::map works, BTW) In case your lookup returns a reference to a special "guard" Object, you have to take special steps. You probably don't want to assign anything to a "guard" object, so you have to "disable" its assignment operator somehow and you are done. The rest should work as is. If your lookup throws an exception in case of a non-existent key, then you have to decide whether this is what you want when the [] is used on the LHS of an assignment. If so, then you don't need to do anything. If not, then it will take some extra work... So, again, what happens if you pass a non-existent key to lookup? P.S. Additionally, it would normally make more sense to declare the [] (and lookup) with either const HashedObj& parameter or just HashedObj parameter. Non-const reference, as in your example, looks strange and might lead to problems in some (actually, in most) cases. I'm surprized it works for you now... A: You need to overload that 2 times. One that will be const, which will be the data access part, and one that will return a reference, which will act as a "setter". A: What you're looking for is functionality similar to the overloaded bracket operator in std::map. In std::map the bracket operator performs a lookup and returns a reference to an object associated with a particular key. If the map does not contain any object associated with the key, the operator inserts a new object into the map using the default constructor. So, if you have std::map<K,V> mymap, then calling mymap[someKey] will either return a reference to the value associated with someKey, or else it will create a new object of type V by calling V() (the default constructor of V) and then return a reference to that new object, which allows the caller to assign a value to the object.
unknown
d3904
train
As suggested in the comments going through leaves in the reverse order using reversed() fixes the problem. (Would be a comment but I don't have the reputation) def moveDown(): leaves = Tree.selection() for i in reversed(leaves): Tree.move(i, Tree.parent(i), Tree.index(i)+1) A: Note, for moveUp, reversing the leaves would result in nothing actually changing in the tree. Simply iterating through the leaves in order is the ticket. def moveUp(): leaves = Tree.selection() for i in leaves: Tree.move(i, Tree.parent(i), Tree.index(i)-1)
unknown
d3905
train
float term1 = currentElement * DetOf2x2(...); The compiler will call DetOf2x2(...) even if currentElement is 0: that's sure to be far more costly than the final multiplication, whether by 0 or not. There are multiple reasons for that: * *DetOf2x2(...) may have side effects (like output to a log file) that need to happen even when currentElement is 0, and *DetOf2x2(...) may return values like the Not-a-Number / NaN sentinel that should propagate to term1 anyway (as noted first by Nils Pipenbrinck) Given DetOf2x2(...) is almost certainly working on values that can only be determined at run-time, the latter possibility can't be ruled out at compile time. If you want to avoid the call to Detof2x2(...), try: float term1 = (currentElement != 0) ? currentElement * DetOf2x2(...) : 0; A: Modern CPUs will actually handle a multiply-by-zero very quickly, more quickly than a general multiply, and much more quickly than a branch. Don't even bother trying to optimize this unless that zero is going to propagate through at least several dozen instructions. A: The compiler is not allowed to optimize this unless the calculation is trival (e.g. all constants). The reason is, that DetOf2x2 may return a NAN floating point value. Multiplying a NAN with zero does not return zero but a NAN again. You can try it yourself using this little test here: int main (int argc, char **args) { // generate a NAN float a = sqrt (-1); // Multiply NAN with zero.. float b = 0*a; // this should *not* output zero printf ("%f\n", b); } If you want to optimize your code, you have to test for zero on your own. The compiler will not do that for you. A: Optimisations performed at runtime are known as JIT (just-in-time) optimisations. Optimisations performed at translation (compilation) are known as AOT (ahead-of-time) optimisations. You're referring to JIT optimisations. A compiler might introduce JIT optimisations into your machine code, but it's certainly a far more complex optimisation to implement than the common AOT optimisations. Optimisations are typically implemented based on significance, and this kind of "optimisation" might be seen to affect other algorithms negatively. C implementations aren't required to perform any of these optimisations. You could provide the optimisation manually, which would be "the logic that searches for rows/columns containing zeros", or something like this: float term1 = currentElement != 0 ? currentElement * DetOf2x2(...) : 0; A: The following construct is valid at compile time when the compiler can guess the value of "currentElement". float term1 = currentElement ? currentElement * DetOf2x2(...) : 0; If it cannot be guessed at compile time, it will be checked at run-time and the performance depends on processor architecture : the trade-off between a branch (include branch latency and the delay to rebuild the instruction pipeline can be up to 10 or 20 cycles) and flat code (some processors run 3 instructions per cycle) and hardware branch prediction (when the hardware supports branch prediction). Since multiplications throughput is close to 1 cycle on a x86_64 processor, there is no perf differenec depending on operand values like 0.0, 1.0, 2.0 or 12345678.99. if such a difference exists, that would be perceived as a covert channel in cryptographic-style software. GCC allows to check function parameters at compile time inline float myFn(float currentElement, myMatrix M) { #if __builtin_constant_p(currentElement) && currentElement == 0.0 return 0.0; #else return currentElement * det(M); #endif } you need to enable inlining and interprocedural optimizations in the compiler.
unknown
d3906
train
I had a similar problem when I added HoloEverywhere 2.0.0 SNAPSHOT and ActionBarCompat as dependencies to my project. I believe HoloEverywhere already has the ActionBarCompat dependency and when I removed ActionBarCompat, the problem duplicates errors went away. Gradle is driving me crazy, I am very new to Android and have never used ActionBarSherlock, but from my trawling and searching the code, it seems ActionBarSherlock includes references to HoloEverywhere in pom.xml as a plugin. Maybe it has already included HoloEverywhere and you are including another version and this is why you are getting the already defined error?
unknown
d3907
train
Yes you can love LINQ too much - Single Statement LINQ RayTracer Where do you draw the line? I'd say use LINQ as much as it makes the code simpler and easier to read. The moment the LINQ version becomes more difficult to understand then the non-LINQ version it's time to swap, and vice versa. EDIT: This mainly applies to LINQ-To-Objects as the other LINQ flavours have their own benefits. A: Its not possible to love Linq to Objects too much, it's a freaking awesome technology ! But seriously, anything that makes your code simple to read, simple to maintain and does the job it was intended for, then you would be silly not to use it as much as you can. A: LINQ's supposed to be used to make filtering, sorting, aggregating and manipulating data from various sources as intuitive and expressive as possible. I'd say, use it wherever you feel it's the tidiest, most expressive and most natural syntax for doing what it is you're trying to do, and don't feel guilty about it. If you start humping the documentation, then it may be time to reconsider your position. A: It's cases like these where it's important to remember the golden rules of optimization: * *Don't Do It *For Experts: Don't do it yet You should absolutely not worry about "abusing" linq unless you can indentify it explicitly as the cause of a performance problem A: Like anything, it can be abused. As long as you stay away from obvious poor decisions such as var v = List.Where(...); for(int i = 0; i < v.Count(); i++) {...} and understand how differed execution works, then it is most likely not going to be much slower than the longhand way. According to Anders Hejlsburg (C# architect), the C# compiler is not particularly good at optimizing loops, however it is getting much better at optimizing and parallelizing expression trees. In time, it may be more effective than a loop. The List<>'s ForEach version is actually as fast as a for loop, although I can't find the link that proves that. P.S. My personal favorite is ForEach<>'s lesser known cousin IndexedForEach (utilizing extension methods) List.IndexedForEach( (p,i) => { if(i != 3) p.DoSomething(i); }; A: LINQ can be like art. Keep using it to make the code beautiful. A: I have to agree with your view - if it's more efficient to write and elegant then what's a few milliseconds. Writing extra code gives more room for bugs to creep in and it's extra code that needs to be tested and most of all it's extra code to maintain. Think about the guy who's going to come in behind you and maintain your code - they'll thank you for writing elegant easy to read code long before they thank you for writing code that's a few ms faster! Beware though, this cost of a few ms could be significant when you take the bigger picture into account. If that few milliseconds is part of a loop of thousands of repetitions, then the milliseconds add up fast. A: You're answering your own question by talking about writing 2-3 times more code for a few ms of performance. I mean, if your problem domain requires that speedup then yes, if not probably not. However, is it really only a few ms of performance or is it > 5% or > 10%. This is a value judgement based on the individual case. A: Where to draw the line? Well, we already know that it is a bad idea to implement your own quicksort in linq, at least compared to just using linq's orderby. A: I've found that using LINQ has speed up my development and made it easier to avoid stupid mistakes that loops can introduce. I have had instances where the performance of LINQ was poor, but that was when I was using it to things like fetch data for an excel file from a tree structure that had millions of nodes. A: While I see how there is a point of view that LINQ might make a statement harder to read, I think it is far outweighed by the fact that my methods are now strictly related to the problems that they are solving and not spending time either including lookup loops or cluttering classes with dedicated lookup functions. It took a little while to get used to doing things with LINQ, since looping lookups, and the like, have been the main option for so long. I look at LINQ as just being another type of syntactic sugar that can do the same task in a more elegant way. Right now, I am still avoiding it in processing-heavy mission critical code - but that is just until the performance improves as LINQ evolves. A: My only concern about LINQ is with its implementation of joins. As I determined when trying to answer this question (and it's confirmed here), the code LINQ generates to perform joins is (necessarily, I guess) naive: for each item in the list, the join performs a linear search through the joined list to find matches. Adding a join to a LINQ query essentially turns a linear-time algorithm into a quadratic-time algorithm. Even if you think premature optimization is the root of all evil, the jump from O(n) to O(n^2) should give you pause. (It's O(n^3) if you join through a joined item to another collection, too.) It's relatively easy to work around this. For instance, this query: var list = from pr in parentTable.AsEnumerable() join cr in childTable.AsEnumerable() on cr.Field<int>("ParentID") equals pr.Field<int>("ID") where pr.Field<string>("Value") == "foo" select cr; is analogous to how you'd join two tables in SQL Server. But it's terribly inefficient in LINQ: for every parent row that the where clause returns, the query scans the entire child table. (Even if you're joining on an unindexed field, SQL Server will build a hashtable to speed up the join if it can. That's a little outside LINQ's pay grade.) This query, however: string fk = "FK_ChildTable_ParentTable"; var list = from cr in childTable.AsEnumerable() where cr.GetParentRow(fk).Field<string>("Value") == "foo" select cr; produces the same result, but it scans the child table once only. If you're using LINQ to objects, the same issues apply: if you want to join two collections of any significant size, you're probably going to need to consider implementing a more efficient method to find the joined object, e.g.: Dictionary<Foo, Bar> map = buildMap(foos, bars); var list = from Foo f in foos where map[f].baz == "bat" select f;
unknown
d3908
train
Most probably, but it's hard to say exactly without details, the problem arise from the following facts: * *Spark is lazy - the actual data processing doesn't happen until you perform action, like writing data into a destination table. So if you have a lot of transformations, etc., they will happen when you're writing data. *You're writing data in the loop - you can potentially speedup it a bit by doing a union of all tables into a single dataframe, that will be written into one go: import functools unioned = functools.reduce(lambda x,y: x.union(y), lots_of_dataframes) unioned.write.insertInto("target_delta_table")
unknown
d3909
train
The symptoms you mention indicate a problem in AJA Kona3G driver (actually, not even a driver per se but it's DirectShow integration implemented as a custom AJA DirectShow filter). The system has this integration but it is either broken or out of date and so you see the DirectShow API issue coming from third party component and forwarded to FFmpeg. You need to have AJA stuff re-installed and/or contact their support for a solution. It is not really a programming question.
unknown
d3910
train
You should be able to get the FieldInfo for the variables within the type using the GetField(...) or GetFields(...) method on the main type. Below is a short program demonstrating how you might go about it: class Program { public string mStringType = null; static void Main(string[] args) { var program = new Program(); try { var field = program.GetType().GetField("mStringType"); Console.WriteLine("Field '{0}' is of type '{1}' and has value '{2}'.", field.Name, field.FieldType.FullName, field.GetValue(program)); program.mStringType = "Some Value"; Console.WriteLine("Field '{0}' is of type '{1}' and has value '{2}'.", field.Name, field.FieldType.FullName, field.GetValue(program)); } catch (NullReferenceException) { Console.WriteLine("Error"); } Console.ReadKey(); } } This gives the following output on the Console window: Field 'mStringType' is of type 'System.String' and has value ''. Field 'mStringType' is of type 'System.String' and has value 'Some Value'. Note: If the fields are not public, you will have to pass some BindingFlags into the GetField(...) or GetFields(...) methods. A: FieldInfo fieldInfo = typeof(MyClass).GetField("ameliyatGirisBilgileri", BindingFlags.Public | BindingFlags.Instance); Type fieldType = fieldInfo.FieldType; Sorry but I'm too lazy to type the name of your class completely.
unknown
d3911
train
Google maps API doesn't provide this feature. So, if you want to highlight regions you have to create custom overlays based on the lat/long of the borders of the state. Once you have the lat/long of the borders you have to draw polygons yourself. For example: // Define the LatLng coordinates for the polygon's path. var washingtonShapeCoords = [new google.maps.LatLng(38.8921, -76.9112), new google.maps.LatLng(38.7991, -77.0320), new google.maps.LatLng(38.9402, -77.1144), new google.maps.LatLng(38.9968, -77.0430), new google.maps.LatLng(38.8996, -76.9167), new google.maps.LatLng(33.7243, -74.8843), new google.maps.LatLng(33.7243, -72.6870), new google.maps.LatLng(32.3243, -72.6870), new google.maps.LatLng(32.3985, -76.7300), new google.maps.LatLng(33.7152, -76.6957), new google.maps.LatLng(33.7243, -74.9489), new google.maps.LatLng(38.8921, -76.9112)]; // Construct the polygon. washingtonPolygon = new google.maps.Polygon({ paths: washingtonShapeCoords, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35 }); washingtonPolygon.setMap(map);
unknown
d3912
train
Whether you build the amalgamation with icu enabled or just icu extension depends on what you want to do with icu. If you need an icu tokenizer (to do fts) you need to build amalgamation, if you just need the icu functions as https://www.sqlite.org/cgi/src/dir?ci=6cb537bdce85e088&name=ext/icu list then icu extension is enough. When building icu extension I find I can not name it libSqliteIcu.so as that readme said b/c when I load it I got this error sqlite> .load ./libSqliteIcu.so Error: dlsym(0x7fa073e02c60, sqlite3_sqliteicu_init): symbol not found After asking the question at sqlit mail list I was told that, which I have confirm. The symbol name is sqlite3_icu_init. When you load module lib<x>.so the symbol sqlite3_<x>_init is called. You need to either (a) rename the shared library to the correct name (libicu.so) or pass the name of the init function (sqlite3_icu_init) to the loader when you load the module, or (b) change the name of the sqlite3_icu_init function in the icu.c source so that it matches the name that the module loader is looking for ... A: 1) You can compile it as dynamic extension of SQLite Citing http://www.sqlite.org/cvstrac/fileview?f=sqlite/ext/icu/README.txt The easiest way to compile and use the ICU extension is to build and use it as a dynamically loadable SQLite extension. To do this using gcc on *nix: gcc -shared icu.c `icu-config --cppflags --ldflags` -o libSqliteIcu.so You may need to add "-I" flags so that gcc can find sqlite3ext.h and sqlite3.h. The resulting shared lib, libSqliteIcu.so, may be loaded into sqlite in the same way as any other dynamically loadable extension. (loading is .load libSqliteIcu.so in SQLite prompt) 2) You can compile SQLite with ICU enabled. According to http://www.sqlite.org/compile.html you should define macro SQLITE_ENABLE_ICU: Add -DSQLITE_ENABLE_ICU to the CFLAGS variable or add #define SQLITE_ENABLE_ICU in some config file. Okay, there is something here not described in standard documentation. Here is an example of calling configure with ICU enabled: CFLAGS='-O3 -DSQLITE_ENABLE_ICU' CPPFLAGS=`icu-config --cppflags` LDFLAGS=`icu-config --ldflags` ./configure You also should have icu-config program installed (it is from libicu or libicu-dev package) A: To compile SQLite with ICU enabled, you should define macro SQLITE_ENABLE_ICU. Make sure that you have libicu-dev (on Debian/Ubuntu) installed. As @osgx wrote, the standard documentation is lacking ICU-specific flags that you also need to set. icu-config is deprecated and is missing on Ubuntu 20.04 onwards, thus you should use pkg-config instead: CFLAGS="-O2 -DSQLITE_ENABLE_ICU `pkg-config --libs --cflags icu-uc icu-io`" ./configure make See: * *How To Use ICU - C++ Makefiles *Compile-time Options of SQLite
unknown
d3913
train
JAVA allows cipher suites to be removed/excluded from use in the security policy file called java.security that’s located in your JRE: $PATH/[JRE]/lib/security The jdk.tls.disabledAlgorithms property in the policy file controls TLS cipher selection. The jdk.certpath.disabledAlgorithms controls the algorithms you will come across in SSL certificates. Oracle has more information about this here In the security policy file, if you entered the following: jdk.tls.disabledAlgorithms=MD5, SHA1, DSA, RSA keySize < 4096 It would make it, so that MD5, SHA1, DSA are never allowed, and RSA is allowed only if the key is at least 4096 bits. To solve the tls version issue. Just have to put SSLContext sc = SSLContext.getInstance("TLSv1.2"); It will support all the versions.
unknown
d3914
train
The UICollectionLayoutListConfiguration, which you used to create the layout, has leadingSwipeActionsConfigurationProvider and trailingSwipeActionsConfigurationProvider properties that are functions taking an index path. Your function can return different swipe actions, or nil, for different rows of the list: var config = UICollectionLayoutListConfiguration(appearance: .plain) config.trailingSwipeActionsConfigurationProvider = { indexPath in let del = UIContextualAction(style: .destructive, title: "Delete") { [weak self] action, view, completion in self?.delete(at: indexPath) completion(true) } return UISwipeActionsConfiguration(actions: [del]) } Writing delete(at:) is left as an exercise for the reader; basically you just do the very same thing you would have done in any collection view.
unknown
d3915
train
The WebKit framework is not available on iPhone - it's only for Macs. The nearest you can get is adding a UIWebView to your app, which gives you a WebKit-based HTML window.
unknown
d3916
train
You have 6 "li" elements in your source but you have only set animation-delay for 1-5, that is why the 6th "li" do not have delay and will display first. Add in 1 more delay for that element will make it OK: li { opacity: 0; animation: fadeIn 3.5s 1s; animation-fill-mode: forwards; } .anim li:nth-child(1) { animation-delay: 1s } .anim li:nth-child(2) { animation-delay: 1.5s } .anim li:nth-child(3) { animation-delay: 2s } .anim li:nth-child(4) { animation-delay: 2.5s } .anim li:nth-child(5) { animation-delay: 3s } .anim li:nth-child(6) { animation-delay: 3.5s } /*...*/ @keyframes fadeIn { 0% { opacity: 0.0; } 100% { opacity: 1.0; } }
unknown
d3917
train
You need get the link first val actionUrl = deepLink.getQueryParameter("continueUrl") And get the email value with subString actionUrl.substring(actionURL.lastIndexOf("=") + 1, actionURL.length)
unknown
d3918
train
I'll assume you are using Azure to run the bot, so I'll answer with that in mind. Otherwise let me know and I can expand the answer. Take the secret from the settings of the bot. It's just like how you access turn.activity.text, but using settings scope instead of the turn scope. So: settings.apiSecret. Local Env Now in development, local environment, you can just put the secret in the settings file. In Azure When you deploy to your azure app service, you can use Key Vault References in the Configuration blade. Remember you need to give the app service Secret Get permission to that Key Vault. This is the easiest way since you don't need to write code to query KeyVault via the API. From DevOps to Azure There's a way to get the secret in the pipeline, but I believe this is not something you need in this scenario, you just want to set the variable in the App Service. So in the App Service Deployment task, under Application and Configuration settings -> App Settings: you can add the same thing you'd put in the Configuration blade in the azure portal. So you can add to the textbox: -apiSecret @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/) or click on the button with the elipsis on the right and enter it on the form
unknown
d3919
train
The scala-maven-plugin (previously named the maven-scala-plugin) requires some extra configuration to do mixed Scala/Java projects, but if you follow their instructions (copied below), it should add all the necessary directories to your build path. <plugins> <plugin> <groupId>net.alchim31.maven</groupId> <artifactId>scala-maven-plugin</artifactId> <executions> <execution> <id>scala-compile-first</id> <phase>process-resources</phase> <goals> <goal>add-source</goal> <goal>compile</goal> </goals> </execution> <execution> <id>scala-test-compile</id> <phase>process-test-resources</phase> <goals> <goal>testCompile</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <executions> <execution> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> </executions> </plugin> </plugins> A: You have two options: the first is to split your project in a parent project with two modules, each of them with its own pom. This is the more natural way to do that with maven but as I am not a scala user myself, I not completely sure is feasible in your setup. <parent> ai.chess (packaging: pom) <module> ai.chess.java (packaging: jar) <module> au.chess.scala (using <sourceDirectory>) The second option is keep the layout as it is, and use build-helper-maven-plugin to add source directories to the build; like this: <project> ... <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>src/main/scala</source> </sources> </configuration> </execution> <execution> <id>add-test-source</id> <phase>generate-test-sources</phase> <goals> <goal>add-test-source</goal> </goals> <configuration> <sources> <source>src/test/scala</source> </sources> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> A: * *update to scala-maven-plugin (scala-tools.org no longer exists, since 2 years) *use the goal add-source (do the same that build-helper-maven-plugin for scala only) You can also store your .java and .scala files under the same src/main/xxx and src/test/xxx, the java compiler ignore *.scala, and the scala compiler used both.
unknown
d3920
train
You can create a FormControl in a reactive form using an empty value, empty string, or even undefined: Component: foo = new FormControl(); Template: <input type="number" [formControl]="foo" /> Here is an example in action that demonstrates the number input being initialized without any value. Hopefully that helps!
unknown
d3921
train
I use this code if(e.KeyCode==Keys.F1){ this.ActiveControl=listView1;}
unknown
d3922
train
Try setting h1.SP = 0 instead of 1 to set the objective to drive it back to 1. Also, these options are not needed if h4.TR_INIT = 0 to create a setpoint that is zero everywhere (not a reference trajectory). h4.TAU = 1 h4.BIAS = 1 h4.FSTATUS = 1 I also added lower bounds of zero for each of the height CVs with lb=0. There is a move on v2 when the disturbance starts. It appears that the controller can't resolve this offset. Is this the correct response? from gekko import GEKKO import numpy import matplotlib.pyplot as plt t = numpy.linspace(0,300,100) m = GEKKO(remote=False) m.time = t T1 = m.Param(value = 53.97272679974334) T2 = m.Param(value = 48.06851424706475) T3 = m.Param(value = 38.48651254747577) T4 = m.Param(value = 31.018933652439845) k1 = m.Param(value = 5.51) k2 = m.Param(value = 6.58) γ1bar = m.Param(value = 0.333) γ2bar = m.Param(value = 0.307) A1 = m.Param(value = 730) A2 = m.Param(value = 730) A3 = m.Param(value = 730) A4 = m.Param(value = 730) v1bar = m.Param(value = 60) v2bar = m.Param(value = 60) # Manipulated variable v1 = m.MV(value=0, lb=0, ub=100) v1.STATUS = 1 #v1.DCOST = 0.1 #v2.DMAX = 20 v2 = m.MV(value=0, lb=0, ub=100) v2.STATUS = 1 #v2.DCOST = 0.1 #v2.DMAX = 20 γ1 = m.MV(value=0, lb=0, ub=1) γ1.STATUS = 1 #γ1.DCOST = 0.1 #v2.DMAX = 20 γ2 = m.MV(value=0, lb=0, ub=1) γ2.STATUS = 1 #γ2.DCOST = 0.1 #v2.DMAX = 20 d = numpy.ones(t.shape) d[0:10] = 0 d22 = numpy.zeros(t.shape) d1 = m.Param(name='d1', value=d) # Disturbance d2 = m.Param(name='d2', value=d22) # Disturbance m.options.CV_TYPE = 2 # squared error # Controlled Variable h1 = m.CV(value=0,lb=0) h1.STATUS = 1 # add the SP to the objective h1.SP = 0 # set point h1.TR_INIT = 0 # set point trajectory #h1.TAU = 1 # time constant of trajectory #h1.BIAS = 1 #h1.FSTATUS = 1 h2 = m.CV(value=0,lb=0) h2.STATUS = 1 # add the SP to the objective h2.SP = 0 # set point h2.TR_INIT = 0 # set point trajectory #h2.TAU = 1 # time constant of trajectory #h2.BIAS = 1 #h2.FSTATUS = 1 h3 = m.CV(value=0,lb=0) h3.STATUS = 1 # add the SP to the objective h3.SP = 0 # set point h3.TR_INIT = 0 # set point trajectory #h3.TAU = 1 # time constant of trajectory #h3.BIAS = 1 #h3.FSTATUS = 1 h4 = m.CV(value=0,lb=0) h4.STATUS = 1 # add the SP to the objective h4.SP = 0 # set point h4.TR_INIT = 0 # set point trajectory #h4.TAU = 1 # time constant of trajectory #h4.BIAS = 1 #h4.FSTATUS = 1 m.Equation(h1.dt() == -(1/T1)*h1 + (A3/(A1*T3))*h3 + (γ1bar*k1*v1)/A1 + (γ1*k1*v1bar)/A1) m.Equation(h2.dt() == -(1/T2)*h2 + (A4/(A2*T4))*h4 + (γ2bar*k2*v2)/A2 + (γ2*k2*v2bar)/A2) m.Equation(h3.dt() == -(1/T3)*h3 + ((1-γ2bar)*k2*v2)/A3 - k2*v2bar*γ2/A3 - (k1*d1)/A3) m.Equation(h4.dt() == -(1/T4)*h4 + ((1-γ1bar)*k1*v1)/A4 - k1*v1bar*γ1/A4 - (k2*d2)/A4) m.options.IMODE = 6 # control m.solve(disp=True) plt.subplot(3,1,1) plt.plot(m.time,d1.value,'k-',label='Disturbance') plt.ylabel('Disturbance'); plt.grid(); plt.legend() plt.subplot(3,1,2) plt.plot(m.time,h1.value,'r-',label='Height 1') plt.plot(m.time,h2.value,'g--',label='Height 2') plt.plot(m.time,h3.value,'b:',label='Height 3') plt.plot(m.time,h3.value,'k--',alpha=0.5,label='Height 4') plt.ylabel('CVs'); plt.grid(); plt.legend() plt.subplot(3,1,3) plt.plot(m.time,v1.value,'r-',label='MV 1a') plt.plot(m.time,v2.value,'g--',label='MV 2a') plt.plot(m.time,γ1.value,'b:',label='MV 1b') plt.plot(m.time,γ2.value,'k--',alpha=0.5,label='MV 2b') plt.ylabel('MVs'); plt.grid(); plt.legend() plt.show()
unknown
d3923
train
This combination of Reduce and Map will produce the desired result in base R. # copy the matrix list l3 <- l2 <- l out2 <- Reduce(function(x, y) Map(`*`, x, y), list(l, l2, l3)) which returns out2 [[1]] [,1] [,2] [,3] [,4] [1,] -5.614351e-01 -0.06809906 -0.16847839 0.8450600 [2,] -1.201886e-05 0.02008037 5.64656727 -2.4845526 [3,] 5.587296e-02 -0.54793853 0.02254552 0.4608697 [4,] -9.732049e-04 11.73020448 1.83408770 -1.4844601 [[2]] [,1] [,2] [,3] [,4] [1,] -4.7372339865 -0.398501528 0.8918474 0.12433983 [2,] 0.0007413892 0.151864126 -0.2138688 -0.10223482 [3,] -0.0790846342 -0.413330364 2.0640126 -0.01549591 [4,] -0.1888032661 -0.003773035 -0.9246891 -2.30731237 We can check that this is the same as the for loop in the OP. identical(out, out2) [1] TRUE
unknown
d3924
train
You aren't laying out the use case so yo aren't going to get the best answer, because the answer DEPENDS on your use case, your domain and your users. That said it's highly unlikely that you want your users to see an exception, even if it is in fact exceptional. Better to either show the dialog with an informative message (ie, "No Items to Display") or just not show it at all. HTH, Berryl
unknown
d3925
train
I would structure the package like this: myPackage + -- __init__.py + -- Component.py + -- user_defined_packages + -- __init__.py # 1 + -- example.py Ideas: * *let the users drop into a different folder so that they do not mix up your code and theirs *The init file in user_defined_packages can load all the subpackages once user_defined_packages is imported. It must print all errors. __init__.py # 1 import os import traceback import sys def import_submodules(): def import_submodule(name): module_name = __name__ + '.' + name try: __import__(module_name) except: traceback.print_exc() # no error should pass silently else: module = sys.modules[module_name] globals()[name] = module # easier access directory = os.path.dirname(__file__) for path_name in os.listdir(directory): path = os.path.join(directory, path_name) if path_name.startswith('_'): # __pycache__, __init__.py and others continue if os.path.isdir(path): import_submodule(path_name) if os.path.isfile(path): name, extension = os.path.splitext(path_name) if extension in ('.py', '.pyw'): import_submodule(name) import_submodules()
unknown
d3926
train
Define the default as, well the default, just make sure that the name of the bean is the same, the one inside the profile will override the default one. <beans> <!-- The default datasource --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> </bean> <beans profile="jndi"> <jndi:lookup id="dataSource" jndi-name="jdbc/db" /> </beans> </beans> This construct would also work with Java based config. @Configuration public DefaultConfig { @Bean public DataSource dataSource() { ... } @Configuration @Profile("jndi") public static class JndiConfig { @Bean public DataSource dataSource() { ... // JNDI lookup } } } When using java based configuration you can also specify a default and in another configuration add another bean of that type and annotate it with @Primary. When multiple instances are found the one with @Primary should be used. @Configuration public DefaultConfig { @Bean public DataSource dataSource() { ... } } @Configuration @Profile("jndi") public class JndiConfig { @Bean @Primary public DataSource jndiDataSource() { ... // JNDI lookup } }
unknown
d3927
train
You shouldn't be using get_posts if you need the query to be paginated. Whilst it can be done, this is a total ball ache to achieve. Instead, you should be looking at WP_Query. Further reading on WP_Query - WP_Query @ wordpress.org Your code could look something like the following; <?php $paged = (get_query_var('page')) ? get_query_var('page') : 1; // explain to wordpress we need this paged $wp_query = new WP_Query(array( // the query 'post_type' => 'post', 'post_category' => '', 'post_status' => 'publish', 'numberposts' => 150, 'posts_per_page' => 15, //'orderby' => 'title', 'order' => 'ASC', 'paged' => $paged)); while ($wp_query->have_posts()) : $wp_query->the_post(); // the loop // some code to make it look pretty ?> <div class="post-grid"> <a href="<?php the_permalink(); ?>"> <h3 class="card-title"><?php the_title(); ?> </h3> </a> </div> <?php endwhile; echo ( paginate_links($args = array( 'base' => site_url().'%_%', // site_url prefix is needed for pagination on homepage 'format' => '?page=%#%', 'total' => $wp_query->max_num_pages, 'current' => $paged, 'show_all' => false, 'end_size' => 2, 'mid_size' => 2, 'prev_next' => true, 'prev_text' => 'Prev', 'next_text' => 'Next', 'type' => 'list', 'add_args' => false, 'add_fragment' => '' ))); wp_reset_query();
unknown
d3928
train
You haven't loaded the jQuery library (or at least prior to attempting to use it based on your <head> tag from above), add: <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script> before useing the $ function. After jQuery has resolved, remove the syntax error cased by the extra } in your submitForm function -right in between the ) and the ;.
unknown
d3929
train
function saveAndTestUser() { // here use const as they are not updated const name = document.getElementById("username").value; const email = document.getElementById("email").value; const password = document.getElementById("password").value; // Get all the records of the users // prefer camelcase : not a rule though but it's better this way const storedUsers = localStorage.getItem('users') // if there are no stored users then assign empty array // so that we don't get unexpected errors const userRecords = storedUsers ? JSON.parse(storedUsers): [] // Checking if email already exists if(userRecords.some(user => user.email === email)){ alert("user already exists") return false; // stops the function execution } // If email doesn't exists then the code below will be executed // Similar to if-else // Add current record to existing records const newRecords = [...storedUsers, {name, email, password}] // Set the new record to storage localStorage.setItem("users", JSON.stringify(newRecords)); } A: this is a basic login, when you verify that the emmail and password are right, you can do wathever you want function checkData() { const name = document.getElementById('username').value; const password = document.getElementById('password').value; let user_records = JSON.parse(localStorage.getItem('users')) || []; if ( user_records.find((user) => { return user.name == name && user.password == password; }) ) { alert('Logged in'); // do your things here } else { alert('wrong email or password'); // do your things here } } <input id="username" /> <input id="password" /> <input type="submit" value="submit" onClick="checkData()" /> Extra: This is a thing that you can do only for learning purpose, wich is to add a key to the local storage, for example: localStorage.setItem('loggedIn', true) and set in every page a check for this value, if is true show the page, if is false redirect to login. In the real world we use JWT tokens that contains all the information about the user etc... You can search for JWT token authentication on google and learn that, wich is really usefull in the front-end world
unknown
d3930
train
I'm not entirely sure of your intent. Relationships are to be established between models (so you can't OneToOne to a class' field). As I understand EspecieZona relates one Especie instance to one Zona instance, but you also would like to easily get all the Zona instances related to some Especie instance that you are accessing through EspecieZona. It seems to me like you should drop that here_is_my_problem field entirely and use foreign keys to Especie and Zona in EspecieZona, instead of OneToOne. With the foreign keys you can use a ManyToMany field from Zona to Especie (or vice versa. you have to declare the MtM field in only one side of the relationship, whichever makes more sense to you) and use EspecieZona as a 'through' field for that relationship (probably with a unique_together constraint for Especie and Zona). That way you can establish a relationship like this: "Each species can be on multiple zones, and each zone can have multiple species (described by the MtM relationship). Additionally, for each zone and species found in them, each species might or not have been recorded(?) in that zone (described in the 'through' model, EspecieZona, thou not sure I understand the meaning of fechado here. In any case, a 'through' model lets you describe whatever details about the relationship between two models)". Then, in order to retrieve Especies.zonas from an instance of EspecieZona you can do someSpecificEspecieZona.especie.zonas.all() (assuming zonas is declared as a MtM field in Especie), which would get you all the zones that are related to that species (as I understand your models) I suggest reading through the documentation of relationship fields https://docs.djangoproject.com/en/1.11/ref/models/fields/#module-django.db.models.fields.related so you get the details about how it all works, like how to use a ManyToManyField.through, and perhaps about reverse relationships if you need them. (also, maybe that was just a mistake when copypasting your code here, but the indentation looks wrong. Different models should be at the same level of indentation there)
unknown
d3931
train
In my opinion, the best way is: $length = ceil(log10($number)) A decimal logarithm rounded up is equal to length of a number. A: If you are using a web form, make sure you limit the text input to only hold 10 characters as well to add some accessibility (users don't want to input it wrong, submit, get a dialog about their mistake, fix it, submit again, etc.) A: if (preg_match('/^\d{10}$/', $string)) { // pass } else { // fail } A: $num_length = strlen((string)$num); if($num_length == 10) { // Pass } else { // Fail } A: This will work for almost all cases (except zero) and easily coded in other languages: $length = ceil(log10(abs($number) + 1)); A: Use intval function in loop, See this example <?php $value = 16432; $length=0; while($value!=0) { $value = intval($value/10); $length++ } echo "Length of Integer:- ".$length; ?> A: $input = "03432 123-456"; // A mobile number (this would fail) $number = preg_replace("/^\d/", "", $number); $length = strlen((string) $number); if ($number == $input && $length == 10) { // Pass } else { // Fail } A: If you are evaluating mobile numbers (phone numbers) then I would recommend not using an int as your chosen data type. Use a string instead because I cannot forsee how or why you would want to do math with these numbers. As a best practice, use int, floats, etc, when you want/need to do math. Use strings when you don't. A: From your question, "You want to get the lenght of an integer, the input will not accept alpha numeric data and the lenght of the integer cannot exceed 10. If this is what you mean; In my own opinion, this is the best way to achieve that:" <?php $int = 1234567890; //The integer variable //Check if the variable $int is an integer: if (!filter_var($int, FILTER_VALIDATE_INT)) { echo "Only integer values are required!"; exit(); } else { // Convert the integer to array $int_array = array_map('intval', str_split($int)); //get the lenght of the array $int_lenght = count($int_array); } //Check to make sure the lenght of the int does not exceed or less than10 if ($int_lenght != 10) { echo "Only 10 digit numbers are allow!"; exit(); } else { echo $int. " is an integer and its lenght is exactly " . $int_lenght; //Then proceed with your code } //This will result to: 1234556789 is an integer and its lenght is exactly 10 ?> A: By using the assertion library of Webmozart Assert we can use their build-in methods to validate the input. * *Use integerish() to validate that a value casts to an integer *Use length() to validate that a string has a certain number of characters Example Assert::integerish($input); Assert::length((string) $input, 10); // expects string, so we type cast to string As all assertions in the Assert class throw an Webmozart\Assert\InvalidArgumentException if they fail, we can catch it and communicate a clear message to the user. Example try { Assert::integerish($input); Assert::length((string) $input, 10); } catch (InvalidArgumentException) { throw new Exception('Please enter a valid phone number'); } As an extra, it's even possible to check if the value is not a non-negative integer. Example try { Assert::natural($input); } catch (InvalidArgumentException) { throw new Exception('Please enter a valid phone number'); } I hope it helps A: A bit optimazed answer in 2 or 3 steps depends if we allow negative value if(is_int($number) && strlen((string)$number) == 10) { // 1 000 000 000 Executions take from 00:00:00.153200 to 00:00:00.173900 //Code } Note that will allow negative up to 9 numbers like -999999999 So if we need skip negatives we need 3rd comparision if(is_int($number) && $number >= 0 && strlen((string)$number) == 10) { // 1 000 000 000 Executions take from 00:00:00.153200 // to 00:00:00.173900 over 20 tests } Last case when we want from -1 000 000 000 to 1 000 000 000 if(is_int($number) && $number >= 0 && strlen(str_replace('-', '', (string)$number)) == 10) { // 1 000 000 000 Executions take from 00:00:00.153200 // to 00:00:00.173900 over 20 tests } For compare First naswer with regex if (preg_match('/^\d{10}$/', $number)) { // Fastest test with 00:00:00.246200 } ** Tested at PHP 8.0.12 ** XAMPP 3.3.0 ** Ryzen 7 2700 ** MSI Radeon RX 5700 8G Tested like $function = function($number) { if(is_int($number) && $number >= 0 && strlen((string)$number) == 10) { return true; } } $number = 1000000000; $startTime = DateTime::createFromFormat('U.u', microtime(true); for($i = 0; $i < 1000000000; $i++) { call_user_func_array($function, $args); } $endTime = DateTime::createFromFormat('U.u', microtime(true); echo $endTime->diff($startTime)->format('%H:%I:%S.%F');
unknown
d3932
train
You can go from one thread to the other in debug. Debug \ Windows \ Threads [ctrl-alt-h] You'll have the list of thread. Be carefull, when stepping inside the code, you might alternate between threads. The best option is to freeze the other threads.
unknown
d3933
train
Okay, I finally figured it out. I forgot to put the :following and :followers actions in the before_filter for :logged_in_user in the User controller. class UsersController < ApplicationController before_filter :logged_in_user, only: [:index, :edit, :update, :destroy, :following, :followers] That took a while. A: Your code is checking current_user.admin? and changing what is displayed based on that. However from the title of your specs it appears that you are testing the behaviour when a non logged in user visits the page: current_user will be nil Sounds like the if statement in the _user partial needs an extra condition to check that there is a logged in user before checking that that user is an admin A: Try looking in the users_controller, your code in the partials looks okay to me which means it's possibly something behind the scenes that is missing. The local server trace seems to point to line 68 and the followers method. Mine looks like this, fyi: def followers @title = "Followers" @user = User.find(params[:id]) @users = @user.followers.paginate(page: params[:page]) render 'show_follow' end Hope that helps. A: I also forgot to put the :following and :followers actions in the before_filter for :logged_in_user in the User controller, but I was curious about this error. Like Frederick Cheung points in is response there is bug in the code of the parcial: _user.html.erb. We should check if current_user is nil before calling the admin? method on it. So instead of: <% if current_user.admin? && !current_user?(user) %> you should have: <% if current_user && current_user.admin? && !current_user?(user) %> This removes the "undefined method admin?" error and gives us the correct test error: Expected response to be a <redirect>, but was <200> This last one we remove by putting the :following and :followers actions in the before_filter for :logged_in_user.
unknown
d3934
train
The script 'dnvm.ps1' cannot be run because it contained a "#requires" statemen t at line 2 for Windows PowerShell version 3.0. If you want to be sure that the script will work, you'll have to use Powershell v3.0. It is certainly possible to modify the script to remove the requirement, but it as probably put there for a good reason. It would just be a roll of the dice if it would actually work if the requirement was removed.
unknown
d3935
train
You should be able to install the files to an external location and define the environment variable PYTHONPATH to point to the directory that contains the modules. A: You should have now both a /usr/lib/python2.6 folder and a /usr/lib/python2.7. Try creating links inside the 2.7 folders to the required files or folders inside the 2.6 folder.
unknown
d3936
train
It seems that using the void message naming convention was the cause of the bug , when I switch to using a Capitiized name for the message spec it started working . All I did was to change from message void{} to message Void{}
unknown
d3937
train
I think that each call to plt.bar gets one label. So, you are giving it a list as a label for each plt.bar call. If you want a label for every color, representing every operating system then I think the solution is to call plt.bar once for each color or os.
unknown
d3938
train
Change in symptomsgrp to into symptomsgrp. And you get rid of the error by changing DiseaseName = diseasedetails.Name to DiseaseName = diseasedetails.disease.Name
unknown
d3939
train
Though there are a lot of ways of creating a task, using job or spring task scheduler, below is one straightforward way. Below task will run every second. Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("hello"); } }, 0, 1000); // o is delay time after which it starts, 1000 is time interval Or you may want to refer here to implement spring task scheduler .
unknown
d3940
train
Here is the related question How to get the size of a single document in MongoDB?
unknown
d3941
train
$(".comment-list").append("<%= j render partial: "comments/comment" %>"); Replace above code with $(".comment-list").append("<%= j render partial: "comments/comment", locals: {comment: @comment} %>");
unknown
d3942
train
Arrays are passed by reference so both snippets are equivalent concerning efficiency except for the fact that if you are not using intArray for some other purpose: The second version will unreference the array and make it a candidate for garbage collection. This is, in the second case, the array will be a candidate to be collected as soon as someMethod execution returns whereas the first version will keep the array referenced until the program ends since it is static. From your comments I understand that you will call className once per file for different files and for each file you will call 'someMethod' many times. Then I like a solution similar to the firstone at some points but different to both the first and the second one. That solution is to have a instance of Testing for each file you load data from: * *Force each instance to be associated with a concrete file. *Make methods and attributes not static. This is for each Testing element to have its own data loaded from its file. *Change className so it will load data from its file only once. *Make a right user of Testing and its instances. class Testing{ public Testing(File f) { this.f = f; } private File f; private int[] intArray; public static ReturnClassName className(){ ReturnClassName returnCN= new ReturnClassName(); byte[] b; if(intArray == null || intArray.length > 0) return //If it was called before, then we don't load the file again. { try{ DataInputStream dataIStream= new DataInputStream(new FileInputStream(f)); intArray= new int[dataIStream.available()]; b = new byte[dataIStream.available()]; dataIStream.read(b); intArray= b; // setting methods for ReturnClassName // counter increment } catch(Exception e) { ... ... } } returnCN.setNumber(someMethod(5)); return returnCN; } private int[] someMethod(int l){ return Arrays.copyOfRange(intArray, counter, counter + l); } } Example of use: Testing forFile1 = new Testing(fileObj01); ReturnClassName x = ReforFile1.className(); ReturnClassName y = ReforFile1.className(); Testing forFile2 = new Testing(fileObj02); ReturnClassName z = ReforFile2.className(); ReturnClassName w = ReforFile2.className(); You could, on the other hand, implement a better solution were you have a map of integer arrays indexed by the input file (like a cache) and you keep a copy if their bytes on it. Having thus a single instance od Testing and keep File f as input parameter for 'className'.
unknown
d3943
train
This may be a typo, but you're missing the $ before the jQuery selector, and you need to be sure the DOM is ready before running this code: $(function() { $("#first_link").click(function() { adjust_menu(); }); }); Doing $(function() { ... }); is a shortcut for jQuery's .ready() method which makes sure the DOM is ready before your code runs. Selecting first_link does no good if it doesn't exist yet. :o) A: Unless it's a typo, you're missing the $ or jQuery at the start: $("#first_link").click(function() { adjust_menu(); }); Or a bit shorter, and maintaining context: $("#first_link").click(adjust_menu); In any case, you should be seeing an error in your console (provided you're executing this when #first_link is present (e.g. `document.ready)), always check your console to see what's blowing up. A: EDIT: Your problem is definitely that you forgot the $ or jQuery before you used jQuery. Also you can just do ("#first_link").click(adjust_menu)
unknown
d3944
train
You define vm.ticketData and after you call it like this.ticketData You can change it by: this.rowData = vm.ticketData A: You are setting this.gridOptions.rowData outside of the axios callback, so this.ticketData is still empty. Set it inside the callback: mounted() { var vm = this axios.get(ticketingAPIURL, {'headers': {'Authorization': authHeader}}) .then(function (response) { vm.ticketData = response.data vm.gridOptions = {} vm.gridOptions.rowData = vm.ticketData vm.gridOptions.columnDefs = DummyData.columnDefs }) .catch(function (error) { console.log(error) }) } A: it is due to overlapped intialization between axios, ag-grid, and vue. after much tinkering, I am able to solve it with using Vue's watch function: watch: { isAxiosReady(val) { if (val) { this.mountGrid() // initiate gridOptions.api functions } } }
unknown
d3945
train
Use Charles or Fiddler to inspect what is actually sent in the HTTP request body. Most likely problems: * *Mismatching character sets for client & server; *Failure to decode the URL encoded body.
unknown
d3946
train
The bullet proof version would be: awk 'match($0,/^Sentencia: */){gsub("\042","\047"/); print substr($0,RLENGTH+1)}' We make use of the octal notation as this is the one which is supported by Posix (See section regular expressions of the POSIX standard). I avoid the usage of FS=":" as there could be an extra : in the respective line. A: awk -F": " '{if ($1 == "Sentencia") {gsub("\042","\047",$2);print}}' $wkdir/xxxx.txt I replace the double quote by \042 and single quote by \047 (octal equivalent) $ awk -F": " '{if ($1 == "Sentencia") {gsub("\042","\047",$2);print}}' $wkdir/MigrarDatosTablas.txt Sentencia select * from pricing_user.prc_promotions where fec_baja is NULL and end_date between NOW() and adddate(NOW(), 30) and werks in ('6027', '0006', '0055', '6785') A: Adding to the others answers, you could also write your program to an awk file and, with the shell not interfering, use the quotes as-is: $ cat program.awk BEGIN { FS=":" # set the delimiter } /^>Sentencia:/ { # match the beginning gsub(/"/,"'",$0) # <- LOOK HERE print $2 } $ awk -f program.awk file select * from pricing_user.prc_promotions where fec_baja is NULL and end_date between NOW() and adddate(NOW(), 30) and werks in ('6027', '0006', '0055', '6785') I'm going to overlook some other problems in the code as others already have pointed them out.
unknown
d3947
train
Select columns for replace missing values first and set NaN: students_df.loc[(students_df['school_name'] == 'College2') & (students_df['grade'] == "9th"),['math_score','art_score']] = np.nan print (students_df) ID Name Gender school_name grade math_score art_score 0 2 John M College2 9th NaN NaN 1 3 Jane F College2 10th 89.0 89.0 2 5 Sam F College10 9th 88.0 89.0 3 7 James M College2 9th NaN NaN 4 11 Stacy F College2 8th 89.0 90.0 5 13 Mary F College2 5th 90.0 94.0
unknown
d3948
train
Site can be anywhere, especially on local machine. Check if * *you copied all files to new location *you changed location of the root of the site in IIS Manager (Start->run->inetmgr) *check event log for any errors *check if accoutn app pool for the site runs under have permissions to read from new folder. A: It is quite simple and easy. Follow the steps here: http://support.microsoft.com/kb/172138 or http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5adfcce1-030d-45b8-997c-bdbfa08ea459.mspx?mfr=true
unknown
d3949
train
Instead of chasing down Web Forms, try using Blazor and .Net Core. You still get to re-use your existing C# code. Quick tutorial here: Blazor Tutorial Starting a new Blazor app (provided you have .Net core installed) is as simple as running one of the following commands from powershell in a folder of your choosing. //serverside (renders views on server and syncs to client) dotnet new blazorserver //clientside (c# is transpiled to webassembly and runs purely in client browser - still finicky but YMMV) dotnet new blazorwasm You could use that existing working project as a springboard to learn a new technology, and gets you up and running fast. I have followed the following article for getting file uploads, and you could customize example to get image bytes. blazor-inputfile
unknown
d3950
train
There's currently no support for custom simulator builds. That's something that we've considered but there has not been a real use case yet. Since Facebook now wants to review iOS builds using a Simulator build, we'll need to add support for that at some point soon. We can continue over email to get your application submitted for review before we can offer custom simulator builds from the Build Service. Edit: Custom Simulator builds have now been available since spring 2015.
unknown
d3951
train
You can use UIViewRoot#getViewId() for this: String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId(); It's also available in EL as follows: #{view.viewId}
unknown
d3952
train
Try this: driver.FindElement(By.XPath("//*[@id='TreeView1_LinkButtonMore']")).Click(); However, it might be worth pointing out that the shortcut for this exact same thing is: driver.FindElement(By.Id("TreeView1_LinkButtonMore")).Click(); A: There is syntax error in your xpath. The closing should be square bracket not the curve bracket Syntax: //tag-name[@attribute='value'] Try this: driver.FindElement(By.XPath("//a[@id='TreeView1_LinkButtonMore']")).Click();
unknown
d3953
train
The documentation has more information and examples, including the basic structure of the dropdown options and how to make a dynamic dropdown menu. The basic structure is: Each dropdown menu is created with a list of menu options. Each option is made up of two strings. The first is the human-readable text to display. The second is a string constant which is used when saving the option to XML. This separation allows a dropdown menu's setting to be preserved between languages. For instance an English version of a block may define [['left', 'LEFT'], ['right', 'RIGHT']] while a German version of the same block would define [['links', 'LEFT'], ['rechts', 'RIGHT']]. And for a dynamic menu: Instead of providing a static list of options, one can provide a function that returns a list of options when called. Every time the menu is opened, the function is called and the options are recalculated. If menuGenerator is an array it is used; if it's a function it is run when the menu is opened. The function does not take in any arguments; it returns a list of options, structured as described above.
unknown
d3954
train
By default, all C programs (CPython included as it is written in C) that use libc will automatically buffer console output when it is connected to a pipe. One solution is to flush the output buffer every time you need: print val sys.stdout.flush() Another solution is to invoke python with the -u flag which forces it to be unbuffered: var py = spawn('python', ['-u', 'scale.py']);
unknown
d3955
train
Here is one approach that might work: Adding vectors1 should allow you to highlight even by clicking MoveUp. Then add a handler to apply style to the features you want: function style_feature(feature) { var hoverStyle =new OpenLayers.Style({ //add style here }); //todo: add logic to check feature you want and style accordingly this.layer.drawFeature(e, hoverStyle); }; selectControl = new OpenLayers.Control.SelectFeature( [vectors2,vectors1], { hover: true, highlightOnly: true, highlight: style_feature });
unknown
d3956
train
Your problems above appear to stem from a bad Swing code practice, one that seems to be reinforced by Swing code generators (although I'm not sure if you're currently using this tool) and the official Swing tutorials, and that is: * *First and foremost, you should avoid having your Swing GUI classes extend JFrame as that unnecessarily paints your GUI code into a corner that requires a bit of effort to get out of. *Instead gear your Swing GUI code towards making JPanels, panels which now can easily be placed into other JPanels, or into JFrames, JDialogs, JOptionPanes, swapped in CardLayouts,... wherever they are needed. *Instead, create, fill, and pack your JFrames when they are needed. So I suggest that you do just this: * *change your code above so that the classes do not extend JFrames, and instead create JPanels, *Create a master JPanel that uses a BorderLayout *Add your grid to the above, BorderLayout.CENTER *Add your JTextArea-containing JScrollPane and its JPanel into the master JPanel in the BorderLayout.PAGE_END position. *Create your JFrame to hold and display the master JPanel. If you've done a good job of separated your GUI code from your logic code, then it should be easy to re-write the GUI code while keeping your same logic (or "model") code. Edit 2 Regarding your changed question where now the first class extends JPanel, simply add that JPanel to your JFrame in the BorderLayout.LINE_END end (also known as BorderLayout.EAST) position.
unknown
d3957
train
$(".scroller p>img").unwrap(); This will select and unwrap only img tags with p parents(inside of .scroller) A: use this as the test for every image image.parent().get(0).tagName​​​​​ == "P" It gets the parent block, gets the first element in the block and checks whether its tagname is P Good luck!
unknown
d3958
train
First, you have to change your log method to take a "variable argument list", for example like this: - (void)log:(NSString *)domain logLevel:(int)level logMessage:(NSString *)message, ... { va_list argList; va_start(argList, message); NSString *fullMessage = [[NSString alloc] initWithFormat:message arguments:argList]; va_end(argList); NSLog(@"domain:%@, level:%d: %@", domain, level, fullMessage); } Then you have to change your MyLog macro to work with a variable number of arguments. This is a GNU feature (http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html), that works with Clang as well: #define MyLog(domain, level, message, ...) \ [[MyLogger sharedInstance] log:domain logLevel:level logMessage:message, ##__VA_ARGS__] Now MyLog(@"common", LL_ERROR, @"There was an error!"); MyLog(@"common", LL_ERROR, @"There was an error: %@", [error debugDescription]); should both work without problems.
unknown
d3959
train
The answer to your question comes in two parts. Part 1 - Calling the Amazon API Most MWS requests do not require any file (be it plain text or XML) to be sent to Amazon. For example, all parameters needed to do send RequestReport can (and must) be sent as regular parameters. I'm not sure what Amazon would do if you did submit a file along with it as I've never tried. But then again... why would you? One of the calls that does require a file to be send is the SubmitFeed call where that file is the actual feed to be submitted. It depends on the type of feed you're submitting if Amazon expects it to be plain text or XML. Part 2 - Handling Amazon's API responses When you get information back from Amazon's API, it usually is in XML format (there are a few calls that may return plaintext instead). You will need to decode this data to get your information out. To make it a bit clearer, I'll outline a typical process for you: The process of getting all your listings from Amazon: * *Do a RequestReport call to Amazon. No XML attached *Decode the XML that you're getting back (it is a RequestReportResponse). If all went well, you'll get a RequestReportId as part of the response, and Amazon will start processing your request. Amazon may need a few minutes to actually create the report, in cases of very complex or large requests or during high activity hours it may actually take up to an hour or more. So we need to find out when the request we made is actually done. *Poke Amazon API with a GetReportRequestList call asking for the status of your request with ReportRequestIdList.Id.1={YourRequestIdHere}. This also does not need a XML attachment. *Decode the XML that you're getting back. (it is a GetReportRequestListResponse) If its ReportProcessingStatus is not _DONE_, wait for at least 45 seconds, then repeat from step 3. If the report is actually done, you'll see a valid GeneratedReportId in the response. If it is missing, you'll need to do an extra GetReportList call to find its ID. *Call GetReport to finally fetch your report with ReportId={YourGeneratedReportIdHere} *Decode whatever you're getting back. Depending on the type of report you requested, the response may be XML or plain text. This process is explained in detail (and with a pretty flow chart) in Amazon Marketplace Web Service Reports API Section Reference (Version 2009-01-01) To finally answer your question with respect to getting active listings from Amazon MWS: None of the three calls require you to send XML to Amazon. The data you receive from Amazon will be in XML format (with the possible exception step 6 if you requested a plain text report).
unknown
d3960
train
With Linux, bash and tee: word123=$( ./test.sh | tee >&255 >(sed -nr 's/Hello world (.*)/\1/p') ) File descriptor 255 is a non-redirected copy of stdout. See: What is the use of file descriptor 255 in bash process
unknown
d3961
train
This works for me: $f = fopen('emails.txt','r'); $content = file('emails.txt'); array_splice($content, 0, 500); file_put_contents('emails.txt', $content); fclose($f); A: It looks like you want to truncate your file. Try with w, instead of w+ http://www.tizag.com/phpT/filetruncate.php You may also want to check your error logs. If the file isn't writeable by the web / apache user then nothing significant will occur. A: If you have this on a cron task, you may want to use sed instead. Sed can remove as many lines as you wish from a file. Unix Sed Command to Delete lines in file sed '1d' file removes the first line in a file, while sed '2,4d' file would remove lines 2 through 4. If you do this via cron, be sure to include the full path to your file, from / (root) forward. A: Assuming that your script have permissions to write to the text file and that the two files are located in the same directory. I guess that you're not running the script from the same directory, so you could try this : $handle = fopen (__DIR__."/emails.txt", "w"); fclose($handle);
unknown
d3962
train
Yes, it is a good idea to create a separate account. Quote from https://developer.nest.com/documentation/cloud/home-simulator "This Home Simulator is intended to be used with virtual devices for testing purposes. We strongly suggest that you create a separate account for testing and add virtual devices to it via the Home Simulator."
unknown
d3963
train
I moved the build to my controller like so and it worked def new @user = User.new @user.build_user_detail end A: Try to prebuild it. <%= form_for [:admin, @user] do |f| %> <p><%= f.text_field(:name, :placeholder => 'Name')%></p> <p><%= f.label(:email) %></p> <p><%= f.email_field(:email, :placeholder => 'Your Email')%></p> <p><%= f.password_field(:password, :placeholder => 'Choose a password') %></p> <p><%= f.password_field(:password_confirmation, :placeholder => 'Confirm Password') %></p> <% @user.user_detail.build if @user.user_detail.nil? %> <%= f.fields_for :user_detail do |u| %> <p><%= u.text_field(:country, :placeholder => 'Country') %></p> <p><%= u.text_field(:state, :placeholder => 'State') %></p> <p><%= u.text_field(:city, :placeholder => 'City') %></p> <p><%= u.text_field(:phone, :placeholder => 'Phone') %> </p> <% end %> <p><%= submit_tag("Add Owner") %></p>
unknown
d3964
train
Definitely! Set up a cron job to call the PHP script: http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/ Alternatively you can use Kermit to automate FTP as well: http://www.columbia.edu/kermit/ftpscripts.html A: What I'd do is loop through a local dir with PHP, make a list (json for easy storage) of all files and then compare that to FTP. If there's items that aren't in the local list, get them through FTP using Kermit as suggested by Jeremy Morgan.
unknown
d3965
train
You probably need to set the display manually, i.e.: * * * * * export DISPLAY=:0 && sh /home/pi/scripts/script.sh As outlined in this article.
unknown
d3966
train
You could also do: case x: {var someVariable = 42;} break; case y: {var someVariable = 40;} break; Essentially the braces create the lexical scope, so without the braces, someVariable is loaded into the symbol table twice. I believe this choice is likely made simply to avoid confusion, and possibly to avoid adding complexity to the building of the symbol table. A: UPDATE: This question was used as the inspiration for this blog post; see it for further details. http://ericlippert.com/2009/08/13/four-switch-oddities/ Thanks for the interesting question. There are a number of confusions and mis-statements in the various other answers, none of which actually explain why this is illegal. I shall attempt to be definitive. First off, to be strictly correct, "scope" is the wrong word to use to describe the problem. Coincidentally, I wrote a blog post last week about this exact mis-use of "scope"; that will be published after my series on iterator blocks, which will run throughout July. The correct term to use is "declaration space". A declaration space is a region of code in which no two different things may be declared to have the same name. The scenario described here is symptomatic of the fact that a switch section does not define a declaration space, though a switch block does. Since the OP's two declarations are in the same declaration space and have the same name, they are illegal. (Yes, the switch block also defines a scope but that fact is not relevant to the question because the question is about the legality of a declaration, not the semantics of an identifier lookup.) A reasonable question is "why is this not legal?" A reasonable answer is "well, why should it be"? You can have it one of two ways. Either this is legal: switch(y) { case 1: int x = 123; ... break; case 2: int x = 456; ... break; } or this is legal: switch(y) { case 1: int x = 123; ... break; case 2: x = 456; ... break; } but you can't have it both ways. The designers of C# chose the second way as seeming to be the more natural way to do it. This decision was made on July 7th, 1999, just shy of ten years ago. The comments in the notes from that day are extremely brief, simply stating "A switch-case does not create its own declaration space" and then giving some sample code that shows what works and what does not. To find out more about what was in the designers minds on this particular day, I'd have to bug a lot of people about what they were thinking ten years ago -- and bug them about what is ultimately a trivial issue; I'm not going to do that. In short, there is no particularly compelling reason to choose one way or the other; both have merits. The language design team chose one way because they had to pick one; the one they picked seems reasonable to me. A: Because cases aren't blocks, there are no curly braces denoting the scope. Cases are, for lack of a better word, like labels. You're better off declaring the variable outside the switch() statement and using it thereafter. Of course, in that scenario, you won't be able to use the var keyword, because the compiler won't know what type to initialize. A: Ah - you don't have fall through, but you can use goto to jump to another labelled case block. Therefore the blocks have to be within the same scope. A: As of C# 8.0 you can now do this with switch expressions you use the switch expression to evaluate a single expression from a list of candidate expressions based on a pattern match with an input expression var someVariable = caseSwitch switch { case x => 42, case y => 40, _ => throw new Exception("This is how to declare default") }; A: You could just declare the variable outside the scope of the switch statement. var someVariable; switch(); case x: someVariable = 42; break; case y: someVariable = 40; break;
unknown
d3967
train
Exactly as you wrote, make separated view for each element with specific listener. Extending View should be sufficient solution - it gives you needed interfaces (e.g. OnDragListener or OnClickListener) and let you to keep clear your solution. This seems to me like really pleasant task, which you can solve step by step, task by taks, component by component... As to container for all animal's parts, it depends on requirements. If in all cases the eyes, ears, hairs etc. would be on the same or proportional location for every animal and you put the animal more then once, it would be worth to think about custom ViewGroup - probably RelativeLayout. It is hard to give you more precise tips, because there will be a lot of minor and major requirements like I mentioned. For example, if size of eyes' images of two different animals aren't equal I would my components (rather than View) extend ImageView, which gives us scaling features. Edit: I' not sure it will be possible to accomplish it in this way, but I would try to do it like that: <RelativeLayout ...> <!-- LAYER 1: Face - background --> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:weightSum="100" android:gravity="center"> <custom.path.FaceBaseComponent android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="60" android:src="@drawable/face_drawable"/> </LinearLayout> <!-- LAYER 1: Ears --> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <!-- Left ear --> <custom.path.EarComponent android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="30" android:src="@drawable/left_ear"/> <!-- Filler --> <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="40"/> <!-- Right ear --> <custom.path.EarComponent android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="30" android:src="@drawable/right_ear"/> </LinearLayout> </RelativeLayout> This help you to save proportions between each element. Keep trying to merge as many "layers" as you can (maybe you can put ears and eyes inside single LinearLayout?).
unknown
d3968
train
This worked- df_tempTable2.join(df_parent, on = [df_tempTable2["`entity_key|inv.entity|entity_id|entity_key|FK`"] == df_parent["enterprise_id"]], how = "inner")
unknown
d3969
train
It is weird but you will have to do this in your header: #ifndef _REENTRANT #define _REENTRANT /* For some reason __erl_errno is undefined unless _REENTRANT is defined */ #endif #include "erl_interface.h" #include "ei.h" This fixed the problem for me. Now I can use erl_errno.
unknown
d3970
train
Not sure if I read the question correctly, but would this work in you situation public void FindCharRepetitions(string toCheck) { var result = new Dictionary<char, int>(); foreach (var chr in toCheck) { if (result.ContainsKey(chr)) { result[chr]++; continue; } result.Add(chr, 1); } foreach (var item in result) { Console.WriteLine("Char: {0}, Count: {1}", item.Key, item.Value); } } A: If the number of different characters is known (say only A-Z) then the code could be like this: int[] counters = new int['Z' - 'A' + 1]; foreach(char c in toCheck) if (c >= 'A' && c <= 'Z') counters[c - 'A']++;
unknown
d3971
train
If you planning to support IOS (APNS) and Android (GCM), you can use PushPlugin https://github.com/bobeast/PushPlugin It is easy to setup, where you can register for GCM using javascript and having the same interface for Android and IOS.
unknown
d3972
train
For rigid body physics, this code line is entirely correct IF fv is going to be added to the existing velocity of this, and the shape is an infinite mass boundary. If your other code is trying to use fv as 'final velocity', it shouldn't have the constant 1 in it's calculation (and is simply wrong in oblique collisions anyway). For extension to finite mass pair collisions the 1D constant turns into a signed weighting function, which I'll leave as an exercise for the reader.
unknown
d3973
train
Your code is OK, but not very object-oriented. I would probably use some kind of Drawer interface, and pass the appropriate implementation, rather than an int, to the draw_graph method (which I would rename drawGraph to respect naming conventions): public interface Drawer { void draw(MyObj obj, Graphics g); } ... private void drawGraph(Drawer drawer) { for(int i = 0; i < amountOfValues; i++) { MyObj obj = arrayList.get(i); drawer.draw(obj, g); } } ... class Drawer1 implements Drawer { @Override public void draw(MyObj obj, Graphics g) { // same code as in case 1 of the switch } } class Drawer2 implements Drawer { @Override public void draw(MyObj obj, Graphics g) { // same code as in case 2 of the switch } } If all the drawers share some code, then make them all extend a base AbstractDrawer class. A: The x,y, and value are properties of MyObj. What does calc_color do, and where does scale_for_this_type come from? Could that work be done within, or largely within MyObj based upon it's fields?? If so, your loop could pretty much call myObj.drawLineYouFigureOutTheColor(perhapsAnArgumentOrTwoHere). You'd have to track last_x and last_y somewhere.
unknown
d3974
train
What identifies a string? Quotation marks. In your case: single quotes. Therefore, we want to match the content between quotes as a string. To do so, we can use the following lazy regex: '.*?' To allow both quotes, you could use: '.*?'|".*?" or the same with a backreference (['"]).*?\1. If it is allowed to escape strings, it gets even more complicated. I suggest using a recursive regex to do so: ((['"])(?>[^'"\\]++|\\.|(?1))*+\2) Samples matched: a = "abc dsfsd", b= ' abc dsfsd' c ="abc\" dsfsd" d= "abc\\" To match any identifiers but the strings you could use: [a-z]+(?=([^']*['][^']*['])*[^']*$) (Or here a version that matches both types of quotes: [a-z]+(?=([^'"]*(["'])[^"']*\2)*[^"']*$)) Again, it gets more involved if you want to account for escaped quotes: [a-z]+(?=([^"'\\]*(\\.|(["'])([^"'\\]*\\.)*[^"'\\]*\3))*[^"']*$) I hope, this helps.
unknown
d3975
train
You probably can't access current_user from controller (devise?). So you need to pass the user as a parameter to the class or instance method. What you should look into are scopes and especially scopes that accept parameters. Scopes could really help you refactor your Auction model (you really don't need any methods that only return a where()), but also solve the inaccessible current_user. Use it like this in your Auction model: scope: :highest_bidder -> (current_user) { where(highest_bidder: current_user) } And call it like this from your controller: @auctions = Auction.closed_auctions.highest_bidder(current_user)
unknown
d3976
train
If you are not using the MediaPlayer again then you can try releasing the MediaPlayer. joker.setOnClickListener(new OnClickListener(){ @Override public void onClick(View view) { jokerAudio.stop(); jokerAudio.reset(); jokerAudio.release(); view.setVisibility(View.INVISIBLE); } }); However if you are using MediaPlayer again later in your code don't forget to reinitialize it again.
unknown
d3977
train
Try to change the Chart's Width to a higher value... <asp:Chart ID="Chart1" runat="server" BorderColor="181, 64, 1" BorderDashStyle="Solid" BorderWidth="2" Height="296px" ImageLocation="~/TempImages/ChartPic_#SEQ(300,3)" ImageType="Png" Palette="None" Width="800px" BorderlineColor=""> Try to set the inverval property to 1 on axisx: <axisx Interval="1" linecolor="64, 64, 64, 64" intervaloffsettype="Months" intervaltype="Months" islabelautofit="False" isstartedfromzero="False"> To fully understand how to format chart axis, take a look at: Formatting Axis Labels on a Chart (source: microsoft.com) How the Chart Calculates Axis Label Intervals? On the category axis, the minimum and maximum value types are determined depending on the type of your category field. Any field in a dataset can be categorized into one of three category field types: Numeric, Date/Time and Strings. Displaying All Labels on the Category Axis On the value axis, axis intervals provide a consistent measure of the data points on the chart. However, on the category axis, this functionality can cause categories to appear without axis labels. Typically, you want all categories to be labeled. You can set the number of intervals to 1 to show all categories. For more information, see How to: Specify an Axis Interval. A: Use Microsoft chart chart.ChartAreas[0].AxisY.ScaleBreakStyle = true to chart the second set of values in thier on Y Axis with thier own Y values
unknown
d3978
train
OK, re-read and this didn't answer what you asked. Post your code, we need to see how you are iterating the results. The answer below is about ordering and not a missing record. You can do this with an order by on your query. SELECT id, description, order FROM mytable ORDER BY order ASC This will cause the query to be retrieved ordered by the order column, and you just need to make sure that the order in the database is largest for the record you want to appear last.
unknown
d3979
train
You could get all the digits till you reach the end of the string $ which will prevent matching the line ending with & yes -?\d+(?:\.\d+)?(?:, -?\d+(?:\.\d+)?)*$ Explanation * *-?\d+(?:\.\d+)? Match 1+ digits with an optional decimal value *(?: Non capture group * *, -?\d+(?:\.\d+)? Match a comma, space and a digit with an optional decimal value *)* Close group and repeat 0+ times *$ End of string Regex demo | Python demo Example code import re strings = [ "BATE Borisov", "BATE Borisov -0.5, -1.0", "Under 2.5", "BATE Borisov", "BATE Borisov 0.0, -0.5", "Over 1.0", "BATE Borisov -2.5", "Over 1.5", "Over 2.0, 2.5", "Over 2.5", "Over 3.5", "Under 2.5 & yes" ] regex = r"-?\d+(?:\.\d+)?(?:, -?\d+(?:\.\d+)?)*$" for s in strings: matches = re.search(regex, s) if matches: print(matches.group()) Output -0.5, -1.0 2.5 0.0, -0.5 1.0 -2.5 1.5 2.0, 2.5 2.5 3.5 A: You may use the following regex to match a CSV list of positive/negative floats: \b-?\d+(?:\.\d+)?(?:, -?\d+(?:\.\d+)?)* Sample scripts: inp = "BATE Borisov -0.5, -1.0" matches = re.findall(r'\b-?\d+(?:\.\d+)?(?:, -?\d+(?:\.\d+)?)*', inp) print(matches) This prints: ['0.5, -1.0'] inp = "Under 2.5 & yes" matches = re.findall(r'\b-?\d+(?:\.\d+)?(?:, -?\d+(?:\.\d+)?)*', inp) print(matches) This prints: ['2.5']
unknown
d3980
train
It looks like the first call to context.WithTimeout shadow the parent context ctx. The later process re-use this already canceled context hence the error. You have to re-use the parent one. Here is the example updated: func main() { // Avoid to shadow child contexts parent := context.Background() t := 2 * time.Second // Use the parent context. ctx1, cancel := context.WithTimeout(parent, t) defer cancel() err := LongProcess(ctx1, 2*time.Second, "first process") fmt.Println(err) // Use the parent context not the canceled one. ctx2, cancel := context.WithTimeout(parent, t) defer cancel() err = LongProcess(ctx2, 1*time.Second, "second process") fmt.Println(err) }
unknown
d3981
train
Try merge then create the summary values via groupby sum: new_df = ( df1.merge(df2) .drop('Area', 1) .groupby(['Month', 'State_Code', 'State_Name', 'Brand'], as_index=False, sort=False) .sum() ) new_df: Month State_Code State_Name Brand Price Sales 0 Jan TX01 Total_Country Nestle 29 610 1 Jan TX01 Total_Country Unilever 31 770 2 Feb TX01 Total_Country Abc 10 320 3 Feb TX01 Total_Country Nestle 29 850 4 Feb TX01 Total_Country Unilever 31 1010 5 Feb TX04 South Abc 10 320 6 Feb TX04 South Nestle 14 420 7 Feb TX04 South Unilever 15 500 8 Feb TX06 North Nestle 15 430 9 Feb TX06 North Unilever 16 510 10 Feb TX12 Mumbai Nestle 15 430 11 Feb TX12 Mumbai Unilever 16 510 A: You can do a pd.merge() with multiple columns, so that it is a dual-key merge/join. edit: you will also need to drop() the 'area' column df3 = pd.merge(df1,df2,on=['Month','Area']).drop('Area',axis=1) output = df3.groupby(['Month','State_Code','State_Name','Brand'],as_index=False,sort=False).sum() df3 Month Area State_Code State_Name Brand Price Sales 0 Jan 101 TX01 Total_Country Nestle 14 300 1 Jan 101 TX01 Total_Country Unilever 15 380 2 Feb 101 TX01 Total_Country Abc 10 320 3 Feb 101 TX01 Total_Country Nestle 14 420 4 Feb 101 TX01 Total_Country Unilever 15 500 5 Feb 101 TX04 South Abc 10 320 6 Feb 101 TX04 South Nestle 14 420 7 Feb 101 TX04 South Unilever 15 500 8 Jan 102 TX01 Total_Country Nestle 15 310 9 Jan 102 TX01 Total_Country Unilever 16 390 10 Feb 102 TX01 Total_Country Nestle 15 430 11 Feb 102 TX01 Total_Country Unilever 16 510 12 Feb 102 TX06 North Nestle 15 430 13 Feb 102 TX06 North Unilever 16 510 14 Feb 102 TX12 Mumbai Nestle 15 430 15 Feb 102 TX12 Mumbai Unilever 16 510 output Month State_Code State_Name Brand Area Price Sales 0 Jan TX01 Total_Country Nestle 203 29 610 1 Jan TX01 Total_Country Unilever 203 31 770 2 Feb TX01 Total_Country Abc 101 10 320 3 Feb TX01 Total_Country Nestle 203 29 850 4 Feb TX01 Total_Country Unilever 203 31 1010 5 Feb TX04 South Abc 101 10 320 6 Feb TX04 South Nestle 101 14 420 7 Feb TX04 South Unilever 101 15 500 8 Feb TX06 North Nestle 102 15 430 9 Feb TX06 North Unilever 102 16 510 10 Feb TX12 Mumbai Nestle 102 15 430 11 Feb TX12 Mumbai Unilever 102 16 510
unknown
d3982
train
You can' t add leading 0 to an integer and store in db you can manage only the selecting result .. eg select concat('0101', lpad(yourcol,2,'0')) from your_table or try force the cast select concat('0101', lpad(yourcol,2,'0'::text)) from your_table
unknown
d3983
train
Top-level (children of xs:schema) component definitions are inherently globally available. Nested definitions are only locally available – not referenceable elsewhere. See also * *How to reference global types in XSD? *How to define a local type in XSD?
unknown
d3984
train
Using OrderBy on Table2.Date var list = db.Table1.Where(some selection) .Where(x => x.Table2.Count() > 0) .OrderBy(x => x.Table2.FirstOrDefault().Date)ToList();
unknown
d3985
train
I solve it. Add osmdroid-android-4.2.jar, osmdroid-third-party-4.2.jar, slf4j-android-1.7.7.jar and slf4j-api-1.7.7 as external JARs. And put all four files into the libs directory of the "test" project.
unknown
d3986
train
<Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid Grid.Row="0" Grid.Column="0"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="200" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0" Content="Date From:" /> <Label Grid.Row="1" Grid.Column="0" Content="Date To:" /> <DatePicker Grid.Column="1" Grid.Row="0" Margin="3" x:Name="DateFrom" /> <DatePicker Grid.Column="1" Grid.Row="1" Margin="3" x:Name="DateTo" /> <Button Grid.Column="1" Grid.Row="2" HorizontalAlignment="Right" MinWidth="80" Margin="3" Content="Send" Click="PopulateGrid" x:Name="BtnPopulateGrid"/> </Grid> <Grid Grid.Row="0" Grid.Column="1"> <DataGrid x:Name="Grid" Padding="10 0 0 0" VerticalScrollBarVisibility="Visible" /> </Grid> </Grid> Firstly if you wanna make your datagrid fill a container automatically, you need to use Grid, not StackPanel also your datagrid sizes need to be set auto. Edit: As @Erjon said : You don't have to use a container when you have a single DataGrid.But if you have more components with your DataGrid, Grid will be a better container choice instead of StackPanel. Your main GridDefination sizes were set as Auto, that was wrong.You need to work with "*" if you want a resposive design.Auto means that "Set this control's size with its children". A: Try adding in the datagrid ColumnWidth="*" It will expand all columns to avaiable space and the datagrid will fill it's parent The second ColumnDefinition of the first grid should be <ColumnDefinition Width="*" /> And as @Zacos said in my answers comment you have to remove Width
unknown
d3987
train
There's unfortunately no way to give you a straight answer at this time: we have no knowledge of how your PDFs are "attached" to your pages or how your DB is structured. The best solution would be to create a robots.txt file that blocks the URLs for the particular PDF files that you want to remove. Google will drop them from the index on its next pass (usually in about an hour). http://www.robotstxt.org/ A: What we ended up doing was tying a check script to the upload script that once it completed the current upload, old files were "unlinked" and the DB records were deleted. For us, this works because it's kind of an "add one/remove one" situation where we want a set number of of items to appear in a rolling order.
unknown
d3988
train
Consider looking at the .gitignor file, please. if you put src folder or src/app in .gitignor then it's not shown in git bash
unknown
d3989
train
You can try a space filling curve and a quadtree data structure. A space filling curve reduces the 2 dimension to 1 dimension and it works best with power of 2 grids. A quadtree divides the plane into 4 quads. A space filling curve is mathematical function taking 2 variables and gives 1 number as result. It can have also 3,4,5 variables but the most simple is with 2. Because it gives 1 number and takes 2 variables it can help for questions with 2 dimensions or more. * *http://social.technet.microsoft.com/wiki/contents/articles/9694.tuning-spatial-point-data-queries-in-sql-server-2012.aspx *https://www.google.com/search?q=nearest+neigbor+search+space+filling+curve A: Use a k-dim tree index (in this case k=2) so a quad tree. This should allow you to efficiently search the space to the left,right,up and down of your point. You can probably formulate a query in a dmbs for this but conceptually I would search the points own "quad" and then depending on the position of the point in the quad we can know if we found the nearest point in one direction or not. Then we know which quads to search for the rest of the points. Since you are doing this for each point you know there exists symmetry i.e. point P1 has P2 as nearest left neighbor so P2 has P1 as nearest right neighbor. So update the point objects accordingly.
unknown
d3990
train
Make an array for your month names like so $montnames = ['', "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dez"]; Trick is to leave first one empty, because months begin with 1 and arrays count at 0. echo $month[2]; // feb
unknown
d3991
train
Here are three ways to import an image (SVG and PNG) into a React project. You can use either file type with all three options. * *Import image and use it in a src attribute. *Import image and use it in a style attribute. *Dynamically insert into a require function. See examples below: import React from 'react'; import backgroundImg from '../assets/images/background.png'; import logoImg from '../assets/images/logo.svg'; const Test = props => { const imageLink = 'another.png' // const imageLink = props.image // You can loop this component in it's parent for multiple images. return ( <div> <img src={logoImg} style={{ width: '200px', height: '45px' }} /> <div style={{ width: '100%', height: '100%', backgroundImage: `url(${backgroundImg})`, backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundSize: 'cover', position: 'fixed'}} /> <img width={900} height={500} alt="test img" src={require(`../assets/images/${imageLink}`)}/> </div> ) } export default Test
unknown
d3992
train
My current pragmatic solution which may be okay since only 4 values need to be handled: public static BitSet transformToBitSet(short[] numbers) { BitSet data = new BitSet(); int nBit = 0; for (int i = 0; i < numbers.length; i++) { short number = numbers[i]; switch (number) { case 0: data.set(nBit++, false); data.set(nBit++, false); break; case 1: data.set(nBit++, true); data.set(nBit++, false); break; case 2: data.set(nBit++, false); data.set(nBit++, true); break; case 3: data.set(nBit++, true); data.set(nBit++, true); break; default: throw new RuntimeException("Invalid number encountered. Can't map values >4"); } } return data; } A: Here is one way to do it. * *set the desired bitLength (used for padding on the left with zero bits); *initialize the BitSet index to 0. *The iterate over the values. *convert each to a bit string. *pad on the left to achieve the desired bit length *then set the bits based on the numeric value of the bit BitSet b = new BitSet(); short[] vals = { 0, 2, 3, 1 }; int bitLength = 2; int idx = 0; for (short v : vals) { String bits = Integer.toBinaryString(v); bits = "0".repeat(bitLength - bits.length())+bits; for (char c : bits.toCharArray()) { b.set(idx++, c - '0' == 1); } } System.out.println(b) prints 2,4,5,7
unknown
d3993
train
You can use ESLint's built-in no-restricted-syntax rule to disallow the FunctionExpression and FunctionDeclaration AST nodes: { "rules": { "no-restricted-syntax": [ "error", "FunctionExpression", "FunctionDeclaration" ] } } This doesn't explicitly "prefer" arrow functions, but if you disallow all ArrowFunctionExpression alternatives, then you effectively enforce arrow functions only. With the above rule, these fail: // VariableDeclaration containing a FunctionExpression const f1 = function () {} // FunctionDeclaration function f2() {} class C { // MethodDefinition containing a FunctionExpression m() {} } These pass: // VariableDeclaration containing an ArrowFunctionExpression const f = () => {} class C { // PropertyDefinition containing an ArrowFunctionExpression m = () => {} } If you want to allow FunctionExpression and FunctionDeclaration nodes when they reference this or when they are generator functions (there's no such thing as an arrow generator function currently), then you can use esquery syntax to specifically disallow those nodes when they don't have a ThisExpression node as a descendant and they aren't generator functions: { "rules": { "no-restricted-syntax": [ "error", "FunctionExpression[generator=false]:not(:has(ThisExpression))", "FunctionDeclaration[generator=false]:not(:has(ThisExpression))" ] } } With the above rule, these fail: // VariableDeclaration containing a FunctionExpression const f1 = function () {} // FunctionDeclaration function f2() {} class C { // MethodDefinition containing a FunctionExpression m() {} } These pass: // VariableDeclaration containing a FunctionExpression containing a ThisExpression const f1 = function () { this.x = 42 } // VariableDeclaration containing a FunctionExpression[generator=true] const f2 = function* () {} // FunctionDeclaration containing a ThisExpression function f3() { this.x = 42 } // FunctionDeclaration[generator=true] function* f4() {} // VariableDeclaration containing an ArrowFunctionExpression const f5 = () => {} class C { // MethodDefinition containing a FunctionExpression containing a ThisExpression m1() { this.x = 42 } // MethodDefinition containing a FunctionExpression[generator=true] *m2() {} // PropertyDefinition containing an ArrowFunctionExpression m3 = () => {} } Unfortunately, the function f in the following example is also allowed even though it could be rewritten as an arrow function: function f() { function g() { this.x = 42 } return g } I wasn't able to come up with an esquery selector that includes functions like f while excluding functions like g. A: You can use this ESLint prefer-arrow-callback rule which would flag with error/warning anywhere you could use an arrow function instead of a function expression A: Anser based on @JohannesEwald comment and @KevinAmiranoff answer. I'm using the following rules: https://www.npmjs.com/package/eslint-plugin-prefer-arrow https://eslint.org/docs/rules/prefer-arrow-callback https://eslint.org/docs/rules/func-style npm install -D eslint-plugin-prefer-arrow .eslintrc or package.json with eslintConfig: "plugins": [ "prefer-arrow" ], "rules": { "prefer-arrow/prefer-arrow-functions": [ "error", { "disallowPrototype": true, "singleReturnOnly": false, "classPropertiesAllowed": false } ], "prefer-arrow-callback": [ "error", { "allowNamedFunctions": true } ], "func-style": [ "error", "expression", { "allowArrowFunctions": true } ] } I think this works really well. If you need to disable the rules for a specific line I do it like this: // eslint-disable-next-line func-style, prefer-arrow/prefer-arrow-functions A: allow only arrow function guide you can refer this. in the .eslintrc.json file enter these in the rules section: "react/function-component-definition": [2, { "namedComponents": "arrow-function" }]
unknown
d3994
train
You could use the ActivatedRoute service and subscribe to the url observable. Based on the value you get there you decide on what data to load. Another approach would be to use params in the path, so you would have something like 'submenu/1' and 'submenu/2' where 1 and 2 are an 'id' parameter and in the activated route you read them from the params Observable. In this way it's more easily extendable and you could use something more meaningful for the param values. Routes config: const routes: Routes = [ { path: "submenu/:menuId", component: SubmenuComponent, outlet: "menus" }, ... ]; And then in the SubmenuComponent you can handle the OnInit lifecycle event and fetch the param: ngOnInit() { this.route.params .subscribe(({ menuId }) => { /* load data based on menuId */ }); } this.route is an instance of the ActivatedRoute service which you can inject in constructor: constructor(private route: ActivatedRoute) { } A: TS import { Component, OnInit } from "@angular/core"; import { Router, Event, NavigationEnd } from "@angular/router"; import { SubMenu, Settings } from "../navbar.model"; @Component({ ... }) export class SubmenuComponent implements OnInit { constructor(private router: Router) { router.events.subscribe((event: Event) => { if (event instanceof NavigationEnd) { let url : string = router.url; let index : number = getIndexFromUrl(url); this.menus = Settings.menus[index].subs; } }); } ngOnInit() { } private menus: SubMenu[]; } Routing const routes: Routes = [ { path: "submenu1", component: SubmenuComponent, outlet: "menus" }, { path: "submenu2", component: SubmenuComponent, outlet: "menus" }, ... ];
unknown
d3995
train
You could fire up the android emulator from the android sdk , then using android debugging bridge fire up the following command adb shell am start -a android.intent.action.VIEW -d http://stackoverflow.com then follow the following blog http://android.amberfog.com/?p=168 , to take screen shot . A: No. It looks like this site renders the website on the server side, and then sends down an image of this to your browser. If you are interested only in Android and iPhone (and similar smartphones with browsers based on webkit) then you could try a similar approach to http://iphonetester.com. This uses a frame embedded to simulate the size (in pixels) of an iPhone. Note, that even though these browsers may be based on webkit, it doesn't mean their implementation is the same - see http://www.quirksmode.org/webkit.html for variance across different webkit based browsers. This won't work if you want to stray to other non webkit based browsers.
unknown
d3996
train
using the indices in the iteration solves the problem! for i in range(len(array)): array[i]*=5
unknown
d3997
train
It's easy to compute the timestamp in milliseconds for now and now-24h so why not do it in your application logic and build the query out of those values? For instance (in JS), const now = new Date().getTime(); const now24h = now - 86400000; const query = `timestamp:[${now24h} TO ${now}]`; query would contain the following value: timestamp:[1647785319578 TO 1647871719578] UPDATE: PS: I might have misunderstood the initial need, but I'm leaving the above answer as it might help others. What you need to do in your case is to change your mapping so that your date field accepts both formats (normal date and timestamp), like this: PUT your-index/_mapping { "properties": { "timestamp": { "type": "date", "format": "date_optional_time||epoch_millis" } } } Then you'll be able to query like this by mix and matching timestamps and date math: GET test/_search?q=timestamp:[now-24h TO 1645825932144] and also like this: GET test/_search?q=timestamp:[1645825932144 TO now]
unknown
d3998
train
Found an alternative, which I think it actually always was the right way to do it. import telegram btc_plot.savefig('signal.png',dpi=300, bbox_inches = "tight") telegram.Bot(token= token_str).send_photo(chat_id= chat_id_str, photo=open("signal.png", 'rb'), caption="Fue detectada una señal bajista en el par BTC/USDT!") Output:
unknown
d3999
train
If you just want to add new event handlers without overwriting the existing event handlers, you can use addEventListener() or attachEvent() (for older versions of IE) instead of setting .onclick, .onsubmit, etc... to add a new event handler without affecting the previous event handlers. Here's a simple cross browser function to add an event: // add event cross browser function addEvent(elem, event, fn) { if (elem.addEventListener) { elem.addEventListener(event, fn, false); } else { elem.attachEvent("on" + event, function() { // set the this pointer same as addEventListener when fn is called return(fn.call(elem, window.event)); }); } } There is no cross browser way that I'm aware of from regular javascript to interrogate existing DOM objects to see which ones have regular javascript event handlers installed via addEventListener or attachEvent. If the event handlers are installed with jQuery, they can be interrogated via this technique. There is some future spec work that has been done to add a property that would list all the event handlers, but I am not sure it is implemented yet. You can read more about that here. For event handlers installed with onclick, onsubmit, onfocus, etc..., you can check all existing DOM elements to see which ones have handlers assigned for those events and you can then hook them if you want to. // add other events here you are interested in var events = ["onclick", "onsubmit", "onfocus", "onblur"]; var elems = document.getElementsByTagName("*"), item; for (var i = 0; i < elems.length; i++) { item = elems[i]; for (var j = 0; j < events.length; j++) { if (item[events[j]]) { console.log("event handler for " + events[j]); } } } A: You can actually get what you want by changing the prototype of addEventListener and attachEvent: // intercept events cross browser var method; if (HTMLElement.prototype.addEventListener) { method = 'addEventListener'; } else { method = 'attachEvent'; } HTMLElement.prototype.realAddEventListener = HTMLElement.prototype[method]; HTMLElement.prototype[method] = function(a,b,c) { console.log('here are all the events being added:', arguments); this.realAddEventListener(a,b,c); }; Of course, it's important that this is added into the page before any other page scripts, but it can come after or before libraries like jQuery, but might have conflicts on the prototype with prototype.js, not sure. You'll also want to check for onclicks and the whole set of events, which you can find by running console.dir(document.createElement('a')) in a javascript console.
unknown
d4000
train
You can think of having @ControllerAdvice or @RestControllerAdvice for exception handling. Here you will have complete control over how you want to handle exception/error.
unknown