text
stringlengths
64
89.7k
meta
dict
Q: Не работает transition в Chrome при :hover на многоцветных иконках, стили которых заданы CSS переменными Есть svg иконка которая вставляется с помощью <use>. Необходимо добиться плавности перехода от одних цветов к другим при :hover. Иконка состоит из нескольких элементов и каждый должен менять цвет на какой-то свой определенный поэтому здесь не подойдет конструкция в css вида svg { fill: #ddd; transition: .25s; } svg:hover { fill: #ddd; } Минимальный пример реализован ниже. p.s. если проверять с FF то все работает, но в chrome и opera беда :root { --color: #33d; --color-bg: #99b; } svg { width: 30px; height: 30px; } circle, path { transition: 0.25s; } svg:hover { --color: #d33; --color-bg: #d99; } <div style="display: none;"> <svg id="play" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle cx="11" cy="11" r="11" fill="var(--color)"/> <circle cx="11.0001" cy="11.0001" r="9.9" fill="var(--color-bg)"/> <path d="M8.7998 13.4619V8.4001C8.7998 7.61556 9.66199 7.13657 10.3281 7.55104L14.1245 9.91323C14.7308 10.2905 14.7577 11.1634 14.1757 11.5772L10.3793 14.2769C9.71725 14.7477 8.7998 14.2743 8.7998 13.4619Z" fill="var(--color)"/> </svg> </div> <svg> <use xlink:href="#play"></use> </svg> A: Похоже, что это действительно проблема Chrome, когда он обрабатывает переменные в <use> Пробовал различные варианты и комбинации, но transition с переменными не работает Убрал <use>, окружности и path обернул в групповой тег <g id="play"> и в chrome заработало. :root { --color: #33d; --color-bg: #99b; } svg { width: 30px; height: 30px; } circle, path { transition: 0.5s; } #play:hover { --color: #d33; --color-bg: #d99; } <div > <svg viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg"> <g id="play"> <circle cx="11" cy="11" r="11" fill="var(--color)"/> <circle cx="11.0001" cy="11.0001" r="9.9" fill="var(--color-bg)"/> <path d="M8.7998 13.4619V8.4001C8.7998 7.61556 9.66199 7.13657 10.3281 7.55104L14.1245 9.91323C14.7308 10.2905 14.7577 11.1634 14.1757 11.5772L10.3793 14.2769C9.71725 14.7477 8.7998 14.2743 8.7998 13.4619Z" fill="var(--color)"/> </g> </svg> </div> Ниже пример с трехцветной иконкой :root { --tr:1s; } #cup { --color-1: #c13127; --color-2: #ef5b49; --color-3: #cacaea; } #cup:hover { --color-1: gold; --color-2: skyblue; --color-3: yellowgreen; } rect, path { transition: var(--tr); { <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 20 20" > <g id="cup"> <path fill="var(--color-1)" d="M15,17H14V9h3a3,3,0,0,1,3,3h0A5,5,0,0,1,15,17Zm1-6v3.83A3,3,0,0,0,18,12a1,1,0,0,0-1-1Z"/> <rect fill="var(--color-2)" x="1" y="7" width="15" height="12" rx="3" ry="3"/> <path fill="var(--color-3)" d="M7.07,5.42a5.45,5.45,0,0,1,0-4.85,1,1,0,0,1,1.79.89,3.44,3.44,0,0,0,0,3.06,1,1,0,0,1-1.79.89Z"/> <path fill="var(--color-3)" d="M3.07,5.42a5.45,5.45,0,0,1,0-4.85,1,1,0,0,1,1.79.89,3.44,3.44,0,0,0,0,3.06,1,1,0,1,1-1.79.89Z"/> <path fill="var(--color-3)" d="M11.07,5.42a5.45,5.45,0,0,1,0-4.85,1,1,0,0,1,1.79.89,3.44,3.44,0,0,0,0,3.06,1,1,0,1,1-1.79.89Z"/> </g> </svg>
{ "pile_set_name": "StackExchange" }
Q: How to find the SyntaxNode for a method Symbol in a CompilationUnit? I've added a bunch of nodes to a compilation unit, and now I would like to look up the syntax node corresponding to a given symbol: var compilation = Compilation.Create("HelloWorld") .AddSyntaxTrees(SyntaxTree.ParseCompilationUnit("<some namespace>")); ISymbol symbol = // some arbitrary symbol, e.g. a method whose syntax node I had compilation.GlobalNamespace.GetNamespaceMembers().First(); SyntaxToken token = ???; // how do I get the token for that symbol? How do I get the token for that symbol? Note: My goal is to be able to get the method body for each method from it MethodSymbol. A: Use ISymbol.DeclaringSyntaxReferences.
{ "pile_set_name": "StackExchange" }
Q: Why do I get null cannot be cast to non-null type net.corda.core.identity.Party error with Oraclize? I've been trying to implement Oraclize into my CorDapp and the flow I have created works perfectly but when I try to add an Oraclize query I received the error: null cannot be cast to non-null type net.corda.core.identity.Party. This is the code in question. val current = LocalDateTime.now().toString() val airplaneStatus = subFlow(OraclizeQueryAwaitFlow( datasource = "URL", query = "json(https://api.flightstats.com/flex/flightstatus/rest/v2/json/flight/status/" + flight.subSequence(0,2) + "/" + flight.subSequence(2, flight.length) + "/arr/" + current.subSequence(0,4) + "/" + current.subSequence(5,7) + "/" + current.subSequence(8,10) + "?appId=******&appKey=***********&utc=false).flightStatuses.status", proofType = ProofType.TLSNOTARY, delay = 1 )) A flight is a simple Flight ID such as AC345 or WS9405. The entire flow is here: https://pastebin.com/7uvPnjEf UPDATE: I have added the delay parameter but the error persists (tried 0 and 1). I have also verified that ProofType.TLSNOTARY is non-null. Thanks in advance! Log Error Report: [WARN ] 2018-07-10T16:08:00,619Z [Node thread-1] flow.[a0362ed5-74b5- 4519-a80e-4adda70adca7].run - Terminated by unexpected exception {} kotlin.TypeCastException: null cannot be cast to non-null type net.corda.core.identity.Party at it.oraclize.cordapi.flows.OraclizeQueryAwaitFlow.call(OraclizeQueryAwaitFlow.kt:36) ~[InsureFlight-0.1.jar:?] at it.oraclize.cordapi.flows.OraclizeQueryAwaitFlow.call(OraclizeQueryAwaitFlow.kt:18) ~[InsureFlight-0.1.jar:?] at net.corda.core.flows.FlowLogic.subFlow(FlowLogic.kt:290) ~[corda-core-3.1-corda.jar:?] at com.insureflight.flows.IssuePolicy$Initiator.call(IssuePolicy.kt:76) ~[cordapp-0.1.jar:?] at com.insureflight.flows.IssuePolicy$Initiator.call(IssuePolicy.kt:37) ~[cordapp-0.1.jar:?] at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:96) [corda-node-3.1-corda.jar:?] at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:44) [corda-node-3.1-corda.jar:?] at co.paralleluniverse.fibers.Fiber.run1(Fiber.java:1092) [quasar-core-0.7.9-jdk8.jar:0.7.9] at co.paralleluniverse.fibers.Fiber.exec(Fiber.java:788) [quasar-core-0.7.9-jdk8.jar:0.7.9] at co.paralleluniverse.fibers.RunnableFiberTask.doExec(RunnableFiberTask.java:100) [quasar-core-0.7.9-jdk8.jar:0.7.9] at co.paralleluniverse.fibers.RunnableFiberTask.run(RunnableFiberTask.java:91) [quasar-core-0.7.9-jdk8.jar:0.7.9] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_172] at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_172] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [?:1.8.0_172] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [?:1.8.0_172] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_172] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_172] at net.corda.node.utilities.AffinityExecutor$ServiceAffinityExecutor$1$thread$1.run(AffinityExecutor.kt:62) [corda-node-3.1-corda.jar:?] A: Seing the repository from library on github and your log error (line 36 from OraclizeQueryAwaitFlow.kt, see here), I am presume that problem occurre because The call serviceHub.identityService.wellKnownPartyFromX500Name(OraclizeUtils.getNodeName()) return null The null value want be casted for Party, but it is no possible, throwing an TypeCastException My sugestions 1. (Recomended) Open an issue on this repository asking for this error solution and wait the response from developers, or 2. Fork this repository and you verify this cast attempt and use your repository forked
{ "pile_set_name": "StackExchange" }
Q: What is the minimum amount of action required to get in to heaven? I've had this discussion with a number of my Christian friends, and have never managed to get a definitive answer. There may not be just one, but I'd like some scriptural backings for each opinion, please. (This is my first question on here, and apologies if it's a bit too broad a topic without a definitive answer. I really hope there is one.) Some friends say that you need to be attending church regularly, praying, repenting, and being seen to "make an effort" to practice the Christian teachings every day, in every decision, etc. Whereas others say that all you need to do is accept Christ as your saviour, and believe that the way to heaven is through him, whether or not you choose to then live your life in a "Christian manner" after that. Are the former being too strict on themselves? Are the latter looking for an "easy way out" in allowing them to lead a life of sin? A: The real question is, where do your friends get their answers? Anyone can have their own ideas of how to get to heaven, but how do they know their ideas coincide with God? We must go to what God has said in his Word. Without throwing too many verses at you, I can tell you that your first group of friends give a "heaven attendance requirement" that is completely contradictory to what's stated in the bible. Romans 3:20 ESV For by works of the law no human being will be justified in his sight, since through the law comes knowledge of sin. Basically, no matter how good you are on the outside, you can never be good enough in God's eyes since his standard is No Sin Allowed. No amount of bible reading or church attendance will remove a person's sin, just like saving a person's life doesn't absolve you from a previous crime of murder. One must be totally righteous (i.e., sinless) to be justified before God. So since we can't get rid of our sin by any good thing we do, how do we make ourselves righteous? Answer: JESUS. Romans 3:21-22,28 ESV But now the righteousness of God has been manifested apart from the law, although the Law and the Prophets bear witness to it— the righteousness of God through faith in Jesus Christ for all who believe ... For we hold that one is justified by faith apart from works of the law. Your latter group of friends got it right: one need only believe that Jesus is the way and that makes you righteous before God. That is the "minimum amount of action required" to get into heaven. So the next question that you have is "Well if all I need to do is accept Jesus, does that mean I can sin all I want and Jesus just covers them?" Well, technically, yes--ALL yours sins are covered forever. But there's more to it. Paul addressed this very question in Romans 5 and 6. Since God's grace (through Jesus) covers all of our sins, can we just sin all we want? Romans 6:1-2,11 ESV What shall we say then? Are we to continue in sin that grace may abound? By no means! How can we who died to sin still live in it? ... So you also must consider yourselves dead to sin and alive to God in Christ Jesus. The answer is: All your sins are covered and are therefore no longer counted against you in God's eyes, but since God has basically saved your eternal life, why would you WANT to sin? Why would you want to submit yourself to the very thing that severed your relationship with God? When you believe in Jesus, God places his Holy Spirit inside of you and leads you into a new way of life--a way of good character. It's not this new way of life that saves you, Jesus already did that. But this Holy Spirit that lives in you convicts you, teaches you, comforts you, and helps you. Basically, you won't WANT to do evil after you become a Christian. Ephesians 1:13-14 ESV In him you also, when you heard the word of truth, the gospel of your salvation, and believed in him, were sealed with the promised Holy Spirit, who is the guarantee of our inheritance until we acquire possession of it, to the praise of his glory. Though we all fail. We all still sin sometimes, even Paul did. But Paul knew that his desire to sin came from his cursed body and that Jesus still covers all his sins: Romans 7:15,24,25 ESV For I do not understand my own actions. For I do not do what I want, but I do the very thing I hate. ... Wretched man that I am! Who will deliver me from this body of death? Thanks be to God through Jesus Christ our Lord! So then, I myself serve the law of God with my mind, but with my flesh I serve the law of sin.
{ "pile_set_name": "StackExchange" }
Q: C# List of splitted strings I have the following problem. I have these strings with whitespace between them. "+name:string" "+age:int" I split them with this code: List<string> stringValueList = new List<string>(); stringValueList = System.Text.RegularExpressions.Regex.Split(stringValue, @"\s{2,}").ToList<string>(); now the elements of List looks like this "+name:string" "+age:int" Now I want to split these strings and create Objects. This looks like this: // Storing the created objects in a List of objects List<myObject> objectList = new List<myObject>(); for(i = 1; i < stringValueList.Count ; i+=2) { myObject object = new myObject(); object.modifier = '+'; object.name = stringValueList[i-1].Trim('+'); // out of the example the object.name should be "name" object.type = stringValueList[i]; // out of the example the object.type value should "string" objectList.Add(object); } At the end I should get two objects with these values: List<myObject> objectList{ myObject object1{modifier = '+' , name ="name" , type="string"}, myObject object2{modifier='+', name="age" type="int"}} But my result looks like this: List<myObject> objectList {myObject object1 {modifier='+', name="name:string" type="+age:int"}} So instead of getting 2 Objects, I am getting 1 Object. It puts both strings into the elements of the first object. Can anyone help me out? I guess my problem is in the for loop because i-1 value is the first string in the List and i is the second string but I cant change this. A: I guess my problem is in the for loop because i-1 value is the first string in the List and i is the second string but I cant change this. I don't know why you do i += 2, because apparently you want to split each string in two again. So just have to change that. Use foreach(), and inside your loop, split your string again: foreach (var stringValue in stringValueList) { myObject object = new myObject(); var kvp = stringValue.Split(':'); object.modifier = '+'; object.name = kvp[0].Trim('+'); object.type = kvp[1]; objectList.Add(object); } Of course this code assumes your inputs are always valid; you'd have to add some boundary checks to make it more robust.
{ "pile_set_name": "StackExchange" }
Q: Winding maps of spheres? I know that the second homotopy group of $S^2$ is $\mathbb{Z}$. I also know that a simple representative of the class of maps that generates this group is the identity map on the sphere, $i:S^2\rightarrow S^2, p \rightarrow p$ In other words, this map has degree 1. My question is, are there simple representatives of the other elements of this group, and if so what are they? For instance, what is an example of map $S^2 \rightarrow S^2$ with degree 2? What about for arbitrary degree $n\in \mathbb{Z}$? Thanks in advance! A: If $n$ is an integer, the complex power map $z \mapsto z^{n}$ extends to a map of the Riemann sphere $\mathbf{C} \cup \{\infty\}$ having degree $n$. (It's understood that if $n = 0$, then $z^{n} = 0$ for all $z$, while if $n > 0$ then $\infty^{n} = \infty$, and if $n < 0$, then $\infty^{n} = 0$ and $0^{n} = \infty$. These conventions do not constitute an unqualified endorsement of the equations "$1/0 = \infty$", "$1/\infty = 0$", or "$\infty^{0} = 1$".) Visually, it may help to restrict the power mapping to the unit circle ("wind the circle around itself $n$ times"), then to suspend.
{ "pile_set_name": "StackExchange" }
Q: Calculating sum of squared deviations in R How can I calculate the sum of squared deviations(from the mean) of a vector? I tried using the command sum(x-mean(x))^2 but unfortunately what this returns is -1.998401e-15 which cannot be right. Is there a subtle operator, like a parenthesis, that I am missing here perhaps? Thanks. A: It may well be correct. -2.0 to the power of 10^15 means it is essentially zero. But as Justin just noted in the comment, you have (sum (x - mean(x) )^2 when you probably meant: sum( (x - mean(x) )^2 ) A: You can also use another way to calculate the sum of squared deviations: x <- 1:10 #an example vector # the 'classic' approach sum( (x - mean(x) )^2 ) # [1] 82.5 # based on the variance var(x) * (length(x) - 1) #[1] 82.5 The latter works because var(x) = (x - mean(x))^2) / (length(x) - 1). This is the sample variance:
{ "pile_set_name": "StackExchange" }
Q: How to find the variance of several images in MATLAB I am relatively new to MATLAB and Image processing, so understand with me. I am working in experiment on image processing, and my current stage, I need to 1) read some images (about 100 images of same dimension) 2) store them in a variable (either cell array, vector or structure) 3) Find the variance of each pixel in each image 4) Form a new matrix to store each computed variance Here is my code, but I am not sure it solves this problem not withstanding that I get result clc; im_File = dir('*.bmp'); files = {im_File.name}; for k=1:numel(files) im{k} = imread(files{k}); %# Get the number of dimensions for your arrays dim = ndims(im{k}); all_images = cat(dim+1,im{:}); % Use linear combine to acquire all the images Linear_comb_im = imlincomb(1,all_images,'uin'); %get the variance of all images computed_variance = var(double(Linear_comb_im),1,dim+1); end A: So it seems that you have a redundant variable here : both im and all_im basically save the same information. if the dimensions werent the same i would use a cell array, otherwise matlab likes matrices better. In addition, I am not sure why you are performing the linear combination. I would do the following: clc; im_File = dir('*.bmp'); files = {im_File.name}; for k=1:numel(files) im(:,:,k) = imread(files{k}); % to save time you should initialize im begore the loop i.e. im = zeros(m,n,numerl(files)), where m,n are the size of the images end %get the variance of all images computed_variance = var(double(im),1,3); so im here is a 3D matrix containing the images in the 3rd dimension. In order to access the idx image: im(:,:,idx)
{ "pile_set_name": "StackExchange" }
Q: How to get node Bundle in hook_form_alter on field config form? Can you wonderful people help me out please? I am altering the field config form (content types > plan > manage fields > edit field) and cannot seem to get the proper bundle out. Every time I call the bundle() function it returns the string "field_config". However the bundle is supposed to be "plan". Perhaps it's different because I am on the field config form, and not a node form? Below is my code, the things I've tried and the field object showing the proper bundle. Does anyone know of another solution for me to get "plan" out? <?php use Drupal\Core\Config\Entity\ThirdPartySettingsInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Entity\ContentEntityForm; /** * Implements hook_form_alter(). */ function rent_plan_custom_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) { // print $form_id; switch ($form_id) { case 'field_config_edit_form': print $form['#title']; $field = $form_state->getFormObject()->getEntity(); $field_name = $field->getName(); //returns correct field_plan_purpose //first try print $field->bundle(); //<---THIS RETURNS "field_config" //second try $bundle = FALSE; if ($form_object = $form_state->getFormObject()) { if ($form_object instanceof Drupal\Core\Entity\ContentEntityForm) { $bundle = $form_object->getEntity()->bundle(); } elseif ($form_object instanceof Drupal\field_ui\Form\FieldConfigEditForm) { $bundle = $form_object->getEntity()->bundle(); } print $bundle; //<---THIS RETURNS "field_config" } //Field Object Results Below print '<pre>'; print_r($field); print '</pre>'; break; } } Results from print_r($field) Drupal\field\Entity\FieldConfig Object ( [deleted:protected] => [fieldStorage:protected] => Drupal\field\Entity\FieldStorageConfig Object ( [id:protected] => node.field_plan_purpose [field_name:protected] => field_plan_purpose [entity_type:protected] => node [type:protected] => text_long [module:protected] => text [settings:protected] => Array ... lots of more stuff ) [id:protected] => node.plan.field_plan_purpose [field_name:protected] => field_plan_purpose [field_type:protected] => text_long [entity_type:protected] => node [bundle:protected] => plan [label:protected] => Purpose [description:protected] => [settings:protected] => Array ( ) ...lots more stuff ) A: You're looking for FieldDefinitionInterface::getTargetBundle Gets the bundle the field is attached to. This method should not be confused with EntityInterface::bundle() (configurable fields are config entities, and thus implement both interfaces): FieldDefinitionInterface::getTargetBundle() answers "as a field, which bundle are you attached to?". EntityInterface::bundle() answers "as a (config) entity, what is your own bundle?" (not relevant in our case, the config entity types used to store the definitions of configurable fields do not have bundles). e.g. $target_bundle = $field->getTargetBundle(); A: FieldConfigBase has a method on it(*) called getTargetBundle(). That will retrieve the field name. To be safe, you should also probably use getTargetEntityTypeId() to make sure you are dealing with a node: $entity_type = $field->getTargetEntityTypeId(); $bundle = $field->getTargetBundle(); if ($entity_type === 'node' && $bundle === 'plan') { do_something_awesome(); } Using a class-aware editor, like PHPStorm, will make things like this a lot easier because you add type-hints, and then it will autocomplete for you. In most OO code and some procedural code, a good IDE will automagiclly figure out your types, so you don't need to add the hinting. (*) You should really be looking at the interface(s) that these define. The one of interest in this case is FieldDefinitionInterface.
{ "pile_set_name": "StackExchange" }
Q: C++20: Concepts of multiple types and its constraint, correct syntax? It is confirmed that in the upcoming c++20 standard, according to this reddit report from the recent Cologne ISO C++ Meeting, we will be able to specify a template's concept and for each class/function template, we will be able to set the constraints on its types. However, in documentations and tutorials (e.g. here), I could not find the correct syntax for the multi-type use-case. Suppose we have a multi-type concept: template<typename T1, typename T2> concept AreEqComparable = requires(T1 a, T2 b) { { a == b } -> bool; }; Let's say, I want to define a simple comparison function between two different types. How can I do that? More specifically, what should I write in the ??? part of the code below: ??? bool are_equal(T1 a, T2 b) { return a == b; } I couldn't find any reference to this case in here, here, and even here. I have randomly tried something like: /* 1 */ template<AreEqComparable T1, T2> /* 2 */ AreEqComparable<T1, T2> /* 3 */ template<AreEqComparable<T1, T2>> But all of them throw syntax errors. I think the answer should lie somewhere in the specification P0557 by Bjarne Stroustrup, but I wasn't able to find it after a quick look. A: You can write it like this: template <typename T1, typename T2> requires AreEqComparable<T1, T2> bool are_equal(T1 a, T2 b) { // ... } Here, we use a requires-clause to impose a requirement on the type template parameters. A: You can write: template <typename T1, AreEqComparable<T1> T2> bool are_equal(T1, T2); This is equivalent to: template <typename T1, typename T2> requires AreEqComparable<T2, T1> bool are_equal(T1, T2); The types are flipped in the constraint here, AreEqComparable<T2, T1> instead of AreEqComparable<T1, T2>. This will certainly matter for many concepts, but probably not this one in particular since == itself becomes symmetric in C++20 (short of pathological cases which should not exist in real code). And if you want to be really sure that this symmetry is valid, you can always make it explicit in the concept (as EqualityComparableWith is in the working draft): template<typename T1, typename T2> concept AreEqComparable = requires(T1 a, T2 b) { { a == b } -> bool; { b == a } -> bool; }; You can actually get the constraint you want in the correct order by flipping the order of the template parameters (h/t Matthieu M.): template <typename T2, AreEqComparable<T2> T1> bool are_equal(T1, T2); A: Yet another syntax that avoids introducing template parameters at all (at the cost of adding other redundancy): bool are_equal(auto x,auto y) requires AreEqComparable<decltype(x),decltype(y)> {return x==y;}
{ "pile_set_name": "StackExchange" }
Q: How to get specific value from a JSON string? Java/Android I'm working on a project in android-studio. But I'm stuck on this point. I've made a request with Okhttp3 and this returns me a Response object. I can retrieve the response as a string (of a json file). MainActivity.java client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if(response.isSuccessful()) { String data = response.body().string(); JsonParser parser = new JsonParser(); try { JsonObject obj = (JsonObject) parser.parse(data); String ad = obj.get("features").toString(); Log.d("msg", data); Log.d("msg", ad); Log.d("msg", "Works"); } catch (Exception e) { Log.d("msg", "Error"); } Response 2019-05-22 10:55:12.785 1301-1631/com.example.triptracker D/msg: {"type":"FeatureCollection","query":[4.35822,51.91962],"features":[{"id":"address.2630076086694170","type":"Feature","place_type":["address"],"relevance":1,"properties":{"accuracy":"point"},"text":"Dotterbloemstraat","place_name":"Dotterbloemstraat 12c, 3135 Vlaardingen, Netherlands","center":[4.358192,51.919666],"geometry":{"type":"Point","coordinates":[4.358192,51.919666]},"address":"12c","context":[{"id":"postcode.7757734261857840","text":"3135"},{"id":"place.6763396954136802","wikidata":"Q210007","text":"Vlaardingen"},{"id":"region.8599455180798270","short_code":"NL-ZH","wikidata":"Q694","text":"Zuid-Holland"},{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"postcode.7757734261857840","type":"Feature","place_type":["postcode"],"relevance":1,"properties":{},"text":"3135","place_name":"3135, Vlaardingen, Zuid-Holland, Netherlands","bbox":[4.340678,51.909008,4.36899,51.925254],"center":[4.35,51.92],"geometry":{"type":"Point","coordinates":[4.35,51.92]},"context":[{"id":"place.6763396954136802","wikidata":"Q210007","text":"Vlaardingen"},{"id":"region.8599455180798270","short_code":"NL-ZH","wikidata":"Q694","text":"Zuid-Holland"},{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"place.6763396954136802","type":"Feature","place_type":["place"],"relevance":1,"properties":{"wikidata":"Q210007"},"text":"Vlaardingen","place_name":"Vlaardingen, Zuid-Holland, Netherlands","bbox":[4.270188,51.896102,4.369914,51.951478],"center":[4.35,51.91667],"geometry":{"type":"Point","coordinates":[4.35,51.91667]},"context":[{"id":"region.8599455180798270","short_code":"NL-ZH","wikidata":"Q694","text":"Zuid-Holland"},{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"region.8599455180798270","type":"Feature","place_type":["region"],"relevance":1,"properties":{"short_code":"NL-ZH","wikidata":"Q694"},"text":"Zuid-Holland","place_name":"Zuid-Holland, Netherlands","bbox":[3.7235244,51.64378,5.150749,52.390802],"center":[4.66667,52],"geometry":{"type":"Point","coordinates":[4.66667,52]},"context":[{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"country.9349515904622050","type":"Feature","place_type":["country"],"relevance":1,"properties":{"short_code":"nl","wikidata":"Q55"},"text":"Netherlands","place_name":"Netherlands","bbox":[3.1862592,50.750667,7.230902,53.665238],"center":[5.55,52.31667],"geometry":{"type":"Point","coordinates":[5.55,52.31667]}}],"attribution":"NOTICE: © 2019 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained. POI(s) provided by Foursquare."} 2019-05-22 10:55:12.786 1301-1631/com.example.triptracker D/msg: [{"id":"address.2630076086694170","type":"Feature","place_type":["address"],"relevance":1,"properties":{"accuracy":"point"},"text":"Dotterbloemstraat","place_name":"Dotterbloemstraat 12c, 3135 Vlaardingen, Netherlands","center":[4.358192,51.919666],"geometry":{"type":"Point","coordinates":[4.358192,51.919666]},"address":"12c","context":[{"id":"postcode.7757734261857840","text":"3135"},{"id":"place.6763396954136802","wikidata":"Q210007","text":"Vlaardingen"},{"id":"region.8599455180798270","short_code":"NL-ZH","wikidata":"Q694","text":"Zuid-Holland"},{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"postcode.7757734261857840","type":"Feature","place_type":["postcode"],"relevance":1,"properties":{},"text":"3135","place_name":"3135, Vlaardingen, Zuid-Holland, Netherlands","bbox":[4.340678,51.909008,4.36899,51.925254],"center":[4.35,51.92],"geometry":{"type":"Point","coordinates":[4.35,51.92]},"context":[{"id":"place.6763396954136802","wikidata":"Q210007","text":"Vlaardingen"},{"id":"region.8599455180798270","short_code":"NL-ZH","wikidata":"Q694","text":"Zuid-Holland"},{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"place.6763396954136802","type":"Feature","place_type":["place"],"relevance":1,"properties":{"wikidata":"Q210007"},"text":"Vlaardingen","place_name":"Vlaardingen, Zuid-Holland, Netherlands","bbox":[4.270188,51.896102,4.369914,51.951478],"center":[4.35,51.91667],"geometry":{"type":"Point","coordinates":[4.35,51.91667]},"context":[{"id":"region.8599455180798270","short_code":"NL-ZH","wikidata":"Q694","text":"Zuid-Holland"},{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"region.8599455180798270","type":"Feature","place_type":["region"],"relevance":1,"properties":{"short_code":"NL-ZH","wikidata":"Q694"},"text":"Zuid-Holland","place_name":"Zuid-Holland, Netherlands","bbox":[3.7235244,51.64378,5.150749,52.390802],"center":[4.66667,52],"geometry":{"type":"Point","coordinates":[4.66667,52]},"context":[{"id":"country.9349515904622050","short_code":"nl","wikidata":"Q55","text":"Netherlands"}]},{"id":"country.9349515904622050","type":"Feature","place_type":["country"],"relevance":1,"properties":{"short_code":"nl","wikidata":"Q55"},"text":"Netherlands","place_name":"Netherlands","bbox":[3.1862592,50.750667,7.230902,53.665238],"center":[5.55,52.31667],"geometry":{"type":"Point","coordinates":[5.55,52.31667]}}] 2019-05-22 10:55:12.786 1301-1631/com.example.triptracker D/msg: Works But what I need is the "place_name" which is nested inside "features". I've tried so much, but still don't know how to access "place_name". In JavaScript it's much simpler like features[0].place_name. But in Java it's unknown for me. Can somebody please help. The result that I want: "Dotterbloemstraat 12c, 3135 Vlaardingen, Netherlands" A: you should get the features as Json Array JsonArray ad = obj.getAsJsonArray("features"); JsonObject ob = ad.get(0).getAsJsonObject(); String placeName = ob.get("place_name").getAsString()
{ "pile_set_name": "StackExchange" }
Q: Save Logging messages when I click html link using log4j in java web application I need to save the logging messages into file when I click html link. I created dynamic web project and .jsp web file in eclipse. Also I'm using log4j for logging. For now I create log4j.properties file to save logging messages in file. Also I implemented Logger: private static final Logger logger = LoggerFactory.getLogger(Application.class); and the message: logger.info("start app"); But I need to save logging when I click some web page link or liked text from the created .jsp file. Something like this logging message: 2014-06-03 09:53:36,001 INFO root:01 - start app 2014-06-03 09:55:01,002 INFO root:02 - Selected: LINKED TEXT Please help or suggest. Thanks in advance A: This is how JSP works. JSP is converted to a servlet, that runs in the server side, serving http requests. When you click on a link in the browser, you're generating an event in the browser. This event may or may not generate a http request, and this request may or may not be sent to your servlet. If you need to capture the events in the browser, you have two ways I guess [1] capture the events in the client side, using for example a browser plugin. This is how automation plugins such as selenium works. They are pieces of code that run in the browser (in the client). [2] attach some javascript code in your page to the click event on every link, so if someone clicks on some anchor element, you also generate a http request to your servlet so you can log the event. The problem of this approach is that you need javascript code for all your pages in order to do that.
{ "pile_set_name": "StackExchange" }
Q: WFS request returns FeatureCollection with no feature - OpenLayers Created the WFS feature request as following: this.map.getViewport().addEventListener("click", (evt) => { //Point transformation to EPSG:25830 var proyeccion = getProjection('EPSG:25830'); var p = new Point(this.map.getEventCoordinate(evt)).transform(this.map.getView().getProjection(),proyeccion); //WFS Feature Request var featureRequest = new WFS().writeGetFeature({ srsName: 'EPSG:25830', featurePrefix: 'CP', featureTypes: ['CadastralParcel'], outputFormat: 'application/json', filter: containsFilter('MultiPolygon',p,'EPSG:25830') }); fetch('https://inspire.navarra.es/services/CP/wfs', { method: 'POST', body: new XMLSerializer().serializeToString(featureRequest) }).then((response) => { return response.json(); }).then((json) => { var features = new GeoJSON().readFeatures(json); this.vectorSource.addFeatures(features); }); }); This makes the getFeature request correctly using POST, with the following request payload: <GetFeature xmlns="http://www.opengis.net/wfs" service="WFS" version="1.1.0" outputFormat="application/json" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"> <Query typeName="CP:CadastralParcel" srsName="EPSG:25830"> <Filter xmlns="http://www.opengis.net/ogc"> <Contains> <PropertyName>MultiPolygon</PropertyName> <Point xmlns="http://www.opengis.net/gml" srsName="EPSG:25830"> <pos srsDimension="2">586784.8369967575 4722127.891344394</pos> </Point> </Contains> </Filter> </Query> </GetFeature> But the request above returns an empty FeatureCollection when clicking a point where there is a feature. The type of Features that I was supposed to get were Polygon. {"type":"FeatureCollection","totalFeatures":"unknown","features":[],"crs":null} Guess it could be because of the projections, but don't know where the mistake is. EDIT I'm using projection EPSG:25830. Defined like this: proj4.defs("EPSG:25830","+proj=utm +zone=30 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"); register(proj4); Added to the map's view and layers as following: const proyeccion = getProjection('EPSG:25830'); view: new View({ projection: proyeccion, center: fromLonLat([-1.629950,42.63],proyeccion), zoom: 9 }) //WMS source: new TileWMS({ url: 'http://localhost:3000/idena', params: {'LAYERS': 'catastro'}, projection: proyeccion }) A: You have used wrong PropertyName in your filter <Filter xmlns="http://www.opengis.net/ogc"> <Contains> <PropertyName>MultiPolygon</PropertyName> <Point xmlns="http://www.opengis.net/gml" srsName="EPSG:25830"> <pos srsDimension="2">586784.8369967575 4722127.891344394</pos> </Point> </Contains> </Filter> The PropertyName must be the name of the geometry as it is announced in the schema of the PropertyType. In WFS the schema can be read with the DescribeFeatureType request. For example the schema of a GeoServer demo layer https://demo.geo-solutions.it/geoserver/wfs?service=WFS&version=1.1.0&request=DescribeFeatureType&typename=states shows that the name of the geometry is "the_geom" <xsd:element name="the_geom" type="gml:MultiSurfacePropertyType" nillable="true" minOccurs="0" maxOccurs="1"/> In your case the request is https://inspire.navarra.es/services/CP/wfs?service=WFS&version=1.1.0&request=DescribeFeatureType&typename=CP:CadastralParcel The response does not show the schema directly but it has a reference to the INSPIRE schema document http://inspire.ec.europa.eu/schemas/cp/4.0/CadastralParcels.xsd that you can try to interpret. Another option is to read one feature with GetFeature request and check the name of the geometry from the response https://inspire.navarra.es/services/CP/wfs?service=WFS&version=1.1.0&request=GetFeature&typename=CP:CadastralParcel&maxFeatures=1 <gml:featureMember> <CP:CadastralParcel gml:id="ES.RRTN.CP.1010001"> <CP:areaValue uom="m2">101.2779</CP:areaValue> <CP:beginLifespanVersion nilReason="other:unpopulated" xsi:nil="true"/> <CP:geometry>MULTIPOLYGON (((42.64858704034896 -2.141289282470453, ... The full name of the geometry is CP:geometry but your experience seems to suggest that the namespace part must be dropped and filter that works looks like <Filter xmlns="http://www.opengis.net/ogc"> <Contains> <PropertyName>geometry</PropertyName> <Point xmlns="http://www.opengis.net/gml" srsName="EPSG:25830"> <pos srsDimension="2">586784.8369967575 4722127.891344394</pos> </Point> </Contains> </Filter>
{ "pile_set_name": "StackExchange" }
Q: How to pass a variable from Class to another Class? I am using Kivy and Kivymd. I have a problem with passing a variable between class Admin and class EditArticle. I need to pass my_string from Admin to EditArticle. I am trying to do this, but getting an empty string. So, in class Admin I have my_string. Then, in a method edit_article of class Admin i am setting value 'some text' for my_string. Then I am trying to get it in the method edit of class EditArticle. But it is empty all the time. I really cannot figure it out. If you run my code you will click on top menu admin. Then to click on any mdchip. Then to click on etit button in dialog window. Then to click on button to get my_string (but it always empty). This is my App.py from kivy.clock import Clock from kivymd.app import MDApp from kivy.properties import StringProperty, NumericProperty from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.boxlayout import BoxLayout from kivymd.uix.card import MDCard from kivymd.uix.chip import MDChip from kivy.core.window import Window Window.size = (600, 853) from kivymd.uix.menu import MDDropdownMenu from kivymd.theming import ThemableBehavior from kivymd.uix.behaviors import RectangularElevationBehavior from kivymd.uix.boxlayout import MDBoxLayout from kivymd.uix.button import MDFlatButton from kivymd.uix.dialog import MDDialog class WindowManager(ScreenManager): pass class AdminFooter(ThemableBehavior, RectangularElevationBehavior, MDBoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) self.md_bg_color = self.theme_cls.primary_color class ToolbarBack(ThemableBehavior, RectangularElevationBehavior, MDBoxLayout): pass class CustomToolbar(ThemableBehavior, RectangularElevationBehavior, MDBoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) self.md_bg_color = self.theme_cls.primary_color Clock.schedule_once(self.create_menu, 1) def create_menu(self, i): self.items = ['admin', 'settings'] menu_items = [{"text": f"{i}"} for i in self.items] self.menu = MDDropdownMenu( caller=self.ids.button_2, items=menu_items, width_mult=4, callback=self.get_item ) def get_item(self, instance): self.menu.dismiss() App.get_running_app().window_manager.current = instance.text class Content(BoxLayout): pass class Admin(Screen): dialog_get_article = None my_string = StringProperty() # My string def __init__(self, **kwargs): super().__init__(**kwargs) def get_article(self, instance,*args): self.dialog_get_article = MDDialog( title="Click the EDIT", buttons=[ MDFlatButton( text="EDIT", on_release = self.edit_article ), ], ) self.dialog_get_article.open() def edit_article(self, instance): self.my_string = 'some text' # set value App.get_running_app().window_manager.current = 'edit-article' self.dialog_get_article.dismiss() def on_enter(self, *args): data = [ {'id': 1, 'title': 'Arcicle 1', 'body': 'body of Article 1'}, {'id': 2, 'title': 'Arcicle 2', 'body': 'body of Article 2'}, {'id': 3, 'title': 'Arcicle 3', 'body': 'body of Article 3'} ] for x in data: chip = BlogChip(id=x.get('id'), title=x.get('title'), body=x.get('body')) self.ids.box.add_widget(chip) class EditArticle(Screen): var = StringProperty() def edit(self, instance): print(self.var, ' << it is goingt to be <my_string> from Admin') class UserSettings(Screen): pass class BlogChip(MDChip): get_admin = Admin() id = NumericProperty() title = StringProperty() body = StringProperty() class BlogCard(MDCard): pass class Detail(Screen): pass class ResultSearch(Screen): pass class Container(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) Clock.schedule_once(self.create_cards) def create_cards(self, i): pass class App(MDApp): def callback(self): self.window_manager.current = 'container' def build(self): self.theme_cls.primary_palette = 'Indigo' self.window_manager = WindowManager() return self.window_manager App().run() My app.kv <WindowManager> Container: id: scr_1 name: 'container' Detail: id: scr_2 name: 'detail' Admin: id: scr_3 name: 'admin' EditArticle: id: scr_4 name: 'edit-article' var: scr_3.my_string # <--------- ResultSearch: id: scr_5 name: 'result-search' UserSettings: id: scr_6 name: 'settings' <Admin>: BoxLayout: id: boxlayout_1 orientation: 'vertical' MDToolbar: pos_hint: {'top': 1} title: 'Admin Blog' left_action_items: [["arrow-left", lambda x: app.callback()]] ScrollView: MDStackLayout: adaptive_height: True padding: 10 spacing: dp(5) id: box <EditArticle> MDToolbar: title: 'Admin Blog' MDLabel: text: str(root.var) MDRaisedButton: text: 'click me to see a variable in console' pos_hint: {'center_x': .5, 'center_y': .5} on_release: root.edit(root) <MyToolbar@CustomToolbar>: size_hint_y: None height: self.theme_cls.standard_increment padding: "25dp" spacing: "12dp" MDLabel: id: label text: 'Blog' font_style: 'H6' theme_text_color: "Custom" text_color: 1,1,1,1 Widget: MDIconButton: id: button_2 icon: "dots-vertical" pos_hint: {"center_y": .5} theme_text_color: "Custom" text_color: 1,1,1,1 on_release: root.menu.open() <Container> BoxLayout: orientation: 'vertical' MyToolbar: MDLabel: text: 'Go To menu (dot-vertical/admin' halign: 'center' <BlogCard> <Detail>: <BlogChip> label: root.title icon: '' callback: root.get_admin.get_article A: Root Cause: In your app, there are two instances of class Admin instantiated. This first instance was instantiated in the kv file when you instantiated the root, WindowManager() in the build method. Snippets: <WindowManager>: ... Admin: id: scr_3 name: 'admin' ... The second instance was instantiated in the class BlogChip. Snippets: class BlogChip(MDChip): get_admin = Admin() ... The class attribute, my_string was updated in the second instance of class Admin. But the screen is referencing the instance instantiated by the root. Therefore, the app displayed empty string. Solution: The solution requires changes to the kv and python files. kv file: Replace callback: root.get_admin.get_article with callback: app.root.ids.scr_3.get_article Snippets: <BlogChip> label: root.title icon: '' callback: app.root.ids.scr_3.get_article Python file: Remove get_admin = Admin() in class BlogChip(MDChip): Snippets: class BlogChip(MDChip): id = NumericProperty() title = StringProperty() body = StringProperty() In method, edit() initialize class attribute, var Snippets: class EditArticle(Screen): var = StringProperty() def edit(self, instance): # Each screen has by default a property manager that # gives you the instance of the ScreenManager used. self.var = self.manager.ids.scr_3.my_string print(self.var, ' << it is going to be <my_string> from Admin') Output:
{ "pile_set_name": "StackExchange" }
Q: accessing derived member variables via pointers to derived class I try to understand the logic behind accessing members of a derived object. I have two pointers: If I change the variable in my derived class via a pointer to the derived class, I notice that I am not able to access the value of the variable via a inheritance type of pointer to the base class. #include <iostream> #include <string> class A { public: int x; }; class B : public A { public: int y; }; int main() { B* pB = new B; A* pA = new B; std::cout<<"Changing x via pB to 11"<<std::endl; pB->x=11; std::cout<<"This is x: " << pB->x<<std::endl; std::cout<<"What about this x: " << pA->x<<std::endl<<std::endl; std::cout<<"Changing x via pA to 42"<<std::endl; pA->x=42; std::cout<<"This is my new x: " << pB->x<<std::endl; std::cout<<"and what about this x now: " << pA->x; delete pA; delete pB; } Output: Changing x via pB to 11 This is x: 11 What about this x: 0 Changing x via pA to 42 This is my new x: 11 and what about this x now: 42 I would like to know what has happens and why there are two different values for x. What also bothers me is that when I work, for example, with multiple lists: a master list with pointers to all my objects (say some animal class) and a secondary list--a sub-sample of the master list with pointers to some objects (say class reptile: public animal, public predator)--and it happens that I wish to modify the values of these members through the second list (bool is_currently_in_water), I cannot do this in a straightforward (and to me intuitive) way. I have to keep track of the master list and first find out which animal object is a reptile, in order to make the necessary changes through the master list. Is polymorphism intended to be like this? This is perhaps a very basic question as I am a beginning to learn C++, and although I know how to overcome the problem my changing my code, I first trying to fully grasp what is going on as the above result was rather surprising. A: I would like to know what has happens and why there are two different values for x. The explanation is quite simple: you have two values of x because you have two separate objects of type B, referenced through two pointers pA and pB, which are completely independent of each other. When you print pB->x you print x attached to the object that you have allocated first; when you print pA-X, you print x attached to the object that you have allocated second. These two objects do not share member variables, so their xs are independent of each other. If you would like to see behavior when two pointers of different type refer to the same object, do this: B* pB = new B; A* pA = pB; Now pA and pB are pointing to the same object, so any changes to x through one pointer would be "visible" through the other pointer. Of course, now that there is only one allocation, you need to remove delete pA (or delete pB if you prefer) to avoid double-deletion of the same object.
{ "pile_set_name": "StackExchange" }
Q: Finding points on a bezier curve based on distance from another point So I have a 3D cubic bezier curve and a start point found anywhere along the curve and need to find a second point further down the curve that is a specific worldspace distance (not arclength distance) away from the first point. Another issue would be if the second point reached the end of the curve and still wasn't at the desired worldspace distance, in which case I would want it to continue along the tangent until the distance was reached. Any ideas? A: Alas, I don't know any closed-form equation giving you the point(s) you want. Perhaps the simplest technique to approximate that point is to recursively chop the Bezier curve up into 2 smaller Bezier curves using de Casteljau's algorithm. The recursion bottoms out when either (a) all the bounding points for the curve are all either too close or too far from the given point, or (b) all the bounding points for the curve are "close enough" to being equal to the desired distance (perhaps they all fit inside the same pixel). I'm pretty sure the maximum number of points on a given Bezier curve that are a given linear distance from some given point is 4 points. (This can happen when the given Bezier curve has a self-intersection). EDIT: Perhaps I should read the entire question before jumping in with a response, yes? The standard "four-points" Bezier curve segment can be seen as one piece of an infinitely long cubic curve. There may be a bend or loop or cusp at one location, but sufficiently far away from that sharp curve the path flattens out to close to 2 straight rays, each of which points in some arbitrary direction. Alas, the above solution only finds points that are on the short Bezier curve segment. I'm assuming you want the point(s) along that infinitely long cubic curve that are the given distance away from the given point, even if they are not on the short Bezier curve segment. == de Casteljau in reverse == You could run (recursive midpoint) de Casteljau's algorithm in reverse, generating a new four-point Bezier curve "double" the size of the last at every iteration, until you got one big enough to include the desired point(s). (When all 4 initial points are "too close" to the given point, then doubling is guaranteed to eventually produce a curve segment with the start point "too close", the end point "too far", and then you can use the above algorithm to converge on a point that is the desired distance away from the given point). This approach relies only on addition, subtraction, multiplication by two, and averaging, so in principle it should be relatively numerically robust. (It never actually evaluates the cubic formula at any location t). == zero-finding == You could convert from the four-point representation to the cubic polynomial representation, and use any root-finding algorithm to converge on one of the desired points. Newton's method should work pretty good, since short pieces of a Bezier curve are nearly straight. Could we adapt the Newton's method equations from Finding the Minimum Distance Between a Point and a Cubic Spline to this problem? I'll use the bisection algorithm for simplicity in description, even though that runs slower than Newton's method. As always, a cubic Bezier curve segment can be described as B(t) = (1-t)^3 * P0 + 3*(1-t)^2*t*P1 + 3*(1-t)*t^2*P2 + t^3*P3. (Unfortunately, this equation is not always numerically robust -- that's why many people use recursive halving using de Casteljau's algorithm instead). I'm assuming you have (or can find) the t_given value for your given point, x_given = B(t_given).x y_given = B(t_given).y The distance between your given point and some other point along the curve is given by Pythagorean theorem, distance2(t) = ( x_given - B(t).x )^2 + ( y_given - B(t).y )^2. distance(t) = sqrt(distance2(t)). The point(s) you are looking for are at the zeros of the function given_distance2 = given_distance^2. f(t) = distance2(t) - given_distance2. Assuming that the given distance is not zero, and the given point has a t_given < 1, the bisection algorithm would run something like left = t_given right = 1 // the endpoint of the given Bezier curve segment while( distance2(right) < given_distance2 ){ right = right*2 } At this point, the t_left is closer to the given point than the desired distance, and t_right is further away than the desired distance (or perhaps exactly equal). Since we have one point too close, and another point too far, the bisection algorithm should work. while( (abs(f(right) is too big) AND (abs(left - right) is too big) ){ // find midpoint midpoint = (t_left + t_right)/2 Next we check: does the first segment left...midpoint contain the zero, or midpoint...right ? if( f(left)*f(midpoint) < 0 ) then // throw away right half right = midpoint else // throw away left half left = midpoint } return( right ) At this point, the "right" value is the value of t, and B(right) is the corresponding point, such that the distance from that point to the original given point is (approximately) the given distance.
{ "pile_set_name": "StackExchange" }
Q: can I use dynamic library(shared object) in my iphone app? As is known to everyone, static libraries can work well in an Iphone App and your App can be easily approved by IOS App Store Unfortunately, the two static libraries I'm using now have the some C functions and variables. so I compiled them into *.dylib (dynamic libraries), and copy them to "Bundle Resources" in XCode. dylib_handle = dlopen(dylib_path_in_resource_bundle, RTLD_LAZY); func = dlsym(dylib_handle, "func"); // invoke func(); This works well in simulator and Ipad (of course, different dynamic libraries). I noticed that somebody said Iphone app does not support any third party dynamic libraries and my app will be rejected. (see here) but I carefully read the "App Store Review Guidelines", I found no item meet my question. I'm confused now! Does iphone app support dynamic libraries? Does IOS AppStore allow this? Who can give me an official response. A: As Bernardo Ramos states in a comment: "Since iOS8 we can use dynamic libraries". Dynamic libraries are not allowed by the App Store. No code may be loaded at run-time. The answer is to convert them to static libraries and compile them into the application. From iPhoneOSTechOverview: "If you want to integrate code from a framework or dynamic library into your application, you should link that code statically into your application’s executable file when building your project." Read "should" as "must" See SO Answer: Can create dynamic library for iOS?
{ "pile_set_name": "StackExchange" }
Q: Problem understanding sin(x) Hey peeps, I got this code: red = red + 1; trace("red: " + red); trace("Math.sin(red): " + Math.sin(red)); var newRed:uint = Math.abs(Math.sin(red)) * 255; trace("newRed: " + newRed); This code outputs the following: red: 256 Math.sin(red): -0.9992080341070627 newRed: 254 red: 257 Math.sin(red): -0.5733571748155426 newRed: 146 red: 258 Math.sin(red): 0.37963562682930313 newRed: 96 red: 259 Math.sin(red): 0.9835931839466808 newRed: 250 etc. When I plug sin(257) into the calculator I get -0.974370064785235 but Flash is coming up with -0.5733571748155426 Edit:- However when I plug sin(256) i get the same number from each. This is what confuses me. I'm a bit confused about why this is. Please help. Alex A: Make sure you supply the right format of input arguments. Some may expect the parameter to express the angle in radians, some in degree. http://en.wikipedia.org/wiki/Sine?section=9#Properties_relating_to_the_quadrants According to the Action Script reference the sin function expects the parameter as radian. A: Flash is using radians units, the calculator is using degree units.
{ "pile_set_name": "StackExchange" }
Q: How to remove a sticker from Telegram sticker set (for every user) I created a sticker set by my bot. I added there some junk images. Now I ask myself a question: How to remove a single sticker from Telegram sticker set for every user? A: You should use @Stickers Bot, all you need to do is type /delsticker and follow the directions from there. As long as you are the owner of the sticker pack, it shouldn't be a problem.
{ "pile_set_name": "StackExchange" }
Q: What is the "->" operator in Java? Is it even an operator? I saw this bit of code on Oracle's java documentation page for java.util.stream int sum = widgets.stream() .filter(b -> b.getColor() == RED) .mapToInt(b -> b.getWeight()) .sum(); My question - what does "b -> b.getColor()" mean? What is the -> operator? A: The -> is part of a lambda expression. These were introduced in Java 8, and you can read more about them in The Java Tutorials. In short, a lambda expression can replace an anonymous class if you are implementing an interface that contains only one method. Also, the syntax of the lambda expression is described in detail in the JLS §15.27: A lambda expression is like a method: it provides a list of formal parameters and a body - an expression or block - expressed in terms of those parameters. LambdaExpression: LambdaParameters -> LambdaBody Examples: () -> {} // No parameters; result is void () -> 42 // No parameters, expression body () -> { // Complex block body with returns if (true) return 12; else { int result = 15; for (int i = 1; i < 10; i++) result *= i; return result; } } (int x) -> x+1 // Single declared-type parameter
{ "pile_set_name": "StackExchange" }
Q: obj.nil? vs. obj == nil Is it better to use obj.nil? or obj == nil and what are the benefits of both? A: Is it better to use obj.nil? or obj == nil It is exactly the same. It has the exact same observable effects from the outside ( pfff ) * and what are the benefits of both. If you like micro optimizations all the objects will return false to the .nil? message except for the object nil itself, while the object using the == message will perform a tiny micro comparison with the other object to determine if it is the same object. * See comments. A: Personally, I prefer object.nil? as it can be less confusing on longer lines; however, I also usually use object.blank? if I'm working in Rails as that also checks to see if the variable is empty. A: Syntax and style aside, I wanted to see how "the same" various approaches to testing for nil were. So, I wrote some benchmarks to see, and threw various forms of nil testing at it. TL;DR - Results First The actual results showed that using obj as a nil check is the fastest in all cases. obj is consistently faster by 30% or more than checking obj.nil?. Surprisingly, obj performs about 3-4 times as fast as variations on obj == nil, for which there seems to be a punishing performance penalty. Want to speed up your performance-intensive algorithm by 200%-300%? Convert all obj == nil checks to obj. Want to sandbag your code's performance? Use obj == nil everywhere that you can. (just kidding: don't sandbag your code!). In the final analysis, always use obj. That jives with the Ruby Style Guide rule: Don't do explicit non-nil checks unless you're dealing with boolean values. The Benchmark Conditions OK, those are the results. So how is this benchmark put together, what tests were done, and what are the details of the results? The nil checks that I came up with are: obj obj.nil? !obj !!obj obj == nil obj != nil I picked various Ruby types to test, in case the results changed based on the type. These types were Fixnum, Float, FalseClass, TrueClass, String, and Regex. I used these nil check conditions on each of the types to see if there was a difference between them, performance-wise. For each type, I tested both nil objects and non-nil value objects (e.g. 1_000_000, 100_000.0, false, true, "string", and /\w/) to see if there's a difference in checking for nil on an object that is nil versus on an object that's not nil. The Benchmarks With all of that out of the way, here is the benchmark code: require 'benchmark' nil_obj = nil N = 10_000_000 puts RUBY_DESCRIPTION [1_000_000, 100_000.0, false, true, "string", /\w/].each do |obj| title = "#{obj} (#{obj.class.name})" puts "============================================================" puts "Running tests for obj = #{title}" Benchmark.bm(15, title) do |x| implicit_obj_report = x.report("obj:") { N.times { obj } } implicit_nil_report = x.report("nil_obj:") { N.times { nil_obj } } explicit_obj_report = x.report("obj.nil?:") { N.times { obj.nil? } } explicit_nil_report = x.report("nil_obj.nil?:") { N.times { nil_obj.nil? } } not_obj_report = x.report("!obj:") { N.times { !obj } } not_nil_report = x.report("!nil_obj:") { N.times { !nil_obj } } not_not_obj_report = x.report("!!obj:") { N.times { !!obj } } not_not_nil_report = x.report("!!nil_obj:") { N.times { !!nil_obj } } equals_obj_report = x.report("obj == nil:") { N.times { obj == nil } } equals_nil_report = x.report("nil_obj == nil:") { N.times { nil_obj == nil } } not_equals_obj_report = x.report("obj != nil:") { N.times { obj != nil } } not_equals_nil_report = x.report("nil_obj != nil:") { N.times { nil_obj != nil } } end end The Results The results were interesting, because Fixnum, Float, and String types performance was virtually identical, Regex nearly so, and FalseClass and TrueClass performed much more quickly. Testing was done on MRI versions 1.9.3, 2.0.0, 2.1.5, and 2.2.5 with very similar comparative results across the versions. The results from the MRI 2.2.5 version are shown here (and available in the gist: ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-darwin14] ============================================================ Running tests for obj = 1000000 (Fixnum) user system total real obj: 0.970000 0.000000 0.970000 ( 0.987204) nil_obj: 0.980000 0.010000 0.990000 ( 0.980796) obj.nil?: 1.250000 0.000000 1.250000 ( 1.268564) nil_obj.nil?: 1.280000 0.000000 1.280000 ( 1.287800) !obj: 1.050000 0.000000 1.050000 ( 1.064061) !nil_obj: 1.070000 0.000000 1.070000 ( 1.170393) !!obj: 1.110000 0.000000 1.110000 ( 1.122204) !!nil_obj: 1.120000 0.000000 1.120000 ( 1.147679) obj == nil: 2.110000 0.000000 2.110000 ( 2.137807) nil_obj == nil: 1.150000 0.000000 1.150000 ( 1.158301) obj != nil: 2.980000 0.010000 2.990000 ( 3.041131) nil_obj != nil: 1.170000 0.000000 1.170000 ( 1.203015) ============================================================ Running tests for obj = 100000.0 (Float) user system total real obj: 0.940000 0.000000 0.940000 ( 0.947136) nil_obj: 0.950000 0.000000 0.950000 ( 0.986488) obj.nil?: 1.260000 0.000000 1.260000 ( 1.264953) nil_obj.nil?: 1.280000 0.000000 1.280000 ( 1.306817) !obj: 1.050000 0.000000 1.050000 ( 1.058924) !nil_obj: 1.070000 0.000000 1.070000 ( 1.096747) !!obj: 1.100000 0.000000 1.100000 ( 1.105708) !!nil_obj: 1.120000 0.010000 1.130000 ( 1.132248) obj == nil: 2.140000 0.000000 2.140000 ( 2.159595) nil_obj == nil: 1.130000 0.000000 1.130000 ( 1.151257) obj != nil: 3.010000 0.000000 3.010000 ( 3.042263) nil_obj != nil: 1.170000 0.000000 1.170000 ( 1.189145) ============================================================ Running tests for obj = false (FalseClass) user system total real obj: 0.930000 0.000000 0.930000 ( 0.933712) nil_obj: 0.950000 0.000000 0.950000 ( 0.973776) obj.nil?: 1.250000 0.000000 1.250000 ( 1.340943) nil_obj.nil?: 1.270000 0.010000 1.280000 ( 1.282267) !obj: 1.030000 0.000000 1.030000 ( 1.039532) !nil_obj: 1.060000 0.000000 1.060000 ( 1.068765) !!obj: 1.100000 0.000000 1.100000 ( 1.111930) !!nil_obj: 1.110000 0.000000 1.110000 ( 1.115355) obj == nil: 1.110000 0.000000 1.110000 ( 1.121403) nil_obj == nil: 1.100000 0.000000 1.100000 ( 1.114550) obj != nil: 1.190000 0.000000 1.190000 ( 1.207389) nil_obj != nil: 1.140000 0.000000 1.140000 ( 1.181232) ============================================================ Running tests for obj = true (TrueClass) user system total real obj: 0.960000 0.000000 0.960000 ( 0.964583) nil_obj: 0.970000 0.000000 0.970000 ( 0.977366) obj.nil?: 1.260000 0.000000 1.260000 ( 1.265229) nil_obj.nil?: 1.270000 0.010000 1.280000 ( 1.283342) !obj: 1.040000 0.000000 1.040000 ( 1.059689) !nil_obj: 1.070000 0.000000 1.070000 ( 1.068290) !!obj: 1.120000 0.000000 1.120000 ( 1.154803) !!nil_obj: 1.130000 0.000000 1.130000 ( 1.155932) obj == nil: 1.100000 0.000000 1.100000 ( 1.102394) nil_obj == nil: 1.130000 0.000000 1.130000 ( 1.160324) obj != nil: 1.190000 0.000000 1.190000 ( 1.202544) nil_obj != nil: 1.200000 0.000000 1.200000 ( 1.200812) ============================================================ Running tests for obj = string (String) user system total real obj: 0.940000 0.000000 0.940000 ( 0.953357) nil_obj: 0.960000 0.000000 0.960000 ( 0.962029) obj.nil?: 1.290000 0.010000 1.300000 ( 1.306233) nil_obj.nil?: 1.240000 0.000000 1.240000 ( 1.243312) !obj: 1.030000 0.000000 1.030000 ( 1.046630) !nil_obj: 1.060000 0.000000 1.060000 ( 1.123925) !!obj: 1.130000 0.000000 1.130000 ( 1.144168) !!nil_obj: 1.130000 0.000000 1.130000 ( 1.147330) obj == nil: 2.320000 0.000000 2.320000 ( 2.341705) nil_obj == nil: 1.100000 0.000000 1.100000 ( 1.118905) obj != nil: 3.040000 0.010000 3.050000 ( 3.057040) nil_obj != nil: 1.150000 0.000000 1.150000 ( 1.162085) ============================================================ Running tests for obj = (?-mix:\w) (Regexp) user system total real obj: 0.930000 0.000000 0.930000 ( 0.939815) nil_obj: 0.960000 0.000000 0.960000 ( 0.961852) obj.nil?: 1.270000 0.000000 1.270000 ( 1.284321) nil_obj.nil?: 1.260000 0.000000 1.260000 ( 1.275042) !obj: 1.040000 0.000000 1.040000 ( 1.042543) !nil_obj: 1.040000 0.000000 1.040000 ( 1.047280) !!obj: 1.120000 0.000000 1.120000 ( 1.128137) !!nil_obj: 1.130000 0.000000 1.130000 ( 1.138988) obj == nil: 1.520000 0.010000 1.530000 ( 1.529547) nil_obj == nil: 1.110000 0.000000 1.110000 ( 1.125693) obj != nil: 2.210000 0.000000 2.210000 ( 2.226783) nil_obj != nil: 1.170000 0.000000 1.170000 ( 1.169347)
{ "pile_set_name": "StackExchange" }
Q: Bind Content to property of an other class I'm trying to bind the Content property of a simple label to a property of an other class. I already tried various approaches but it didn't work yet. Here is the property in the source class (MainWindow.xaml.cs): public String FileTitle { get { return this.GetValue(FiletitleProperty) as string; } set { this.SetValue(FiletitleProperty, value); } } public DependencyProperty FiletitleProperty; public MainWindow() { FiletitleProperty = DependencyProperty.Register("FileTitle", typeof(String), typeof(MainWindow)); ... } In my target class i have an object of the source class called CallbackObject (the naming is not really suitable) Here is my xaml code of the binding: <Label x:Name="lblFiletitle" Content="{Binding Source=CallbackObject, Path=FileTitle}" Margin="10,213,10,0" Height="35" VerticalAlignment="Top" FontSize="16" Padding="0,5,5,5" /> Is it even possible to do it that way or do i have to make it more complicated and inelegant? A: If CallbackObject is in code behind try: <Label Content="{Binding RelativeSource={RelativeSource AncestorLevel=1, AncestorType=UserControl,Mode=FindAncestor}, Path=CallbackObject.FileTitle}" />
{ "pile_set_name": "StackExchange" }
Q: How to check if a files exists in a specific directory in a bash script? This is what I have been trying and it is unsuccessful. If I wanted to check if a file exists in the ~/.example directory FILE=$1 if [ -e $FILE ~/.example ]; then echo "File exists" else echo "File does not exist" fi A: You can use $FILE to concatenate with the directory to make the full path as below. FILE="$1" if [ -e ~/.myexample/"$FILE" ]; then echo "File exists" else echo "File does not exist" fi
{ "pile_set_name": "StackExchange" }
Q: Cannot initiate an object with Activator when the same assembly is referenced in the project I have faced a strange situation recently which I do not understand and ask someone of you to describe me what I did wrong or what I am missing here. The solution is build from 3 projects (some of code parts has been cut out to make it more readable): Project 1 - Main namespace TestRun { class Program { static void Main(string[] args) { Assembly assembly = Assembly.LoadFrom(PluginPath); foreach (Type type in assembly.GetTypes()) { if (type.IsSubclassOf(Plugins.Plugin) && type.IsAbstract == false) { if(Parameters != null && Parameters.Length > 0) Result = (T) Activator.CreateInstance(type, Parameters); else Result = (T) Activator.CreateInstance(type); } } } } } This one is responsible for loading all files with dll extension from a given folder (plugins). Next I have a main plugin class: namespace Plugins { public interface IPlugin { void func(); } public abstract class Plugin : IPlugin { //Basic implementation } } And a plugin assemblies: namespace DevicePlugins { public class DevicePlugin : Plugins.Plugin { {...} } } The problem is that if Project 1 has the reference to the plugin assembly (i.E. DevicePlugins) it cannot create an instance of an object from this assembly (DevicePlugin). I do not get any error or exception - only information about "Result" from Project 1 - "Value cannot be evaluated". If I remove the reference to the plugin's assembly from Project 1 (I mean that in the Project 1 I have not the reference to DevicePlugins assembly) everything is working like a charm (I can create an object of DevicePlugin from DevicePlugins assembly). Moreover, when I have the reference I can initiate an object in the normal way DevicePlugins.DevicePlugin plug = new DevicePlugins.DevicePlugin(); Can someone tell me what am I missing or do not understand?? Why it working in that way? A: When you add an assembly reference to a project, it builds a dependency on the assembly into the executable and this causes the assembly to be loaded at runtime into the execution context. As you are actually loading the same assembly twice into the execution context (once manually using LoadFrom, once by assembly reference), you should check the behaviour of LoadFrom for your specific case. If you are doing what I think you are, which is loading the assembly from a "plugins" folder, then LoadFrom will start behaving incorrectly with regards to what you want to achieve, I believe. Read up on MSDN for the specifics: http://msdn.microsoft.com/en-us/library/1009fa28(v=vs.110).aspx
{ "pile_set_name": "StackExchange" }
Q: Difference between `print(9)` and `print(str(9))` What is the difference between print(9) and print(str(9)) in Python when the output is the same for both functions? A: print will always first try to call __str__ on the object you give it. In the first case the __str__ of the int instance 9 is '9'. In the second case, you first explicitly call str on 9 (which calls its __str__ and yields '9'). Then, print calls '9''s __str__ which, if supplied with a string instance, returns it as it is resulting in '9' again. So in both cases, in the end print will print out similar output.
{ "pile_set_name": "StackExchange" }
Q: OpenCV UMat operators With cv::Mat one can use ~ for cv::bitwise_not or > to compare 2 matrices. But cv::UMat doesn't seem to have these operators, understandably you could simply do cv::bitwise_not(umat,umat) (though I've understood copying from a matrix to itself isn't very efficient, correct me if I'm wrong), but how can one compare 2 cv::UMat matrices, or a cv::UMat with a cv::Scalar? A: TLDR use OpenCV compare function You can use .getMat() cv::UMat A = cv::Mat(1000, 1000, CV_8UC3), B = cv::UMat(1000, 1000, CV_8UC3); cv::randu(A, Scalar::all(0), Scalar::all(255)); cv::randu(B, Scalar::all(0), Scalar::all(255)); cv::UMat C = A.getMat(cv::ACCESS_READ) > B.getMat(cv::ACCESS_READ); But this doesn't use cv::UMats' hardware acceleration. Instead you should just use OpenCV compare function cv::UMat A = cv::Mat(1000, 1000, CV_8UC3), B = cv::UMat(1000, 1000, CV_8UC3); cv::randu(A, Scalar::all(0), Scalar::all(255)); cv::randu(B, Scalar::all(0), Scalar::all(255)); cv::UMat C; cv::compare(A, B, C, CMP_GT);
{ "pile_set_name": "StackExchange" }
Q: Javascript: What is the benefit of two sets of parentheses after function call I understand that in Javascript a function can return another function and it can be called immediately. But I don't understand the reason to do this. Can someone please explain the reason and benefit why you might want to do this in your code? Also, is the function that returns 'hello' considered a closure? function a () { return function () { console.log('hello'); } } //then calling the function a()(); A: Can someone please explain the reason and benefit why you might want to do this in your code? There's no reason to do it when you'll always do it whenever calling the function (a in your case). The reason in the general case is that the author of a is allowing for the possibility you may not want to call the resulting function right away. So the a()(); case is just a special case of the general case of var f = a(); // later... f(); Also, is the function that returns 'hello' considered a closure? Yes, technically, although in your example it doesn't have anything special to close over that a doesn't already close over, since there are no arguments to a or variables within a. More (on my anemic blog): Closures are not complicated
{ "pile_set_name": "StackExchange" }
Q: why do I get 'Undefined control sequence' for KOMAoptions? I am trying to include A3 pages in an A4 LaTeX document (following this answer) but get the following when I run pdflatex: Chapter 1. [1{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}] [2] ! Undefined control sequence. \AP@ ->{ \clearpage \KOMAoptions {paper=a3,paper=landscape} \recalctypearea ... l.27 \end{document} ? SSCCE below: \documentclass[11pt,twoside,a4paper,pagesize]{report} \usepackage{pslatex,palatino,avant,graphicx,color,nextpage,afterpage,comment} \usepackage[margin=2cm]{geometry} \usepackage[absolute]{textpos} \usepackage[hyphens]{url} \PassOptionsToPackage{hyphens}{url} \begin{document} \chapter{Introduction} foo \clearpage bar \afterpage{ % Insert after the current page \clearpage \KOMAoptions{paper=a3,paper=landscape} \recalctypearea A3 stuff goes here ... \clearpage \KOMAoptions{paper=A4,pagesize} \recalctypearea } \end{document} I understand that "undefined control sequence" means I've forgotten to use some package on my document preamble. However it is not clear to me what's wrong in this case. A: The preamble of LaTeX files usually starts with \documentclass. You use the documentclass report, which is included in LaTeX. The KOMA-script bundle offers its own documentclasses: scrartcl instead of article, screprt instead of report and scrbook instead of book. So please switch from report to screprt for using KOMA-script commands. You don't need to load typearea, if you do this. In case you just need some features of KOMAscript, have a look at the package scrextend. I did not test your example regarding the size of the included page. But it is a bad idea to mix geometry and typearea. Choose one of them and stick to it.
{ "pile_set_name": "StackExchange" }
Q: Print barcode generated from URL in Shipment PDF I want to insert barcode image in PDF which is generated from URL eg. http:\\example.com\barcode.php?barcode=12345 $pdf->drawImage() seem not working with URL. Any Idea How we can insert images using URL? A: You have to first get the contents of the remote image and than you can add them to the pdf. Read this article: http://www.andrew-kirkpatrick.com/2012/11/using-zend_pdf-with-remote-amazon-s3-urls-files/
{ "pile_set_name": "StackExchange" }
Q: Can I sort Lucene results while using a custom collector? Is it possible to sort Lucene results when using a custom collector, or would I have to implement that functionality myself, in the collector object? I can't find an overload of IndexSearcher.Search that allows me to pass in both my own collector object and a sort field. Lucene.Net, v2.9 A: You have to implement the sort yourself. But Lucene.Net has an abstract class PriorityQueue that can be used in custom collectors (it is used internally in Lucene.Net while sorting (instead of collecting all results and then applying a sort on them) ) public class MyQueue : Lucene.Net.Util.PriorityQueue<int> { public MyQueue(int MaxSize) : base() { Initialize(MaxSize); } public override bool LessThan(int a, int b) { return a < b; } } int queueSize = 3; MyQueue pq = new MyQueue(queueSize); pq.InsertWithOverflow(1); pq.InsertWithOverflow(9); pq.InsertWithOverflow(8); pq.InsertWithOverflow(3); pq.InsertWithOverflow(5); int i1 = pq.Pop(); int i2 = pq.Pop(); int i3 = pq.Pop();
{ "pile_set_name": "StackExchange" }
Q: git rebase --interactive | fails renamed path case I try to interactive rebase some commits. My git-log looks something like this A - Files added B - Some commit C - Some commit D - Renamed path from A (dir/dir/dir => Dir/Dir/Dir) E - Some commit F - Some commit I can rebase E,F without problems but anything from A-D is impossible to drop, squash, edit. Error: error: The following untracked working tree files would be overwritten by checkout: *** list of files contain the lowercase pathes *** error: could not detach HEAD Ignore case config value $git config --global core.ignorecase false Commit from D (there are multiple files) rename from php/software/utils/GlobalManager.php rename to php/software/Utils/GlobalManager.php similarity index 100% What am I doing wrong, how can I get along this. A: A stupid thing to try : add an extra commit at the tip of your current branch, where you rename the problematic paths to paths that will not conflict : # from your current HEAD : git mv php/software/Utils php/software/Utils-wip # rename other folders if necessary git commit After that, run your interactive rebase : git rebase -i HEAD~41 and see if it works. Whatever the issue, you can revert the extra commit afterwards : git reset --hard HEAD~ # that or drop the last commit from your `rebase -i` list
{ "pile_set_name": "StackExchange" }
Q: Como pegar setar/pegar objeto no localstorage? Estou enviando um objeto do JSON para o localStorage: window.localStorage.setItem('tarefa',aux); E tento pegar esse objeto em outro controller assim: $scope.tarefa=window.localStorage.getItem('tarefa') Porém, ao mostrar no console esse $scope.tarefa.id (propriedade do objeto passado) dá undefined. Isso para essa propriedade ou para qualquer outra. A: Acontece que só é possível salvar pares de chave/valor no localStorage/sessionStorage. Então, ao tentar salvar um objeto como o valor da chave tarefa o que é salvo é a string "[object Object]". Se quiser testar, tente fazer um console.log, dessa forma console.log(window.localStorage.getItem('tarefa')); A saída será "[object Object]" É possível resolver isso convertendo o objeto para JSON antes de salvá-lo no localStorage. // Cria um json a partir do objeto "aux" var jsonAux = JSON.stringify(aux); // "Seta" este json no localStorage window.localStorage.setItem('tarefa', jsonAux); // Recupera o json do localStorage var jsonTarefa = window.localStorage.getItem('tarefa'); // Converte este json para objeto var tarefa = JSON.parse(jsonTarefa); console.log(tarefa.id);
{ "pile_set_name": "StackExchange" }
Q: How to deploy next.js app on Firebase Hosting? I am trying to deploy next.js app on Firebase hosting. But I don't understand which files to push to the server. When I run npm run build and pushed the build folder to firebase. But gives error that No index.html file found. Here is the image of output of build folder. I have just created a simple component for testing purposes. Output of build command A: Check this out first. This is the official example provided by the next.js in their github repo. The idea behind the example The goal is to host the Next.js app on Firebase Cloud Functions with Firebase Hosting rewrite rules so our app is served from our Firebase Hosting URL. Each individual page bundle is served in a new call to the Cloud Function which performs the initial server render. This is based off of the work at https://github.com/geovanisouza92/serverless-firebase & https://github.com/jthegedus/firebase-functions-next-example as described here. PS : I know posting links as answers is not the best way, but my rep power is not enough to put this as a comment. Update I recently found out that firebase git repo has a nextjs example, be sure to check this out too. Path in the repo => firebase/functions-samples/nextjs-with-firebase-hosting A: On package.json you need to add npm scripts for building and exporting like. "scripts": { "dev": "next", "build": "next build", "start": "next start", "export": "next export" }, And then you can run npm run build && npm run export Next build will build your project for shipping and export will put your files ready for hosting on a static hosting server (like firebase hosting). npm run export will create an out/ directory and place all your files there ready for uploading. Note: If your app needs to generate dynamic pages at the runtime, you can't deploy it as a static app. Read more
{ "pile_set_name": "StackExchange" }
Q: Executing ScriptIntrinsicYuvToRgb I want to convert a byte[] in Yuv into a byte[] in Rgb. The ScriptIntrinsic (ScriptIntrinsicYuvToRgb) is supposed to do this (based on this example). Here's some code I have right now: byte[] imageData = ...gatheryuvbuffer... Type.Builder tb = new Type.Builder(mRS, Element.createPixel(mRS, Element.DataType.UNSIGNED_8, Element.DataKind.PIXEL_YUV)); tb.setX(outputWidth); tb.setY(outputHeight); tb.setMipmaps(false); tb.setYuvFormat(ImageFormat.NV21); Allocation ain = Allocation.createTyped(mRS, tb.create(), Allocation.USAGE_SCRIPT); ain.copyFrom(imageData); Type.Builder tb2 = new Type.Builder(mRS, Element.RGBA_8888(mRS)); tb2.setX(outputWidth); tb2.setY(outputHeight); tb2.setMipmaps(false); // Allocation aOutBitmap = Allocation.createFromBitmap(mRS, bitmap); Allocation aOut = Allocation.createTyped(mRS, tb2.create(), Allocation.USAGE_IO_OUTPUT); aOut.setSurface(null); mYuvToRgb.setInput(ain); mYuvToRgb.forEach(aOut); Bitmap bitmap = Bitmap.createBitmap(outputWidth, outputHeight, Bitmap.Config.ARGB_8888); aOut.copyTo(bitmap); By the end of this script, I expect bitmap to contain something (I'm displaying it in an ImageView). But the bitmap shows up blank. What's wwrong with this code snippet? A: I think the problem is the output allocation is created with USAGE_IO_OUTPUT but a surface is never attached. I would try with (USAGE_SCRIPT & USAGE_SHARED) or just use the defaults.
{ "pile_set_name": "StackExchange" }
Q: Using Facebook Graph API 2.2 to get like and share count I'm working on updating project from old FQL to graph api 2.2 and i dont have idea how to get likes count on specific link, their documentation is not very transparent for me(i'm beginer). I believe it shoud be something like this: https://graph.facebook.com/v2.2/?id={myURL}/{some fields like like_count} but i have no clue how to do it right using graph API. I will appreciate any help. A: Well, the docs are quite clear I think: https://developers.facebook.com/docs/graph-api/reference/v2.2/url#read There is NO like count on the /?id={url} endpoint! A sample call would be GET /?id=http://mashable.com/2015/02/17/10-minute-rule/ Response: { "og_object": { "id": "664547577004455", "description": "Three tips for making the 10-minute rule work for you.", "title": "A 10-minute timer could revolutionize your productivity", "type": "article", "updated_time": "2015-02-17T13:55:11+0000", "url": "http://mashable.com/2015/02/17/10-minute-rule/" }, "share": { "comment_count": 0, "share_count": 180 }, "id": "http://mashable.com/2015/02/17/10-minute-rule/" } If you just want the share count, use GET /?fields=id,share&id=http://mashable.com/2015/02/17/10-minute-rule/ Response: { "id": "http://mashable.com/2015/02/17/10-minute-rule/", "share": { "comment_count": 0, "share_count": 180 } }
{ "pile_set_name": "StackExchange" }
Q: How to extract the value of an element in a period of time data in excel? I'm sorry if the title didn't match with my explanation. But here's my problem: I have data about uber request for 2 weeks each hour. I want to know which hour of the day I had the most request for 2 weeks period. The data looks like this: Date Time request 12/1/16 0 2 1 1 2 3 .. .. .. .. 23 6 12/2/16 0 4 1 2 2 5 .. .. .. .. 23 6 and it goes on until 2 weeks. I want to know which hour of the day I had the most request. Any idea how I do this? A: Like Aganju says, Create a pivot table by selecting the two Columns (Time & Request), in the Pivot Table Window use "Time" as RowLabels & "Request" as Values, change the value settings to "Sum".
{ "pile_set_name": "StackExchange" }
Q: Python Pandas value counts for multiple columns and generate graph from the result I have a csv to read from as follows A B C Sam 123 PID-213 Sam 145 PID-432 Sam 123 PID-546 Dan 786 PID-321 Dan 897 PID-432 and I want a group as below: count of unique B elements and Pids. (Bis 2 because 123 is repeated twice so) A B C Sam 2 3 Dan 2 2 And from the above plot a graph as below : and also a pie chart from column A and B and save it in a pdf in 2 different page. How do i achieve this A: IIUC: In [18]: df.groupby('A')['B','C'].nunique().plot.bar(rot=0) Out[18]: <matplotlib.axes._subplots.AxesSubplot at 0xb7d7a90>
{ "pile_set_name": "StackExchange" }
Q: What do taxiway lane, taxiway strip and taxiway shoulder mean? I am developing a game which involves an airport simulation. And I am looking into the general rules that traffic control has for busy airports and am also confused on the terminology of a taxiway. According to ICAO taxiway widths have 3 types of labeling which is as follows: Taxiway Lane Taxiway Strip Taxiway Shoulder What is the taxiway shoulder? I am fairly sure the lane is the 2 outer yellow lines from the center taxiway line right? And the strip is the entire taxiway width, but I am unclear on the shoulder label? I could not find an image that showed what this was. A: According to the Skybrary from EUROCONTROL and a UK CAA document on taxiways markings (Visual Aids Handbook UK CAA CAP 637 (2007)), the definitions are: Taxiway Strip An area which contains the taxiway and gives protection to aircraft from obstacles and other taxiways. Image Source: Transport Canada Taxiway Lane This one is ambiguous and could not be found citation on, except for a document from the BAZL. Taxilanes or Taxiway Lanes are dashed taxiways, which give guidance to stands and aircraft parking positions. Taxiway Shoulder The taxiway shoulder is the paved or unpaved area beyond the double taxiway edge line, indicating that the load bearing capabilities beyond these lines can be different from the taxiway weight allowance. A: Take a look at Section 3. Airport Marking Aids and Signs of the FAA's AIM and AIRPORT SIGN AND MARKING – QUICK REFERENCE GUIDE
{ "pile_set_name": "StackExchange" }
Q: Where can I get Ubuntu Stickers Where can I get Ubuntu inside or Powered by Ubuntu or any Ubuntu sticker for that matter to stick on my Laptops? A: System76 offers free Ubuntu stickers, which you can check with your local Ubuntu community through https://system76.com/swag/stickers A: Have a look at the below link Ubuntu Stickers
{ "pile_set_name": "StackExchange" }
Q: Jquery multiple checkbox get value in var or print in span the code for html is : <div id="container"><h1>Add-ons</h1> <input type="checkbox" name="ch1" value="10" id="qr1" />Add-on Number 1 - 10 QR <br /> <input type="checkbox" name="ch1" value="20" id="qr1" />Add-on Number 2 - 20 QR <br /> <input type="checkbox" name="ch1" value="40" id="qr1" />Add-on Number 3 - 40 QR <br /> <input type="checkbox" name="ch1" value="60" id="qr1" />Add-on Number 4 - 60 QR <br /> </div> <div> I want more add-ons <select id="more" name="more"> <option value="0 QR">0</option> <option value="30 QR">1</option> <option value="50 QR">2</option> <option value="100 QR">3</option> </select> <span id="span"></span> User total usage: <span id="usertotal"> </span> Jquery: //For select function displayVals() { var singleValues = $("#more").val(); $("#span").html("<b>more addons:</b> " + singleValues); } $("select").change(displayVals); displayVals(); //For checkboxes var $cbs = $('input[name="ch1"]'); $cbs.click(function() { var total = 0; $cbs.each(function() { if (this.checked) var singleValues = $("#more").val(); total += +this.value + singleValues; }); $("#usertotal").text(total); }); I want at the user total usage: to create the sum of the checkboxes and add with the value of the option so that if I select 1 checkbox and 2 plus option 1 I will have written in user total usage: 60 . Thank YOU in advance ! A: Note that it is invalid html to use the same id for multiple elements. Select the checkboxes using their name attribute. On click of any checkbox loop through them all, and add the value of any checked ones. Note that the values need to be converted to numbers, which I do with the unary plus operator. var $cbs = $('input[name="ch1"]'); $cbs.click(function() { var total = 0; $cbs.each(function() { if (this.checked) total += +this.value; }); $("#usertotal").text(total); });​ Demo: http://jsfiddle.net/6GX7g/ A: working demo: http://jsfiddle.net/GNDAG/ Hope it helps. You can read more about each here. However, like @nnnnnn mentioned, your html isn't right -- ID attributes need to be unique. Code $('input[type="checkbox"]').change(function() { var total_span = 0; $('input[type="checkbox"]').each(function() { if ($(this).is(':checked')) { total_span += parseInt($(this).prop('value'), 10); } }); $("#usertotal").html(total_span); });​
{ "pile_set_name": "StackExchange" }
Q: How can I decode this string which is represented as unicode? I get s when trying to parse a web page by readability(Python 2.7 on Windows 10, Sublime Text 2/cmd) >>> import requests >>> from readability import Document >>> >>> response = requests.get('http://www.gamersky.com/news/201806/1064930.shtml') >>> doc = Document(response.text.encode("utf-8")) >>> print doc.title() Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'gbk' codec can't encode character u'\xe3' in position 0: illegal multibyte sequence >>> print doc.title().encode("utf-8") lots of messy codes >>> print doc.title().encode("utf-16") lots of messy codes >>> print doc.title().encode("gbk") Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'gbk' codec can't encode character u'\xe3' in position 0: illegal multibyte sequence I found I can never print out doc.title(), so I looked into doc.title() by running s = repr(doc.title()) print type(doc.title()) print s The result is very strange <type 'unicode'> u'\xe3\x80\x8a\xe5\xa5\x87\xe5\xbc\x82\xe4\xba\xba\xe7\x94\x9f\xe3\x80\x8b\xe5\x9b\xa2\xe9\x98\x9f\xe6\x96\xb0\xe4\xbd\x9c\xe3\x80\x8a\xe8\xb6 \xe8\x83\xbd\xe9\x98\x9f\xe9\x95\xbf\xe3\x80\x8b\xe5 \x8d\xe8\xb4\xb9\xe4\xb8\x8b\xe8\xbd\xbd \xe5\xb0\x8f\xe7\x94\xb7\xe5\xad\xa9\xe7\x9a\x84\xe8\x8b\xb1\xe9\x9b\x84\xe6\xa2\xa6\xe6\x83\xb3 _ \xe6\xb8\xb8\xe6\xb0\x91\xe6\x98\x9f\xe7\xa9\xba GamerSky.com' It seem that s is actually encoded in multibytes, because when I run print '\xe3\x80...' And it prints 《奇异人生》团队新作《? 能队长》? ?费下载 小男孩的英雄梦想 _ 游民星空 GamerSky.com Where the accurate title is 《奇异人生》团队新作《超能队长》免费下载 小男孩的英雄梦想 _ 游民星空 GamerSky.com Though there are some characters still missing, but the result convince me that the \xe3 should not be represented as a unicode form. After some searching, I found the following code helps, but there are still some missing characters. >>> print s.encode("raw_unicode_escape") 《奇异人生》团队新作《? 能队长》? ?费下载 小男孩的英雄梦想 _ 游民星空 GamerSky.com My questions are: Why is this problem probably happen? Is the encode("raw_unicode_escape") solution neat? When I run the following codes, it works >>> import requests >>> from readability import Document >>> >>> response = requests.get('https://zh.wikipedia.org/wiki/Wikipedia:%E9%A6%96%E9%A1%B5') >>> doc = Document(response.text.encode("utf-8")) >>> print doc.title() 维基百科,自由的百科全书 How to handle the missing characters? A: The problem is that when you use response.text, it makes a guess at what the encoding is when decoding response.content into unicode. In this case its guess is incorrect. You have to force the encoding by setting response.encoding to 'utf-8', per documentation. import requests from readability import Document response = requests.get('http://www.gamersky.com/news/201806/1064930.shtml') response.encoding = 'utf-8' doc = Document(response.text) print doc.title() And this prints: 《奇异人生》团队新作《超能队长》免费下载 小男孩的英雄梦想 _ 游民星空 GamerSky.com
{ "pile_set_name": "StackExchange" }
Q: Calculate links between nodes using Spark I have the following two DataFrames in Spark 2.2 and Scala 2.11. The DataFrame edges defines the edges of a directed graph, while the DataFrame types defines the type of each node. edges = +-----+-----+----+ |from |to |attr| +-----+-----+----+ | 1| 0| 1| | 1| 4| 1| | 2| 2| 1| | 4| 3| 1| | 4| 5| 1| +-----+-----+----+ types = +------+---------+ |nodeId|type | +------+---------+ | 0| 0| | 1| 0| | 2| 2| | 3| 4| | 4| 4| | 5| 4| +------+---------+ For each node, I want to know the number of edges to the nodes of the same type. Please notice that I only want to count the edges outgoing from a node, since I deal with the directed graph. In order to reach this objective, I performed the joining of both DataFrames: val graphDF = edges .join(types, types("nodeId") === edges("from"), "left") .drop("nodeId") .withColumnRenamed("type","type_from") .join(types, types("nodeId") === edges("to"), "left") .drop("nodeId") .withColumnRenamed("type","type_to") I obtained the following new DataFrame graphDF: +-----+-----+----+---------------+---------------+ |from |to |attr|type_from |type_to | +-----+-----+----+---------------+---------------+ | 1| 0| 1| 0| 0| | 1| 4| 1| 0| 4| | 2| 2| 1| 2| 2| | 4| 3| 1| 4| 4| | 4| 5| 1| 4| 4| +-----+-----+----+---------------+---------------+ Now I need to get the following final result: +------+---------+---------+ |nodeId|numLinks |type | +------+---------+---------+ | 0| 0| 0| | 1| 1| 0| | 2| 0| 2| | 3| 0| 4| | 4| 2| 4| | 5| 0| 4| +------+---------+---------+ I was thinking about using groupBy and agg(count(...), but I do not know how to deal with directed edges. Update: numLinks is calculated as the number of edges outgoing from a given node. For example, the node 5 does not have any outgoing edges (only ingoing edge 4->5, see the DataFrame edges). The same refers to the node 0. But the node 4 has two outgoing edges (4->3 and 4->5). My solution: This is my solution, but it lacks those nodes that have 0 links. graphDF.filter("from != to").filter("type_from == type_to").groupBy("from").agg(count("from") as "numLinks").show() A: You can filter, aggregate by id and type and add missing nodes using types: val graphDF = Seq( (1, 0, 1, 0, 0), (1, 4, 1, 0, 4), (2, 2, 1, 2, 2), (4, 3, 1, 4, 4), (4, 5, 1, 4, 4) ).toDF("from", "to", "attr", "type_from", "type_to") val types = Seq( (0, 0), (1, 0), (2, 2), (3, 4), (4,4), (5, 4) ).toDF("nodeId", "type") graphDF // I want to know the number of edges to the nodes of the same type .where($"type_from" === $"type_to" && $"from" =!= $"to") // I only want to count the edges outgoing from a node, .groupBy($"from" as "nodeId", $"type_from" as "type") .agg(count("*") as "numLinks") // but it lacks those nodes that have 0 links. .join(types, Seq("nodeId", "type"), "rightouter") .na.fill(0) // +------+----+--------+ // |nodeId|type|numLinks| // +------+----+--------+ // | 0| 0| 0| // | 1| 0| 1| // | 2| 2| 1| // | 3| 4| 0| // | 4| 4| 2| // | 5| 4| 0| // +------+----+--------+ To skip self-links add $"from" =!= $"to" to the selection: graphDF .where($"type_from" === $"type_to" && $"from" =!= $"to") .groupBy($"from" as "nodeId", $"type_from" as "type") .agg(count("*") as "numLinks") .join(types, Seq("nodeId", "type"), "rightouter") .na.fill(0) // +------+----+--------+ // |nodeId|type|numLinks| // +------+----+--------+ // | 0| 0| 0| // | 1| 0| 1| // | 2| 2| 0| // | 3| 4| 0| // | 4| 4| 2| // | 5| 4| 0| // +------+----+--------+
{ "pile_set_name": "StackExchange" }
Q: Boto DynamoDB error when using attributes_to_get in table.query I've got a DynamoDB database set up with string hash key and range keys. This works: >>> x = table.query(hash_key='[email protected]', range_key_condition=BEGINS_WITH("20"), request_limit=5) >>> [i for i in x] [{u'x-entry-page': ... This doesn't, and I can't figure out why not: >>> x = table.query(hash_key='[email protected]', range_key_condition=BEGINS_WITH("20"), attributes_to_get=[u'x-start-time'], request_limit=5) >>> [i for i in x] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/boto-2.3.0-py2.7.egg/boto/dynamodb/layer2.py", line 588, in query yield item_class(table, attrs=item) File "/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/boto-2.3.0-py2.7.egg/boto/dynamodb/item.py", line 45, in __init__ raise DynamoDBItemError('You must supply a hash_key') boto.dynamodb.exceptions.DynamoDBItemError: BotoClientError: You must supply a hash_key This makes very little sense to me. I clearly am supplying a hash key. I can't tell what the issue is just by looking at the Boto source. The attribute in question is definitely present in every record (not that that should throw an error). Any suggestions? Thanks! A: Coincidentally, this was just fixed in boto earlier today. See: https://github.com/boto/boto/issues/656
{ "pile_set_name": "StackExchange" }
Q: AngularJS : controller with factory I am new to Angular and I am creating my first app right now. I have a factory in place and my controller should be pulling in data from my source, however I keep on getting this error. My factory is called SpreadsheetFactory. I have the code for my controller below. Any help is appreciated, thanks! (function () { angular .module('beerApp') .controller('appController', appController, ['$scope', 'SpreadsheetFactory']); function appController($scope, SpreadsheetFactory) { SpreadsheetFactory.getData().then( function (data) { console.log(data) }); // $scope.brews = []; return data; } })(); A: This line is wrong: .controller('appController', appController, ['$scope', 'SpreadsheetFactory']); It should be: .controller('appController', ['$scope', 'SpreadsheetFactory', appController]);
{ "pile_set_name": "StackExchange" }
Q: How to manage NHibernate Sessions per request in Structuremap.MVC5 I'm new to IoC and NHibernate, and am having a great deal of difficulty trying to get my head around best practices for dependency injection. I've spent the last couple of days looking around and reading documentation, but unfortunately the documentation I've found has been either obsolete or incomplete. For instance, this tells me what to do, I but I have no idea how to do it. XSockets.Net - how to manage NHibernate Session Context I have learned that, according to the official documentation, I need to use nested containers in structuremap to make sure that sessions are created and disposed appropriately for each request. Unfortunately the examples are all set within unit tests that construct their own container. I have no idea how to apply this to MVC. If I have a repository like this public class Repository : IRepository { public Repository(ISession session) { ... } ... } How do I make this work: public NHibernateRegistry() { ISessionFactory factory = config.BuildSessionFactory(); For<IRepository>.Use<Repository>() For<ISession>.???????? } Or have I got it all backwards somehow? A: So, it turns out that this behaviour is automatic - I don't need to switch it on. I was making an unrelated error and thought that this was the problem. It isn't helped by somewhat unclear documentation. If you are using the structuremap.MVC5 nuget package then: SessionFactory _factory; public NHibernateRegistry() { _factory = config.BuildSessionFactory(); For<IRepository>.Use<Repository>() For<ISession>.Use(() => _factory.OpenSession()); } This will cause structuremap to open a session once per httprequest. Of course, you shouldn't open the session here, as there are a bunch of things relating to transactions, binding and unit of work stuff that you'll want to handle properly - but that's a separate NHibernate thing that is beyond the scope of this problem.
{ "pile_set_name": "StackExchange" }
Q: Google Apps Scripts trouble indexing values within a row I have an array within a spreadsheet that has stock data. I want to find a column number "restock value", and the row number product/sku (Row) to eventually build a custom function. The column is indexing fine, but the Row keeps logging 0. I've tested a few objects within my array. I've also tried removing the column index. but no dice. still logging 0. I've also tried removing [0] from my code. It seems that this is part of the problem, because when I log lookupRowValues without [0] I get the value of each row with their own individual brackets, when I add [0] I only log the first row. function UnitsToShip(){ var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("US"); //Lookup Column var lc = ss.getLastColumn(); var lookupColumnValues = ss.getRange(4,2,1,lc).getValues()[0]; var indexColumn = lookupColumnValues.indexOf("Restock Amount") + 1; //Lookup Row var lr = ss.getLastRow(); var lookupRowValues = ss.getRange(4,2,lr,1).getValues()[0]; var indexRow = lookupRowValues.indexOf("AH-POR-DIF-WHT")+1; Logger.log(indexRow); } I'm testing it with a product in the array that should return 6. A: Try this: function UnitsToShip(){ var ss=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("US"); //Lookup Column var lc = ss.getLastColumn(); var lookupColumnValues = ss.getRange(4,2,1,lc-1).getValues()[0]; var indexColumn = lookupColumnValues.indexOf("Restock Amount") + 2; Logger.log('indexColumn: %s',indexColumn); //Lookup Row var lr = ss.getLastRow(); var lookupRowValues = ss.getRange(4,2,lr-3,1).getValues().map(function(r){return r[0];}); var indexRow = lookupRowValues.indexOf("AH-POR-DIF-WHT")+4; Logger.log('indexRow: %s',indexRow); var restockAmount=ss.getRange(indexRow,indexColumn).getValue(); Logger.log('Restock Amount: %s',restockAmount); }
{ "pile_set_name": "StackExchange" }
Q: Add code with a function I'm trying to insert some code thanks to a submit button. To sum up, I want that this button call an PHP function wich add a block of HTML code. Here is my function : function ajouterStag(){ print_r('<form method="post" action="AjoutFormation.php"> <label>Nom d\'un stagiaire : </label><input type="text" name="ajoutStagiaireNom"/><br/> <label>Mail du stagiaire : </label><input type="text" name="ajoutStagiaireMail"/><br/> <label>Telephone du stagiaire : </label><input type="text" name="ajoutStagiaireTel"/><br/> </form>'); } And here is how i use it : <h5>Et ses employés ?</h5> <label>Nom d'un stagiaire : </label><input type="text" name="ajoutStagiaireNom"/><br/> <label>Mail du stagiaire : </label><input type="text" name="ajoutStagiaireMail"/><br/> <label>Telephone du stagiaire : </label><input type="text" name="ajoutStagiaireTel"/><br/> <form method="post" action="AjoutFormation.php"> <?php ajouterStag(); ?> //Right there <input type="submit" value="Ajouter un stagiaire"/> </form> In result, i just have the same labels (the tree you can see) twice and my button do nothing. I'm a beginnner in PHP and dont see how to do that. Do you mind help me ? A: Update If you want something like, repeating additional form elements, you should be using JavaScript for that. This is something like a start using jQuery (an awesome JS library): $(function () { $(".add").click(function (e) { e.preventDefault(); $(this).before('<label>Nom d\'un stagiaire : </label><input type="text" name="ajoutStagiaireNom"/><br/><label>Mail du stagiaire : </label><input type="text" name="ajoutStagiaireMail"/><br/><label>Telephone du stagiaire : </label><input type="text" name="ajoutStagiaireTel"/><br/><br/>'); }); }); <script src="https://code.jquery.com/jquery-2.2.4.js"></script> <h5>Et ses employés ?</h5> <form method="post" action="AjoutFormation.php"> <label>Nom d'un stagiaire : </label><input type="text" name="ajoutStagiaireNom[]"/><br/> <label>Mail du stagiaire : </label><input type="text" name="ajoutStagiaireMail[]"/><br/> <label>Telephone du stagiaire : </label><input type="text" name="ajoutStagiaireTel[]"/><br/> <br/><a href="#" class="add">Add Another Set</a><br/> <input type="submit" value="Ajouter un stagiaire"/> </form> While using the above way, you need to send the data to the server in an array way. Like above. See the name for all the input elements. Let me know if this is what you want? I'm trying to insert some code thanks to a submit button. To sum up, I want that this button call an PHP function which add a block of HTML code. PHP is a server side language, which gets executed before the client side code renders. This is not possible with PHP, but you need to use some client side programming language such as JavaScript. For this, you can simply load the file with the form elements hidden and the on the click of a button, you can make it display with JavaScript. <h5>Et ses employés ?</h5> <form method="post" action="AjoutFormation.php"> <div style="display: none;" id="hidform"> <label>Nom d'un stagiaire : </label><input type="text" name="ajoutStagiaireNom" /><br/> <label>Mail du stagiaire : </label><input type="text" name="ajoutStagiaireMail" /><br/> <label>Telephone du stagiaire : </label><input type="text" name="ajoutStagiaireTel" /><br/> </div> <a href="#" onclick="hidform.style.display = 'block'; return false;">Show Form</a><br/> <input type="submit" value="Ajouter un stagiaire" /> </form>
{ "pile_set_name": "StackExchange" }
Q: Pandas is blocking python when it reads big file I am reading a 5 G file on my 8G memory MacBook : pd.read_csv(filepath). I see the memory usage going to 12 G (orange, then red), and then suddenly the memory usage drops back to 6G, and then slowly goes back up.... And my script doesn't deliver anything, not even an exit error.... What can happen ? Seems like python is completely blocked (ventilator are very silencious...) A: I believe the file you are loading is far to large reference what your computer can handle. Unless you need to load all the data at once, I would try to load the data based on what you need at that time e.g., load data based on a specific criteria then run your program over those specifics. This should help with the two things. First, you will be able to load your data and run your program. Second, your program will run faster as it is only working on subsets of data at a time.
{ "pile_set_name": "StackExchange" }
Q: PBKDF in Crypto++ I have following code in C# PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(32); .Net's PasswordDeriveBytes uses PBKDF1. I am using "SHA1" hashing algorithm to generate 32 byte key. Kindly tell me how I can achieve this in crypto++. In crypto++ using PBKDF2 its generate 20 byte key. How can I make 32 byte key which C# generating. A: You can't, because PasswordDerivedBytes is not standard PBKDF1, while the crypto++ implementation is. Use the PBKDF2 implementation instead (Rfc2898DeriveBytes in .NET).
{ "pile_set_name": "StackExchange" }
Q: Fonts are blurry / big in Android Studio is there any way I can change the resolution of Android Studio? I looked in Settings->Appearance but it seems like there is no official way to change it. I have a 1920x1080 Display and the whole window and text looks a little bit blurry. I am running a Windows machine on Windows 8.1. Thanks! A: You need to set a compatibility option "Disable display scaling on high DPI settings" for the application. Right-click the taskbar button, then right-click the app name, select Properties, Compatibility. Set the option, save changes, restart Studio. Those instructions are for a Win7 machine, but Win8.1 should behave the same. To explain what is happening: apparently, the Studio is not "high DPI aware", i.e. does not declare "I know how to handle myself on a high-DPI screen", and Windows tries to scale the window so that its elements do not get too tiny. You can override this on an app-by-app basis, but be prepared for possible glitches / tiny UI elements. A: Modify the font size in the "File > Settings..." screen on Windows A: Right click on your android studio icon. Go to : Properties -> Compatibility. 2.Check the "Override high DPI scaling behaviour" option also select "Application" for "Scaling performed by" from the drop down menu. 3.Press apply and restart your android studio.
{ "pile_set_name": "StackExchange" }
Q: Spring vs Jboss What are the advantages and disadvantages for Spring vs. Jboss for an enterprise web application. A: This is a good question. Some have incorrectly stated here that this is an apples to oranges comparison, i.e. Jboss is a container, and Spring is simply a framework, like Struts. However, the reason this is a bit confusing is that both JBoss and Spring have expanded considerably from their original, simple origins, and are thus moving closer towards each other. One easy way to understand JBoss is that the name was original "EJBoss", and it was intended on being an open-source J2EE application server, so it had the advantage over tomcat over serving as an EJB container, and thus could compete with WebSphere and other proprietary application servers. And Spring was an IoC framework (now referred to as "Dependency Injection"), essentially a factory for objects so that you can follow a more "loosely coupled" design. However, with their popularity, both products expanded. For example, JBoss now has it's own IoC container: JBoss IoC JBoss provides its own lightweight IoC container called: JBoss Microcontainer. JBoss Microcontainer is a lightweight, Inversion of Control/Dependency Injection container similar in concept to Spring, Pico Container, and Plexus. And while Spring can run perfectly well, coexisting (mostly) happily with JBoss, it doesn't need a full-blown EJB container, it can run easily in tomcat. The whole design goal of Spring was based on the idea of lightweight design, and the use of POJOs, and the lack of requirement for a heavy-weight container, which was very contrary to EJBs, and thus would seem at odds with JBoss. Rod Johnson has pointed out that there's no reason you can't run Spring in JBoss: Spring is designed to work in any application server (or outside an application server); using Spring does not mean ignoring what the server may have to offer. It just provides greater choice in a lot of cases. So what you have to decide is what parts of the two systems you want to use, and what Java standards you want to adhere to. According to this article, on JBoss and Spring, which covers how well they adhere to standards, it does seem, depending on which technology you select, you are picking a side, as this seems to be a pretty contentious battle. What comes next is anything but detente, as JBoss and Spring Source battle over everything from XML to integration to tools to eventually virtualization, itself....its a healthy competition, [snip] Only time will tell, but i think that this battle only makes things better for developers, more choices rather than .Net, and more innovation around Java, it will be a tough test for JBoss, but one that they can handle if execution is flawless, otherwise, look for Spring Source to drive a wedge between perceived and real advantages of JEE 6...sooner, rather than later, portability of applications will have to be demonstrated in order to counter the proprietary models, and that has not happened, For a more up-to-date look at adherence to the various Java standards, take a look the request for feedback on Spring 5. You can get an idea of the constraints the Spring designers face, while also highlighting the fact that, for the Spring market, it is important to ensure Spring supports the various EE servers: We intend to softly upgrade the EE baseline as well. Now, this is a bit tricky since we effectively have individual requirements here - and we need to consider the enterprise adoption levels in production environments: We’ll definitely raise to Servlet 3.0+ (from our present Servlet 2.5 runtime compatibility) but no higher since we’d like Spring 5 applications to run on EE 6 baselined servers still. See my previous blog post for a discussion on why this is unavoidable, given the market situation with Java EE 7 and the multitude of servers which is still based on the Servlet 3.0 API. [snip] It’s just a shame that we have to keep supporting the 2002-era JMS 1.1 API… We’d like to raise to JPA 2.1+ and Bean Validation 1.1+ but our hands seem to be tied: TomEE 1.7 and JBoss EAP 6.4 have hard JPA 2.0 and Bean Validation 1.0 APIs in them, and WebLogic 12.1.3 has JPA 2.1 but no Bean Validation 1.1 API (despite them being related). A: As already said, but let me just restate the point. JBoss is an application server. Some Java application servers include Websphere Glassfish JBoss Spring is a framework. A rather large framework which offers quite a bit but for me one of the main features is MVC. MVC is a design pattern where you separate your Model from View from your Contoller. The model is the representation of the data. This can be backed by things like database or XML files. The view is what is used to view the model. This can be either web frontend or a windows application. The user will interact with the view. The user will express their desire for the model to be updated. This is where the controller comes in. We use the contoller to tell the model to update. And because the view is based on the model the view then gets updated too. This is over simplifying but in a nutshell. Other MVC framework that you can look at is Struts. Like I said earlier there are other features that Spring offers such as Security framework Inversion Of Control Dependency Injection A: Here's my opinion: Spring represents all that is good in Java EE, whereas JBoss represents all that is bad. Well... that didn't go over so well (not that I thought it would). I'm just saying that I would never choose JBoss to host any application. It's just so clunky and heavyweight, and does not do anything particularly well. I like Spring because it feels less monolithic and clunky. Granted, Spring is not an application container, but it can be used to build up most of the infrastructure you need to host an app - you just have to plug it into a container, and Spring handles the rest.
{ "pile_set_name": "StackExchange" }
Q: Get Feeds from FeedParser and Import to Pandas DataFrame I'm learning python. As practice I'm building a rss scraper with feedparser putting the output into a pandas dataframe and trying to mine with NLTK...but I'm first getting a list of articles from multiple RSS feeds. I used this post on how to pass multiple feeds and combined it with an answer I got previously to another question on how to get it into a Pandas dataframe. What the problem is, I want to be able to see the data from all the feeds in my dataframe. Currently I'm only able to access the first item in the list of feeds. FeedParser seems to be doing it's job but when putting it into the Pandas df it only seems to grab the first RSS in the list. import feedparser import pandas as pd rawrss = [ 'http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/front_page/rss.xml', 'https://www.yahoo.com/news/rss/', 'http://www.huffingtonpost.co.uk/feeds/index.xml', 'http://feeds.feedburner.com/TechCrunch/', ] feeds = [] for url in rawrss: feeds.append(feedparser.parse(url)) for feed in feeds: for post in feed.entries: print(post.title, post.link, post.summary) df = pd.DataFrame(columns=['title', 'link', 'summary']) for i, post in enumerate(feed.entries): df.loc[i] = post.title, post.link, post.summary df.shape df A: Your code will loop through each post and print its data. The part of your code that adds the post data to the dataframe is not part of the loop (in python indentation is meaningful!), so you only see the data from one feed in your dataframe. You can build a list of posts as you loop through the feeds, and then create a dataframe at the end: import feedparser import pandas as pd rawrss = [ 'http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/front_page/rss.xml', 'https://www.yahoo.com/news/rss/', 'http://www.huffingtonpost.co.uk/feeds/index.xml', 'http://feeds.feedburner.com/TechCrunch/', ] feeds = [] # list of feed objects for url in rawrss: feeds.append(feedparser.parse(url)) posts = [] # list of posts [(title1, link1, summary1), (title2, link2, summary2) ... ] for feed in feeds: for post in feed.entries: posts.append((post.title, post.link, post.summary)) df = pd.DataFrame(posts, columns=['title', 'link', 'summary']) # pass data to init You could optimize this a little bit by combining the two for loops: posts = [] for url in rawrss: feed = feedparser.parse(url) for post in feed.entries: posts.append((post.title, post.link, post.summary))
{ "pile_set_name": "StackExchange" }
Q: many to one relationship between composite keys I am building a spring mvc application with hibernate, and JPA that needs to model a few underlying MYSQL data tables that each have composite keys with the same two data types, so each table has its own composite key class, even though all the composite keys are based on the same two data types with exact same property names. I am getting a hibernate mapping error when I try to compile the app, and I am wondering if this might be because hibernate might not be able to equate the different primary key classes. Can someone show me how to fix this so that my app will compile? Here is the part of my Description class that establishes the ManyToOne relationship between Description and Concept classes based on their corresponding composite primary key classes: @ManyToOne @JoinColumn(name="descriptionPK", referencedColumnName = "conceptPK") private Concept concept; Here is the error that I am getting: Caused by: org.hibernate.MappingException: Unable to find column with logical name: conceptPK in org.hibernate.mapping.Table(sct2_concept) and its related supertables and secondary tables The code for ConceptPK is: @Embeddable class ConceptPK implements Serializable { @Column(name="id", nullable=false) protected BigInteger id; @Column(name="effectiveTime", nullable=false) @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime") private DateTime effectiveTime; public ConceptPK() {} public ConceptPK(BigInteger bint, DateTime dt) { this.id = bint; this.effectiveTime = dt; } /** getters and setters **/ public DateTime getEffectiveTime(){return effectiveTime;} public void setEffectiveTime(DateTime ad){effectiveTime=ad;} public void setId(BigInteger id) {this.id = id;} public BigInteger getId() {return id;} @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ConceptPK other = (ConceptPK) obj; if (effectiveTime == null) { if (other.effectiveTime != null) return false; } else if (!effectiveTime.equals(other.effectiveTime)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public int hashCode() { int hash = 3; hash = 53 * hash + ((effectiveTime == null) ? 0 : effectiveTime.hashCode()); hash = 53 * hash + ((id == null) ? 0 : id.hashCode()); return hash; } } The code for DescriptionPK is: @Embeddable class DescriptionPK implements Serializable { @Column(name="id", nullable=false) protected BigInteger id; @Column(name="effectiveTime", nullable=false) @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime") private DateTime effectiveTime; public DescriptionPK() {} public DescriptionPK(BigInteger bint, DateTime dt) { this.id = bint; this.effectiveTime = dt; } /** getters and setters **/ public DateTime getEffectiveTime(){return effectiveTime;} public void setEffectiveTime(DateTime ad){effectiveTime=ad;} public void setId(BigInteger id) {this.id = id;} public BigInteger getId() {return id;} @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final DescriptionPK other = (DescriptionPK) obj; if (effectiveTime == null) { if (other.effectiveTime != null) return false; } else if (!effectiveTime.equals(other.effectiveTime)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public int hashCode() { int hash = 3; hash = 53 * hash + ((effectiveTime == null) ? 0 : effectiveTime.hashCode()); hash = 53 * hash + ((id == null) ? 0 : id.hashCode()); return hash; } } A: You need to change @ManyToOne annotation to use multiple columns as shown below, and also you dont need to create duplicate two embeddable classes ConceptPK and DescriptionPK if all properties are same, just create one EmbeddablePK and use in both entities. @OneToMany(mappedBy = "concept", cascade = CascadeType.ALL, fetch = FetchType.EAGER) public List<Description> descriptions = new LinkedList<Description>(); And Description class: @ManyToOne @JoinColumns({ @JoinColumn(name = "A_COLUMN", referencedColumnName = "A_COLUMN", insertable = false, updatable = false), @JoinColumn(name = "B_COLUMN", referencedColumnName = "B_COLUMN", insertable = false, updatable = false), }) public Concept concept;
{ "pile_set_name": "StackExchange" }
Q: Integral being less than or equal to zero. I'm having a bit of trouble understanding this question: If $f(x) \leq 0$ for all $x \in [a, b]$ then $\int_a^b f(x) dx \leq 0$. If $\int_a^b f(x) dx \leq 0$ then $f(x) \leq 0$ for all $x \in [a, b]$. Are the above statements True of False? Justify your response. I believe it is asking if the area under the graph between $a$ and $b$ is negative then $f(x)$ will also be below zero on the graph and vice versa. However I'm still not sure how to justify my response. A: The first is true cause all the upper sums are negative. the second is false. take the example: $$f:[0,1]\to\mathbb R $$ $x \mapsto -7$ if $x\neq 0$ and $f (0)=+1$. then $$\int_0^1 f=-7$$ but $f (0)>0$. Or $$\int_{\frac {\pi}{2}}^\pi \sin (x)dx=-1$$ but $\sin (\frac {\pi}{2})=1>0$.
{ "pile_set_name": "StackExchange" }
Q: How can I pin a Leaflet marker to a location from database? I have some Leaflet marker that I load from a database and I want to pin it to that location. I'm using ajax, and I don't know how to use php code in my ajax... i use the .change function but it doesn t work, any ideas? $(".edit_scoala").click(function(){ var id_scoala = $(this).attr("id").substring(12); //alert(id_scoala); $.ajax({ type: "POST", url: "ajax/edit_scoala.php", data:{ id: id_scoala }, cache:false, dataType: "html" }).done(function(ms){ $("#response").html(ms); var map = L.map('map').setView([44.9323281,26.0306833], 12,25); L.tileLayer( 'https://api.mapbox.com/styles/v1/mapbox/streets-v10/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWVnYTYzODIiLCJhIjoiY2ozbXpsZHgxMDAzNjJxbndweDQ4am5mZyJ9.uHEjtQhnIuva7f6pAfrdTw', { maxZoom: 18, attribution: 'Map data &copy; <a href="http://openstreetmap.org/"> OpenStreetMap </a> contributors, ' + '<a href="http://creativecommons.org/"> CC-BY-SA </a>, ' + 'Imagery © <a href="http://mapbox.com"> Mapbox </a>', id: 'examples.map-i875mjb7' }).addTo(map); function putDraggable() { /* create a draggable marker in the center of the map */ draggableMarker = L.marker([ map.getCenter().lat, map.getCenter().lng], {draggable:true, zIndexOffset:900}).addTo(map); /* collect Lat,Lng values */ draggableMarker.on('dragend', function(e) { $("#latitudine").val(this.getLatLng().lat); $("#longitudine").val(this.getLatLng().lng); }); } $( document ).ready(function() { putDraggable(); $("#id_scoala").change(function() { for(var i=0;i<arr.length;i++) { if(arr[i]['id'] == $("#id_scoala").val()) { $('#detalii').val(arr[i]['detalii']); $('#latitudine').val(arr[i]['latitudine']); $('#longitudine').val(arr[i]['longitudine']); $('#telefon').val(arr[i]['telefon']); $('#cuv_cheie').val(arr[i]['cuv_cheie']); map.panTo([arr[i]['longitudine'], arr[i]['latitudine']]); draggableMarker.setLatLng([arr[i]['longitudine'], arr[i]['latitudine']]); break; } } var arr = $.parseJSON( '<?php echo json_encode($arr) ?>' ); }); }); }); }); And the edit_scoala.php file: <?php if (isset($msg)) echo $msg; include_once ("../../class/DB/DBConn.includeall.php"); include_once ('../include/config.inc.php'); $db = new DBconn(NULL); $scoala = new tableScoala($db,$_POST["id"]); //$scoala = $db->DbGetRow("SELECT * FROM scoala WHERE id = ".$_POST["id"]); echo ' <form action="" method="POST"> <a href="?page=tabel_scoala"><span class="inchide1">Inchide</span><i class="fa fa-times-circle" id="close" aria-hidden="true" style="cursor: pointer;"></i></a> <h1>Modifica Datele scolii '.$scoala->row->nume.'</h1> <div id="map" style="width: 600px; height: 400px"></div> <input type="hidden" name="id_scoala" value="'.$scoala->id.'" /> <p class="form1">Nume:</p> <input type= "text" class= "form-control form2" style="padding:12px 20px;" name= "scoala" id="scoalal" value="'.$scoala->row->nume.'" /> <br /> <p class="form1">Detalii:</p> <input type= "text" class= "form-control form2" style="padding:12px 20px;" name= "detalii" id="detalii" value="'.$scoala->row->detalii.'" /> <br /> <p class="form1">Latitudine:</p> <input type= "text" class= "form-control form2" style="padding:12px 20px;" name= "latitudine" id="latitudine" value="'.$scoala->row->latitudine.'" /> <br /> <p class="form1">longitudine:</p> <input type= "text" class= "form-control form2" style="padding:12px 20px;" name= "longitudine" id="longitudine" value="'.$scoala->row->longitudine.'" /> <br /> <p class="form1">Numar telefon:</p> <input type= "text" class= "form-control form2" style="padding:12px 20px;" name= "telefon" id="telefon" value="'.$scoala->row->telefon.'" /> <br /> <p class="form1">Cuvinte cheie:</p> <input type= "text" class= "form-control form2" id="cuv_cheie" style="padding:12px 20px;"name= "cuv_cheie" value="'.$scoala->row->cuv_cheie.'"> <br /> <br> <br> <p class="form1"> <input type="submit" name="submit" value="Salveaza"> <br> </p> </form> '; ?> I think I made a mistake somewhere.....Can you help me please? A: One way of rendering markers is querying a MySQL table/view and return the results in GeoJSON format, which is suitable for use in OpenLayers or in your case in Leaflet (I've used Leaflet as well) Below is php code which I used: <?php #Build SQL SELECT statement and return the geometry as a GeoJSON element $conn = new PDO('mysql:host=localhost;dbname=DB_NAME;charset=utf8','DB_NAME','PASS',array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); # Build SQL SELECT statement and return the geometry as a GeoJSON element $sql = 'SELECT *, coor_x AS x, coor_y AS y FROM table'; # Try query or error $rs = $conn->query($sql); if (!$rs) { echo 'An SQL error occured.\n'; exit; } # Build GeoJSON feature collection array $geojson = array( 'type' => 'FeatureCollection', 'features' => array() ); # Loop through rows to build feature arrays while ($row = $rs->fetch(PDO::FETCH_ASSOC)) { $properties = $row; # Remove x and y fields from properties (optional) unset($properties['x']); unset($properties['y']); $feature = array( 'type' => 'Feature', 'geometry' => array( 'type' => 'Point', 'coordinates' => array( $row['x'], $row['y'] ) ), 'properties' => $properties ); # Add feature arrays to feature collection array array_push($geojson['features'], $feature); } header('Content-type: application/json'); echo json_encode($geojson, JSON_NUMERIC_CHECK); $conn = NULL; ?> Hope it helps
{ "pile_set_name": "StackExchange" }
Q: Is there a chance to use App_Browsers to detect support of the HTML5 File API? Using the HTML5 File API to upload files, I am currently using some hardcoded checking of the browsers that support them, depending on the user agent string: internal bool IsHtml5FileUploadCapable { get { var browser = Request.Browser; var n = browser.Browser.ToLowerInvariant(); var major = browser.MajorVersion; var minor = browser.MinorVersion; return n.Contains(@"chrome") && major >= 6 || n.Contains(@"ie") && major >= 10 || n.Contains(@"firefox") && (major >= 3 && minor > 6 || major >= 4) || n.Contains(@"opera") && (major >= 11 && minor >= 5 || major >= 12) || n.Contains(@"safari") && major >= 4; } } What I love to use would be the built-in "App_Browsers" functionality in conjunction with the HttpBrowserCapabilities class. My question: Is it possible to deduce the ability of a browser to support the HTML5 File API directly from the browser capabilities? A: It may not be exactly what you are asking about, but having a look on the javascript library, called Modernizr ( http://www.modernizr.com/docs/ ), might be useful for your usecase. It's, of course, client-side check and not server-side one. It is capable of detecting quite a lot of HTML5 features.
{ "pile_set_name": "StackExchange" }
Q: How to publish and precompile projects that used GleamTech FileUltimate in? I used GleamTech FileUltimate file management component in my project. I add this assembly to each page that I want to use FileUltimate: <%@ Register TagPrefix="GleamTech" Assembly="GleamTech.FileUltimate" Namespace="GleamTech.FileUltimate" %> Or Add this to web.config file : <httpModules> <add name="FileUploaderModule" type="GleamTech.Web.UploadModule"/> </httpModules> <pages> <controls> <add tagPrefix="GleamTech" assembly="GleamTech.FileUltimate" namespace="GleamTech.FileUltimate"/> </controls> </pages> When I want to build and run website, give me a message that : there were build errors. would you like to continue and run the last successful build. I choose yes in this case and website works correctly, But when I want to publish website and choose precompile in the last step, compiler give some error: Error: Cannot create an object of type 'GleamTech.FileSystems.Location' from its string representation '~/upload/fm/' for the 'Location' property. Error: Literal content ('') is not allowed within a 'System.Collections.ObjectModel.Collection`1[[GleamTech.FileUltimate.FileManagerRootFolder, GleamTech.FileUltimate, Version=4.5.0.0, Culture=neutral, PublicKeyToken=a05198837413a6d8]]'. Error: System.Collections.ObjectModel.Collection`1[[GleamTech.FileUltimate.FileManagerRootFolder, GleamTech.FileUltimate, Version=4.5.0.0, Culture=neutral, PublicKeyToken=a05198837413a6d8]] must have items of type 'GleamTech.FileUltimate.FileManagerRootFolder'. 'GleamTech:FileManagerAccessControl' is of type 'GleamTech.FileUltimate.FileManagerAccessControl'. Is there any way to precompile my project and ignore these errors? How can I solve my problem? Best regards. A: For future reference, This issue is fixed in FileUltimate v5.3.8. The problem was only with “Web Site” projects and not “Web Application” projects. Fixed: In Web Site projects, when you added FileManager markup in an aspx page and built the web site, the build failed with the following error message (actually 3 error messages but main one is this, others are consequences): Cannot create an object of type 'GleamTech.FileSystems.Location' from its string representation. Actually there was a workaround for older versions: Include only this markup in aspx page: <GleamTech:FileManager ID="fileManager" runat="server" Width="800" Height="600" Resizable="True" /> Then in the codebehind aspx.cs file, add your root folders and access controls: protected void Page_Load(object sender, EventArgs e) { var rootFolder = new FileManagerRootFolder { Name = "A Root Folder", Location = "~/App_Data/RootFolder1" }; rootFolder.AccessControls.Add(new FileManagerAccessControl { Path = @"\", AllowedPermissions = FileManagerPermissions.Full }); fileManager.RootFolders.Add(rootFolder); }
{ "pile_set_name": "StackExchange" }
Q: How to update an object in an array of Objects using setState I am using React, my state is defined as an array of object. I need to be able to change only one specific element in the state.data array, example object with id 1. I would like to know: what is the proper way how to use setState() in this scenario. constructor(props) { super(props); this.state = { data: [{ id: 0, title: 'Buy a', status: 0, // 0 = todo, 1 = done }, { id: 1, title: 'Buy b', status: 0, }, { id: 2, title: 'Buy c', status: 0, } ] }; this.onTitleChange = this.onTitleChange.bind(this); } onTitleChange(id, title) { console.log(id, title); debugger } A: You can get do a cloning of the state object using spread operator and then find the index of object in array with a given id using findIndex method Modify the object and set the state. constructor(props) { super(props); this.state = { data: [{ id: 0, title: 'Buy a', status: 0, // 0 = todo, 1 = done }, { id: 1, title: 'Buy b', status: 0, }, { id: 2, title: 'Buy c', status: 0, } ] }; this.onTitleChange = this.onTitleChange.bind(this); } onTitleChange(id, title) { var data = [...this.state.data]; var index = data.findIndex(obj => obj.id === id); data[index].title = title; this.setState({data}); }
{ "pile_set_name": "StackExchange" }
Q: Script not executing with a dynamically generated JQuery script tag I have the following code in an external JS file (ie: test.js); which creates an additional script tag pointing to a JQuery source if it detects that a JQuery source isn't already there. The code actually creates the script tag and inserts it before the actual script that's doing the creating: if (typeof(jQuery) == "undefined") { var head = document.getElementsByTagName("head")[0]; // get any and all script tags var scripts = document.getElementsByTagName("script"); // the actual script call the actions (ie: this one "test.js") thisScript = scripts[scripts.length - 1]; // create element var script = document.createElement("script"); script.setAttribute("type", "text/javascript"); script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"); head.insertBefore(script,thisScript); } The above works fine. However, the problem I'm having is that once the JQuery source script tag is created, the rest of the code on "test.js" doesn't work. It's as if the code can't access the JQuery functions (or doesn't know that JQuery is there). Thus, the following code on "test.js" doesn't work: $(document).ready(function() { // ... }); The error I'm getting according to FireBug with FF 12 is: "$ is not defined" Any ideas as to why this is happening or how I can fix it? NOTE: I know I can just place JQuery on target page; however, that isn't an option as the code has to be able to detect if JQuery is there; and if not, then create the script tag pointing to JQuery and run the Jquery code. A: When you insert a script tag manually like you are doing, that script is loaded asynchronously. That means that other parts of the page will NOT wait for that script to be loaded. This is different than if the script tag is present in the source of the page because in that case, the script will load synchronously and other parts of the page will not execute until after that script is loaded. The result of this is that the rest of your page javascript is executing BEFORE the dynamically inserted script tag has been loaded, parsed and run. Thus, you are trying to use jQuery before it's been installed. I'm aware of two options for solving your issue: Change the insertion of your jQuery script tag to something that loads synchronously. The only way I know of to do that is to use document.write() to write the new script tag to your document, not insert it into the head section like you're doing. Stuff that is added to the document with document.write() is processed synchronously. Continue to insert your script dynamically like you are doing, but add a monitoring event so you will know when the script has been loaded successfully and only run your initialization code that uses jQuery AFTER you get that notification that jQuery has been successfully loaded. There are also script loading libraries (such as require.js) that will do the second option for you.
{ "pile_set_name": "StackExchange" }
Q: Start crond.service on Ubuntu 16.04 I am programming some schedule task in my Ubuntu 16.04. But when I try to start the crond.service by sudo service crond start I receive the message crond.service Loaded: not-found (Reason: No such file or directory) Active: inactive (dead) What's the problem? The tasks was added to the schedule by crontab command and look fine (the command works in the terminal, have the correct tree folder, I just added the day-hours parameters). A: It's because the service name on 16.04 is cron, not crond. So your command should be: sudo service cron start You can verify on your server by looking in the /etc/init.d folder. All the services are there. ls -l /etc/init.d
{ "pile_set_name": "StackExchange" }
Q: Does the ScaleX scaleY makes the Width and height change? Am working in flex 4 the sample mxml is <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" > <fx:Script> <![CDATA[ protected function button1_clickHandler(event:MouseEvent):void { // TODO Auto-generated method stub trace(hgroup.width ,hgroup.height); hgroup.scaleX = 1.5; hgroup.scaleY = 1.5; trace(hgroup.scaleX, hgroup.scaleY); trace(hgroup.width ,hgroup.height); } ]]> </fx:Script> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <s:HGroup id="hgroup" width="85%" height="85%" clipAndEnableScrolling="true"> <s:Button click="button1_clickHandler(event)" label="Click to Scale"/> </s:HGroup> </s:Application> If i debug on a first button click the trace shows like this 870 535 1.5 1.5 870 535 on second click of button the trace shows like this 580 356.6666666666667 1.5 1.5 580 356.6666666666667 on the perpendicular clicks it shows as like the second click my question is does the scaleX scaleY affects the width height?? please guide me i need increase in width height perpendicular with the scaleX scaleY A: Yes, scaling does affect width and height. I'm a little surprised that isn't reflected immediately in the third trace statement but my guess is it has something to do with the invalidation and redrawing of flex components. I double checked on a simple non-flex app and the properties for width and height updated immediately. ============= Finally i got Answer the scaling will not change width height. but what the thing is i used the percent width height so it get reduced. I double checked with the static width height i does not get increased but when the width height increased the scaleX scaleY increases simultaneously.Keep this in the Mind Thanks all for the support by Sudharsanan ~~~~Happy Coding~~~~~
{ "pile_set_name": "StackExchange" }
Q: Swift: Adding Headers to my REST POST Request I am still learning Swift and I am trying to make a POST request to my web service via my new iOS App written in Swift. I need to know how to add 2 headers to my already existing code. Also am I adding the parameters correctly? What I have so far: let myUrl = NSURL(string: "https://MY-MOBILE-SERVICE.azure-mobile.net/api/login"); let request = NSMutableURLRequest(URL:myUrl!); request.HTTPMethod = "POST"; // Compose a query string let postString = "[email protected]&password=123"; request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding); let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { print("error=\(error)") return } print("response = \(response)") } task.resume() Here are the Headers I need to add to this request: X-ZUMO-APPLICATION: 45634243542434 ACCEPT: application/json How do I attach these headers to my request? A: if you use alamofire, this should work, it also eases things for you so you choose get or post var pars2 : Dictionary<String,String> = ["api_key":"value"] Alamofire.request(.POST, "someURLString" ,parameters: pars2).responseJSON() { (request, response, data, error) in if(data != nil) { self.countryIDArray.removeAll(keepCapacity: false) var status = data!["status"]!! as! String } }
{ "pile_set_name": "StackExchange" }
Q: Levi-Civita connection on a vector space let $V$ be vector space, and let $\nabla$ be the Levi-Civita connection wrt. a constant metric on $V$ (in the sense that the metric is the same at every point of $V$). Let $w$ be a vector in $V$, and consider it a constant vector field on V, along some curve $\gamma$ on V. Does it hold that $\nabla_{\dot{\gamma}_t}w = 0$ ? A: Yes. This is the easiest possible case of a Riemannian manifold. The Christoffel symbols $\Gamma^i_{jk}$ are 0 because all the derivatives of the metric are 0. So, in coordinates/components, $\nabla_j w^i = \dfrac{\partial w^i}{\partial x^j} + \Gamma^j_{ik}w^k = 0$ for every $i,j$ (and hence also for the vector $\dot\gamma$).
{ "pile_set_name": "StackExchange" }
Q: What is a "minute thread"? Each caterpillar unravels a single strand of delicate raw silk from its salivary glands and wraps the minute thread thousands of times around its body in a figure of eight pattern. A: In this context the word "minute" means very, very small. In this sentence, it is talking about how small/thin the strands of silk are. Synonyms of "minute" are "miniscule" or "tiny". This can be confusing, because the word "minute" has a variety of other meanings in English, including as a unit of time ("there are 60 minutes in an hour"), as units in geographical coordinates/bearings ("the ship plotted a course towards 2 degrees, 10 minutes east") and as a form of written records of proceedings during meetings/conferences/etc ("the secretary kept detailed minutes of each of the board's meetings"). However, while they are spelled the same, these latter two senses of the word are pronounced differently in spoken English. When referring to something tiny as "minute", the word is pronounced like "my-noot" whereas the other two senses are both pronounced more like "min-nett".
{ "pile_set_name": "StackExchange" }
Q: Can I remove ORDER BY from a Django ORM query? It seems like Django by default adds ORDER BY to queries. Can I clear it? from slowstagram.models import InstagramMedia print InstagramMedia.objects.filter().query SELECT `slowstagram_instagrammedia`.`id`, `slowstagram_instagrammedia`.`user_id`, `slowstagram_instagrammedia`.`image_url`, `slowstagram_instagrammedia`.`video_url`, `slowstagram_instagrammedia`.`created_time`, `slowstagram_instagrammedia`.`caption`, `slowstagram_instagrammedia`.`filter`, `slowstagram_instagrammedia`.`link`, `slowstagram_instagrammedia`.`attribution_id`, `slowstagram_instagrammedia`.`likes_count`, `slowstagram_instagrammedia`.`type` FROM `slowstagram_instagrammedia` ORDER BY `slowstagram_instagrammedia`.`id` ASC ``` A: Actually, just do a query.order_by() is enough. This is specified in the docs although it is a bit hard to find. The docs say: If you don’t want any ordering to be applied to a query, not even the default ordering, call order_by() with no parameters. Here is the implementation of order_by, for your reference - def order_by(self, *field_names): """ Returns a new QuerySet instance with the ordering changed. """ assert self.query.can_filter(), \ "Cannot reorder a query once a slice has been taken." obj = self._clone() obj.query.clear_ordering(force_empty=False) obj.query.add_ordering(*field_names) return obj A: You can use: clear_ordering method from query """Removes any ordering settings. If 'force_empty' is True, there will be no ordering in the resulting query (not even the model's default). """ Example: >>> from products.models import Product >>> products = Product.objects.filter(shortdesc='falda').order_by('id') >>> print products.query SELECT "products_product"."id", "products_product"."shortdesc" WHERE "products_product"."shortdesc" = falda ORDER BY "products_product"."id" ASC >>> products.query.clear_ordering() >>> print products.query SELECT "products_product"."id", "products_product"."shortdesc" WHERE "products_product"."shortdesc" = falda
{ "pile_set_name": "StackExchange" }
Q: CRA - React production build with dynamic CSS imports The issue: Using the out-of-the-box react-scripts package included with create-react-app to build a production build of React, dynamically imported CSS files get ignored and instead all CSS seems to get compiled into the production build. Example of what is happening: /* styles/desktop.css */ .some-class { background-color: white; margin: 0; } /* styles/mobile.css */ .some-class { border: 1px solid black; margin: 1em; } .another-class { background-color: black; padding: 3px; } Note we are using require() with template strings as the import statement only accepts string literals and cssEnv could be any number of things which would make a conditional statement untenable. /* config.js */ const cssEnv = 'desktop'; require(`./styles/${cssEnv}.css`); We build our production build. $ npm run build In the build folder, we find our compiled CSS. Note how all our CSS files have been compiled into one (including even CSS we never imported). /* compiledCSS.chunk.css */ .some-class { background-color: white; border: 1px solid black; margin: 0; } .another-class { background-color: black; padding: 3px; } A similar SO question I found in Googling for a solution: react-scripts build ignores conditional css imports A: I'm immediately answering my own question because I've already solved it, but also because I had a bit of a Homer Simpson "d'oh!" moment when I finally found the solution after scouring Google and documentation far and wide. This is why I posted the question, in hopes of saving other people that time searching for a solution that wasn't super obvious (and doesn't seem to be addressed anywhere that I have found). So I didn't realize that the import statement had a dynamic importing functionality via import(). So the solution was simply to replace require() with import(). /* config.js */ const cssEnv = 'desktop'; import(`./styles/${cssEnv}.css`); Now when we build our production build, we get the correct compiled CSS /* compiledCSS.chunk.css */ .some-class { background-color: white; margin: 0; } So my best guess as to what is happening is that react-scripts treats require() differently than import(), where providing a template string with variables to require() causes the variables to act like wildcards (*). So when we were building the production build earlier, require(`./styles/${cssEnv}.css`); got treated like require(`./styles/*.css`); Hence all css files in the styles folder were compiled together. I'm not entirely sure of the intimate inner workings of what is happening here, so I wouldn't mind getting input from folks like Dan Abramov and others who might better understand what exactly is happening to clarify this.
{ "pile_set_name": "StackExchange" }
Q: Unit Test Zendframework: Failed saving metadata to metadataCache I am trying to setup a controller unit test but I get the following error: InscricaoControllerTest::testInscricaoPage() Zend_Controller_Exception: Failed saving metadata to metadataCache#0 [internal function]: PHPUnit_Util_ErrorHandler::handleError(1024, 'Failed saving m...', 'C:\xampp\ZendFr...', 838, Array) #1 C:\xampp\ZendFramework-1.11.12\library\Zend\Db\Table\Abstract.php(838): trigger_error('Failed saving m...', 1024) #2 C:\xampp\ZendFramework-1.11.12\library\Zend\Db\Table\Abstract.php(874): Zend_Db_Table_Abstract->_setupMetadata() #3 C:\xampp\ZendFramework-1.11.12\library\Zend\Db\Table\Abstract.php(982): Zend_Db_Table_Abstract->_setupPrimaryKey() #4 C:\xampp\ZendFramework-1.11.12\library\Zend\Db\Table\Select.php(100): Zend_Db_Table_Abstract->info() #5 C:\xampp\ZendFramework-1.11.12\library\Zend\Db\Table\Select.php(78): Zend_Db_Table_Select->setTable(Object(Application_Model_DbTable_TipoUsuario)) #6 C:\xampp\ZendFramework-1.11.12\library\Zend\Db\Table\Abstract.php(1018): Zend_Db_Table_Select->__construct(Object(Application_Model_DbTable_TipoUsuario)) #7 C:\htdocs\sgsa\application\models\DbTable\TipoUsuario.php(19): Zend_Db_Table_Abstract->select() #8 C:\htdocs\sgsa\library\Sistema\Controller\Plugin\Acl.php(10): Application_Model_DbTable_TipoUsuario->getTipoUsuario() #9 C:\xampp\ZendFramework-1.11.12\library\Zend\Controller\Plugin\Broker.php(309): Sistema_Controller_Plugin_Acl->preDispatch(Object(Zend_Controller_Request_HttpTestCase)) #10 C:\xampp\ZendFramework-1.11.12\library\Zend\Controller\Front.php(941): Zend_Controller_Plugin_Broker->preDispatch(Object(Zend_Controller_Request_HttpTestCase)) #11 C:\xampp\ZendFramework-1.11.12\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch() #12 C:\xampp\ZendFramework-1.11.12\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run() #13 C:\xampp\ZendFramework-1.11.12\library\Zend\Test\PHPUnit\ControllerTestCase.php(206): Zend_Application->run() #14 C:\htdocs\sgsa\tests\application\controllers\InscricaoControllerTest.php(11): Zend_Test_PHPUnit_ControllerTestCase->dispatch('/inscricao') #15 [internal function]: InscricaoControllerTest->testInscricaoPage() ... In my bootstrap I have APC cache: protected function _initCache() { $frontendOptions = array( 'lifetime' => 7200, // cache lifetime of 2 hours 'automatic_serialization' => true ); $backendOptions = array( //'cache_dir' => APPLICATION_PATH. '/../data/cache/' // Directory where to put the cache files ); // getting a Zend_Cache_Core object $cache = Zend_Cache::factory('Core', 'Apc', $frontendOptions, $backendOptions); Zend_Db_Table::setDefaultMetadataCache($cache); Zend_Locale::setCache($cache); Zend_Date::setOptions(array('cache' => $cache)); return $cache; } I am running the test below: public function testInscricaoPage() { $this->dispatch('/inscricao'); $this->assertResponseCode(200); $this->assertQueryContentContains('h1', 'Inscrição'); } Why I am getting this error? seems php cli can't use caching but the application runs normally on browser A: APC is disabled for PHP CLI by default, adding the following config line in php.ini solves the issue. apc.enable_cli=1 This configuration can only be set in php.ini or httpd.conf.
{ "pile_set_name": "StackExchange" }
Q: Partially forgotten encryption password I encrypted important files with Veracrypt and I remember most of the password but some parts are forgotten. I need some advice as to what would be the most efficient way of getting the encryption password. My operating system is Windows. I've been trying to get the password for months now. Any help would be appreciated. A: To elaborate further on Mike's comment. You will need an idea of the last known password and then use John the Ripper to produce a wordlist mutation (similar) passwords. You will need to create a rules configuration file for John, the wordlist will give a smaller password set if thought through carefully. Hence, a smaller keyspace to brute force; reducing overall brute force time. root@kali:~# john –wordlist=mustangwords.txt –stdout –rules:convtolowerplus000 > newmustangwords.txt Basically this is broken up as follows: john self-explanitory, start John the Ripper –wordlist= specifying the word list we want to mutate –stdout output the words generated –rules: this is the rule set we generated in the configuration file > output the results to a new text file Next, you will need to brute force the VeraCrypt header key this can be done with vUte. vUte is a VeraCrypt Bruteforcer written in BASH. As I understand the header key can be obtained via use of a hex editor, A back-to-front TrueCrypt recovery story: the plaintext is the ciphertext. For context, Is there a reason to use TrueCrypt over VeraCrypt?. As I understand HashCat can do a similar process, with less intermediate steps. However, I am not familiar with this. Furthermore, due to the nature of this brute force, it is not known to be a particularly fast crack. VeraCrypt uses PBKDF2, see About how fast can you brute force PBKDF2?.
{ "pile_set_name": "StackExchange" }
Q: Which of the following have the same molecular formula as the molecule shown in the model? This model has 3 hydrogens connected the the first and last carbon and 2 hydrogens connected to the other carbons Finding the same molecular formula as the alkane model I have to check all that apply I know the last two options are not correct, because they don't have the same amount of carbons, but when it comes to the first two I'm confused because there is only two carbons attached to 3 hydrogens yet in these options there are 3 different carbons attached to 3 hydrogens. Would they both be correct or does it matter if it's connected to the second bond instead of the third? Im assuming since they are isomers that they are equal to eachother. A: Remember they are asking for the molecular formulas which are the same, not the structural formulas. The structural formulas are shown in the question, but for example the first option, if you count up the number of carbons and hydrogens you get the molecular formula $\ce{C7H16}$, so you'll need to check if the molecule shown has the same formula. So for molecular formulas, it doesn't matter how the atoms are arranged; all isomers have the same molecular formula. Only in structural formulas do you get information on the arrangement of atoms in the molecule. Note there is also condensed structural formulas which look similar to the molecular formula but is still a structural formula. For the first option the condensed structural formula would be $\ce{CH3CH(CH3)CH2CH2CH2CH3}$.
{ "pile_set_name": "StackExchange" }
Q: The urge to combine 1- and 2-morphisms in slicing a 2-category. Suppose that $C$ is a 2-category, perhaps $C=\rm{Cat}$, the 2-category of small categories, functors, and natural transformations. Let $T$ be an object in $C$. I form the new 1-category whose objects are morphisms $f\colon A\rightarrow T$ in $C$, and in which a morphism from $f$ to some $f'\colon A'\rightarrow T$ consists of a pair $(\phi,\phi^\sharp)$ where $\phi\colon A\rightarrow A'$ is a 1-morphism in $C$ and $\phi^\sharp\colon\phi\circ f'\rightarrow f$ is a 2-morphism between arrows $A\rightarrow T$. Call this new category the $(C\Uparrow T)$. An obvious variation comes about by reversing the direction of the 2-morphism, i.e. we could take $\phi^\sharp\colon f\rightarrow\phi\circ f'$; perhaps I might call this variation $(C\Downarrow T)$. What is the high-brow way to refer to these strange slice-categories? How do you locate them within a good understanding of 2-categories? Where are the properties of such things discussed? What is the relation between these strange slices and the usual 2-categorical slices? Thanks! A: The second definition looks like the 'lax comma category' $C // T$, where a morphism $f \to f'$ is given by a 2-cell $f \to f'\phi$. The defining universal property is the same as for comma objects, except that the 2-cells in the squares are lax natural transformations. Your first definition should be the oplax version. See Kelly, On clubs and doctrines, LNM 420, or Gray, Adjointness For 2-Categories, LNM 391, who calls these '2-comma categories'. In more detail, Gray's 2-comma categories come from (strict, I think) 2-functors $A \overset{F}{\rightarrow} K \overset{G}{\leftarrow} B$. An object is a 1-cell $FA \to GB$, a morphism is a square with a 2-cell in, and a 2-cell is given by a pair of 2-cells in $K$ that fit into a commuting cylinder (it's pretty obvious if you draw a picture). In your example, (what I've called) $C // T$ has 2-cells $(\phi,\phi^\sharp) \Rightarrow (\psi,\psi^\sharp)$ given by 2-cells $\alpha \colon \phi \Rightarrow \psi$ such that $\psi^\sharp \circ f'\alpha = \phi^\sharp$. (Again, pictures make it much clearer!) So your slices are actually 2-categories, coming from $C \overset{1}{\rightarrow} C \overset{T}{\leftarrow} \bullet$. A: Interesting question! If C is a 1-category then the overcategory C/T can be described as the lax (or oplax, I forget) limit of the diagram • → C in the 2-category Cat, where the arrow is given by the object T of C. The lax limit means we ask for a universal limit cone on the diagram where the triangle is filled with a noninvertible 2-morphism. We can adapt this definition to any object C of any 2-category equipped with a map T from the terminal object. When C is a 2-category, I believe we need to ask for a "very lax" limit, in which the triangle is not even filled by a (noninvertible) natural transformation, but only a lax (or oplax, depending on which of your constructions you want) natural transformation. As far as I can see, there is no way to perform your constructions starting only with 2Cat as a 3-category and the data of C and T; we need the extra structure of the (op)lax natural transformations in 2Cat. Moreover, there is no 3-category of 2-categories, functors, and lax natural transformations in which to take a lax limit and obtain your constructions. So, these "lax" overcategories are still rather mysterious to me. I assume by "the usual 2-categorical slices" you mean to require the 2-morphism between $\phi \circ f'$ and $f$ to be invertible, which is the (op?)lax limit of the diagram • → C in 2Cat. A: For what it's worth, the construction you describe features prominently in http://front.math.ucdavis.edu/0807.4146, though that paper does not use 2-categorical language. More generally, given a 2-category $C$ (which I usually assume is pivotal, though maybe that's not necessary here), one can construct a 1-category $D$ whose objects are 1-morphisms $f:a\to b$, and whose morphisms are "rectangles": the domain $f:a\to b$ along the bottom, the range $f':a'\to b'$ along the top, additional 1-morphisms (of $C$) $g:a\to a'$ and $h:b\to b'$ along the right and left sides, and a 2-morphism of $C$ filling in the rectangle. Composition in $D$ is given by stacking the rectangles vertically. I like to think of the pair $(g, h)$ as the (bi)grading of the morphisms of $D$. What you describe is the case where we restrict $h$ to be an identity 1-morphism (of $C$). In the paper linked to above we put an inner product on $D$ and complete it to a von Neumann algebra (in fact, a factor). In response to David's comment below: Modulo some details, a planar algebra is equivalent to a pivotal 2-category whose 2-morphisms are vector spaces and whose 1-morphisms are finitely generated. The standard example is constructed from a pair of factors (irreducible von Neumann algebras) $N\subset M$. From this data we construct a 2-category whose objects are $N$ and $M$, whose 1-morphisms are generated by the two bimodules $_N M_M$ and $_M M_N$, and whose 2-morphisms are intertwinors. (So for example the 1-morphisms are $M\otimes_N M\otimes_N\cdots\otimes_N M$, thought of as either an $N$-$N$ or $N$-$M$ or $M$-$N$ or $M$-$M$ bimodule.) You can think of the usual planar algebra definition as axiomatizing the "string diagrams" you would draw for this 2-category. The diagrams in the paper I referred to are rotated 90 degrees from my explanation above. The left and right sides of the rectangles in the paper correspond to the $f$ and $f'$ of your (David's) original question. The tops of the rectangles corresponds to your $\phi$, and the interiors of the rectangles correspond to your $\phi^\sharp$.
{ "pile_set_name": "StackExchange" }
Q: How to use ServiceStack DTO TranslateTo and PopulateWith? I am a ServiceStack newbie. I have a quite large .NET C# solution using Cambium ORM. I am adding ServiceStack WebService project to my solution. I have followed the guide. Working correctly. Now I want to add UserService:Service returning User DTO using TranslateTo or PopulateWith like written here. [Route("/user")] [Route("/user/{Id}")] public class User { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } } public class UserService : Service { private Users users = new Users(); public UserResponse Get(User request) { return new UserResponse { Result = users.Single(request.Id).TranslateTo<User>() }; } } However I am unable to locate these methods. I am getting <my_object_returned_from_database> does not contain a definition for 'TranslateTo'. I did cloned the ServiceStack repository and I cannot find any implementation of those methods in any extension. What am I missing? Thanks a lot for your help! A: For ServiceStack v3, which is the stable version currently available in NuGet, TranslateTo and related methods are extension methods in the ServiceStack.Common namespace. Note that if you are cloning the GitHub repo, v3 is not the master branch. So adding a using ServiceStack.Common to your file should be sufficient to import the extension method. ServiceStack v4, the master branch in GitHub, is a preview release. I think the TranslateTo extension method got renamed to ConvertTo.
{ "pile_set_name": "StackExchange" }
Q: How to solve Rubocop respond_to_missing? offence Rubocop gives me the following offence lib/daru/vector.rb:1182:5: C: Style/MethodMissing: When using method_missing, define respond_to_missing? and fall back on super. def method_missing(name, *args, &block) ... ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The method missing is defined as: def method_missing(name, *args, &block) if name =~ /(.+)\=/ self[$1.to_sym] = args[0] elsif has_index?(name) self[name] else super(name, *args, &block) end end I tried fixing it with the below code sighting an example from here def respond_to_missing?(method_name, include_private=false) (name =~ /(.+)\=/) || has_index?(name) || super end But now Rubocop give me the follow offence: lib/daru/vector.rb:1182:5: C: Style/MethodMissing: When using method_missing, fall back on super. def method_missing(name, *args, &block) ... ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ I can't seem to figure out what's wrong. As you can see I'm falling back on super in the else block. A: Rubocop expects super to be called without arguments. As the arguments you are passing to super are the same as those you received, you can simply remove the arguments: def method_missing(name, *args, &block) if name =~ /(.+)\=/ self[$1.to_sym] = args[0] elsif has_index?(name) self[name] else super end end
{ "pile_set_name": "StackExchange" }
Q: VS2017 MVC project wont open from .sln but Team Explorer works fine I'm working on a project which creates large XML files of 800k plus. I was having memory issues so I changed my IIS option in Tools>Options to 64 bit which helped. The problem worsened when my project hung and wasn't responding so I closed it forcibly. When I tried to re-open from the project .sln it told me it was incompatible even though the Team Explorer showed my latest changes as below. It produced a Migration Report which looked like this The project folder layout looks like this I've tried running old backed up folders but VS2017 always says they are not recognised and tries to migrate them, some are only three or four days old! Has this reset broken my Visual Studio, do I need to re-install? I don't really have the time to mess around with this but if I can't restore from GIT/Team Explorer or backups, i don't know how to get my project running again. It seems ridiculous that Team Explorer shows my latest changes but Solution explorer is blank! A: Team explorer is only concerned with files on disk, it isn't trying to run anything. Solution explorer needs to open the solution file, read the contents, and interpret them in some way. It is failing to do this. This is why the former is working, when the latter isnt.
{ "pile_set_name": "StackExchange" }
Q: Is there really a choice of the best language for a specific project? Programmers.SE has plenty of questions of beginner programmers asking if they must use a specific language or another one in their daily work, or if they must learn a language or another. Those questions are quickly closed, and when they receive answers, those answers are of type: Use what is best for a specific project. There are languages that cannot be reasonably used for some sorts of projects. For example, it would be strange to use Assembly to create a dynamic website, or to use PHP to create a rich desktop Windows application or to use Ruby to create a video game with hardware acceleration. But in general, does the "Use what is best for a specific project" rule work? If I create a simple business desktop application, how can I say that for this business app, C# is not appropriate at all, while Java is the best choice? If I create an ordinary small or medium-scale website, how can I say that I must use C#/ASP.NET MVC over Ruby on Rails? Comparing mainstream languages, they are all pretty similar. I choose C# over Java because I don't know Java very well; I choose ASP.NET MVC over PHP because in my opinion, PHP sucks; I choose PHP over ASP.NET MVC when my customers have a web server running Linux. In all cases, every time I have to to a choice, I consider: my skills in the languages to choose from, languages I personally want and enjoy to use, software and hardware requirements (i.e. difficulty to deploy Java or Ruby on Rails website on a server which has already a support for PHP), legacy and interoperability concerns. Does it mean that I lack broad knowledge in several  languages? What happens in other companies? Is there a real choice, for every project, of the language which is the best one in a precise case? How could such choice be made in a situation where the mainstream languages are so similar? A: As we engineers all know, there is no such thing as the best, best can only be defined if you have some kind of metric to compare alternatives. Do you feel comfortable in working in that language? If not, you'll probably pick bad design choices on the language level. How fast can you develop features for your app in that language? Is it easy to extend functionality for an existing code or it is going to be a PITA because the language creates too much constraints? Is the language fast enough? For some tasks this is mandatory, for others, where you can easily scale with multiple machines it hardly matters. Does it compile to native code? For some software this is mandatory, people won't install your small up if it comes with a 50-500M runtime environment. Does it provide the necessary libraries and tools (reading XML, working with all kind of databases, etc..) You don't want to reinvent the wheel. Ok, this is probably not the best point on the list, most languages are mature enough for this, but if you pick a relatively new language/framework this can be a problem. If you need external hosting, is it well supported? (if the project is large enough) Is it easy to find developers? Are they cheap? This is an economic factor. I agree that PHP sucks, but there is an abundance of PHP developers and they are cheep (at least compared to a Java or C# developer). Let's be honest, making an average website is not rocket science, doesn't require much skill (at least until you have a lot of visitors or a really complex system). So, a metric is a mixture of all these factors with different weights. Now choose your weights and pick the best ;) Because the weights are judged subjectivily I would say that theoretically YES, there is an ideal language (or a handful of languages) for a specific project, but practically NO, you have to choose a language you are already familiar with and think that is the best for the job. A: A trademan always uses the right tool for the job. As a rule a programmer will usually turn every problem into a nail so he can use his hammer. The reason for this is unlike an average tradesman, who has a hope of becoming proficent using all the commonly available tools, even an expert programmer has no hope for that, and therefore must become proficent in one or two "tools" of many, or pretty average in many and proficent in none. Therefore the "best choice", unlike a trademan's, is more about the environment rather than the technical "best". For instance, I am aware of a large ADA project recently re-written in Java, largely because you cannot recruit ADA developers anymore, and Java programmers are a dime a dozen. Java is probably a long way from the ideal technical solution, but Erlang (likely a far better language for their problem domain) isn't even a contender in 2011 due to lack of potential recruits.
{ "pile_set_name": "StackExchange" }
Q: java.io.FileNotFoundException: (No such file or directory) when running from eclipse I am writing to a file and want console output, // TODO Create a game engine and call the runGame() method public static void main(String[] args) throws Exception { NewGame myGame = new TheGame().new NewGame(); myGame.runGame(); PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out); } This gives me console output, but it throws the following exception: java.io.FileNotFoundException: TheGame.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:138) at game.main(TheGame.java:512) The file does exist. A: The file should be in contained within the root of your project. When you execute a project in eclipse, the working directory is the most top level of your project. Right click your project, click New>File, and make a txt file called "TheGame.txt".
{ "pile_set_name": "StackExchange" }
Q: PHP preg_replace replacing newlines, but nothing works I have a text field retrieved by a Solr query that contains the body of an email. I am trying to replace embedded line breaks with paragraph tags via PHP like so: $text = $item->Body[0]; $new_line = array("\r\n", "\n", "\r"); preg_replace($new_line, '</p><p>', $text); echo $text; When I show the result in my IDE/debugger the newline characters are not replaced and are still there: I have been going through threads on this site trying patterns suggested by different people including "/\s+/" and PHP_EOL and "/(\r\n|\r|\n)/" and nothing works. What am I doing wrong? A: You are missing the delimiter around your regex strings and you are not assigning the value. You can also reduce your regex: $text = preg_replace("/\r?\n|\r/", '</p><p>', $text); You might want switch to the multibyte safe version. They work with Unicode and you don't need delimiters there ;) $text = mb_ereg_replace("\r?\n|\r", '</p><p>', $text); A: preg_replace is for regular expressions. You want a simple string replacement, so you should use str_replace: $text = $item->Body[0]; $new_line = array("\r\n", "\n", "\r"); $text = str_replace($new_line, '</p><p>', $text); echo $text;
{ "pile_set_name": "StackExchange" }
Q: CSS Drawing on an Angle My CSS looks as follows: .block1 { height:20px; width:70px; background-color:#09F; background-repeat:no-repeat; position:absolute; } This draws a rectangle. Next i would like to draw a rectangle on an angle, such as at 45 degrees. I am not aware of an angle option, how could i do this? A: It's not fully supported in all browsers, but you can use CSS Rotation. Here's an article on it. Basically, apply: -moz-transform:rotate(45deg); /* Firefox */ -webkit-transform:rotate(45deg); /* WebKit (Chrome, Safari) */ -o-transform: rotate(45deg); /* Opera */ -ms-transform:rotate(45deg); /* IE9 */ transform: rotate(45deg); /* No support currently, but hooray future! */ /* Fun IE code (you should probably put this in a separate css file controlled with conditional comments) */ /* IE8+ - must be on one line, unfortunately */ -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.7071067811865474, M12=-0.7071067811865477, M21=0.7071067811865477, M22=0.7071067811865474, SizingMethod='auto expand')"; /* IE6 and 7 */ filter: progid:DXImageTransform.Microsoft.Matrix( M11=0.7071067811865474, M12=-0.7071067811865477, M21=0.7071067811865477, M22=0.7071067811865474, SizingMethod='auto expand'); /* These are necessary for the IE code only */ margin-left: 5px; margin-top: -70px; IE code generated with this tool, which is incredibly useful.
{ "pile_set_name": "StackExchange" }
Q: Linq to XML - Find an element I am sure that this is basic and probably was asked before, but I am only starting using Linq to XML. I have a simple XML that i need to read and write to. <Documents> ... <Document> <GUID>09a1f55f-c248-44cd-9460-c0aab7c017c9-0</GUID> <ArchiveTime>2012-05-15T14:27:58.5270023+02:00</ArchiveTime> <ArchiveTimeUtc>2012-05-15T12:27:58.5270023Z</ArchiveTimeUtc> <IndexDatas> <IndexData> <Name>Name1</Name> <Value>Some value</Value> <DataType>1</DataType> <CreationTime>2012-05-15T14:27:39.6427753+02:00</CreationTime> <CreationTimeUtc>2012-05-15T12:27:39.6427753Z</CreationTimeUtc> </IndexData> <IndexData> <Name>Name2</Name> <Value>Some value</Value> <DataType>3</DataType> <CreationTime>2012-05-15T14:27:39.6427753+02:00</CreationTime> <CreationTimeUtc>2012-05-15T12:27:39.6427753Z</CreationTimeUtc> </IndexData> ... </IndexDatas> </Document> ... </Documents> I have a "Documents" node that contains bunch of "Document" nodes. I have GUID of the document and a "IndexData" name. I need to find the document by GUID and check if it has "IndexData" with some name. If it does not have it i need to add it. Any help would be apreciated, as i have problem with reading and searching trough elements. Currently I am trying to use (in C#): IEnumerable<XElement> xmlDocuments = from c in XElement .Load(filePath) .Elements("Documents") select c; // fetch document XElement documentElementToEdit = (from c in xmlDocuments where (string)c.Element("GUID").Value == GUID select c).Single(); EDIT xmlDocuments.Element("Documents").Elements("Document") This returns no result, even tho xmlDocuments.Element("Documents") does. It looks like i cant get Document nodes from Documents node. A: You can find those docs (docs without related name in index data) with below code, after that you could add your elements to the end of IndexData elements. var relatedDocs = doc.Elements("Document") .Where(x=>x.Element("GUID").Value == givenValue) .Where(x=>!x.Element("IndexDatas") .Elements("IndexData") .Any(x=>x.Element("Name") == someValue);
{ "pile_set_name": "StackExchange" }
Q: Filter Coefficients in MATLAB are always float data type I will be using the filter coefficients generated by MATLAB in my code that will run on a microcontroller. The poor microcontroller is very bad in floating point Arithmetic. So What do I do? Shall I directly truncate all float values to nearest int? shall I do ceil? or floor? Is there any function that can automatically do this conversion for me? Update All my filter coefficeints are coming like: 0.465, 0.76, 0.23 etc, so If I use ciel then all will become zero. What should I do now? Actual Filter Coefficients are: > -0.00385638 > 0.004944457 > 0.01505063 > 0.018768283 > 0.009635631 > -0.01192891 > -0.035809426 > -0.045043857 > -0.023993426 > 0.032106934 > 0.111777547 > 0.18997355 > 0.238374966 > 0.238374966 > 0.18997355 > 0.111777547 > 0.032106934 > -0.023993426 > -0.045043857 > -0.035809426 > -0.01192891 > 0.009635631 > 0.018768283 > 0.01505063 > 0.004944457 > -0.00385638 A: Normally you would use fixed-point arithmetic for performing DSP on a a floating-point-challenged CPU. So for, say, 16 bit fixed-point coefficients with a range of -1.0 to +1.0 your coeffs would translate to e.g.: 0.465 => 0.465 * 0x7fff = 0x3b5 If your microcontroller does not have direct support for fixed point arithemtic (most DSPs do, general purpose microcontrollers typically do not) then you'll need to take care of scaling when you multiply or divide. (Addition and subtraction work as normal of course, provided you are not mixing different fixed point types.)
{ "pile_set_name": "StackExchange" }
Q: CSS: Maintain Aspect Ration of Div Element I tried to solve my problem searching through the various questions already posted, but I have not found one that is made for my I'm creating my new website using the "responsive" technique and now I'm missing just one little thing: I enter inside a DIV a background image The DIV should have a width of 100% to fill the entire page, and I have to make sure that the height of the DIV that contains the image will auto resize when resizing the page. A: If you want the image to retain the width and height of the containing div, use: background-size: 100% 100%; The image will distort, but you may not mind. If you want the background to be whatever portion of the image is sufficient to cover the entire div as the viewport changes, use: background-size: cover; If you want to ensure that the entire image is in the background with the proper aspect ratio, use: background-size: contain; In this case, the image may be tiled to cover the div. HTML <div id="thediv"></div> CSS html, body { height: 100%; } #thediv { height: 100%; background-image: url(http://i.imgur.com/MabCTXH.jpg); background-size: 100% 100%; }
{ "pile_set_name": "StackExchange" }
Q: What are the performance impacts of 'functional' Rust? I am following the Rust track on Exercism.io. I have a fair amount of C/C++ experience. I like the 'functional' elements of Rust but I'm concerned about the relative performance. I solved the 'run length encoding' problem: pub fn encode(source: &str) -> String { let mut retval = String::new(); let firstchar = source.chars().next(); let mut currentchar = match firstchar { Some(x) => x, None => return retval, }; let mut currentcharcount: u32 = 0; for c in source.chars() { if c == currentchar { currentcharcount += 1; } else { if currentcharcount > 1 { retval.push_str(&currentcharcount.to_string()); } retval.push(currentchar); currentchar = c; currentcharcount = 1; } } if currentcharcount > 1 { retval.push_str(&currentcharcount.to_string()); } retval.push(currentchar); retval } I noticed that one of the top-rated answers looked more like this: extern crate itertools; use itertools::Itertools; pub fn encode(data: &str) -> String { data.chars() .group_by(|&c| c) .into_iter() .map(|(c, group)| match group.count() { 1 => c.to_string(), n => format!("{}{}", n, c), }) .collect() } I love the top rated solution; it is simple, functional, and elegant. This is what they promised me Rust would be all about. Mine on the other hand is gross and full of mutable variables. You can tell I'm used to C++. My problem is that the functional style has a SIGNIFICANT performance impact. I tested both versions with the same 4MB of random data encoded 1000 times. My imperative solution took under 10 seconds; the functional solution was ~2mins30seconds. Why is the functional style so much slower than the imperative style? Is there some problem with the functional implementation which is causing such a huge slowdown? If I want to write high performance code, should I ever use this functional style? A: TL;DR A functional implementation can be faster than your original procedural implementation, in certain cases. Why is the functional style so much slower than the imperative style? Is there some problem with the functional implementation which is causing such a huge slowdown? As Matthieu M. already pointed out, the important thing to note is that the algorithm matters. How that algorithm is expressed (procedural, imperative, object-oriented, functional, declarative) generally doesn't matter. I see two main issues with the functional code: Allocating numerous strings over and over is inefficient. In the original functional implementation, this is done via to_string and format!. There's the overhead of using group_by, which exists to give a nested iterator, which you don't need just to get the counts. Using more of itertools (batching, take_while_ref, format_with) brings the two implementations much closer: pub fn encode_slim(data: &str) -> String { data.chars() .batching(|it| { it.next() .map(|v| (v, it.take_while_ref(|&v2| v2 == v).count() + 1)) }) .format_with("", |(c, count), f| match count { 1 => f(&c), n => f(&format_args!("{}{}", n, c)), }) .to_string() } A benchmark of 4MiB of random alphanumeric data, compiled with RUSTFLAGS='-C target-cpu=native': encode (procedural) time: [21.082 ms 21.620 ms 22.211 ms] encode (fast) time: [26.457 ms 27.104 ms 27.882 ms] Found 7 outliers among 100 measurements (7.00%) 4 (4.00%) high mild 3 (3.00%) high severe If you are interested in creating your own iterator, you can mix-and-match the procedural code with more functional code: struct RunLength<I> { iter: I, saved: Option<char>, } impl<I> RunLength<I> where I: Iterator<Item = char>, { fn new(mut iter: I) -> Self { let saved = iter.next(); // See footnote 1 Self { iter, saved } } } impl<I> Iterator for RunLength<I> where I: Iterator<Item = char>, { type Item = (char, usize); fn next(&mut self) -> Option<Self::Item> { let c = self.saved.take().or_else(|| self.iter.next())?; let mut count = 1; while let Some(n) = self.iter.next() { if n == c { count += 1 } else { self.saved = Some(n); break; } } Some((c, count)) } } pub fn encode_tiny(data: &str) -> String { use std::fmt::Write; RunLength::new(data.chars()).fold(String::new(), |mut s, (c, count)| { match count { 1 => s.push(c), n => write!(&mut s, "{}{}", n, c).unwrap(), } s }) } 1 — thanks to Stargateur for pointing out that eagerly getting the first value helps branch prediction. A benchmark of 4MiB of random alphanumeric data, compiled with RUSTFLAGS='-C target-cpu=native': encode (procedural) time: [19.888 ms 20.301 ms 20.794 ms] Found 4 outliers among 100 measurements (4.00%) 3 (3.00%) high mild 1 (1.00%) high severe encode (tiny) time: [19.150 ms 19.262 ms 19.399 ms] Found 11 outliers among 100 measurements (11.00%) 5 (5.00%) high mild 6 (6.00%) high severe I believe this more clearly shows the main fundamental difference between the two implementations: an iterator-based solution is resumable. Every time we call next, we need to see if there was a previous character that we've read (self.saved). This adds a branch to the code that isn't there in the procedural code. On the flip side, the iterator-based solution is more flexible — we can now compose all sorts of transformations on the data, or write directly to a file instead of a String, etc. The custom iterator can be extended to operate on a generic type instead of char as well, making it very flexible. See also: How can I add new methods to Iterator? If I want to write high performance code, should I ever use this functional style? I would, until benchmarking shows that it's the bottleneck. Then evaluate why it's the bottleneck. Supporting code Always got to show your work, right? benchmark.rs use criterion::{criterion_group, criterion_main, Criterion}; // 0.2.11 use rle::*; fn criterion_benchmark(c: &mut Criterion) { let data = rand_data(4 * 1024 * 1024); c.bench_function("encode (procedural)", { let data = data.clone(); move |b| b.iter(|| encode_proc(&data)) }); c.bench_function("encode (functional)", { let data = data.clone(); move |b| b.iter(|| encode_iter(&data)) }); c.bench_function("encode (fast)", { let data = data.clone(); move |b| b.iter(|| encode_slim(&data)) }); c.bench_function("encode (tiny)", { let data = data.clone(); move |b| b.iter(|| encode_tiny(&data)) }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches); lib.rs use itertools::Itertools; // 0.8.0 use rand; // 0.6.5 pub fn rand_data(len: usize) -> String { use rand::distributions::{Alphanumeric, Distribution}; let mut rng = rand::thread_rng(); Alphanumeric.sample_iter(&mut rng).take(len).collect() } pub fn encode_proc(source: &str) -> String { let mut retval = String::new(); let firstchar = source.chars().next(); let mut currentchar = match firstchar { Some(x) => x, None => return retval, }; let mut currentcharcount: u32 = 0; for c in source.chars() { if c == currentchar { currentcharcount += 1; } else { if currentcharcount > 1 { retval.push_str(&currentcharcount.to_string()); } retval.push(currentchar); currentchar = c; currentcharcount = 1; } } if currentcharcount > 1 { retval.push_str(&currentcharcount.to_string()); } retval.push(currentchar); retval } pub fn encode_iter(data: &str) -> String { data.chars() .group_by(|&c| c) .into_iter() .map(|(c, group)| match group.count() { 1 => c.to_string(), n => format!("{}{}", n, c), }) .collect() } pub fn encode_slim(data: &str) -> String { data.chars() .batching(|it| { it.next() .map(|v| (v, it.take_while_ref(|&v2| v2 == v).count() + 1)) }) .format_with("", |(c, count), f| match count { 1 => f(&c), n => f(&format_args!("{}{}", n, c)), }) .to_string() } struct RunLength<I> { iter: I, saved: Option<char>, } impl<I> RunLength<I> where I: Iterator<Item = char>, { fn new(mut iter: I) -> Self { let saved = iter.next(); Self { iter, saved } } } impl<I> Iterator for RunLength<I> where I: Iterator<Item = char>, { type Item = (char, usize); fn next(&mut self) -> Option<Self::Item> { let c = self.saved.take().or_else(|| self.iter.next())?; let mut count = 1; while let Some(n) = self.iter.next() { if n == c { count += 1 } else { self.saved = Some(n); break; } } Some((c, count)) } } pub fn encode_tiny(data: &str) -> String { use std::fmt::Write; RunLength::new(data.chars()).fold(String::new(), |mut s, (c, count)| { match count { 1 => s.push(c), n => write!(&mut s, "{}{}", n, c).unwrap(), } s }) } #[cfg(test)] mod test { use super::*; #[test] fn all_the_same() { let data = rand_data(1024); let a = encode_proc(&data); let b = encode_iter(&data); let c = encode_slim(&data); let d = encode_tiny(&data); assert_eq!(a, b); assert_eq!(a, c); assert_eq!(a, d); } } A: Let's review the functional implementation! Memory Allocations One of the big issues of the functional style proposed here is the closure passed to the map method which allocates a lot. Every single character is first mapped to a String before being collected. It also uses the format machinery, which is known to be relatively slow. Sometimes, people try way too hard to get a "pure" functional solution, instead: let mut result = String::new(); for (c, group) in &source.chars().group_by(|&c| c) { let count = group.count(); if count > 1 { result.push_str(&count.to_string()); } result.push(c); } is about as verbose, yet only allocates when count > 1 just like your solution does and does not use the format machinery either. I would expect a significant performance win compared to the full functional solution, while at the same time still leveraging group_by for extra readability compared to the full imperative solution. Sometimes, you ought to mix and match!
{ "pile_set_name": "StackExchange" }
Q: Trigger a event on Zoom change SAP UI 5 I want an event to be triggered when zoom of the map changes. I am using sap ui5 google maps. In my view.xml i bound the map as following <gmaps:Map id="map1" class="googleMap" height="600px" width="100%" zoom="4" lat="100" lng=100" markers="{/co}" ready="onMapReady" zoomControl = 'true' zoom_changed = "renderNewMap"> But it doesn't trigger the event. A: I'm afraid John Patterson's Google Maps control doesn't have a zoom event. According to Map.js on Github, only a click and ready event are present. However, this control is open source though, meaning that you have the possibility to add whatever you think is missing in a subclass, or even your own version of this control. If you make any useful modifications that could be useful for other people as well, it would also show good etiquette, if you could submit your changes in a pull request. In the open source community this is considered saying "thank you". When you make a pull request, John could then easily include your contributions in future releases of the Google Maps control.
{ "pile_set_name": "StackExchange" }
Q: pandas rolling_apply TypeError: int object is not iterable" I have a function saved and defined in a different script called TechAnalisys.py This function just outputs a scalar, so I plan to use pd.rolling_apply() to generate a new column into the original dataframe (df). The function works fine when executed, but I have problems when using the rolling_apply() application.This link Passing arguments to rolling_apply shows how you should do it, and that is how I think it my code is but it still shows the error "TypeError: int object is not iterable" appears This is the function (located in the script TechAnalisys.py) def hurst(df,days): import pandas as pd import numpy as np df2 = pd.DataFrame() df2 = df[-days:] rango = lambda x: x.max() - x.min() df2['ret'] = 1 - df.PX_LAST/df.PX_LAST.shift(1) df2 = df2.dropna() ave = pd.expanding_mean(df2.ret) df2['desvdeprom'] = df2.ret - ave df2['acum'] = df2['desvdeprom'].cumsum() df2['rangorolled'] = pd.expanding_apply(df2.acum, rango) df2['datastd'] = pd.expanding_std(df2.ret) df2['rango_rangostd'] = np.log(df2.rangorolled/df2.datastd) df2['tiempo1'] = np.log(range(1,len(df2.index)+1)) df2 = df2.dropna() model1 = pd.ols(y=df2['rango_rangostd'], x=df2['tiempo1'], intercept=False) return model1.beta and now this is the main script: import pandas as pd import numpy as np import TechAnalysis as ta df = pd.DataFrame(np.log(np.cumsum(np.random.randn(100000)+1)+1000),columns =['PX_LAST']) The following works: print ta.hurst(df,50) This doesn't work: df['hurst_roll'] = pd.rolling_apply(df, 15 , ta.hurst, args=(50)) Whats wrong in the code? A: If you check the type of df within the hurst function, you'll see that rolling_apply passes it as numpy.array. If you create a DataFrame from this numpy.array inside rolling_apply, it works. I also used a longer window because there were only 15 values per array but you seemed to be planning on using the last 50 days. def hurst(df, days): df = pd.DataFrame(df, columns=['PX_LAST']) df2 = pd.DataFrame() df2 = df.loc[-days:, :] rango = lambda x: x.max() - x.min() df2['ret'] = 1 - df.loc[:, 'PX_LAST']/df.loc[:, 'PX_LAST'].shift(1) df2 = df2.dropna() ave = pd.expanding_mean(df2.ret) df2['desvdeprom'] = df2.ret - ave df2['acum'] = df2['desvdeprom'].cumsum() df2['rangorolled'] = pd.expanding_apply(df2.acum, rango) df2['datastd'] = pd.expanding_std(df2.ret) df2['rango_rangostd'] = np.log(df2.rangorolled/df2.datastd) df2['tiempo1'] = np.log(range(1, len(df2.index)+1)) df2 = df2.dropna() model1 = pd.ols(y=df2['rango_rangostd'], x=df2['tiempo1'], intercept=False) return model1.beta def rol_apply(): df = pd.DataFrame(np.log(np.cumsum(np.random.randn(1000)+1)+1000), columns=['PX_LAST']) df['hurst_roll'] = pd.rolling_apply(df, 100, hurst, args=(50, )) PX_LAST hurst_roll 0 6.907911 NaN 1 6.907808 NaN 2 6.907520 NaN 3 6.908048 NaN 4 6.907622 NaN 5 6.909895 NaN 6 6.911281 NaN 7 6.911998 NaN 8 6.912245 NaN 9 6.912457 NaN 10 6.913794 NaN 11 6.914294 NaN 12 6.915157 NaN 13 6.916172 NaN 14 6.916838 NaN 15 6.917235 NaN 16 6.918061 NaN 17 6.918717 NaN 18 6.920109 NaN 19 6.919867 NaN 20 6.921309 NaN 21 6.922786 NaN 22 6.924173 NaN 23 6.925523 NaN 24 6.926517 NaN 25 6.928552 NaN 26 6.930198 NaN 27 6.931738 NaN 28 6.931959 NaN 29 6.932111 NaN .. ... ... 970 7.562284 0.653381 971 7.563388 0.630455 972 7.563499 0.577746 973 7.563686 0.552758 974 7.564105 0.540144 975 7.564428 0.541411 976 7.564351 0.532154 977 7.564408 0.530999 978 7.564681 0.532376 979 7.565192 0.536758 980 7.565359 0.538629 981 7.566112 0.555789 982 7.566678 0.553163 983 7.566364 0.577953 984 7.567587 0.634843 985 7.568583 0.679807 986 7.569268 0.662653 987 7.570018 0.630447 988 7.570375 0.659497 989 7.570704 0.622190 990 7.571009 0.485458 991 7.571886 0.551147 992 7.573148 0.459912 993 7.574134 0.463146 994 7.574478 0.463158 995 7.574671 0.535014 996 7.575177 0.467705 997 7.575374 0.531098 998 7.575620 0.540611 999 7.576727 0.465572 [1000 rows x 2 columns]
{ "pile_set_name": "StackExchange" }
Q: Fatal error: require_once(): I'm getting the following error: Warning: require_once(D:/xampp/htdocs/inc/head.php): failed to open stream: No such file or directory in D:\xampp\htdocs\ecommerce1\index.php on line 3 Fatal error: require_once(): Failed opening required 'D:/xampp/htdocs/inc/head.php' (include_path='.;D:\xampp\php\PEAR') in D:\xampp\htdocs\ecommerce1\index.php on line 3 I have the following code : located in D:\xampp\htdocs\ecommerce1 Index.php <!--head--> <?php $title="Gamer"?> <?php require_once $_SERVER["DOCUMENT_ROOT"]. '/inc/head.php';?> <?php require_once $_SERVER["DOCUMENT_ROOT"]. '/inc/menu.php';?> <!--body of the page--> <!--footer of the page--> <?php require_once $_SERVER["DOCUMENT_ROOT"]. '/inc/footer.php';?> ` This is the head.php which is located in D:\xampp\htdocs\ecommerce1\inc <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title><?php print $title ?> </title> <link rel="stylesheet" type="text/css" href="/css/style.css"> <script type="text/javascript" src="/jquery/jquery-1.12.3.min.js"></script> </head> <body> A: Unless you explicitly change the DocumentRoot setting in Apache's httpd.conf, the Document Root is by default in D:/xampp/htdocs . So you need to call: <?php require_once $_SERVER["DOCUMENT_ROOT"]. 'ecommerce1/inc/head.php';?> instead of <?php require_once $_SERVER["DOCUMENT_ROOT"]. '/inc/head.php';?> A: Do this in your index.php. <?php $title="Gamer"?> <?php require_once 'inc/head.php';?> <?php require_once 'inc/menu.php';?> <!--body of the page--> <!--footer of the page--> <?php require_once 'inc/footer.php';?> Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Accessing a project resource from a plugin in Maven I've written a Maven plugin which when running standalone is working fine. I have some custom XML resource files within the plugin source code that are visible and accessible to the plugin when testing (Plugin POM below). So I install the plugin and all is well. Now I create a new project that refers to the newly installed plugin (Project POM below). I have some custom XML resource files similar to those embedded within the plugin project. The project has the following structure: tester | pom.xml | +---src | +---main | | +---java | | | \---[BLAH} | | | | | \---resources | | tester-catalog-env.xml | | | \---test | \---java | \---[BLAH] Within the plugin I have the following method: public TesterProcessCatalog getTesterProcessCatalog(Properties properties) throws TesterDataSourceException { try { InputStream in = getClass().getClass().getResourceAsStream("tester-catalog-env.xml"); Reader reader = ReaderFactory.newXmlReader(in); return readCatalog(reader); } catch (IOException e) { throw new TesterDataSourceException("Error reading catalog", e); } } The line: InputStream in = getClass().getClass().getResourceAsStream("tester-catalog-env.xml"); is returning null when run from the project using mvn tester:test (as defined in the plugin mojo) even though I can see that the resource is present on the classpath. I've tried the following InputStream in = getClass().getClass().getResourceAsStream("/tester-catalog-env.xml"); and that also returns null. If I copy the resource file over to the plugin resource directory and run, it works fine. Ultimately what I'm trying to achieve is to have multiple config files in the projects resources directory (ie tester-catalog-xxx.xml - where xxx can be a new file created by the user) that when a command like mvn tester:test -DprocessCatalog=env2 is run the file called tester-catalog-env2.xml will be loaded. Any ideas on what I'm doing wrong? Maven Info Apache Maven 3.0.4 (r1232337; 2012-01-17 10:44:56+0200) Maven home: C:\Apps\apache-maven-3.0.4 Java version: 1.6.0_35, vendor: Sun Microsystems Inc. Java home: C:\java\jdk1.6.0_35\jre Default locale: en_GB, platform encoding: Cp1252 OS name: "windows xp", version: "5.1", arch: "x86", family: "windows" Plugin POM <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.testing.tester.maven</groupId> <artifactId>tester</artifactId> <packaging>maven-plugin</packaging> <version>1.0-SNAPSHOT</version> <name>tester Maven Mojo</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.2-beta-5</version> </dependency> <dependency> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-component-annotations</artifactId> <version>1.5.5</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>com.sun</groupId> <artifactId>tools</artifactId> <version>1.6</version> <scope>system</scope> <systemPath>C:\java\jdk1.6.0_35\lib\tools.jar</systemPath> <optional>true</optional> </dependency> <dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.brsanthu</groupId> <artifactId>data-exporter</artifactId> <version>1.0.0</version> <!-- http://code.google.com/p/data-exporter/wiki/UserGuide --> <!-- mvn install:install-file -DgroupId=com.brsanthu -DartifactId=data-exporter -Dversion=1.0.0 -Dpackaging=jar -Dfile=http://data-exporter.googlecode.com/files/data-exporter-1.0.0.jar--> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-component-metadata</artifactId> <version>1.5.5</version> <executions> <execution> <goals> <goal>generate-metadata</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> Project POM <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.testing.tester</groupId> <artifactId>tester</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>tester</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.testing.tester.maven</groupId> <artifactId>tester</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>com.testing.tester.maven</groupId> <artifactId>tester</artifactId> <version>1.0-SNAPSHOT</version> </plugin> </plugins> </build> </project> A: I have found a working solution. This post details the steps required. Basically I added the following class to the plugin (I've removed the references to LOGGER in the original post) /** * A custom ComponentConfigurator which adds the project's runtime classpath elements * to the * * @author Brian Jackson * @since Aug 1, 2008 3:04:17 PM * * @plexus.component role="org.codehaus.plexus.component.configurator.ComponentConfigurator" * role-hint="include-project-dependencies" * @plexus.requirement role="org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup" * role-hint="default" */ public class IncludeProjectDependenciesComponentConfigurator extends AbstractComponentConfigurator { public void configureComponent( Object component, PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm, ConfigurationListener listener ) throws ComponentConfigurationException { addProjectDependenciesToClassRealm(expressionEvaluator, containerRealm); converterLookup.registerConverter( new ClassRealmConverter( containerRealm ) ); ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter(); converter.processConfiguration( converterLookup, component, containerRealm.getClassLoader(), configuration, expressionEvaluator, listener ); } private void addProjectDependenciesToClassRealm(ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm) throws ComponentConfigurationException { List<String> runtimeClasspathElements; try { //noinspection unchecked runtimeClasspathElements = (List<String>) expressionEvaluator.evaluate("${project.runtimeClasspathElements}"); } catch (ExpressionEvaluationException e) { throw new ComponentConfigurationException("There was a problem evaluating: ${project.runtimeClasspathElements}", e); } // Add the project dependencies to the ClassRealm final URL[] urls = buildURLs(runtimeClasspathElements); for (URL url : urls) { containerRealm.addConstituent(url); } } private URL[] buildURLs(List<String> runtimeClasspathElements) throws ComponentConfigurationException { // Add the projects classes and dependencies List<URL> urls = new ArrayList<URL>(runtimeClasspathElements.size()); for (String element : runtimeClasspathElements) { try { final URL url = new File(element).toURI().toURL(); urls.add(url); } catch (MalformedURLException e) { throw new ComponentConfigurationException("Unable to access project dependency: " + element, e); } } // Add the plugin's dependencies (so Trove stuff works if Trove isn't on return urls.toArray(new URL[urls.size()]); } } then added @configurator include-project-dependencies To my mojo declaration and it works!
{ "pile_set_name": "StackExchange" }
Q: Is there an Infinite ammo and rapid fire command? I like to mess around in TF2 practice, is there an infinite ammo and rapid fire command in TF2? A: https://wiki.teamfortress.com/wiki/List_of_useful_console_commands addcond 74 - Makes the player 10 times bigger and 10 times the health, also player will have infinite ammo but not clip size - player's melee range will remain the same
{ "pile_set_name": "StackExchange" }
Q: React router private route with local storage? I have a private route component which I use in my app. import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import PropTypes from 'prop-types'; const PrivateRoute = ({ component: Component, ...rest }) => { const userLoggedIn = localStorage.getItem('token'); return ( <Route {...rest} render={(props) => ( userLoggedIn ? <Component {...props} /> : ( <Redirect to={{ pathname: '/login', }} /> ) )} /> ); }; PrivateRoute.propTypes = { component: PropTypes.elementType.isRequired, }; export default PrivateRoute; When logging in I'm setting token to localStorage and redirecting to PrivateRoute. The problem is that here userLoggedIn is null although if I check DevTools token is there in localStorage. I'm not sure what to do here. I'm using localStorage so that when the page is refreshed user still logged in. All the help will be appreciated. Parent of Private Route const Routes = () => ( <> <Provider store={store}> <HeaderContainer /> <Switch> <> <PrivateRoute path="/" component={HomeContainer} exact /> </> </Switch> </Provider> </> ); export default Routes; App.js const App = () => ( <div className={styles.App}> <Routes /> </div> ); A: According to their documentation: All children of a <Switch> should be <Route> or <Redirect> elements. Only the first child to match the current location will be rendered. It looks like your Private Route is wrapped in a React fragment, which could be causing the issue. Does moving the routes outside the fragment fix things? <Switch> {/* <> // remove line */} <PrivateRoute path="/" component={HomeContainer} exact /> {/* </> // remove line */} </Switch>
{ "pile_set_name": "StackExchange" }
Q: what is the difference between ndk-build and make APP for android? I am having too many confusions in native coding for android. My application wants to play mms:// stream and I'm facing some serious problems in that. But the basic question is What is the difference between ndk-build (that i usually use) and make APP (i have seen many blogs on them one of them is this) Another related question Suppose my project is in E:\WorkSpace\mmsTests\AnotherMMS (path edited if you want to test : it contained whitespace) And my ndk path is D:\android-ndk-r4b-windows\android-ndk-r4b How can i use make APP with cygwin? My os is windows xp sp2. EDIT : I have added ndk location in my PATH variable Thanks in advance A: The 'make APP=...' method was the original NDK build system but is now deprecated in favor of the ndk-build method. Anything that can be built with make APP=xxx can be built with ndk-build. ndk-build requires less manual setup and hard coded paths.
{ "pile_set_name": "StackExchange" }
Q: With py.test, database is not reset after LiveServerTestCase I have a number of Django tests and typically run them using py.test. I recently added a new test case in a new file test_selenium.py. This Test Case has uses the LiveServerTestCase and StaticLiveServerTestCase classes (which is a first for me, usually I am using just TestCase). Adding this new batch of tests in this new file has caused subsequent tests to start failing in py.test (when before they all passed). It appears that the database is not being "reset" after the LiveServerTestCase in py.test. I can tell because of the incrementation of my model's pk values. When I run these tests using the Django test runner, they all pass and the pk's are reset in subsequent tests; in the py.test test runner the pk's are being incremented in subsequent tests after the LiveServerTestCase is run. So if I have hardcoded in my test to create an object and retrieve it based on the pk I am expecting it fails because the databases are different between Django and py.test. Any ideas why this might be and how to fix it? New test test causing the DB behavior: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By class UpdateCountSelenium(StaticLiveServerTestCase): def setUp(self): self.selenium = webdriver.Firefox() self.delay = 3 def tearDown(self): self.selenium.quit() def test_ajax_hit(self): self.selenium.get("%s%s" % (self.live_server_url, '/1/')) # waits for javascript to load and tests the ajax view wait = WebDriverWait(self.selenium, 3) response = wait.until(EC.text_to_be_present_in_element((By.ID, 'counted-value'), 'true')) self.assertTrue(response) A: A LiveServerTestCase and it's subclass StaticLiveServerTestCase both inherit from TransactionTestCase which differs from TestCase in the manner it resets the DB on test case tearDown. Here is the quote from the aforementioned documentation: Django’s TestCase class (described below) makes use of database transaction facilities to speed up the process of resetting the database to a known state at the beginning of each test. A consequence of this, however, is that some database behaviors cannot be tested within a Django TestCase class. For instance, you cannot test that a block of code is executing within a transaction, as is required when using select_for_update(). In those cases, you should use TransactionTestCase. TransactionTestCase and TestCase are identical except for the manner in which the database is reset to a known state and the ability for test code to test the effects of commit and rollback: A TransactionTestCase resets the database after the test runs by truncating all tables. A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database. A TestCase, on the other hand, does not truncate tables after a test. Instead, it encloses the test code in a database transaction that is rolled back at the end of the test. This guarantees that the rollback at the end of the test restores the database to its initial state. As you mentioned, you see the PK counter retained. This is because truncating tables, means dropping all rows, but this generally does not mean the PK counter is reset. I assume you care about this because you are using asserting objects by specifying a PK (e.g assert YourModel.objects.filter(pk=1).exists(). Instead, I suggest that in your tests, you assert the existence of X objects (e.g assert YourModel.objects.count() == 1, or even assert the specific objects you expect to exist) and then use these objects in your test as you would usually.
{ "pile_set_name": "StackExchange" }
Q: Buying bunnies, eggs and elections with tax and a discount I have a small problem with the code below. Although it executes the task perfectly, It's supposed to be more "short" and compact according to the assignment feedback. I was wondering if someone can please help me change my code from its longer version to a more short version that completes the same task... from math import * ask = input("Would you like to buy bunnies, eggs, or elections?: ") if ask == 'bunnies': bunnies = 30 print("Bunnies will cost " + str(bunnies) + " dollars each.") quantity = int(input("How many would you like to buy?: ")) cost1 = bunnies * quantity tax = (0.089 * cost1) final_cost = (cost1 + tax) if final_cost == final_cost > 57.89: discount1 = (0.13 * final_cost) with_discount1 = (final_cost - discount1) print("Your total will be " + str(with_discount1) + " with a discount.") if final_cost == final_cost < 57.89: print("Your total will be " + str(final_cost) + " without a discount") if ask == 'eggs': eggs = 10 print("Eggs will cost " + str(eggs) + " dollars each.") quantity = int(input("How many would you like to buy?: ")) cost2 = eggs * quantity tax = (0.089 * cost2) final_cost2 = (cost2 + tax) if final_cost2 == final_cost2 > 57.89: discount = (0.13 * final_cost2) with_discount = (final_cost2 - discount) print("Your total will be " + str(with_discount) + " with a discount for eggs.") if final_cost2 == final_cost2 < 57.89: print("Your total will be " + str(final_cost2) + " without a discount for eggs") if ask == 'elections': elections = 20 print("Elections will cost " + str(elections) + " dollars.") quantity = int(input("How many are you looking to purchase?: ")) cost3 = quantity * elections tax = (0.089 * cost3) final_cost3 = (cost3 + tax) if final_cost3 == final_cost3 > 57.89: discount2 = (0.13 * final_cost3) withdiscount = (final_cost3 - discounts) print("Your total will be " + str(withdiscount) + " dollars with a discount for elections.") if final_cost3 == final_cost3 < 57.89: print("Your total will be " + str(final_cost3) + " dollars without a discount for elections.") A: Using from math import * is highly discouraged. Please always use either: from math import sqrt, or import math and use math.sqrt instead of sqrt. You are not using math and so the import is not needed. It is commonly recommended to use either f-strings or str.format to format your strings. This is as they make reading the format easier on more complex formats. In your case you won't see this benefit too much but it would be a good habit to get now, rather than later. print("Bunnies will cost {} dollars each.".format(bunnies)) print(f"Bunnies will cost {bunnies} dollars each.") Please don't use unnecessary parentheses. This is as they add unneeded clutter to your code. You can simplify the calculation for final_cost $$ \begin{array}{r l} c &= bq\\ t &= 0.089c\\ f &= c + t\\ f &= 0.089c + c\\ f &= (0.089 + 1)c\\ f &= 1.089bq \end{array} $$ The statement final_cost == final_cost > 57.89 is confusing and only works due to Python splitting the code into two different conditionals connected with an and. The statement final_cost == final_cost will always be true, and so by all metrics is just bad. Your ifs are missing if the final cost is 57.89 exactly. I assume this is a mistake. When you have two ifs like this when one is getting half the options and the other is getting the other half it is better to use an if and an else rather than two ifs. You don't need to store discount1 in a variable, it's just adding lines with no visible benefit. Whilst there's nothing inherently wrong with printing the same string with a slight modification twice, you may be inclined to change it so you only define the structure of the print once. Overall this would get: bunnies = 30 print(f"Bunnies will cost {bunnies} dollars each.") quantity = int(input("How many would you like to buy?: ")) final_cost = 1.089 * bunnies * quantity if final_cost >= 57.89: with_discount = final_cost - 0.13 * final_cost print(f"Your total will be {with_discount} with a discount") else: print(f"Your total will be {final_cost} without a discount") From here we can see all the other options have almost exactly the same code. There are only three things that change: The variable name bunnies. The value of the variable bunnies The name of the item you're buying. From this we can see that a function would be good. def price_to_buy(item, price): print(f"{item} will cost {price} dollars each.") quantity = int(input("How many would you like to buy?: ")) final_cost = 1.089 * price * quantity if final_cost >= 57.89: with_discount = final_cost - 0.13 * final_cost print(f"Your total will be {with_discount} with a discount") else: print(f"Your total will be {final_cost} without a discount") ask = input("Would you like to buy bunnies, eggs, or elections?: ") if ask == "bunnies": price_to_buy("Bunnies", 30) if ask == "eggs": price_to_buy("Eggs", 10) if ask == "elections": price_to_buy("Elections", 20) Advanced changes Whilst the above is probably what your instructor expects from you, there are more ways to improve the code and make it shorter. You can store the name and value in a dictionary, allowing you to condense those ifs into two lines of code. You may want to use a try and except here to get the code to function the same if you don't enter valid input. You can use str.title() to make the inputted item's name display in title case. You can use an if __name__ == "__main__": guard to prevent the code from running when imported, normally by accident. You can use a turnery to apply the discount, this is basically just an if and else but on one line! By also using tuple unpacking we can get the preposition (with/without) and the discount percentage in one line. You can use a try and except to display a nice error message. You can use foo -= ... rather than foo = foo - .... def price_to_buy(item, price): print(f"{item} will cost {price} dollars each.") value = input("How many would you like to buy?: ") try: quantity = int(value) except ValueError: print(f"{value} is not an integer.") return cost = 1.089 * price * quantity discount, prep = (0.13, "with") if cost >= 57.89 else (0, "without") cost -= discount * cost print(f"Your total will be {cost} {prep} a discount") PRICES = {"bunnies": 30, "eggs": 10, "elections": 20} if __name__ == "__main__": item = input("Would you like to buy bunnies, eggs, or elections?: ") price_to_buy(item.title(), PRICES[item])
{ "pile_set_name": "StackExchange" }
Q: Use Jenkins API to find information about the current user I'm building a client-side dashboard that makes use of the Jenkins REST API to fetch data about jobs. That's the easy part. I haven't yet figured out how to display, for example, the current user's name (though I did find the path to any particular user, but that's not dynamic: [jenkinsRoot]/users/[name]/api ). Is there a hidden REST path that contains any information about the current user? If not, is there an alternative? I've already checked the cookie, and it doesn't have the username. A: The only place I can find to hit data about a user in Jenkins 1.5 is: /user/[user_name]/api/[json|xml] Currently, there doesn't seem to be a REST endpoint for 'who am i'. Also, none of the other resources look as if they expose the current user. I guessing it's assumed if you're using the credentials with the [user_name] to authenticate you should just enter it in the request ULR for the user resource endpoint to get the user resource. You could probably make a simple plugin to expose the currently authenticated user: https://wiki.jenkins-ci.org/display/JENKINS/Exposing+data+to+the+remote+API
{ "pile_set_name": "StackExchange" }
Q: Search for the word (BRL) in tag and output the entire contents of this tag There are several tags in the xml file. How can I find an tag with the content in "BRL"? i have tried $usd_brazilRate = $usdXML->item[89]->title;<br> $usd_brazilDate = $usdXML->item[89]->pubDate;<br> but the item number (position) always changes example cropped xml content: <channel> <item> <title>1 USD = 64.78833120 RUB</title> <link>http://www.floatrates.com/usd/rub/</link> <description>1 U.S. Dollar = 64.78833120 Russian Rouble</description> <pubDate>Thu, 2 May 2019 12:00:02 GMT</pubDate> <baseCurrency>USD</baseCurrency> <baseName>U.S. Dollar</baseName> <targetCurrency>RUB</targetCurrency> <targetName>Russian Rouble</targetName> <exchangeRate>64.78833120</exchangeRate> <inverseRate>0.01543488</inverseRate> <inverseDescription>1 Russian Rouble = 0.01543488 U.S. Dollar</inverseDescription> </item> <item> <title>1 USD = 3.92245587 BRL</title> <link>http://www.floatrates.com/usd/brl/</link> <description>1 U.S. Dollar = 3.92245587 Brazilian Real</description> <pubDate>Thu, 2 May 2019 12:00:02 GMT</pubDate> <baseCurrency>USD</baseCurrency> <baseName>U.S. Dollar</baseName> <targetCurrency>BRL</targetCurrency> <targetName>Brazilian Real</targetName> <exchangeRate>3.92245587</exchangeRate> <inverseRate>0.25494232</inverseRate> <inverseDescription>1 Brazilian Real = 0.25494232 U.S. Dollar</inverseDescription> </item> <item> <title>1 USD = 0.76733706 GIP</title> <link>http://www.floatrates.com/usd/gip/</link> <description>1 U.S. Dollar = 0.76733706 Gibraltar pound</description> <pubDate>Thu, 2 May 2019 12:00:02 GMT</pubDate> <baseCurrency>USD</baseCurrency> <baseName>U.S. Dollar</baseName> <targetCurrency>GIP</targetCurrency> <targetName>Gibraltar pound</targetName> <exchangeRate>0.76733706</exchangeRate> <inverseRate>1.30320826</inverseRate> <inverseDescription>1 Gibraltar pound = 1.30320826 U.S. Dollar</inverseDescription> </item> </channel> $usdXML = simplexml_load_file("http://www.floatrates.com/daily/usd.xml") or die("Failed to load"); $usd_brazilRate = $usdXML->item->title; $usd_brazilDate = $usdXML->item->pubDate; output 1 USD = 3.92245587 BRL Thu, 2 May 2019 12:00:02 GMT A: You can use XPath: $brazil = $usdXML->xpath('/channel/item[targetCurrency="BRL"]'); print($brazil[0]->description . "\n"); print($brazil[0]->pubDate . "\n");
{ "pile_set_name": "StackExchange" }
Q: Pythonic way to get the greatest value with the same index from different lists I have a dict of lists like the following: { 'FR-8_20190502_MD_Case1': [11595, 8250, 13023, 7223], 'FR-8_20190505_MD_Case1': [11595, 8250, 13023, 7418], 'FR-8_20190507_MD_Case1': [11595, 8250, 13023, 7223], 'FR-8_20190509_MD_Case1': [11595, 8250, 13023, 7384], 'FR-8_20190508_MD_Case1': [12948, 8250, 13023, 7223], 'FR-8_20190506_MD_Case1': [12056, 8250, 13023, 7223] } And I would like to have a list of the greatest values of each index of these lists, for example: [12948, 8250, 13023, 7418] Here is what I have so far, it works but I am pretty sure it can be improved: (ima_sizes is my dict of lists) max_sizes = [0, 0, 0, 0] for k, v in ima_sizes.items(): for i in range(4): if v[i] > max_sizes[i]: max_sizes[i] = v[i] Is there a more pythonic way to achieve that? A: Using zip() to transpose the values and max() to find maximum value: d = { 'FR-8_20190502_MD_Case1': [11595, 8250, 13023, 7223], 'FR-8_20190505_MD_Case1': [11595, 8250, 13023, 7418], 'FR-8_20190507_MD_Case1': [11595, 8250, 13023, 7223], 'FR-8_20190509_MD_Case1': [11595, 8250, 13023, 7384], 'FR-8_20190508_MD_Case1': [12948, 8250, 13023, 7223], 'FR-8_20190506_MD_Case1': [12056, 8250, 13023, 7223] } print([max(v) for v in zip(*d.values())]) Prints: [12948, 8250, 13023, 7418]
{ "pile_set_name": "StackExchange" }
Q: Call viewmodel method after control id is generated using attr binding I have to call a viewmodel method after controls id are generated dynamically attr binding. Below is my html code <div data-bind="attr: {id: 'bookScreen_' + bookId }"> </div> Once control id is generated i want to call a method to where i am doing some work using $(id) selector. How do i call a viewmodel method once id gets generated for div? A: The general rule is: Whenever you want to touch the DOM, Try to do as much as possible via knockout's default bindings. Most event handling can be done by using the event or click binding. Values can be linked to your viewmodel with the value or textInput bindings. Styles can be applied with css. If there's no default binding, create a custom binding. Some default bindings have an afterRender option in which you can specify a callback method that will be passed the element to which bindings have been applied (for example, the foreach binding). However, these methods are meant to be used for animations/transitions; changing the DOM isn't recommended. An example of a custom binding with an init method: ko.bindingHandlers.logIDAfterBind = { init: function(element) { console.log(element.id); } }; With the HTML: <div data-bind="attr: {id: 'bookScreen_' + bookId }, logIDAfterBind"></div> Edit after question in the comments: How do I pass a constant to my custom binding handler? The init method's signature is actually a lot more versatile than I showed in my simplified example. You can pass a value (any valid javascript actually) to a binding using bindingKey: bindingValue. For example: <div data-bind="attr: {id: 'bookScreen_' + bookId }, logIDAfterBind: 'a_constant_string'"></div> This value is wrapped in a function and accessible via the second parameter of init: init: function(element, valueAccessor) { var myConstant = valueAccessor(); // Will be "a_constant_string" } In bindings that support both observable and other values, you'll often see ko.unwrap being used. // Gets the value from the binding; if it's an observable, // it "gets" the inner value var bindingValue = ko.unwrap(valueAccessor());
{ "pile_set_name": "StackExchange" }
Q: how to make radio buttons selected in angularjs i am new to angularjs and javascript,I am having a list of radio buttons and have to make some of them selected,so can anybuddy please tell me how to achieve this?I tried ng-value=true with no luck,my code is as below: <ons-list-item modifier="tappable" ng-repeat="area in vm.AreaList" > <label class="radio-button radio-button--list-item line-h45"> <input type="radio" ng-bind="area.name" ng-model="vm.selectedArea" name="area" ng-value="area.code" > <div class="radio-button__checkmark radio-button--list-item__checkmark"> </div> {{area.name}} </label> </ons-list-item> A: you can do something like this in your controller: $scope.results = { favorites: [{ id: "WatchList1", title: "WatchList1" }, { id: "WatchList2", title: "WatchList2" }, { id: "WatchList3", title: "WatchList3" }] }; $scope.selectedRow = { id: 'WatchList2' }; $scope.event = { type: { checked: true } } and your html: <div> <div ng-repeat="row in results.favorites"> <input type="radio" ng-model="selectedRow.id" value="{{ row.id }}" style="opacity: 1;" class="pointer" /> <span>{{ row.title }}</span> </div> </div> Single box
{ "pile_set_name": "StackExchange" }
Q: Wireing Breeze (with Angular) to an existing WCF Data Service The Short I have an existing WCF Data Service that I would like to wire up to use in an AngularJS SPA using Breeze. Can anyone show a noobie level example of how to do that with out access to the actual database (just the OData Service)? The Long I have an existing WCF Data Service that is already in use by a WPF app. I experimenting with web development and would like to wire up to that service using Breeze. In case it matters, I am using Angular (and am setting up via the HotTowel.Angular nuget package). I have done a fair amount of Googling and I am stuck. I can see two ways outlined from my searching: The First Make is to make a Breeze controller on the server side of my web app. The problem I see with that is the metadata. From my limited understanding I need to tell breeze all the meta data of my WCF Data Service. I know how to get the meta from my WCF Data Service (the url + $Metadata), but I don't know how to tell this to Breeze. The Second This way is more vague in implementation. I got it from the accepted answer on this question: Breeze.js with WCF Data Service. Basically the answer here does not seem to work. It relies on something called the entityModel that I cannot seem to find (I have an entityManager, but not an entityModel. And the entityManager does not have the properties that the entityModel is shown to have. In the end I like the idea of the second method best. That way I can directly connect to my odata service with out needed my web app to have a "in-between" server component. But I would happily take anything that does not need entity framework to connect to my database. I tried several variations of the second option, but I just can't seem to get it to work. I also tried the Breeze samples. It has one for OData, but it still relies on having Entity Framework hook up to the source database. To to clearly summarize what I am asking: I am looking for a Breeze example that connects to an existing WCF Data Service. A: We regret that you were mislead by that old StackOverflow answer which was way out of date and (therefore) incorrect. There is no longer a type called entityModel. I updated the answer there and repeat here the same advice. The recommended way to configure Breeze so that it talks to a standard OData source (such as a WCF OData service) is breeze.config.initializeAdapterInstance('dataService', 'OData', true); Here's how you might proceed with defining an EntityManager and querying the service: // specify the absolute URL to the WCF service address var serviceName = "http://localhost:9009/ODataService.svc"; var em = new breeze.EntityManager(serviceName); var query = breeze.EntityQuery.from("Customers") .where("CompanyName", "startsWith", "B") .orderBy("City"); em.executeQuery(query).then(function(data) { // process the data.results here. }); There is some documentation on this subject here. A Web API OData service differs from a WCF OData service in several respects. But you may still find value in the Angular Web API OData sample.
{ "pile_set_name": "StackExchange" }
Q: Retrieve an aggregated SQL value from a ResultSet in Java I've been stuck with this problem for several hours: there are 3 tables, one of them connects the others through a place number and the tray ID. To find out how many samples are on a specific tray I aggregated the places by the tray ID, which works perfectly in pure SQL Code. My Java code: ps = connection.prepareStatement("SELECT TRAYID, COUNT(PlaceNo) AS OCCUPIED " + "FROM PLACE " + "GROUP BY TRAYID " + "HAVING TRAYID = ?"); ps.setInt(1, trayId); rs = ps.executeQuery(); if (!rs.isBeforeFirst()) { throw new CoolingSystemException(); } else { spaceOccupied = rs.getInt("OCCUPIED"); And with the last line the program crashes. I have also tried getInt(1) instead of the name but nothing works. And if the result set would be empty it would crash at if (!rs.isBeforeFirst()) { throw new CoolingSystemException(); } What I know for sure is that there is a value Image: DBeaver using the same TrayID I am sure that it is this spot because I logged it at each imaginable point before and after each line. Does anyone has an idea how to solve it? I also tried every datatype in the get...() function :( A: Your problem is that after you check whether there is any data in the result set, you're not moving the cursor forward with rs.next() before calling rs.getInt(). Now as it seems that you're only ever expecting the result set to contain up to one row, you can do the following instead: ps = connection.prepareStatement("SELECT TRAYID, COUNT(PlaceNo) AS OCCUPIED " + "FROM PLACE " + "GROUP BY TRAYID " + "HAVING TRAYID = ?"); ps.setInt(1, trayId); rs = ps.executeQuery(); if (rs.next()) { spaceOccupied = rs.getInt("OCCUPIED"); } else { throw new CoolingSystemException(); } The first invocation of rs.next() will return a falsey if the query didn't return any data.
{ "pile_set_name": "StackExchange" }
Q: C++ template gotchas just now I had to dig through the website to find out why template class template member function was giving syntax errors: template<class C> class F00 { template<typename T> bar(); }; ... Foo<C> f; f.bar<T>(); // syntax error here I now realize that template brackets are treated as relational operators. To do what was intended the following bizarre syntax is needed, cf Templates: template function not playing well with class's template member function: f.template bar<T>(); what other bizarre aspects and gotcha of C++/C++ templates you have encountered that were not something that you would consider to be common knowledge? A: I got tripped up the first time I inherited a templated class from another templated class: template<typename T> class Base { int a; }; template<typename T> class Derived : public Base<T> { void func() { a++; // error! 'a' has not been declared } }; The problem is that the compiler doesn't know if Base<T> is going to be the default template or a specialized one. A specialized version may not have int a as a member, so the compiler doesn't assume that it's available. But you can tell the compiler that it's going to be there with the using directive: template<typename T> class Derived : public Base<T> { using Base<T>::a; void func() { a++; // OK! } }; Alternatively, you can make it explicit that you are using a member of T: void func { T::a++; // OK! } A: This one got me upset back then: #include <vector> using std::vector; struct foo { template<typename U> void vector(); }; int main() { foo f; f.vector<int>(); // ambiguous! } The last line in main is ambiguous, because the compiler not only looks up vector within foo, but also as an unqualified name starting from within main. So it finds both std::vector and foo::vector. To fix this, you have to write f.foo::vector<int>(); GCC does not care about that, and accepts the above code by doing the intuitive thing (calling the member), other compilers do better and warn like comeau: "ComeauTest.c", line 13: warning: ambiguous class member reference -- function template "foo::vector" (declared at line 8) used in preference to class template "std::vector" (declared at line 163 of "stl_vector.h") f.vector<int>(); // ambiguous! A: The star of questions about templates here on SO: the missing typename! template <typename T> class vector { public: typedef T * iterator; ... }; template <typename T> void func() { vector<T>::iterator it; // this is not correct! typename vector<T>::iterator it2; // this is correct. } The problem here is that vector<T>::iterator is a dependent name: it depends on a template parameter. As a consequence, the compiler does not know that iterator designates a type; we need to tell him with the typename keyword. The same goes for template inner classes or template member/static functions: they must be disambiguated using the template keyword, as noted in the OP. template <typename T> void func() { T::staticTemplateFunc<int>(); // ambiguous T::template staticTemplateFunc<int>(); // ok T t; t.memberTemplateFunc<int>(); // ambiguous t.template memberTemplateFunc<int>(); // ok }
{ "pile_set_name": "StackExchange" }
Q: Prove that $T_n(x)={}_2F_1\left(-n,n;\tfrac 1 2; \tfrac{1}{2}(1-x)\right) $ Prove that, for Chebyshev polynomials of the first kind, \begin{align} T_n(x) & = \tfrac{n}{2} \sum_{k=0}^{\left \lfloor \frac{n}{2} \right \rfloor}(-1)^k \frac{(n-k-1)!}{k!(n-2k)!}~(2x)^{n-2k} && n>0 \\ & = {}_2F_1\left(-n,n;\tfrac 1 2; \tfrac{1}{2}(1-x)\right) \\ \end{align} where $${}_2F_1(a,b;c;z) = \sum_{k=0}^\infty \frac{(a)_k (b)_k}{(c)_k} \frac{z^k}{k!}$$ is the hypergeometric function, and $$(x)_{n}=x(x-1)(x-2)\cdots(x-n+1).$$ The main difficulty is to understand why $z=\tfrac{1}{2}(1-x)$. In this way, I have $$\sum_{k=0}^\infty \ldots (1-x)^k$$ and not $$\sum_{k=0}^\infty \ldots (2x)^k$$ Any suggestions please? A: $y=\phantom{}_2 F_1(a,b;c;z)$ is the regular solution of the ODE: $$z(1-z)y''+\left[c-(a+b+1)z\right]y'-ab y=0 $$ hence $y=\phantom{}_2 F_1(-n,n;1/2;z)$ is the regular solution of the ODE: $$z(1-z)y''+\left(\frac{1}{2}-z\right)y'+ n^2 y=0 $$ and $y=\phantom{}_2 F_1\left(-n,n;\frac{1}{2};\frac{1-z}{2}\right)$ is the regular solution of the ODE: $$(1-z^2)\,y'' - z y'+ n^2\,y=0 \tag{1}$$ so to prove our claim we just need to prove that $T_n(z)$ fulfills the same ODE. Since: $$ T_n(\cos\theta) = \cos(n\theta) $$ by differentiating twice that identity we have: $$ -\sin(\theta)\, T_n'(\cos\theta) = -n\sin(n\theta),$$ $$ \sin^2(\theta)\, T_n''(\cos\theta) -\cos(\theta)\, T_n'(\cos\theta) = -n^2\cos(n\theta) $$ and $(1)$ just follows from replacing $\cos(\theta)$ with $z$.
{ "pile_set_name": "StackExchange" }
Q: Proving equality of two functions Lef $f, g$ be two $\mathbb{N}\rightarrow \mathbb{N}$ functions satisfying the following conditions. $f(g(n))=g(n)+1$ $g(f(n))=f(n)+1$ Show that $f = g$. I have tried a lot of things and got lots of results, none of which look promising. A: Let $f(2n) = 2n; f(2n+1) = f(2n+2); g(2n) = 2n+1; g(2n+1)= 2n+1$. (i.e. $f$ takes $n$ to the first even number equal or larger than $n$. $g$ takes $n$ to the first odd number equal or larger than $n$. Then $f(g(2n)) = f(2n+1) = 2n+2 = 2n + 1 + 1 = g(2n) + 1$ $f(g(2n+1)) = f(2n+1) = 2n+2 = 2n+1 + 1 = g(2n+1) + 1$ $g(f(2n)) = g(2n)=2n+1 = f(2n) + 1$ $g(f(2n+1)) = g(2n+2) = 2n + 3 = 2n+2 + 1 = f(2n+1) + 1$. So the statement isn't true. But is true for all $n \in Im(f) \cap Im(g)$
{ "pile_set_name": "StackExchange" }