date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/18
896
2,324
<issue_start>username_0: So I'm trying to Install Rails with this guide: <http://guides.rubyonrails.org/getting_started.html> And I keep getting this error (below). Any suggestion? I'm working on the cmd (windows 8). (c) 2013 Microsoft Corporation. All rights reserved. I'm typing: `ruby -v` And then I get: `ruby 2.4.3p205 (2017-12-14 revision 61247) [x64-mingw32]` I'm typing: `sqlite3 --version` And then I get: `3.22.0 2018-01-22 18:45:57 0c55d179733b46d8d0ba4d88e01a25e10677046ee3da1d5b1581e 86726f2171d` I'm typing: `gem install rails` And then I get: ``` Temporarily enhancing PATH for MSYS/MINGW... Building native extensions. This could take a while... ERROR: Error installing rails: ERROR: Failed to build gem native extension. current directory: C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/websocket-driver-0 .6.5/ext/websocket-driver C:/Ruby24-x64/bin/ruby.exe -r ./siteconf20180318-5748-xd7wo5.rb extconf.rb creating Makefile current directory: C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/websocket-driver-0.6.5 /ext/websocket-driver make "DESTDIR=" clean current directory: C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/websocket-driver-0.6.5 /ext/websocket-driver make "DESTDIR=" generating websocket_mask-x64-mingw32.def make: *** No rule to make target `/C/Ruby24-x64/include/ruby-2.4.0/ruby.h', need ed by `websocket_mask.o'. Stop. make failed, exit code 2 Gem files will remain installed in C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/websoc ket-driver-0.6.5 for inspection. Results logged to C:/Ruby24-x64/lib/ruby/gems/2.4.0/extensions/x64-mingw32/2.4.0 /websocket-driver-0.6.5/gem_make.out ```<issue_comment>username_1: Try using rvm using Cygwin. It should help solve ruby version issues. see <https://rvm.io/rvm/install> Upvotes: 0 <issue_comment>username_2: I just had exactly the same problem with websocket-driver native extension (Windows 10) with exact the same error message: ``` make: *** No rule to make target `/C/Ruby24-x64/include/ruby-2.4.0/ruby.h', need ed by `websocket_mask.o'. Stop. make failed, exit code 2 ``` The solution in my case was to pay attention during "MSYS2-Devkit" installation to chose the option **"3"** (MSYS2 and MINGW development toolchain) After that "bundle install" in my case installed and compiled all dependencies of a rails project Upvotes: 2
2018/03/18
511
1,386
<issue_start>username_0: I have a nested list that contains both None elements and integers. It looks pretty much like this: ``` aList = [[None, 8.0, 1.0], [2.0, 3.0], [9.0], [5.0, None, 4.0]] ``` None elements don't follow any particular pattern and therefore can be found at any position inside the list. I'd like to obtain two things: 1. The minimum value (*minimum*) among all integers. 2. The indexes that define completely the position of this minimum value. In other words, those two numbers ( *i, j* ) that satisfy: ``` aList[i][j] = minimum ```<issue_comment>username_1: You can use this: ``` aList = [[None, 8.0, 1.0], [2.0, 3.0], [9.0], [5.0, None, 4.0]] minimum = sys.maxsize i_min, j_min = 0, 0 for i, a in enumerate(aList): for j, b in enumerate(a): if b and b < minimum: i_min, j_min, minimum = i, j, b print(minimum, i_min, j_min) # 1.0 0 2 print(aList[i_min][j_min] == minimum) # True ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: This is a possible solution: ``` import sys aList = [[None, 8.0, 1.0], [2.0, 3.0], [9.0], [5.0, None, 4.0]] mininum = sys.maxsize for j, ele in enumerate(aList): cur_min = min(float(i) for i in ele if i is not None) if cur_min < mininum: minimum = cur_min pos_index = ele.index(minimum) list_index = j print(aList[list_index][pos_index]) ``` Upvotes: 0
2018/03/18
627
1,803
<issue_start>username_0: I was using following kind of wait/signal way to let threads inform each other. ``` std::condition_variable condBiz; std::mutex mutexBar; .. void Foo::wait() { std::unique_lock waitPoint(mutexBar); if (waitPoint.owns\_lock()) { condBiz.wait(waitPoint); } } void Foo::signal() { std::unique\_lock waitPoint(mutexBar); condBiz.notify\_all(); } void Foo::safeSection(std::function & f) { std::unique\_lock waitPoint(mutexBar); f(); } ``` Then converted lock/unlock mechanism from unique\_lock to lock\_guard because I'm not returning unique\_lock to use somewhere else(other than wait/signal) and lock\_guard is said to have less overhead: ``` void Foo::safeSection(std::function & f) { std::lock\_guard waitPoint(mutexBar); // same mutex object f(); } ``` and it works. Does this work for all platforms or just looks like working for current platform? Can unique\_lock and lock\_guard work with each other using same mutex object?<issue_comment>username_1: You can use this: ``` aList = [[None, 8.0, 1.0], [2.0, 3.0], [9.0], [5.0, None, 4.0]] minimum = sys.maxsize i_min, j_min = 0, 0 for i, a in enumerate(aList): for j, b in enumerate(a): if b and b < minimum: i_min, j_min, minimum = i, j, b print(minimum, i_min, j_min) # 1.0 0 2 print(aList[i_min][j_min] == minimum) # True ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: This is a possible solution: ``` import sys aList = [[None, 8.0, 1.0], [2.0, 3.0], [9.0], [5.0, None, 4.0]] mininum = sys.maxsize for j, ele in enumerate(aList): cur_min = min(float(i) for i in ele if i is not None) if cur_min < mininum: minimum = cur_min pos_index = ele.index(minimum) list_index = j print(aList[list_index][pos_index]) ``` Upvotes: 0
2018/03/18
463
1,331
<issue_start>username_0: I have a csv file with traffic density data per road segment of a certain high way, measured in Annual average daily traffic (AADT). Now I want to visualize this data. Since I have the locations (lat and lon) of the road segments, my idea is to create lines between these points and give it a color which relates to the AADT value. So suppose, road segments / lines with high AADT are marked red and low AADT are marked green. Which package should I use for this visualization?<issue_comment>username_1: You can use this: ``` aList = [[None, 8.0, 1.0], [2.0, 3.0], [9.0], [5.0, None, 4.0]] minimum = sys.maxsize i_min, j_min = 0, 0 for i, a in enumerate(aList): for j, b in enumerate(a): if b and b < minimum: i_min, j_min, minimum = i, j, b print(minimum, i_min, j_min) # 1.0 0 2 print(aList[i_min][j_min] == minimum) # True ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: This is a possible solution: ``` import sys aList = [[None, 8.0, 1.0], [2.0, 3.0], [9.0], [5.0, None, 4.0]] mininum = sys.maxsize for j, ele in enumerate(aList): cur_min = min(float(i) for i in ele if i is not None) if cur_min < mininum: minimum = cur_min pos_index = ele.index(minimum) list_index = j print(aList[list_index][pos_index]) ``` Upvotes: 0
2018/03/18
445
1,804
<issue_start>username_0: I was fallowing a [guide](https://cloud.google.com/tools/intellij/docs/create-flexible?hl=uk) of creating a new java project in IntellIJ IDEA and in the end I got empty folder src without any files or sub-folders in it. Does anybody know what did I do wrong? [![enter image description here](https://i.stack.imgur.com/YN3bf.png)](https://i.stack.imgur.com/YN3bf.png)<issue_comment>username_1: I work on this plugin. This is unfortunately all that is available for now using the App Engine flexible new project wizard. I would suggest instead to start from publicly available AE flex github project (such as the one referenced in [this guide](https://cloud.google.com/appengine/docs/flexible/java/quickstart)). You could also start with any Java 8 project as well since you are running on flex - you can then use the plugin to add App Engine flexible support to it: ``` Tools > Google Cloud Tools > Add App Engine support > Google App Engine Flexible ``` This will generate a template `app.yaml` for you and also expose the App Engine plugin features (like deploying to GCP). Upvotes: 1 <issue_comment>username_2: There is nothing wrong with the project that you created. Since you were creating a new project, your project has an empty `src` folder with a `.iml` file. As *username_1* commented, if you selected `Create app.yaml` box in the wizard, then the project will contain a template `app.yaml` under `src/main/appengine`. Regarding [this image](https://cloud.google.com/tools/images/intellij-vcs-checkout.png), the files in the project `helloworld` are imported from `Cloud Repositories`. The procedure to import an existing project in Cloud Source Repositories is explained in the same tutorial that you was following (Checking out an existing project). Upvotes: 0
2018/03/18
564
2,289
<issue_start>username_0: I have a wordpress website where customers make an image with text and icons, once processed thru woocommerce and payed for that image name `12345.png` is saved as Customer\_product\_image ``` function add_order_item_meta($item_id, $values) { $key = 'customer_product_image'; // Define your key here $value = $values['user_img']; // Get your value here woocommerce_add_order_item_meta($item_id, $key, $value); } ``` And i works great, but now i'm banning my head against the wall! When the purchased image is displayed on the Order admin detail page, it shows up as `CUSTOMER_PRODUCT_IMAGE: 1234.png` how on earth would i go about wrapping that within an image tag so the image is displayed there? I've searched high and low on google but haven't been able to find anything, its probably that i dont know what do actually search for....<issue_comment>username_1: I work on this plugin. This is unfortunately all that is available for now using the App Engine flexible new project wizard. I would suggest instead to start from publicly available AE flex github project (such as the one referenced in [this guide](https://cloud.google.com/appengine/docs/flexible/java/quickstart)). You could also start with any Java 8 project as well since you are running on flex - you can then use the plugin to add App Engine flexible support to it: ``` Tools > Google Cloud Tools > Add App Engine support > Google App Engine Flexible ``` This will generate a template `app.yaml` for you and also expose the App Engine plugin features (like deploying to GCP). Upvotes: 1 <issue_comment>username_2: There is nothing wrong with the project that you created. Since you were creating a new project, your project has an empty `src` folder with a `.iml` file. As *username_1* commented, if you selected `Create app.yaml` box in the wizard, then the project will contain a template `app.yaml` under `src/main/appengine`. Regarding [this image](https://cloud.google.com/tools/images/intellij-vcs-checkout.png), the files in the project `helloworld` are imported from `Cloud Repositories`. The procedure to import an existing project in Cloud Source Repositories is explained in the same tutorial that you was following (Checking out an existing project). Upvotes: 0
2018/03/18
1,211
4,650
<issue_start>username_0: I am creating a web extension and need to dynamically change inner text to a link. Since it's a web extension, I can't make too many assumptions about where this text will be located. Furthermore, the changes need to be dynamically loaded (this is the main problem I have). For example, I need to find all instances of the text "foo" on a page and replace it with `[foo](www.mylink.com)`, so that the text on the page now is displayed as a link. I have the following functions, which correctly replaces occurrences, but the tag that it inserts simply gets displayed in the browser as the raw html, instead of being displayed as a link. ```js function replace_with_link() { var link = "https://google.com"; var name = "<NAME>"; var link_wrapper = "[" + name + "](\"")"; replaceText('*', name, link_wrapper, 'g'); } function replaceText(selector, text, newText, flags) { var matcher = new RegExp(text, flags); $(selector).each(function () { var $this = $(this); var replaced_text = ""; if (!$this.children().length) { $this.text($this.text().replace(matcher, newText)); } }); } ``` ```html Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Click me ```<issue_comment>username_1: TLDR: Change [`$this.text(...)`](http://api.jquery.com/text/) to [`$this.html(...)`](http://api.jquery.com/html/). The longer answer is the main difference between the two methods: * The `html` method will "set the HTML contents of each element in the set of matched elements". * The `text` method will also set the content of the elements but "escapes the string provided as necessary so that it will render correctly in HTML." That last point is critical because "to do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML". This basically means that any HTML would be escaped so as to be a able to be displayed as text. ``` function replace_with_link() { var link = "https://google.com"; var name = "<NAME>"; var link_wrapper = "[" + name + "](\"")"; replaceText('*', name, link_wrapper, 'g'); } function replaceText(selector, text, newText, flags) { var matcher = new RegExp(text, flags); $(selector).each(function() { var $this = $(this); var replaced_text = ""; if (!$this.children().length) { $this.html($this.text().replace(matcher, newText)); } }); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: The function **[`$.text()`](http://api.jquery.com/text/)** returns as text the already rendered/processed HTML by the engine and receives the text to be shown. In your approach, you're passing as text the new generated HTML, so the engine will handle it as text and none rendering process will be executed. To render that new generated HTML use the function **[`$.html()`](http://api.jquery.com/html/)** instead. ```js function replace_with_link() { var link = "https://google.com"; var name = "<NAME>"; var link_wrapper = "[" + name + "](\"")"; replaceText('*', name, link_wrapper, 'g'); } function replaceText(selector, text, newText, flags) { var matcher = new RegExp(text, flags); $(selector).each(function() { var $this = $(this); var replaced_text = ""; if (!$this.children().length) { $this.html($this.text().replace(matcher, newText)); } }); } ``` ```html Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Click me ``` **Aside note**, for future approaches use the function **[`$.on`](http://api.jquery.com/on/)** to bind events to the elements. Upvotes: 1
2018/03/18
498
2,080
<issue_start>username_0: Is there a way I can define a method, that is called in every case, when a getter for any property in a class is called? The class is a base class, and I want to implement various SubClasses of it, but each one should have in common that regardless of the property that should be accessed by its getter function, an action should be performed before the attribute is returned.<issue_comment>username_1: No, not unless you code it into every Getter, or you abandon "Plain Old C# Classes" altogether and construct a data model paradigm based around a read-audited set of data. If you go down that route that you simply have each "data class" being an Dictionary of Get/Set delegates and access its data values through those delegates. Its not an uncommon design, but it no longer follows the OO paradigms. Example (psuedo code) ``` public class MonitoredCustomerObject { // Assumption that the Get/Set delegates are stored in a simple Tuple. private Dictionary> getterSetterDict = new ... public GetValue(string key) { executeMyOnReadCode(); return getterSetterDict[key].Item1(); } public SetValue(string key) { executeMyOnWriteCode(); getterSetterDict[key].Item2(); } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can kind of fake this, or you can write a Fody extension that does it. For example, you can have your base class defined as: ``` public abstract class MyBaseClass { public object MyProperty { get { RunSomeMethod(); return MyPropertyValue; } } protected abstract object MyPropertyValue { get; } } ``` Which "kind of" forces the implementer to write it like: ``` public class MyDerivedClass : MyBaseClass { protected override object MyPropertyValue { get { return SomeObjectValue(); } } } ``` The derived class can still hide the base class properties with `new`, but at least that causes the developer to explicitly realize that they are doing something unintended. Upvotes: 0
2018/03/18
697
2,225
<issue_start>username_0: I am creating a program for hypothetical venture capitalists in Tkinter to input their last year and second last year revenue amount their businesses earned. The program will sum up the amount, analyse it and assign points (ranging from 0 to 18). 18 is a full score, which means revenue is high. 0 is the lowest score, which means revenue is too low. To be specific in the program, I set increments of $50,000 (for example, earning any total value between $100,000 and $150,000 in revenue would add 1 point, earning any total value between $150,000 and $200,000 in revenue would add 2 points, etc. all the way to 18). Because that would occupy many lines of code and would not be efficient, is there a better way to abstract all this? I still want to preserve specificity. Here is the code: ``` TotalPoints = 0 def SumOfTwoYearRevenue(): global TotalPoints LastYearRevenue = (float(Revenue_LastYear.get())) SecondLastYearRevenue = (float(Revenue_SecondLastYear.get())) Sum = LastYearRevenue + SecondLastYearRevenue if Sum < 100000: pass elif Sum >= 100000 and Sum < 150000: TotalPoints = TotalPoints + 1 elif Sum >= 150000 and Sum < 200000: TotalPoints = TotalPoints + 2 elif Sum >= 200000 and Sum < 250000: TotalPoints = TotalPoints + 3 elif Sum >= 250000 and Sum < 300000: TotalPoints = TotalPoints + 4 elif Sum >= 300000 and Sum < 350000: TotalPoints = TotalPoints + 5 elif Sum >= 350000 and Sum < 400000: TotalPoints = TotalPoints + 6 #etc... all the way until "TotalPoints = TotalPoints + 18" ```<issue_comment>username_1: At first glance your code would be more nicely represented by a `switch` statement available in languages such as C but not in python. However, if you look at it more closely, then you will realize that you probably do not need a bunch of conditional statements anyways and would be better suited by using something like the following: ``` if Sum < 100000: pass TotalPoints = TotalPoints + (Sum // 50000) - 1 ``` Hope this helps! Upvotes: 1 <issue_comment>username_2: I guess this should work: ``` TotalPoints += max(0, Sum//50000 - 1) ``` Upvotes: 0
2018/03/18
739
2,449
<issue_start>username_0: I am new to Jenkins, and stuck at replacing branch name in Jenkinsfile from Jenkins. I want to write a common Jenkinsfile, and in that I want to pick branch name from Jenkins. Below is the snippet from my Jenkinsfile > > checkout([$class: 'GitSCM', branches: [[name: '\*/master']], > > > Whatever the branch name I select from Jenkins, it should replace the same in Jenkinsfile and do the build. I have gone through the answers [parametrized build](https://stackoverflow.com/questions/32108380/jenkins-how-to-build-a-specific-branch) Somewhat not able to do the same. Can anyone refer me to the doc/link which I can go through and implement the same? My Changes: ``` checkout([$class: 'GitSCM', branches: [[name: 'params.Branch_Select']], ``` enter image description here [![GIT PARAMETER](https://i.stack.imgur.com/DDmhT.png)](https://i.stack.imgur.com/DDmhT.png) [![BRANCH SPECIFIER](https://i.stack.imgur.com/jThYC.png)](https://i.stack.imgur.com/jThYC.png) [![Jenkinsfile](https://i.stack.imgur.com/d8YJ6.png)](https://i.stack.imgur.com/d8YJ6.png) [![Error](https://i.stack.imgur.com/oafAW.png)](https://i.stack.imgur.com/oafAW.png)<issue_comment>username_1: In your Jenkinsfile, add a parameters section which will accept BRANCH\_NAME as parameter ``` parameters { string(defaultValue: "master", description: 'enter the branch name to use', name: 'BRANCH_NAME') } ``` and use that variable in your checkout step as follows: ``` checkout([$class: 'GitSCM', branches: [[name: "*/${BRANCH_NAME}"]]]) ``` Note: You have to run the build once to see the 'Build with parameters' option. Sample pipeline with just a checkout stage: ``` pipeline{ agent any parameters { string(defaultValue: "develop", description: 'enter the branch name to use', name: 'BRANCH_NAME') } stages{ stage('Checkout'){ steps{ checkout([$class: 'GitSCM', branches: [[name: "*/${BRANCH_NAME}"]], gitTool: 'jgit', userRemoteConfigs: [[url: "https://github.com/githubtraining/hellogitworld.git"]]]) //checkout([$class: 'GitSCM', branches: [[name: "*/${BRANCH_NAME}"]],url:'https://github.com/brianmyers/hello']) } } } } ``` Upvotes: 0 <issue_comment>username_2: I have fixed the above question. UNCHECK the box. [![Lightbox](https://i.stack.imgur.com/3unWi.png)](https://i.stack.imgur.com/3unWi.png) Upvotes: 2
2018/03/18
1,548
5,343
<issue_start>username_0: **Updated**: Attached `pom.xml` and `application.property` and some more error / warning msgs. Hi I am very new to Spring Boot and just taking some classes on Udemy for it. While following through a class, I create a starter project via spring.io and added actuator and Hal browser dependencies including Dev tools. Just ran my app and tried to go to `localhost:8080/application` & `/browser` as well but I get 404. What am I doing wrong? I wrote a simple bean which returns a hard coded value and then print that, I changed the value to test Dev tools and it didn’t restart the resource , I had to kill and restart the app to reflect the new changes .. How can I check what the issue ? I can provide console grab if needed. Please help. **Update**: I don't know the significance of the following so putting it in here. in the XML editor hal is red underlined with the following msg on hover: > > The managed version is 3.0.5.RELEASE The artifact is managed in org.springframework.data:spring-data-releasetrain:Kay-SR5 > > > in the XML editor devtools is red underlined with the following msg on hover: > > The managed version is 2.0.0.RELEASE The artifact is managed in org.springframework.boot:spring-boot-dependencies:2.0.0.RELEASE > > > `pom.xml`: ``` xml version="1.0" encoding="UTF-8"? 4.0.0 com.myoxigen.training.springboot library 0.0.1-SNAPSHOT jar library Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 2.0.0.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-actuator org.springframework.data spring-data-rest-hal-browser org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-devtools org.springframework.boot spring-boot-maven-plugin ``` `application.properties` file: ``` logging.level.org.springframework = DEBUG management.security.enabled=false ```<issue_comment>username_1: *Note: This answer is based on Spring Boot 2 (paths and properties have changed from version 1).* Your `pom.xml` looks fine to me. To get the "HAL Browser" to work with actuator you should have starters: `web`, `actuator`, and `Rest Repositories HAL Browser`. I recommend [Spring Initializr](https://start.spring.io) as a nice way to construct an initial valid project structure. The default path for the actuator is `/actuator`. Health, for example, is at `/actuator/health`. To view the actuator endpoints in the HAL Browser, go to `/browser/index.html#/actuator`. You can change the actuator path in `application.properties` by setting the following. ``` management.endpoints.web.base-path=/actuator ``` To run your server, use the following console command: ``` ./mvnw clean spring-boot:run ``` If you have `DevTools` in your project, then changes to files in your classpath will restart the server. See my further comments on how to take advantage of DevTools [here](https://stackoverflow.com/a/46506588). --- Here's the relevant documentation on a single page for easy searching: * <https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle> * <https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle> Upvotes: 3 <issue_comment>username_2: Ain't you were studying a course by "in28minutes"? =) Anyway when I studied on a [Spring Boot for Beginners in 10 Steps](https://in28minutes1.teachable.com/p/spring-boot-for-beginners-in-10-steps) course, I faced the same issue with accessing `http://localhost:8080/application`. For `http://localhost:8080/browser` I got a plain `json`: ``` {"cause":null,"message":"Fragment must not be empty"} ``` In `pom.xml` I had the same dependencies as you outlined in question. Some googling brought me to [this](https://grokonez.com/spring-framework/spring-data/use-hal-browser-spring-data-rest-springboot-mysql) article. In section named "II. Hal Browser" you can see a screenshot, where in browser a link is `http://localhost:8080/browser/index.html#`. If use this link, then Hal Browser should magically appear. So `/index.html#` was the only puzzle piece you missed. Note: above approach worked with Spring Boot version 2.1.7 **EDIT**: despite the fact that Hal Browser itself works with above approach, it still doesn't show actuator endpoints. And DevTools also ain't working for me. Upvotes: 0 <issue_comment>username_3: For enabling actuator, add this into the property file (application.properties) ``` management.endpoints.web.exposure.include=* ``` Restart the Spring boot application and access the actuator endpoints using: ``` http://localhost:8080/actuator/ ``` the health of the application can also be monitored using: ``` http://localhost:8080/actuator/health ``` dependency required: ``` org.springframework.boot spring-boot-starter-actuator ``` Upvotes: 1 <issue_comment>username_4: ``` Add this Dependency: org.springframework.data spring-data-rest-hal-browser 3.3.5.RELEASE `enter code here` And then go to link: http://localhost:8080/browser/index.html# ``` Upvotes: 3 <issue_comment>username_5: Spring Boot 2.2 apps should use **spring-data-rest-hal-explorer** rather than **spring-data-rest-hal-browser** ``` org.springframework.data spring-data-rest-hal-explorer ``` Upvotes: 2
2018/03/18
1,115
3,857
<issue_start>username_0: I'm new to react and redux, and I'm attempting to create new state, but it appears that I'm not updating the state properly. here's the code inside my case: ``` case SUBMIT_NOTE: console.log(payload.note); return{ ...state, notes: state.notes.push(payload.note)}; ``` `payload.note` resolves to the object I want to push into the array, but in redux-logger it shows as `state.notes = 2` Not sure how this happened. I'm new to the spread operator, and pure functions.<issue_comment>username_1: *Note: This answer is based on Spring Boot 2 (paths and properties have changed from version 1).* Your `pom.xml` looks fine to me. To get the "HAL Browser" to work with actuator you should have starters: `web`, `actuator`, and `Rest Repositories HAL Browser`. I recommend [Spring Initializr](https://start.spring.io) as a nice way to construct an initial valid project structure. The default path for the actuator is `/actuator`. Health, for example, is at `/actuator/health`. To view the actuator endpoints in the HAL Browser, go to `/browser/index.html#/actuator`. You can change the actuator path in `application.properties` by setting the following. ``` management.endpoints.web.base-path=/actuator ``` To run your server, use the following console command: ``` ./mvnw clean spring-boot:run ``` If you have `DevTools` in your project, then changes to files in your classpath will restart the server. See my further comments on how to take advantage of DevTools [here](https://stackoverflow.com/a/46506588). --- Here's the relevant documentation on a single page for easy searching: * <https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle> * <https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle> Upvotes: 3 <issue_comment>username_2: Ain't you were studying a course by "in28minutes"? =) Anyway when I studied on a [Spring Boot for Beginners in 10 Steps](https://in28minutes1.teachable.com/p/spring-boot-for-beginners-in-10-steps) course, I faced the same issue with accessing `http://localhost:8080/application`. For `http://localhost:8080/browser` I got a plain `json`: ``` {"cause":null,"message":"Fragment must not be empty"} ``` In `pom.xml` I had the same dependencies as you outlined in question. Some googling brought me to [this](https://grokonez.com/spring-framework/spring-data/use-hal-browser-spring-data-rest-springboot-mysql) article. In section named "II. Hal Browser" you can see a screenshot, where in browser a link is `http://localhost:8080/browser/index.html#`. If use this link, then Hal Browser should magically appear. So `/index.html#` was the only puzzle piece you missed. Note: above approach worked with Spring Boot version 2.1.7 **EDIT**: despite the fact that Hal Browser itself works with above approach, it still doesn't show actuator endpoints. And DevTools also ain't working for me. Upvotes: 0 <issue_comment>username_3: For enabling actuator, add this into the property file (application.properties) ``` management.endpoints.web.exposure.include=* ``` Restart the Spring boot application and access the actuator endpoints using: ``` http://localhost:8080/actuator/ ``` the health of the application can also be monitored using: ``` http://localhost:8080/actuator/health ``` dependency required: ``` org.springframework.boot spring-boot-starter-actuator ``` Upvotes: 1 <issue_comment>username_4: ``` Add this Dependency: org.springframework.data spring-data-rest-hal-browser 3.3.5.RELEASE `enter code here` And then go to link: http://localhost:8080/browser/index.html# ``` Upvotes: 3 <issue_comment>username_5: Spring Boot 2.2 apps should use **spring-data-rest-hal-explorer** rather than **spring-data-rest-hal-browser** ``` org.springframework.data spring-data-rest-hal-explorer ``` Upvotes: 2
2018/03/18
749
3,270
<issue_start>username_0: I'm wondering about compressing relatively small strings, between 1 and 10kb, for storage on my server. The server and receiving client application will not be using my chosen compression during actual requests. The compression will only be used to conserve storage space on the server. In a case like this, is using gzip with its headers really necessary? Could I use deflate? Maybe even deflate raw, since I know the encoding of the strings in all cases? The #1 argument I see against deflate is inconsistent implementations in browsers, but this seems irrelevant in my case. Am I getting something wrong in my thinking? If deflate is a viable alternative to gzip here, what about deflate raw?<issue_comment>username_1: Internally in your web application, you can use *any* compression - if you send the uncompressed data to the HTTP client, there's simply no difference on the wire. However, doing so is always a trade-off - the implementation of the server will be more complex, and you'll need more CPU power. It also only works if the data is compressible, and large objects (e.g. video files / disk images) tend to be compressed already. For many applications, disk space is not a problem, and low latency and minimal complexity are much more important concerns. If your application stores a large amount of compressible data which gets requested very infrequently, such a compression scheme may indeed be a good idea. But before you implement complex code, calculate whether it's really worth the trade-off. Also consider filesystem-level compression (very simple to enable, implementation is somebody else's problem). If your aim is to conserve space, you should also consider various algorithms, from LZ4(very fast) over gzip/deflate/deflateRaw (all identical, just different headers) to LZMA (very slow but very efficient). Upvotes: 1 <issue_comment>username_2: First some terminology. Deflate refers to the raw deflate format, as described in RFC 1951. So there is no distinction between "deflate" and "deflate raw". You may be thinking of the misnamed "deflate" HTTP encoding, which is not actually deflate but rather zlib, as described in RFC 1950. Second, compressing small strings as standalone, decompressible files, which it seems you are implying, will result in rather poor compression in most cases. You should be concatenating those strings, along with whatever structure you need to be able to pull them apart again, at least to about the 1 MB level and applying compression to those. You did not say how you want to later access these strings, which would need to be taken into account in such a scheme. Third, even when compressing your small strings in the 1 KB to 10 KB range, the differences between gzip, zlib, and deflate will be essentially negligible in the space taken. The header and trailers account for 18 bytes, 6 bytes, and 0 bytes respectively for the three formats. So if it is space you are concerned about, there's little gain in going away from gzip. Fourth, there might be a small speed advantage in not calculating the CRC-32 or Adler-32 check values when compressing (used in gzip and zlib respectively), but it will again be negligible compared to the time spent compressing. Upvotes: 3
2018/03/18
812
3,071
<issue_start>username_0: We are looking to move a specific directory from one git repository to another. I found [these instructions](http://gbayer.com/development/moving-files-from-one-git-repository-to-another-preserving-history/), which went well until the point of the pull from the remote branch; it appears that having files on both sides that are tracked by git-lfs complicates the process somewhat. I tried this both directly between my local clones, as well as doing the filter-branch on a branch and pushing it to the main server (VSTS). In both cases the smudge filter failed, saying it couldn't find the LFS-tracked file; with the VSTS remote the error logged is a 404. I'd like to keep these files as LFS tracked in the destination, whether the move is done using the local clones direct or involves the server. Are there any additional commands/switches or preparation steps that will allow this?<issue_comment>username_1: According to [repository clone times-out lfs files cannot be retrieved #1181](https://github.com/git-lfs/git-lfs/issues/1181#issuecomment-214435967 "repository clone times-out lfs files cannot be retrieved #1181") > > In both cases the smudge filter failed, saying it couldn't find the LFS-tracked file; with the VSTS remote the error logged is a 404. > > > It means that the files do not exist on the server. You can try to find a local clone of that repository that has it, and run `git lfs push REMOTE_NAME --all`. And you may need to execute `git lfs fetch --all` to download all LFS-tracked files before you push them to your new Git repository. Upvotes: 2 <issue_comment>username_2: (Upvoted the other answer for the hint in the right direction, though my newbie rep won't have it show.) The key here seems to have been `git lfs fetch --all` before branching off and running `filter-branch`, move and commit as described in the article. It looks like LFS isn't intended to work between local clones; reversing the procedure so as to `push` to the destination clone also resulted in an error, but it did work when pushing to the remote server for the destination repo. From there, a fetch into the destination clone and merge with `--allow-unrelated-histories` looks to have given us what we were after. Upvotes: 3 [selected_answer]<issue_comment>username_3: for my the easiest way was to fork the repository (it means on the server side) Upvotes: 0 <issue_comment>username_4: Turning @djdanlib 's comment into an answer (with some clarification) as this was the most helpful answer for me and my team during a transition from GitHub to ADO. * `git clone` (if you don't already have it locally) * `git remote -v` (check that you are pointed to the old repo) * `git lfs fetch --all` (forces the download of all the LFS files) * `git remote set-url origin` (you are now pointing to your new repo) * `git remote -v` or `git ls-remote` (double-check you are pointing to the new URL) * `git push origin --all` (pushes all branches to the repo) * `git lfs push origin --all` (pushes all LFS files to the repo) Upvotes: 0
2018/03/18
751
2,691
<issue_start>username_0: I’m constantly failing to install Platform IO IDE for Visual Studio Code or Atom. I’m working on OSX with High Sierra. I have two users, both are Admins. The first user can install with VSC and Atom just fine. The second user always gets this error message: > > PIP: Error: spawn /Volumes/Macintosh > HD/Users/micha/.platformio/penv/bin/pip ENOENT > > > I already tried to delete the .platformio folder and start over, without success. The error shows up for Visual Studio Code and Atom. Any ideas?<issue_comment>username_1: According to [repository clone times-out lfs files cannot be retrieved #1181](https://github.com/git-lfs/git-lfs/issues/1181#issuecomment-214435967 "repository clone times-out lfs files cannot be retrieved #1181") > > In both cases the smudge filter failed, saying it couldn't find the LFS-tracked file; with the VSTS remote the error logged is a 404. > > > It means that the files do not exist on the server. You can try to find a local clone of that repository that has it, and run `git lfs push REMOTE_NAME --all`. And you may need to execute `git lfs fetch --all` to download all LFS-tracked files before you push them to your new Git repository. Upvotes: 2 <issue_comment>username_2: (Upvoted the other answer for the hint in the right direction, though my newbie rep won't have it show.) The key here seems to have been `git lfs fetch --all` before branching off and running `filter-branch`, move and commit as described in the article. It looks like LFS isn't intended to work between local clones; reversing the procedure so as to `push` to the destination clone also resulted in an error, but it did work when pushing to the remote server for the destination repo. From there, a fetch into the destination clone and merge with `--allow-unrelated-histories` looks to have given us what we were after. Upvotes: 3 [selected_answer]<issue_comment>username_3: for my the easiest way was to fork the repository (it means on the server side) Upvotes: 0 <issue_comment>username_4: Turning @djdanlib 's comment into an answer (with some clarification) as this was the most helpful answer for me and my team during a transition from GitHub to ADO. * `git clone` (if you don't already have it locally) * `git remote -v` (check that you are pointed to the old repo) * `git lfs fetch --all` (forces the download of all the LFS files) * `git remote set-url origin` (you are now pointing to your new repo) * `git remote -v` or `git ls-remote` (double-check you are pointing to the new URL) * `git push origin --all` (pushes all branches to the repo) * `git lfs push origin --all` (pushes all LFS files to the repo) Upvotes: 0
2018/03/18
693
1,989
<issue_start>username_0: In R markdown I want to make the table with 2 rows and 8 columns. ``` \begin{table}[ht] \begin{tabular}{c|c|c|c|c|c|c|c} \hline variable & N & Mean & Std.Dev & SE Mean & 95% cI & T & P \\ Y & 25 & 92.5805 & ? & 0.4673 & (91.6160, ?) & ? & 0.002 \\ \hline \end{tabular} \end{table} ``` I entered this command and it returns this error message. ``` ! Extra alignment tab has been changed to \cr. \endtemplate l.101 Y & 25 & 92.5805 & pandoc.exe: Error producing PDF error: pandoc document conversion failed with error 43 ``` I guess I entered tabular right and nothing to be calculated. They' are just texts and numbers. I tried to search similar questions and compare the examples codes. But I don't know how to solve it.<issue_comment>username_1: Specify your tablar correctly with extra vertical bars `|` at the beginning and at the end. In addition escape the percent sign with a backslash `\%`, otherwise it has a meaning as a program code. ``` \begin{table}[ht] \begin{tabular}{|c|c|c|c|c|c|c|c|} \hline variable & N & Mean & Std.Dev & SE Mean & 95\% cI & T & P \\ Y & 25 & 92.5805 & ? & 0.4673 & (91.6160, ?) & ? & 0.002 \\ \hline \end{tabular} \end{table} ``` Hope this would work for you? Upvotes: 3 [selected_answer]<issue_comment>username_2: I encountered the same error when omitting a justification argument for one of the aligned columns. In this example, I want to left justify two equations using an `array` rather than a `table`: ``` \begin{array}{l} \hat{z} =& \frac{\beta_0}{1 - \beta_z} \\ \hat{z}' =& \beta_0+\beta_z\left(\frac{\beta_0}{1-\beta_z}\right). \end{array} ``` For which we see the same error: ``` ! Extra alignment tab has been changed to \cr. \endtemplate ``` Indeed the principle of the issue is the same as for `\tabular`, however adding vertical bars `|` will not fix the problem. Only by adding the missing `l` in `\begin{array}{l}` (which becomes `\begin{array}{ll}`) resolved the error. Upvotes: 0
2018/03/18
1,196
5,021
<issue_start>username_0: I have an SchoolActivity that has two buttons: -Primary (adds the PrimaryFragment) -Secondary (adds the SecondaryFragment) ``` xml version="1.0" encoding="utf-8"? ``` Both the fragments has content and footer area, which are themselves are fragments (PrimaryContentFragment, PrimaryFooterFragment, SecondaryContentFragment, SecondaryFooterFragment) I am adding the fragments from the activity using: ``` public void onClick(View view) { Button button = (Button)view; Toast.makeText(this, "Going to Add Children", Toast.LENGTH_SHORT).show(); switch(view.getId()) { case R.id.button_primary: getSupportFragmentManager().beginTransaction() .replace(R.id.main_container, new PrimaryFragment()) .addToBackStack("primary") .commit(); break; case R.id.button_secondary: getSupportFragmentManager().beginTransaction() .replace(R.id.main_container, new SecondaryFragment()) .addToBackStack("secondary") .commit(); break; } } ``` And, finally adding the each children fragments using: The layout file: ``` xml version="1.0" encoding="utf-8"? ``` The children fragments adding: ``` public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.primary_fragment, container, false); getChildFragmentManager() .beginTransaction() .add(R.id.content_container, new PrimaryContentFragment()) .add(R.id.footer_container, new PrimaryFooterFragment()) .addToBackStack("primarychildren") .commit(); return view; } ``` I am adding the similar logics for the another fragment also and so on for the rest which is working. **THE PROBLEM:** The solution as stated is working but seems as very raw naive approach. Could anybody suggest the better architecture I could follow such as: * all the fragments (Primary/Secondary/...) uses the same designs so can I create some base class to inherit common features * all the footer are similar for all of fragments but with simple text change (might be like breadcrumb) So, Can I use same footer for all fragments with some settext method ... * how can I effectively communicate between activity and fragments BEING A NEW ANDROID DEV, MY ONLY CONCERN IS AM I DOING THE RIGHT WAY !!!<issue_comment>username_1: Try this using `bundle` :- ``` ContentFragment content=new ContentFragment(); content.setArguments( ( new Bundle()).putString("value","primary")); getChildFragmentManager() .beginTransaction() .add(R.id.content_container, content) .add(R.id.footer_container, new PrimaryFooterFragment()) .addToBackStack("primarychildren") .commit(); ``` Similarly For secondary use :- ``` ContentFragment content=new ContentFragment(); content.setArguments( ( new Bundle()).putString("value","secondary")); ``` > > Use same `content` and `footer` fragments just set the texts by using `bundle arguments` > > > Upvotes: 1 <issue_comment>username_2: > > All the fragments (Primary/Secondary/...) uses the same designs so can > I create some base class to inherit common features > > > If they are using the same design and with slight changes in their content, then there's no need of create different `Fragment` classes. You can just pass necessary values from your calling `Activity` or `Fragment` to populate the contents in each of your child fragments. > > All the footer are similar for all of fragments but with simple text > change (might be like breadcrumb) So, Can I use same footer for all > fragments with some settext method ... > > > If they are just simple text changes, then please use the `setArguments` and `getArguments` methods to pass values between `Fragment`s rather creating different `Fragment` classes. Here's how you can [pass values between fragments](https://stackoverflow.com/a/16036693/3145960). And here's how you [can pass data from your `Activity` to `Fragment`](https://stackoverflow.com/a/12739968/3145960). > > How can I effectively communicate between activity and fragments > > > Please follow the two links above to communicate between `Activity` and `Fragment`. **Update** Following up the comment, as you have said that the `PrimaryFragment` and `SecondaryFragment` are mostly likely, I would suggest you to have one single `Fragment` having all these. Instead of having `PrimaryFragment`, `SecondaryFragment` and a `CommonFragment`, you might consider a single `Fragment` having the footer `Fragment` as well. When you are about to launch an instance of that `Fragment`, just pass necessary values to populate data as the contents of those `Fragment`. Please let me know if I have not clarified enough. Upvotes: 0
2018/03/18
2,747
8,582
<issue_start>username_0: I have a wireframe shader that displays triangles such as on the left cube, and wanted to update it so that it would only display quads such as on the right cube. [![Triangles VS Quads](https://i.stack.imgur.com/vDJUZ.png)](https://i.stack.imgur.com/vDJUZ.png) Here's the code: ``` Shader "Custom/Wireframe" { Properties { _WireColor("WireColor", Color) = (1,0,0,1) _Color("Color", Color) = (1,1,1,1) } SubShader { Pass { CGPROGRAM #include "UnityCG.cginc" #pragma target 5.0 #pragma vertex vert #pragma geometry geom #pragma fragment frag half4 _WireColor, _Color; struct v2g { float4 pos : SV_POSITION; float2 uv : TEXCOORD0; }; struct g2f { float4 pos : SV_POSITION; float2 uv : TEXCOORD0; float3 dist : TEXCOORD1; }; v2g vert(appdata_base v) { v2g OUT; OUT.pos = mul(UNITY_MATRIX_MVP, v.vertex); OUT.uv = v.texcoord; return OUT; } [maxvertexcount(3)] void geom(triangle v2g IN[3], inout TriangleStream triStream) { float2 WIN\_SCALE = float2(\_ScreenParams.x/2.0, \_ScreenParams.y/2.0); //frag position float2 p0 = WIN\_SCALE \* IN[0].pos.xy / IN[0].pos.w; float2 p1 = WIN\_SCALE \* IN[1].pos.xy / IN[1].pos.w; float2 p2 = WIN\_SCALE \* IN[2].pos.xy / IN[2].pos.w; //barycentric position float2 v0 = p2-p1; float2 v1 = p2-p0; float2 v2 = p1-p0; //triangles area float area = abs(v1.x\*v2.y - v1.y \* v2.x); g2f OUT; OUT.pos = IN[0].pos; OUT.uv = IN[0].uv; OUT.dist = float3(area/length(v0),0,0); triStream.Append(OUT); OUT.pos = IN[1].pos; OUT.uv = IN[1].uv; OUT.dist = float3(0,area/length(v1),0); triStream.Append(OUT); OUT.pos = IN[2].pos; OUT.uv = IN[2].uv; OUT.dist = float3(0,0,area/length(v2)); triStream.Append(OUT); } half4 frag(g2f IN) : COLOR { //distance of frag from triangles center float d = min(IN.dist.x, min(IN.dist.y, IN.dist.z)); //fade based on dist from center float I = exp2(-4.0\*d\*d); return lerp(\_Color, \_WireColor, I); } ENDCG } } ``` Someone has mentioned that one way to do it would be to compare the normals of the neighboring triangles. If the dot product of the two normals is close to 1, the edge can be skipped. But I don't know how to implement it as I don't have any knowledge on geometry shaders. Can you please help me edit this shader? Thanks.<issue_comment>username_1: Unity, and graphics engines in general (OpenGL/D3D) do not operate on quads, its an alien term to them. I am not a shader ninja who would just whip out a snippet for you, but you can try filtering your geometry by normal dicontinuity - only draw the edge between tris that have different normals (or more specifically different enough as this is float math and stuff is rarely precisely equal) - that would hide edges on surfaces that are flat. One approach would involve sampling the depthmap, and checking if the difference between us and our neighbours is relatively constant in fragment shader. Maybe you could pass the info via vertex colour While not directly related to the question, reading Keijiro's code is always illuminating and he writes a bit about how he approached modifying skinned geometry. His approach involves caching normals in a 3D texture (you could also use spare UV coordinates) to expose additional geometry information to the shader. <https://github.com/keijiro/SkinnedVertexModifier> The shader cannot access any data regarding other points than itself, but if you put that data in textures or UV, you can feed it some guidance as to how to progress. in general there is know easy to way to know from a shader level how you relate to the rest of the geometry, you need to generate that data in advance on the CPU and feed it to the shader so its already computer by the time the shader starts. I hope this helps Upvotes: 2 <issue_comment>username_2: [Someone posted a question](https://stackoverflow.com/questions/54535181/why-my-shader-doesnt-render-the-subshader-with-the-color) where one of the pieces that they started with was...*a diagonal-less wireframe shader!* Being on the lookout for one of these for some time (and remembering this question) I figured it deserved an answer. The shader below was found [at this site](http://www.shaderslab.com/demo-94---wireframe-without-diagonal.html). ``` Shader "Custom/Geometry/Wireframe" { Properties { [PowerSlider(3.0)] _WireframeVal ("Wireframe width", Range(0., 0.5)) = 0.05 _FrontColor ("Front color", color) = (1., 1., 1., 1.) _BackColor ("Back color", color) = (1., 1., 1., 1.) [Toggle] _RemoveDiag("Remove diagonals?", Float) = 0. } SubShader { Tags { "Queue"="Geometry" "RenderType"="Opaque" } Pass { Cull Front CGPROGRAM #pragma vertex vert #pragma fragment frag #pragma geometry geom // Change "shader_feature" with "pragma_compile" if you want set this keyword from c# code #pragma shader_feature __ _REMOVEDIAG_ON #include "UnityCG.cginc" struct v2g { float4 worldPos : SV_POSITION; }; struct g2f { float4 pos : SV_POSITION; float3 bary : TEXCOORD0; }; v2g vert(appdata_base v) { v2g o; o.worldPos = mul(unity_ObjectToWorld, v.vertex); return o; } [maxvertexcount(3)] void geom(triangle v2g IN[3], inout TriangleStream triStream) { float3 param = float3(0., 0., 0.); #if \_REMOVEDIAG\_ON float EdgeA = length(IN[0].worldPos - IN[1].worldPos); float EdgeB = length(IN[1].worldPos - IN[2].worldPos); float EdgeC = length(IN[2].worldPos - IN[0].worldPos); if(EdgeA > EdgeB && EdgeA > EdgeC) param.y = 1.; else if (EdgeB > EdgeC && EdgeB > EdgeA) param.x = 1.; else param.z = 1.; #endif g2f o; o.pos = mul(UNITY\_MATRIX\_VP, IN[0].worldPos); o.bary = float3(1., 0., 0.) + param; triStream.Append(o); o.pos = mul(UNITY\_MATRIX\_VP, IN[1].worldPos); o.bary = float3(0., 0., 1.) + param; triStream.Append(o); o.pos = mul(UNITY\_MATRIX\_VP, IN[2].worldPos); o.bary = float3(0., 1., 0.) + param; triStream.Append(o); } float \_WireframeVal; fixed4 \_BackColor; fixed4 frag(g2f i) : SV\_Target { if(!any(bool3(i.bary.x < \_WireframeVal, i.bary.y < \_WireframeVal, i.bary.z < \_WireframeVal))) discard; return \_BackColor; } ENDCG } Pass { Cull Back CGPROGRAM #pragma vertex vert #pragma fragment frag #pragma geometry geom // Change "shader\_feature" with "pragma\_compile" if you want set this keyword from c# code #pragma shader\_feature \_\_ \_REMOVEDIAG\_ON #include "UnityCG.cginc" struct v2g { float4 worldPos : SV\_POSITION; }; struct g2f { float4 pos : SV\_POSITION; float3 bary : TEXCOORD0; }; v2g vert(appdata\_base v) { v2g o; o.worldPos = mul(unity\_ObjectToWorld, v.vertex); return o; } [maxvertexcount(3)] void geom(triangle v2g IN[3], inout TriangleStream triStream) { float3 param = float3(0., 0., 0.); #if \_REMOVEDIAG\_ON float EdgeA = length(IN[0].worldPos - IN[1].worldPos); float EdgeB = length(IN[1].worldPos - IN[2].worldPos); float EdgeC = length(IN[2].worldPos - IN[0].worldPos); if(EdgeA > EdgeB && EdgeA > EdgeC) param.y = 1.; else if (EdgeB > EdgeC && EdgeB > EdgeA) param.x = 1.; else param.z = 1.; #endif g2f o; o.pos = mul(UNITY\_MATRIX\_VP, IN[0].worldPos); o.bary = float3(1., 0., 0.) + param; triStream.Append(o); o.pos = mul(UNITY\_MATRIX\_VP, IN[1].worldPos); o.bary = float3(0., 0., 1.) + param; triStream.Append(o); o.pos = mul(UNITY\_MATRIX\_VP, IN[2].worldPos); o.bary = float3(0., 1., 0.) + param; triStream.Append(o); } float \_WireframeVal; fixed4 \_FrontColor; fixed4 frag(g2f i) : SV\_Target { if(!any(bool3(i.bary.x <= \_WireframeVal, i.bary.y <= \_WireframeVal, i.bary.z <= \_WireframeVal))) discard; return \_FrontColor; } ENDCG } } } ``` Do note the `#pragma shader_feature __ _REMOVEDIAG_ON` lines, which will cause two shaders to [get compiled internally](https://docs.unity3d.com/Manual/SL-MultipleProgramVariants.html), so if you only need it to do the One Thing, you will need to remove this line and adjust any other references appropriately. Upvotes: 2
2018/03/18
603
2,400
<issue_start>username_0: WebRTC requires too much processing power on server so doing it massively will be cost-prohibitive. For nearly all other platforms - both for Windows and Mac - Chrome, Safari desktop, even IE and Edge, and Android - there is a Media Source Extensions API (<https://en.wikipedia.org/wiki/Media_Source_Extensions>) which allows sending stream over websockets and play it, it works. Problem is just with iOS. Is there anything better (lower latency) than HLS which would work for me? If not, is there a WebRTC server which is free and better scalable/more stable than Kurento Media Server (<https://github.com/Kurento/kurento-media-server>)? There is a jsmpeg player <http://jsmpeg.com/> but it is MPEG-1 only so will require unacceptable amount of bandwidth. There is broadway.js but it does not support audio...<issue_comment>username_1: Since you don't want to implement webRTC by yourself and need lower latency than HLS, I would prefer a media server. There are many media servers available in the market. But if you are looking for free and open source media server, your options are limited to few. I would suggest red5 media server which is free and open source. Please check [this](http://red5.org/) link to find more about red5. If you use free red 5 media server you need little knowledge of java. Red5 also has a paid version called [red5 pro](https://red5pro.com/) which has better webRTC support and higher capabilities. Red5 is mostly for rtmp with flash player pulgin and its fairly new for [red 5 webRTC](https://github.com/rajdeeprath/red5-webrtc-demo) streaming. Also you can use [wowza streaming engine](https://www.wowza.com/products/streaming-engine) trail version with limited number of connections. So these are the easiest options for you. Upvotes: -1 <issue_comment>username_2: > > Is there anything better (lower latency) than HLS which would work for me? > > > HTTP Progressive is a fine technology for this. It can be ran at much lower latencies than a segmented technology like DASH or HLS, and requires very little in terms of server-side resources. Look into Icecast for your server, and FFmpeg as your source. There's no point in sending video over Web Sockets, unless you're implementing a bi-directional protocol. This isn't uncommon for ABR support, but it's definitely not the most efficient or simple way to do it. Upvotes: 0
2018/03/18
1,115
3,753
<issue_start>username_0: I have an html table which should do two things: 1) Inside the tables i need to display some anchors 2) If clicked anywhere besides the anchor i want it to execute a certain javascript Here is what i have so far: ``` | | | | | --- | --- | --- | | [asdfasdf](goaway) | [asdfasdf](goaway) | [asdfasdf](goaway) | $(document).ready(function() { $('tr[data-href]').click(function () { var $parent = $(this).closest('tr[data-href]'); alert($parent.data('href')); }); }); ``` So when clicked anywhere inside that table my javascript is executed which is fine. The problem is that when i click on the anchor it is also executed which i would like to avoid. How could that be avoided? JSFiddle: <https://jsfiddle.net/o2gxgz9r/35761/> Edit: Actually some of my anchors may have a onclick event so that should still work, just the tr[data-href] action should be explicitly avoided.<issue_comment>username_1: You should use `event.stopPropagation()` <https://api.jquery.com/event.stoppropagation/> JSFiddle: <https://jsfiddle.net/o2gxgz9r/35756/> Upvotes: 2 <issue_comment>username_2: As you have more element that has click handlers than just the the anchor `a` and table row `tr`, you can use `if (e.target == this)` to make sure each element type will run its intended code. With this, `this` represent the element that the event handler were set on, `e.target` the element that were clicked on, and when they match you'll know which one that were clicked. Stack snippet ```js $(document).ready(function() { $('tr[data-href]').click(function (e) { if (e.target == this) { var $parent = $(this).closest('tr[data-href]'); alert($parent.data('href')); } }); $('tr[data-href] td').click(function (e) { if (e.target == this) { alert('this should work'); } }); }); ``` ```html | | | | | --- | --- | --- | | [asdfasdf](goaway) | [asdfasdf](goaway) | [asdfasdf](goaway) | ``` --- With this in mind, and if there will be some cells `td` that might not have a click handler, you can stop the propagation on them instead, as if, and someone click on such cell, the table row `tr` handler won't run. Now, in the `tr` handler, we need to check so the clicked element is not of type anchor `a`. Stack snippet ```js $(document).ready(function() { $('tr[data-href]').click(function (e) { if (e.target.tagName.toLowerCase() != 'a') { var $parent = $(this).closest('tr[data-href]'); alert($parent.data('href')); } }); $('tr[data-href] td:first-child').click(function (e) { if (e.target == this) { alert('this should work'); } e.stopPropagation(); }); }); ``` ```html | | | | | --- | --- | --- | | [asdfasdf](goaway) | [asdfasdf](goaway) | [asdfasdf](goaway) | ``` --- If you will have inline script it will be more complicated, where you will need to check in `tr` handler so it wasn't an anchor `a`, or a cell `td` with an `onclick` attribute, which could look something like this, and add `stopPropagation()` to those anchors that have a parent `td` with an inline `onclick` handler. Stack snippet ```js $(document).ready(function() { $('tr[data-href]').click(function (e) { if (e.target.tagName.toLowerCase() != 'a' && !e.target.hasAttribute('onclick')) { var $parent = $(this).closest('tr[data-href]'); alert($parent.data('href')); } }); $('tr[data-href] td[onclick] a').click(function (e) { e.stopPropagation(); }); }); ``` ```html | | | | | --- | --- | --- | | [asdfasdf](goaway) | [asdfasdf](goaway) | [asdfasdf](goaway) | ``` Upvotes: 2 [selected_answer]
2018/03/18
249
983
<issue_start>username_0: I `git reset --hard` and then made some new commits. When I try to push these new changes, I'm prompted to git pull to get the changes made after . I'm trying to just write over these changes git is prompting me to pull. This is a simple project so I just have the one master branch. What is the best way to rectify?<issue_comment>username_1: You can force push your changes with this command: `git push origin --force` Upvotes: 0 <issue_comment>username_2: By doing `git reset --hard` and then trying to push that, you are effectively trying to modify history (by removing it). History modification is not allowed unless the `--force` or `--force-with-lease` (preferably) flag is given on `git push`. Keep in mind that if anyone else has the older version of the branch, you may want to notify them so that they can correct their copy to match the new history. More info at [man git-push](https://gitirc.eu/git-push.html). Upvotes: 2 [selected_answer]
2018/03/18
2,910
6,653
<issue_start>username_0: I have an ebook text file named `Frankenstein.txt` and I would like to know how many times each letter used in the novel. **My Setup:** I imported the text file, like this inorder to get a vector of characters `character_array` ``` string <- readChar("Frankenstein.txt", filesize) character_array <- unlist(strsplit(string, "")) ``` `character_array` gives me something like this. ``` "F" "r" "a" "n" "k" "e" "n" "s" "t" "e" "i" "n" "\r", ... ``` **My Goal:** I would like to get the count of each time a character appears in the text file. In other words, I would like to get a count for each `unique(character_array)` ``` [1] "F" "r" "a" "n" "k" "e" "s" "t" "i" "\r" "\n" "b" "y" "M" [15] " " "W" "o" "l" "c" "f" "(" "G" "d" "w" ")" "S" "h" "C" [29] "O" "N" "T" "E" "L" "1" "2" "3" "4" "p" "5" "6" "7" "8" [43] "9" "0" "_" "." "v" "," "g" "P" "u" "D" "—" "Y" "j" "m" [57] "I" "z" "?" ";" "x" "q" "B" "U" "’" "H" "-" "A" "!" ":" [71] "R" "J" "“" "”" "æ" "V" "K" "[" "]" "‘" "ê" "ô" "é" "è" ``` **My Attempt** When I call `plot(as.factor(character_array))` I get a nice graph which gives me what I want visually. [![enter image description here](https://i.stack.imgur.com/a7Dms.png)](https://i.stack.imgur.com/a7Dms.png) However, I need to get the exact values for each of these characters. I would like something like a 2D array like: ``` [,1] [,2] [,3] [,4] ... [1,] "a" "A" "b" "B" ... [2,] "1202" "50" "12" "9" ... ```<issue_comment>username_1: One nice way to make these kinds of text processing pipelines is with `magrittr::%>%` pipes. Here is one approach, assuming that your text is in `"frank.txt"` (see bottom for explanation of each step): ``` library(magrittr) # read the text in frank_txt <- readLines("frank.txt") # then send the text down this pipeline: frank_txt %>% paste(collapse="") %>% strsplit(split="") %>% unlist %>% `[`(!. %in% c("", " ", ".", ",")) %>% table %>% barplot ``` Note that you can just stop at the `table()` and assign the result to a variable, which you can then manipulate however you want, e.g. by plotting it: ``` char_counts <- frank_txt %>% paste(collapse="") %>% strsplit(split="") %>% unlist %>% `[`(!. %in% c("", " ", ".", ",")) %>% table barplot(char_counts) ``` You can also convert the table into a data frame for easier manipulation/plotting later: ``` counts_df <- data.frame( char = names(char_counts), count = as.numeric(char_counts), stringsAsFactors=FALSE) head(counts_df) ## char count ## a 13 ## b 2 ## c 7 ## d 5 ## e 24 ## f 6 ``` **Each step explained:** Here is the full pipe-chain with each step explained: ``` # going to send this text down a pipeline: frank_txt %>% # combine lines into a single string (makes things easier downstream) paste(collapse="") %>% # tokenize by character (strsplit returns a list, so unlist it) strsplit(split="") %>% unlist %>% # remove instances of characters you don't care about `[`(!. %in% c("", " ", ".", ",")) %>% # make a frequency table of the characters table %>% # then plot them barplot ``` Note that this is exactly equivalent to the following horrendous (**"monstrous"**?!?!) code -- the forward pipe `%>%` just applies the function on its right to the value on its left (and `.` is a pronoun referring to the value on the left; see [intro vignette](https://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html)): ``` barplot(table( unlist(strsplit(paste(frank_txt, collapse=""), split=""))[ !unlist(strsplit(paste(frank_txt, collapse=""), split="")) %in% c(""," ",".",",")])) ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Using gutenbergr, tidytext and dplyr you can do the following: ``` library(gutenbergr) library(tidytext) library(dplyr) frank <- gutenberg_download(c(84), meta_fields = "title") ``` Removes unneeded chars like . [ ] etc. ``` frank %>% unnest_tokens(chars, text, "characters") %>% group_by(chars) %>% summarise(n = n()) %>% t() #transpose to get in order of OP [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] chars "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "a" "b" "c" "d" "e" "f" n " 2" " 35" " 15" " 6" " 4" " 4" " 3" " 16" " 5" " 4" "25733" " 4749" " 8644" "16327" "44210" " 8341" [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25] [,26] [,27] [,28] [,29] [,30] [,31] [,32] chars "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" n " 5564" "19194" "23483" " 413" " 1617" "12239" "10237" "23306" "23886" " 5672" " 313" "19647" "20380" "28835" " 9897" " 3717" [,33] [,34] [,35] [,36] chars "w" "x" "y" "z" n " 7364" " 649" " 7578" " 239" ``` If you want these chars, the code is like this: ``` frank %>% unnest_tokens(chars, text, stringr::str_split, pattern = "") %>% group_by(chars) %>% summarise(n = n()) %>% t() #transpose to get in order of OP [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] chars "'" "-" " " "!" "\"" "(" ")" "," "." ":" ";" "?" "[" "]" "_" "0" n " 221" " 370" "71202" " 238" " 774" " 16" " 16" " 4945" " 2904" " 48" " 970" " 220" " 3" " 3" " 2" " 2" [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25] [,26] [,27] [,28] [,29] [,30] [,31] [,32] chars "1" "2" "3" "4" "5" "6" "7" "8" "9" "a" "b" "c" "d" "e" "f" "g" n " 35" " 15" " 6" " 4" " 4" " 3" " 16" " 5" " 4" "25733" " 4749" " 8644" "16327" "44210" " 8341" " 5564" [,33] [,34] [,35] [,36] [,37] [,38] [,39] [,40] [,41] [,42] [,43] [,44] [,45] [,46] [,47] [,48] chars "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" n "19194" "23483" " 413" " 1617" "12239" "10237" "23306" "23886" " 5672" " 313" "19647" "20380" "28835" " 9897" " 3717" " 7364" [,49] [,50] [,51] chars "x" "y" "z" n " 649" " 7578" " 239" ``` Upvotes: 0
2018/03/18
1,834
6,460
<issue_start>username_0: I have a table inside a form, generated by a formset. In this case, my problem is to save all the items after one of them is modified, adding a new "virtual" column as the sum of other two (that is only generated when displaying the table, not saved). I tried different ways, but no one is working. **Issues**: * This `save` is not working at all. It worked when it was only one form, but not for the formset * I tried to generate the column `amount` as a `Sum` of `box_one` and `box_two` without success. I tried generating the form this way too, but this is not working: > > > ``` > formset = modelformset_factory( > Item, form=ItemForm)(queryset=Item.objects.order_by( > 'code__name').annotate(amount=Sum('box_one') + Sum('box_two'))) > > ``` > > This issue is related to this previous one, but this new one is simpler: [Pre-populate HTML form table from database using Django](https://stackoverflow.com/questions/49158138/pre-populate-html-form-table-from-database-using-django) Previous related issues at StackOverflow are very old and not working for me. I'm using Django 2.0.2 Any help would be appreciated. Thanks in advance. Current code: *models.py* ``` class Code(models.Model): name = models.CharField(max_length=6) description = models.CharField(max_length=100) def __str__(self): return self.name class Item(models.Model): code = models.ForeignKey(Code, on_delete=models.DO_NOTHING) box_one = models.IntegerField(default=0) box_two = models.IntegerField(default=0) class Meta: ordering = ["code"] ``` *views.py* ``` class ItemForm(ModelForm): description = CharField() class Meta: model = Item fields = ['code', 'box_one', 'box_two'] def save(self, commit=True): item = super(ItemForm, self).save(commit=commit) item.box_one = self.cleaned_data['box_one'] item.box_two = self.cleaned_data['box_two'] item.code.save() def get_initial_for_field(self, field, field_name): if field_name == 'description' and hasattr(self.instance, 'code'): return self.instance.code.description else: return super(ItemForm, self).get_initial_for_field( field, field_name) class ItemListView(ListView): model = Item def get_context_data(self, **kwargs): data = super(ItemListView, self).get_context_data() formset = modelformset_factory(Item, form=ItemForm)() data['formset'] = formset return data ``` *urls.py* ``` app_name = 'inventory' urlpatterns = [ path('', views.ItemListView.as_view(), name='index'), ``` *item\_list.html* ``` ... {% csrf\_token %} {{ formset.management\_form }} {% for form in formset %} | {% if forloop.first %} {{ form.code.label\_tag }} | {{ form.description.label\_tag }} | Amount: | {{ form.box\_one.label\_tag }} | {{ form.box\_two.label\_tag }} | {% endif %} | --- | --- | --- | --- | --- | | {{ form.code }} | {{ form.description }} | {{ form.amount }} | {{ form.box\_one }} | {{ form.box\_two }} | {% endfor %} ... ```<issue_comment>username_1: You're already on the right path. So you say you need a virtual column. You could define a virtual property in your model class, which won't be stored in the database table, nevertheless it will be accessible as any other property of the model class. This is the code you should add to your model class `Item`: ``` class Item(models.Model): # existing code @property def amount(self): return self.box_one + self.box_one ``` Now you could do something like: ``` item = Item.objects.get(pk=1) print(item.box_one) # return for example 1 print(item.box_two) # return for example 2 print(item.amount) # it will return 3 (1 + 2 = 3) ``` EDIT: Through the `ModelForm` we have access to the model instance and thus to all of its properties. When rendering a model form in a template we can access the properties like this: ``` {{ form.instance.amount }} ``` The idea behind the virtual property `amount` is to place the business logic in the model and follow the approach **fat models - thin controllers**. The `amount` as sum of `box_one` and `box_two` can be thus reused in different places without code duplication. Upvotes: 2 <issue_comment>username_2: ### Annotating query with virtual column `Sum` is an [aggregate expression](https://docs.djangoproject.com/en/2.0/ref/models/expressions/#aggregate-expressions) and is not how you want to be annotating this query in this case. Instead, you should use an [F exrepssion](https://docs.djangoproject.com/en/2.0/ref/models/expressions/#using-f-with-annotations) to add the value of two numeric fields ``` qs.annotate(virtual_col=F('field_one') + F('field_two')) ``` So your corrected queryset would be ``` Item.objects.order_by('code__name').annotate(amount=F('box_one') + F('box_two')) ``` The answer provided by username_1 works great if intend to use the property only for 'row-level' operations. However, if you intend to make a query based on `amount`, you need to annotate the query. ### Saving the formset You have not provided a `post` method in your view class. You'll need to provide one yourself since you're not inheriting from a generic view that provides one for you. See the docs on [Handling forms with class-based views](https://docs.djangoproject.com/en/2.0/topics/class-based-views/intro/#handling-forms-with-class-based-views). You should also consider inheriting from a generic view that handles forms. For example `ListView` does not implement a `post` method, but `FormView` does. Note that your template is also not rendering form errors. Since you're rendering the formset manually, you should consider adding the field errors (e.g. `{{ form.field.errors}}`) so problems with validation will be presented in the HTML. See the docs on [rendering fields manually](https://docs.djangoproject.com/en/2.0/topics/forms/#rendering-fields-manually). Additionally, you can log/print the errors in your `post` method. For example: ``` def post(self, request, *args, **kwargs): formset = MyFormSet(request.POST) if formset.is_valid(): formset.save() return SomeResponse else: print(formset.errors) return super().post(request, *args, **kwargs) ``` Then if the form does not validate you should see the errors in your console/logs. Upvotes: 2
2018/03/18
727
2,624
<issue_start>username_0: I have a `var` result in `try/catch`. I want to use the result out of the `try/catch` block, but I can not declare before the `try` block because the `var` gets the type at runtime. Can I do it? ``` public long getConfigVal( int key, ref T sResult) { var myValue; try { myValue = (from el in keyValueList select (string)el.Attribute("value").Value).FirstOrDefault(); } catch (Exception ex) { } if (sResult is string) sResult = (T)(object)myValue; if (sResult is int) sResult = (T)(object)int.Parse(myValue); if (sResult is DateTime) sResult = (T)(object)DateTime.Parse(myValue); } ``` Or is there any way to use `myValue` outside of the block?<issue_comment>username_1: No, you cannot declare a variable having the receiver type be `var` and then decide not to initialize it inline. Assuming `select el.Value` doesn't return an anonymous type you'll need to resort to using an explicitly typed variable. i.e. ``` IEnumerable myValue; ``` for example: Upvotes: 2 <issue_comment>username_2: It has nothing to do with the `try/catch`, you must initialise usages of `var` where you define them. They *infer* the type from the right hand part of the assignment - they are still typed. `var myInt = 1;` is still typed to an integer, you just let the compiler infer that from the literal `1`. What you are trying to do can't be done in C# with implicit typing. '...because the var gets the type at runtime.' - nope, it's all at compile time. You just need to declare the type of your variable. Upvotes: 2 <issue_comment>username_3: you can also use a dynamic variable: ``` dynamic _myvalue; public MainWindow() { try { var myValue = from el in keyValueList select el.Value; _myvalue = myValue; } catch (Exception ex) { } } ``` Upvotes: -1 <issue_comment>username_4: Thanks to Evk for the good answer (But in the comments...) I declare myValue as an object: ``` string myValue; try { myValue = from el in keyValueList select el.Value; } catch (Exception ex) { } ``` Upvotes: 1 [selected_answer]<issue_comment>username_5: I think you don’t need to declare a var myValue. You have a generic method, so you need T as resultType. Why you don’t use this? It’s easier or at least saver to cast to a generic type, than declare a var as dynamic type. And this answer might not contain code, but looking for an Extension Method for casting string to a value-Type..., or string isn’t that big effort to get a save solution. ;-) Upvotes: 1
2018/03/18
652
2,455
<issue_start>username_0: I have function which answer for pushing items into array. On end function I assign empty string to $scope.newTask for clearing value inside **textarea**. But... Problem is that it not working, after execute function, value inside textarea still is. Could someone explain me why? **HTML** ``` Add ``` **Controller** ``` $scope.addTask = (newTask, index) => { $scope.board.lists[index].cards.push({ 'name': newTask, 'deadline': null, members: [] }); $scope.newTask = ''; }; ```<issue_comment>username_1: No, you cannot declare a variable having the receiver type be `var` and then decide not to initialize it inline. Assuming `select el.Value` doesn't return an anonymous type you'll need to resort to using an explicitly typed variable. i.e. ``` IEnumerable myValue; ``` for example: Upvotes: 2 <issue_comment>username_2: It has nothing to do with the `try/catch`, you must initialise usages of `var` where you define them. They *infer* the type from the right hand part of the assignment - they are still typed. `var myInt = 1;` is still typed to an integer, you just let the compiler infer that from the literal `1`. What you are trying to do can't be done in C# with implicit typing. '...because the var gets the type at runtime.' - nope, it's all at compile time. You just need to declare the type of your variable. Upvotes: 2 <issue_comment>username_3: you can also use a dynamic variable: ``` dynamic _myvalue; public MainWindow() { try { var myValue = from el in keyValueList select el.Value; _myvalue = myValue; } catch (Exception ex) { } } ``` Upvotes: -1 <issue_comment>username_4: Thanks to Evk for the good answer (But in the comments...) I declare myValue as an object: ``` string myValue; try { myValue = from el in keyValueList select el.Value; } catch (Exception ex) { } ``` Upvotes: 1 [selected_answer]<issue_comment>username_5: I think you don’t need to declare a var myValue. You have a generic method, so you need T as resultType. Why you don’t use this? It’s easier or at least saver to cast to a generic type, than declare a var as dynamic type. And this answer might not contain code, but looking for an Extension Method for casting string to a value-Type..., or string isn’t that big effort to get a save solution. ;-) Upvotes: 1
2018/03/18
965
3,486
<issue_start>username_0: I've got a simple React App going on. My `index.js` file looks, of course, like this: ``` import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(, document.getElementById('root')); registerServiceWorker(); ``` Going deeper, my `App.js` file declares an `App extends Compoennt` class, which contains my to-be-rendered elements and their functions: ``` import React, { Component } from "react"; import logo from "./SmartTransit_logo.png"; import MyButton from "./components/MyButton"; import "./App.css"; import { isWallet, helloWorld } from "./services/neo-service"; class App extends Component { state = { inputValue: "" }; render() { return ( ![logo]({logo}) Smart Transit Live Demo ======================= {helloWorld();}} /> ); } } export default App; ``` And the declaration of `MyButton` from `/components/MyButton`: ``` import React, { Component } from "react"; import PropTypes from "prop-types"; class MyButton extends Component { render() { return ( {this.props.children} ); } } MyButton.propTypes = { buttonText: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired, }; export default MyButton; ``` Finally, the declaration for `helloWorld()` is done like so (NOTE: `neon-js` is an npm package I'm using): ``` import { wallet } from "@cityofzion/neon-js"; export function isWallet(address) { console.log(wallet.isAddress(address)); return wallet.isAddress(address); } export function helloWorld() { console.log("Hello world"); return 1; } ``` My problem is that the resulting Button doesn't get its `value` text rendered, and although it gets the `CSS` code for it just fine, it appears empty! [![enter image description here](https://i.stack.imgur.com/3dDqg.png)](https://i.stack.imgur.com/3dDqg.png) Not only that, but pressing it doesn't log a **"Hello World"** in the console, as it should, so it's even disconnected from its `onClick` function. Any idea on what I'm doing wrong?<issue_comment>username_1: You need to define `super(props)` in class constructor when you are going to use `this.props` ``` constructor(props) { super(props); } ``` Define this in `MyButton` component. Upvotes: 0 <issue_comment>username_2: 1. Buttons don't receive a "value" prop. The text inside of the button element is what gives it its text. 2. The button does appear to accept children to use as button text, but no children is actually being passed down to it. `this.props.children` is the content between JSX tags when the component is rendered. 3. React doesn't add the event handlers to elements automatically. You have to pass them along yourself in order for them to be properly triggered. With that in mind, here's how you should render your button in `App`: ``` helloWorld()}> My Button ``` And here's how `MyButton`'s code should look: ``` class MyButton extends Component { render() { return ( {this.props.children} ) } } ``` As you can see, the `buttonText` prop is no longer required; that's what the `children` prop is for. Upvotes: 2 [selected_answer]<issue_comment>username_3: The problem is, you are not calling onClick method from mybutton component and button take it's value between it's opening and closing tag. Use this code: this.props.onClick()}> {this.props.buttonText} Upvotes: 0
2018/03/18
502
1,580
<issue_start>username_0: I'm following a tutorial on YouTube on how to customize my checkboxes (<https://youtu.be/ojWA8pdT-zY?t=5m58s>) for a form but my CSS classes won't get recognized. Not sure why. This is how I got it's referenced in HTML: ``` 1 ``` And this is how I got it in CSS: ``` .labeltext:before { content: "hello"; } ``` I'm not sure what I'm doing wrong. I can already see in Visual Studio Code that it doesn't get recognized because the color of **.labeltext** doesn't change like it normally does. I tried to make it an ID to see if that would resolve it, but no luck on that. Thank you for taking your time to at least read my question! **EDIT:** I realized the typo.. lol. But after the typo fix, it didn't fix my issue. **EDIT2:** my entire CSS what I got so far. As suggested by a user ``` h1 { font-family: sans-serif; text-align: center; } p { font-family: sans-serif; } h3 { font-family: sans-serif; } label { cursor: pointer; } input[type="checkbox"] { display: none; } +.label-text:before { content: "hello"; } ``` **EDIT3:** solved it! the + in the CSS was interfering for some reason. Anyway, it works like I wanted to now. Thanks everyone for trying to help me!<issue_comment>username_1: **Typo** ```css .labeltext:before { content: "hello"; } ``` ```html 1 ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: The code is working fine on jsfiddle: <https://jsfiddle.net/nabtron/h7ntro6x/2/> However, your code has an error, the closing span tag doesn't have a `/span` ( `/` is missing) Upvotes: 0
2018/03/18
1,426
5,088
<issue_start>username_0: ``` Exception in thread "main" java.lang.IllegalStateException : The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html at com.google.common.base.Preconditions.checkState(Preconditions.java:199) at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:109) at org.openqa.selenium.chrome.ChromeDriverService.access$0(ChromeDriverService.java:1) at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137) at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:296) at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88) at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:116) at practise\_locators.DatePicker.main(DatePicker.java:11) ``` Here is my code: ``` package practise_locators; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class DatePicker { public static void main(String[] args){ WebDriver driver = new ChromeDriver(); System.setProperty("WebDriver.Chrome.driver", "E:\\chromedriver.exe"); driver.get("https://www.google.com"); } } ```<issue_comment>username_1: The error says it all : ``` Exception in thread "main" java.lang.IllegalStateException : The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html at com.google.common.base.Preconditions.checkState(Preconditions.java:199) ``` The following phrases from the error implies that there is an error in the line containing **webdriver.chrome.driver** The error can be either of the following : * Error in the [*System Class Method*](https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#setProperty(java.lang.String,%20java.lang.String)) `setProperty()`(including sequence) : ``` System.setProperty() ``` > > This line should be the very **first line** in your script. > > > * Error in the specified [*Key*](https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html) : ``` "WebDriver.Chrome.driver" ``` * Error in the *Value* field : ``` "E:\\chromedriver.exe" ``` > > You have to pass the absolute path of the *WebDriver* through either of the following options : > > > + Escaping the back slash (`\\`) e.g. `"C:\\path\\to\\chromedriver.exe"` + Single forward slash (`/`) e.g. `"C:/path/to/chromedriver.exe"` Your code seems to be having two issues as follows : * First issue is in specifying the *Key* which instead of `"WebDriver.Chrome.driver"` should have been **`"webdriver.chrome.driver"`** as follows : ``` System.setProperty("webdriver.chrome.driver", "E:\\chromedriver.exe"); ``` * Second issue is in the *sequence* of mentioning the *Key* **`"webDriver.chrome.driver"`** in your program which should be before **`WebDriver driver = new ChromeDriver();`** as follows : ``` System.setProperty("WebDriver.Chrome.driver", "E:\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.google.com"); ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: I have seen many people are using wrong sequence. the sequence should be. 1. First set the property and then launch the browser System.setProperty("webdriver.chrome.driver", "F:/chrome/chromedriver.exe"); WebDriver driver = new ChromeDriver(); ``` driver.navigate().to("https://www.google.com"); ``` Upvotes: 0 <issue_comment>username_3: Download the chromedriver version corresponding to the chrome version in your system from <https://chromedriver.chromium.org/downloads> . Unzip the file and run the below code in the IDE. import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Selintroduction { ``` public static void main(String[] args) { //Invoking browser System.setProperty("webdriver.chrome.driver","C:\\Users\\HP\\Downloads\\chromedriver_win32\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); } ``` } (Path would depend on your file location in the PC.) Upvotes: 1 <issue_comment>username_4: I was facing the same error when my code was like so: ``` System.setProperty("webdriver.chrome.driver","C:\\Users\\abs\\chromedriver_win32.exe"); ``` It works after adding `"chromedriver"` before `".exe"` like so: ``` System.setProperty("webdriver.chrome.driver","C:\\Users\\abs\\chromedriver_win32\\chromedriver.exe"); ``` Upvotes: 0 <issue_comment>username_5: try to use WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); if the path is not working, please use latest selenium webdriver like 4.10 and use above code Upvotes: 0
2018/03/18
550
1,698
<issue_start>username_0: My id #kiwi doesn't seem to work. Could anyone explain me why it is not working? I've been searching for some help but couldn't find it. It doesn't even work when I try to class it too. ``` this is the title sucker #kiwi {background-color:green;} | Statistics | | --- | | Car model name | Vegetables | Delicious Fruits | | Jaguar | Tomato | Kiwi | | BMW | Potato | Apples | | AUDI | Cabbage | Watermelon | ```<issue_comment>username_1: In fact it does work. It is the matter of `div` content. Instead of ``` | Jaguar | Tomato | Kiwi | ``` Try for example: ``` | Jaguar | Tomato | Kiwi | ``` Upvotes: 0 <issue_comment>username_2: you should assign the id to `| | |` tag and not put it in a div This works: ``` this is the title sucker #kiwi {background-color:green;} | Statistics | | --- | | Car model name | Vegetables | Delicious Fruits | | Jaguar | Tomato | Kiwi | | BMW | Potato | Apples | | AUDI | Cabbage | Watermelon | ``` Upvotes: 1 <issue_comment>username_3: Edit: As it turns out, you can use a `div` inside a `tr` as well. So you can either place it inside the `td` tag, as shown below. Or if you want to color the whole row, you can put id on 'tr' itself, as suggested by others here. There are a few things there. First of all, you cannot put a directly inside a tag. You have to place it inside a `|` or `|` tag. See more here : [div inside table](https://stackoverflow.com/questions/2974573/div-inside-table) Also, you tag is opened before `| | |`, but closed after it, which is not correct. Always open and close tags in correct order. You can do something like this: ``` | Jaguar | Tomato | Kiwi | ``` Upvotes: 0
2018/03/18
1,037
4,291
<issue_start>username_0: I have the following unit test: ``` let apiService = FreeApiService(httpClient: httpClient) apiService.connect() {(status, error) in XCTAssertTrue(status) XCTAssertNil(error) } ``` The actual function looks like this: ``` typealias freeConnectCompleteClosure = ( _ status: Bool, _ error: ApiServiceError?)->Void class FreeApiService : FreeApiServiceProtocol { func connect(complete: @escaping freeConnectCompleteClosure) { ... case 200: print("200 OK") complete(true, nil) } } ``` This unit test is passing, but the problem is, if I forget the `complete(true, nil)` part, the test will still pass. I can't find a way to make my test fail by default if the closure isn't called. What am I missing?<issue_comment>username_1: You need to use an [`XCTTestExpectation`](https://developer.apple.com/documentation/xctest/xctestexpectation) for this. That will fail the test unless it is explicitly fulfilled. Create the expectation as part of your test method setup by calling [`expectation(description:)`](https://developer.apple.com/documentation/xctest/xctestcase/1500899-expectation) or one of the related methods. Inside the callback in your test, invoke `fulfill()` on the expectation. Finally, after your call to `connect()`, call one of `XCTestCase`'s "wait" methods, such as [`waitForExpectations(timeout:)`](https://developer.apple.com/documentation/xctest/xctestcase/1500748-waitforexpectations). If you forget to invoke the callback in your app code, the timeout will elapse and you will no longer have a false positive. A full example is given in Apple's ["Testing Asynchronous Operations with Expectations"](https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations/testing_asynchronous_operations_with_expectations) doc. Upvotes: 3 [selected_answer]<issue_comment>username_2: It looks like you are trying to write a test against FreeApiService. However, judging from the name (and the completion handler), FreeApiService makes a network call. This is something to avoid in unit tests, because the test no longer depends on just your code. It depends on * Having a reliable Internet connection * The back end being up * The back end responding before a given time-out * The back end issuing the expected response If you're willing to endure tests that are flaky (due to the dependencies above) and slow (due to network latency), then you can write an asynchronous test. It would look something like this: ``` func testConnect_ShouldCallCompletionHandlerWithTrueStatusAndNilError() { let apiService = FreeApiService(httpClient: httpClient) var capturedStatus: Bool? var capturedError: Error? let promise = expectation(description: "Completion handler invoked") apiService.connect() {(status, error) in capturedStatus = status capturedError = error promise.fulfill() } waitForExpectations(timeout: 5, handler: nil) XCTAssertTrue(capturedStatus ?? false, "status") XCTAssertNil(capturedError, "error") } ``` If the completion handler isn't called, `waitForExpectations` will time out after 5 seconds. The test will fail as a result. I avoid putting assertions inside completion handlers. Instead, as I describe in [A Design Pattern for Tests that Do Real Networking](https://qualitycoding.org/asynchronous-tests/), I recommend: * Capture arguments we want to test * Trigger the escape flag All assertions can then be performed outside of the completion handler. …But! I try to reserve asynchronous tests for acceptance tests of the back-end system itself. If you want to test your own code, the messy nature of asynchronous tests suggests that the design of the code under test is calling for improvements. A network call forms a clear boundary. We can test up to that boundary. And we can test anything that gets tossed back at us, but on our side of the boundary. In other words, we can test: * Is the network request formed correctly? But don't issue the request. * Are we handling network responses correctly? But simulate the responses. Reshaping the code to allow these tests would let us write tests that are fast and deterministic. They don't even need an Internet connection. Upvotes: 2
2018/03/18
1,211
5,261
<issue_start>username_0: I'm making a game similar to 'who wants to be a millionaire?' and I have a 'Next' button which takes the player to the next question. However, since I am allowing up to four players to play, I want this 'Next' button to disable after a maximum of 3 clicks, (or less if there is one/two/three players playing). Here is my code so far for the 'Next' button: ``` nextButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { StatusPage.setVisible(false); QuestionPage.setVisible(true); option1.setEnabled(true); option2.setEnabled(true); option3.setEnabled(true); option4.setEnabled(true); if (Player2JButton.isEnabled()){ counter = 1; } else if (Player3JButton.isEnabled()){ counter = 2; } else if (Player4JButton.isEnabled()){ counter = 3; } else { System.out.println("Error getting next question."); } if (generalKnowledge.isEnabled()){ currentQuest = quest.setQnA(option1, option2, option3, option4, question1, "generalKnowledge"); } else if (geography.isEnabled()){ currentQuest = quest.setQnA(option1, option2, option3, option4, question1, "geography"); } else if (hipHopMusic.isEnabled()){ currentQuest = quest.setQnA(option1, option2, option3, option4, question1, "hipHopMusic"); } else { System.out.println("Error getting next question."); } } }); ```<issue_comment>username_1: You need to use an [`XCTTestExpectation`](https://developer.apple.com/documentation/xctest/xctestexpectation) for this. That will fail the test unless it is explicitly fulfilled. Create the expectation as part of your test method setup by calling [`expectation(description:)`](https://developer.apple.com/documentation/xctest/xctestcase/1500899-expectation) or one of the related methods. Inside the callback in your test, invoke `fulfill()` on the expectation. Finally, after your call to `connect()`, call one of `XCTestCase`'s "wait" methods, such as [`waitForExpectations(timeout:)`](https://developer.apple.com/documentation/xctest/xctestcase/1500748-waitforexpectations). If you forget to invoke the callback in your app code, the timeout will elapse and you will no longer have a false positive. A full example is given in Apple's ["Testing Asynchronous Operations with Expectations"](https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations/testing_asynchronous_operations_with_expectations) doc. Upvotes: 3 [selected_answer]<issue_comment>username_2: It looks like you are trying to write a test against FreeApiService. However, judging from the name (and the completion handler), FreeApiService makes a network call. This is something to avoid in unit tests, because the test no longer depends on just your code. It depends on * Having a reliable Internet connection * The back end being up * The back end responding before a given time-out * The back end issuing the expected response If you're willing to endure tests that are flaky (due to the dependencies above) and slow (due to network latency), then you can write an asynchronous test. It would look something like this: ``` func testConnect_ShouldCallCompletionHandlerWithTrueStatusAndNilError() { let apiService = FreeApiService(httpClient: httpClient) var capturedStatus: Bool? var capturedError: Error? let promise = expectation(description: "Completion handler invoked") apiService.connect() {(status, error) in capturedStatus = status capturedError = error promise.fulfill() } waitForExpectations(timeout: 5, handler: nil) XCTAssertTrue(capturedStatus ?? false, "status") XCTAssertNil(capturedError, "error") } ``` If the completion handler isn't called, `waitForExpectations` will time out after 5 seconds. The test will fail as a result. I avoid putting assertions inside completion handlers. Instead, as I describe in [A Design Pattern for Tests that Do Real Networking](https://qualitycoding.org/asynchronous-tests/), I recommend: * Capture arguments we want to test * Trigger the escape flag All assertions can then be performed outside of the completion handler. …But! I try to reserve asynchronous tests for acceptance tests of the back-end system itself. If you want to test your own code, the messy nature of asynchronous tests suggests that the design of the code under test is calling for improvements. A network call forms a clear boundary. We can test up to that boundary. And we can test anything that gets tossed back at us, but on our side of the boundary. In other words, we can test: * Is the network request formed correctly? But don't issue the request. * Are we handling network responses correctly? But simulate the responses. Reshaping the code to allow these tests would let us write tests that are fast and deterministic. They don't even need an Internet connection. Upvotes: 2
2018/03/18
1,425
4,796
<issue_start>username_0: I'm new to Ruby, please bear with me if this is a stupid question, or if I'm not following the best practice. I'm finding an object in the DB using `find()`, and expect it to throw `RecordNotFound` in case the object of the id does not exist, like this. ``` begin event = Event.find(event_id) rescue ActiveRecord::RecordNotFound => e Rails.logger.debug "Event does not exist, id: " + event_id return { # return "unauthorized" to avoid testing existence of event id # (some redacted codes) } end ``` But somehow it is not caught (the log in the rescue block is not printed) and the entire program just return internal server error. Here's the stack trace: ``` Completed 500 Internal Server Error in 22ms (ActiveRecord: 1.0ms) ActiveRecord::RecordNotFound (Couldn't find Event with 'id'=999): lib/sync/create_update_event_handler.rb:78:in `handleRequest' app/controllers/sync_controller.rb:36:in `block in sync' app/controllers/sync_controller.rb:31:in `each' app/controllers/sync_controller.rb:31:in `sync' Rendering /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout Rendering /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.html.erb Rendered /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (6.4ms) Rendering /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb Rendered /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.3ms) Rendering /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb Rendered /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.9ms) Rendered /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (36.6ms) ``` The only thing I can think of is there are two different ActiveRecord::RecordNotFound, and I'm catching the wrong one, but I don't know if it is the case or how I can verify it. What did I do wrong? ====================================== **Update** The problem is in the rescue block, I was concatenating `event_id` (an integer) to a string. The `RecordNotFound` exception was indeed caught, but when the type error was thrown in the rescue block, the wrong error message was printed.<issue_comment>username_1: You won't get an error if you do ``` event = Event.find_by(id: event_id) ``` In this case if the record can't be found by ID it will just `event == nil` be nil. In this case if the record can't be found by ID it will just `event == nil` be nil. The code you pasted works fine for me. If you don't see output in the log, check your environment and log level settings INFO, WARN, DEBUG etc. 500 error indicates some kind of controller action raising the error. see [Set logging levels in Ruby on Rails](https://stackoverflow.com/questions/12180690/set-logging-levels-in-ruby-on-rails) To be sure your rescue block is executing try doing something besides log. If you're running a development server you can try : ``` begin event = Event.find(event_id) rescue ActiveRecord::RecordNotFound => e msg = "Event does not exist, id: #{event_id.to_s}" Rails.logger.debug msg. puts msg binding.pry # if you have gem 'pry' in your development gems. File.open('test.log', 'w') {|f| f.write msg} #check if this appears in root of your app return { # return "unauthorized" to avoid testing existence of event id # (some redacted codes) } end ``` UPDATE: I changed the string interpolation according to your answer. You can also call `.to_s` inside interpolation instead of closing quotes and appending. Upvotes: 2 <issue_comment>username_2: `@event = Event.find(params[:id])`. you should write instead `params[:id]` .That's the cause of an error. Upvotes: 0 <issue_comment>username_3: Turned out the error message is wrong. The problem is that I was concentating the `event_id` (an integer) to a string. But somehow Rails prints out the RecordNotFound exception. The problem is fixed by replacing `Rails.logger.debug "Event does not exist, id: " + event_id` with `Rails.logger.debug "Event does not exist, id: " + event_id.to_s` Thanks @username_1 for bringing my attention to the error message. Upvotes: 2 [selected_answer]
2018/03/18
879
2,653
<issue_start>username_0: I am not sure if the problem lies in my logic, or incorrect use of syntax :/ Gives the error "ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SET Answer = "Leap Year"; ELSE SET Answer = "Not a Leap Year";" ``` DELIMITER $$ DROP FUNCTION IF EXISTS f_Leap_Year; CREATE FUNCTION f_Leap_Year(ENTER_YEAR INT) RETURNS VARCHAR(30) BEGIN DECLARE Answer VARCHAR(30); DECLARE ENTER_YEAR INTEGER; If (Enter_Year % 400 = 0 OR (Enter_Year % 4 =0 and not Enter_Year % 100 = 0)) SET Answer = "Leap Year"; ELSE SET Answer = "Not a Leap Year"; RETURN Answer; END $$ ```<issue_comment>username_1: This is a redundant function. Here's why... ``` SET @year = '2016'; SELECT CASE WHEN DATE_FORMAT(CONCAT(@year,'-03-01') - INTERVAL 1 DAY,'%d') = 29 THEN 1 ELSE 0 END is_leap; +---------+ | is_leap | +---------+ | 1 | +---------+ ``` Upvotes: 2 <issue_comment>username_2: This answer is based on username_1's answer. it is also possible without using `- INTERVAL 1 DAY` because `DATE_FORMAT('2015-02-29', '%d')` will generate a NULL value when it is a invalid date. **Queries** ``` SET @year = '2015'; SELECT CASE WHEN DATE_FORMAT(CONCAT(@year, '-02-29'), "%d") IS NOT NULL THEN 1 ELSE 0 END is_leap; SET @year = '2016'; SELECT CASE WHEN DATE_FORMAT(CONCAT(@year, '-02-29'), "%d") IS NOT NULL THEN 1 ELSE 0 END is_leap; ``` **Results** ``` +---------+ | is_leap | +---------+ | 0 | +---------+ +---------+ | is_leap | +---------+ | 1 | +---------+ ``` **demo** <http://rextester.com/NQB35930> Upvotes: 1 <issue_comment>username_3: Thanks for your responses. In fact, I think the problem was that I was missing `THEN` from each of the `SET` statements, and a `DETERMINISTIC`; the code below worked. ``` DROP FUNCTION IF EXISTS LeapYear; CREATE FUNCTION LeapYear(EnterYear INT) RETURNS VARCHAR(30) DETERMINISTIC BEGIN DECLARE answer VARCHAR(35); IF (Enter_Year % 400 = 0 OR (Enter_Year % 4 =0 and not Enter_Year % 100 = 0)) THEN SET answer = 'Leap year'; ELSE SET answer = 'Not a leap year'; END IF; RETURN (answer); END ``` But now I have a new problem - while I can create the function and it shows up as existing within the database, when I try to use it, I get the following error: ``` MariaDB [my_dbname]> select leapyear(1976)$$ ERROR 1054 (42S22): Unknown column 'Enter_Year' in 'field list' ``` It seems to think I am trying to select a column rather than calling a function - does anyone know why this might be happening? Upvotes: 0
2018/03/18
929
2,958
<issue_start>username_0: I'm doing a C application that reads and parses data from a set of sensors and, according to the readings of the senors, it turns on or off actuators. For my application I will be using two threads, one to read and parse the data from the sensors and another one to act on the actuators. Obviously we may face the problem of one thread reading data from a certain variable while another one is trying to write on it. This is a sample code. ``` #include int sensor\_values; void\* reads\_from\_sensor(){ //writes on sensor\_values, while(1) loop } void\* turns\_on\_or\_off(){ //reads from sensor\_values, while(1) loop } int main(){ pthread\_t threads[2]; pthread\_create(&threads[1],NULL,reads\_from\_sensor,NULL); pthread\_create(&threads[2],NULL,turns\_on\_or\_off,NULL); //code continues after } ``` My question is how I can solve this issue, of a certain thread writing on a certain global variable while other thread is trying to read from it, at the same time. Thanks in advance.<issue_comment>username_1: This is a redundant function. Here's why... ``` SET @year = '2016'; SELECT CASE WHEN DATE_FORMAT(CONCAT(@year,'-03-01') - INTERVAL 1 DAY,'%d') = 29 THEN 1 ELSE 0 END is_leap; +---------+ | is_leap | +---------+ | 1 | +---------+ ``` Upvotes: 2 <issue_comment>username_2: This answer is based on username_1's answer. it is also possible without using `- INTERVAL 1 DAY` because `DATE_FORMAT('2015-02-29', '%d')` will generate a NULL value when it is a invalid date. **Queries** ``` SET @year = '2015'; SELECT CASE WHEN DATE_FORMAT(CONCAT(@year, '-02-29'), "%d") IS NOT NULL THEN 1 ELSE 0 END is_leap; SET @year = '2016'; SELECT CASE WHEN DATE_FORMAT(CONCAT(@year, '-02-29'), "%d") IS NOT NULL THEN 1 ELSE 0 END is_leap; ``` **Results** ``` +---------+ | is_leap | +---------+ | 0 | +---------+ +---------+ | is_leap | +---------+ | 1 | +---------+ ``` **demo** <http://rextester.com/NQB35930> Upvotes: 1 <issue_comment>username_3: Thanks for your responses. In fact, I think the problem was that I was missing `THEN` from each of the `SET` statements, and a `DETERMINISTIC`; the code below worked. ``` DROP FUNCTION IF EXISTS LeapYear; CREATE FUNCTION LeapYear(EnterYear INT) RETURNS VARCHAR(30) DETERMINISTIC BEGIN DECLARE answer VARCHAR(35); IF (Enter_Year % 400 = 0 OR (Enter_Year % 4 =0 and not Enter_Year % 100 = 0)) THEN SET answer = 'Leap year'; ELSE SET answer = 'Not a leap year'; END IF; RETURN (answer); END ``` But now I have a new problem - while I can create the function and it shows up as existing within the database, when I try to use it, I get the following error: ``` MariaDB [my_dbname]> select leapyear(1976)$$ ERROR 1054 (42S22): Unknown column 'Enter_Year' in 'field list' ``` It seems to think I am trying to select a column rather than calling a function - does anyone know why this might be happening? Upvotes: 0
2018/03/18
1,094
3,680
<issue_start>username_0: I am using a nRF52832 chip attached to a DW1000 module. The issue is when requesting data from the DW1000, the first byte is missing. The chip is supposed to send 0xDECA0130 but instead I receive 0xCA0130FF. When I make the receive buffer larger, the missing 0xDE shows up (the transmission starts with the lowest byte). My question is, how and why this is happening. Configuration ============= The SPI configuration was made according to the datasheet of the DW1000, using the nRF SPI driver. It includes * SPI Default Frequency set to 1MHz * SPI Chip Select Pin configured as active LOW * using SPI Mode 0 * MSB first transmission Before starting the communication, the DW1000 is reset by pulling its reset pin low and kept low for a long enough duration before releasing it. After resetting, the master waits some time to let the module boot up. After that, the first thing is reading said value as a 32 bit register value. nRF Settings ------------ The nRF settings include * SPI and SPI0 enabled * SPI0 easyDMA disabled * reading the value includes `nrf_drv_spi_transfer` with said configuration and a buffer lenght of 4 bytes Steps taken =========== I already tried the following things, without any solving of the problem: * Changing the SPI Frequency * Changing the SPI Mode\* * Increased waiting time after reset * Increased waiting time between transmissions * Changing MISO Pull-Up Configuration\* * Manual Chip Select (including Pull-Up Configuration\*) The steps indicated with (\*) I'm aware of that they should not resolve the problem. Unfortunately it is an embedded device, so I cannot access the CLK and MISO pins to hook up to an oscilloscope. I appreciate any input on the matter.<issue_comment>username_1: This is a redundant function. Here's why... ``` SET @year = '2016'; SELECT CASE WHEN DATE_FORMAT(CONCAT(@year,'-03-01') - INTERVAL 1 DAY,'%d') = 29 THEN 1 ELSE 0 END is_leap; +---------+ | is_leap | +---------+ | 1 | +---------+ ``` Upvotes: 2 <issue_comment>username_2: This answer is based on username_1's answer. it is also possible without using `- INTERVAL 1 DAY` because `DATE_FORMAT('2015-02-29', '%d')` will generate a NULL value when it is a invalid date. **Queries** ``` SET @year = '2015'; SELECT CASE WHEN DATE_FORMAT(CONCAT(@year, '-02-29'), "%d") IS NOT NULL THEN 1 ELSE 0 END is_leap; SET @year = '2016'; SELECT CASE WHEN DATE_FORMAT(CONCAT(@year, '-02-29'), "%d") IS NOT NULL THEN 1 ELSE 0 END is_leap; ``` **Results** ``` +---------+ | is_leap | +---------+ | 0 | +---------+ +---------+ | is_leap | +---------+ | 1 | +---------+ ``` **demo** <http://rextester.com/NQB35930> Upvotes: 1 <issue_comment>username_3: Thanks for your responses. In fact, I think the problem was that I was missing `THEN` from each of the `SET` statements, and a `DETERMINISTIC`; the code below worked. ``` DROP FUNCTION IF EXISTS LeapYear; CREATE FUNCTION LeapYear(EnterYear INT) RETURNS VARCHAR(30) DETERMINISTIC BEGIN DECLARE answer VARCHAR(35); IF (Enter_Year % 400 = 0 OR (Enter_Year % 4 =0 and not Enter_Year % 100 = 0)) THEN SET answer = 'Leap year'; ELSE SET answer = 'Not a leap year'; END IF; RETURN (answer); END ``` But now I have a new problem - while I can create the function and it shows up as existing within the database, when I try to use it, I get the following error: ``` MariaDB [my_dbname]> select leapyear(1976)$$ ERROR 1054 (42S22): Unknown column 'Enter_Year' in 'field list' ``` It seems to think I am trying to select a column rather than calling a function - does anyone know why this might be happening? Upvotes: 0
2018/03/18
529
1,981
<issue_start>username_0: I have 2 classes in Java. One is a Car class that consists of 5 variables. Among them I have a List equipment variable. Another class contains the list of the Car class objects: List carlist. My task is: I have to sort the list of car object, using Streams in Java based on the amount of the equipment items that the given car have. How do I do that? I tried to build a separate method to count the items on the list of the object - but then within the Comparator I can't place an Object as an argument of this method. Here's an excerpt of my code: ``` private int countEquipmentItems (Car s){ if (s == null){ return 0; } int countEquipment = 0; List a = s.getEquipment(); for (int i = 0; i ``` And I have tried to use this method within the Stream: ``` public void sortbyEquipment (List carList){ carList.stream() .sorted(Comparator.comparing(countEquipmentItems(Car s))); } } ``` I appreciate any help<issue_comment>username_1: You don't need that `countEquipmentItems` method to count the amount of equipment. Just use `car.getEquipment().size()`: ``` public void sortbyEquipment (List carList){ carList.stream() .sorted(Comparator.comparing(car -> car.getEquipment().size())) ... } ``` Of course, you can pass that `Comparator` directly to `Collections.sort()`, which will sort the list without having to create a `Stream`. Upvotes: 3 [selected_answer]<issue_comment>username_2: Your `countEquipmentItems` method is redundant and completely unnecessary. Another solution to what username_1 has provided would be to call the default `sort` method that is available for the `List` type. ``` carList.sort(Comparator.comparingInt(car -> car.getEquipment().size())); ``` or if you want the sorted items to be in a new collection then you can do: ``` List clonedList = new ArrayList<>(carList); // clone the carList clonedList.sort(Comparator.comparingInt(car -> car.getEquipment().size())); ``` Upvotes: 2
2018/03/18
456
1,611
<issue_start>username_0: I was trying to use `scanf` but when I run the code the code goes on forever. And when I stop the code I get > > [Done] exited with code=1 in 28.291 second > > > My question is what am I doing wrong? Here is the code I was trying to execute. My editor is VS code 1.21.0. ``` #include #include int main(){ char midInitial; printf("What is your middle initial? "); scanf(" %c", &midInitial); printf("Middle inital &c ", midInitial); } ```<issue_comment>username_1: int main(){ char midInitial; printf("What is your middle initial? "); scanf(" %c", &midInitial); printf("Middle inital %c ", midInitial); (see it should be %c) } Upvotes: 0 <issue_comment>username_2: The code does not *run forever*, it is waiting for the user to complete the input. Standard input is line buffered, so the user must type enter after the character for `scanf()` to process it. It will skip any white space characters, store the first non white space character into `midInitial` and return `1`. Another possible explanation is the environment you use does not support console input. Run your program from shell interpreter window in Windows. There is another problem: the format `"Middle inital &c "` is incorrect, use `%` for conversion specifiers. Here is a corrected version: ``` #include int main() { char midInitial; printf("What is your middle initial? "); if (scanf(" %c", &midInitial) == 1) { printf("Middle initial: %c\n", midInitial); } return 0; } ``` Upvotes: 1 <issue_comment>username_3: go to code-runner extention setting and make sure checked Upvotes: 1
2018/03/18
313
1,238
<issue_start>username_0: My activity's current layout: ``` xml version="1.0" encoding="utf-8"? ``` So it is essentially just a toolbar and a FrameLayout (which is a container thats populated by Fragments). Because of this, every fragment ends up having this toolbar, which I only want in the `MainActivity`. How do I get around this? Some Fragments have their own toolbar, but because only the `FrameLayout` in the activity gets replaced by the fragment's layout, the activity's toolbar is always there. If I give a fragment it's own toolbar, the activity's toolbar will still be displayed above the fragment's toolbar - I want it to replace the toolbar instead. In my AndroidManifest I've set my theme to be `NoActionBar`. Appreciate any help!<issue_comment>username_1: In your `first` fragment in `onViewCreated(..)` use this :- ``` if (getActivity()!=null) getActivity().findViewById(R.id.main_toolbar).setVisibility(View.GONE); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: if you do not need toolbar in activity. Delete this code from your layout : ``` ``` Upvotes: -1 <issue_comment>username_2: if you do not need toolbar in your activity. Delete this code from your layout ``` ``` Upvotes: -1
2018/03/18
4,282
14,025
<issue_start>username_0: I'm trying to create a horizontal timeline but I'm not sure the best way to go about arranging the events divs correctly. At the moment it looks like this: ``` • Entry 1 • Entry 2 • Entry 3 • Entry 4 ``` [![enter image description here](https://i.stack.imgur.com/yeN5b.png)](https://i.stack.imgur.com/yeN5b.png) I'm trying to make `Entry 4` position itself at the top (as there are no divs in the way) but I'm not sure the best solution. It also needs to allow for any number of events overlapping. [![enter image description here](https://i.stack.imgur.com/4eCCK.png)](https://i.stack.imgur.com/4eCCK.png) Most css options / jQuery plugins don't seem to offer a solution as far as I'm aware they are mostly for flexible grids but this only needs to be flexible vertically and have fixed positions horizontally to line up correctly with the dates. An obvious first step is to `position: absolute` and set a `top: x` but how would one go about checking previous entries to make sure it's not overlapping an older & longer entry. The timeline will hold quite a number of events with various lengths so it can't be too intensive either. Any suggestions for the best/easiest way to do this?<issue_comment>username_1: I think this cannot be done with only CSS, so we need to rely on some JS/jQuery. My idea is to only set the left property within the element, then I loop through all the element to define the top value. I start by setting top to 0 and check if there is already an element in that position. If not: I place it there and move to next element. if yes: I increase the top value and check again. I continue until I find a place. Here a simplified code where I set a random value to left and apply the logic described above. ```js $('.event').each(function(){ var top=0; var left = Math.floor(Math.random() *(400)); /* we need to test between left and left+ width of element*/ var e1 = document.elementFromPoint(left, top); var e2 = document.elementFromPoint(left+80, top); /* we check only placed element to avoid cycle*/ while ((e1 && e1.classList.contains('placed')) || (e2 && e2.classList.contains('placed'))) { top += 20; /*Height of an element*/ e1 = document.elementFromPoint(left, top) e2 = document.elementFromPoint(left+80, top) } $(this).css({top:top, // we set the top value left:left, // we set the left value zIndex:3// we increase z-index because elementFromPoint consider the topmost element }); $(this).addClass('placed'); //we mark the element as placed }); ``` ```css * { box-sizing: border-box; } body { margin:0; } #events { height: 300px; width:calc(80px * 6 + 2px); background:repeating-linear-gradient(to right,blue 0,blue 2px,transparent 2px,transparent 80px); position:relative; } .event { position: absolute; width: 80px; height: 20px; border: 1px solid #000; z-index:2; background:red; color:#fff; } ``` ```html • Entry 1 • Entry 2 • Entry 3 • Entry 4 • Entry 5 • Entry 6 • Entry 7 • Entry 8 ``` Upvotes: 1 <issue_comment>username_2: I suppose you have an events array with start and end dates, then you should check whether events are overlapping by start and end dates. To simulate this, you can check this method: ```js var events = [{ start: "2018/10/24 15:00", end: "2018/10/24 18:00" }, { start: "2018/10/25 12:00", end: "2018/10/26 12:00" }, { start: "2018/10/25 07:00", end: "2018/10/25 10:00" }, { start: "2018/10/24 12:00", end: "2018/10/24 20:00" }, { start: "2018/10/25 08:00", end: "2018/10/25 13:00" }]; var stack = [], s = 0, lastStartDate, lastEndDate, newEvents; events.sort(function(a,b){ if(a.start > b.start) return 1; if(a.start < b.start) return -1; return 0; }); while (events.length > 0) { stack[s] = []; newEvents = []; stack[s].push(events[0]); lastStartDate = events[0].start; lastEndDate = events[0].end; for (var i = 1; i < events.length; i++) { if (events[i].end < lastStartDate) { stack[s].push(events[i]); lastStartDate = events[i].start; delete events[i]; } else if (events[i].start > lastEndDate) { stack[s].push(events[i]); lastEndDate = events[i].end; }else{ newEvents.push(events[i]); } } events = newEvents; s++; } console.log(stack); ``` This method picks the first event as the key and checks for other events whether they overlap or not, if they don't overlap, they will be added to the first stack, then if there are any events left, a new stack will be created and then with the remaining events, the code will be run again and a new stack will be prepared again. Until there are any events left in the array, it should continue creating stacks. Then you can use these stacks to build your events grid. One stack per line. I used this algorithm in my [Evendar](http://preview.codecanyon.net/item/evendar-event-calendarpicker/full_screen_preview/19985423?_ga=2.235058369.1373800416.1522650235-1286415805.1516947806) plugin. You can check it's grid view. Upvotes: 2 <issue_comment>username_3: You can get something of that effect with just `display: grid`. Though you will need to be mindful of the order you create the divs. ```js var grid = document.getElementById("grid") for (let i = 0; i <= 9; i++) { let div = document.createElement("div"); div.innerHTML = i grid.append(div); } let div div = document.createElement("div"); div.innerHTML = "Entry 1"; div.style.gridColumn = 1 grid.append(div) div = document.createElement("div"); div.innerHTML = "Entry 4"; div.style.gridColumn = 10 grid.append(div) div = document.createElement("div"); div.innerHTML = "Entry 2"; div.style.gridColumn = 1 grid.append(div) div = document.createElement("div"); div.innerHTML = "Entry 3"; div.style.gridColumn = 2 grid.append(div) ``` ```css #grid { display: grid; grid-template-columns: repeat(10, 1fr); } ``` ```html ``` Upvotes: 0 <issue_comment>username_4: grid display has a mode, [auto-flow : dense](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow), that can do what you want. In the following example, I have divided every visible column in 4 subcolumns, to allow to set positions in quartes of an hour . Then, I have classes to set the beginning and end of the events. Of course, you could inject the styles inline and get the same result: ```css .grid { margin: 10px; width: 525px; border: solid 1px black; display: grid; grid-template-columns: repeat(24, 20px); grid-auto-flow: dense; grid-gap: 2px; } .head { grid-column: span 4; background-color: lightblue; border: solid 1px blue; } .elem { background-color: lightgreen; } .start1 { grid-column-start: 1; } .start2 { grid-column-start: 2; } .start3 { grid-column-start: 3; } .start4 { grid-column-start: 4; } .start5 { grid-column-start: 5; } .start6 { grid-column-start: 6; } .end2 { grid-column-end: 3; } .end3 { grid-column-end: 4; } .end4 { grid-column-end: 5; } .end5 { grid-column-end: 6; } .end6 { grid-column-end: 7; } ``` ```html 1 2 3 4 5 6 A B C D E F G H ``` **UPDATE** In addition to inline style, You can also rely on CSS variables in order to easily manage the grid with less of code: ```css .grid { margin: 10px; width: 525px; border: solid 1px black; display: grid; grid-template-columns: repeat(24, 20px); grid-auto-flow: dense; grid-gap: 2px; } .head { grid-column: span 4; background-color: lightblue; border: solid 1px blue; } .elem { background-color: lightgreen; grid-column-start: var(--s, 1); grid-column-end: var(--e, 1); } ``` ```html 1 2 3 4 5 6 A B C D E F G H ``` Upvotes: 2 <issue_comment>username_5: Next is an example of how I would go about it, I have populated events' starting/ending points with random values along a 12h time line. Since the values are random, they might be a little *rough around the edges* sometimes ;). Also I assumed two events, A and B, can have the same *top* if, for instance, A ends at exactly the same time as B or vice versa. I have commented the code as much as I thought necessary to explain the proceedings. Hope it helps ```js $(document).ready(function() { var timeline = $('#time-line'); for (var i = 0; i < 12; i++) timeline.append('' + (i + 1) + '') /*to check event overlapping later*/ var eventData = []; /*generate random amount of events*/ var eventCount = Math.random() * 10 + 1; var eventsContainer = $('#events'); var total = 720; //12h * 60min in the example for (var i = 0; i < eventCount; i++) { var start = Math.floor(Math.random() * total); var end = Math.floor(Math.random() * (total - start)) + start; var duration = end - start; var event = $('E' + i + '(' + duration + ' min.' + ')'); event.attr('title', 'Start: ' + Math.floor(start / 60) + ':' + (start % 60) + ' | ' + 'End: ' + Math.floor(end / 60) + ':' + (end % 60)); event.css('width', (duration * 100 / 720) + "%"); event.css('left', (start * 100 / 720) + "%"); var top = getTop(start, end); event.css('top', top); /*store this event's data to use it to set next events' top property in getTop()*/ eventsContainer.append(event); eventData.push([start, end, top, event.height() + 1]); //the +1 is to compensate for the 1px-wide border } /** * Get the event's top property by going through the previous events and * getting the 'lowest' yet * * @param {Number} start * @param {Number} end * @returns {Number} */ function getTop(start, end) { var top = 0; /*for each previous event check for vertical collisions with current event*/ $.each(eventData, function(i, data /*[start, end, top]*/) { if (data[2] + data[3] > top //if it's height + top is not the largest yet, skip it //if any of the next 6 conditions is met, we have a vertical collision //feel free to optimize but tread carefully && (data[0] >= start && data[0] < end || data[0] < start && data[1] >= end || data[0] < start && data[1] > start || data[0] < end && data[1] >= end || data[0] >= start && data[1] < end || data[0] <= start && data[1] > start)) { top = data[2] + data[3]; } }); return top; } }); ``` ```css #time-line { width: 100%; text-align: center } #time-line div { display: inline-block; width: calc(100% / 12); //12h for the example text-align: right; background: lightgray; } #time-line div:nth-child(odd) { background: gray } #events { position: relative } #events .event{ position: absolute; background: lightblue; text-align: center; border: 1px solid black } ``` ```html ``` Upvotes: 0 <issue_comment>username_6: Here's a relatively simple function which can be applied to the HTML markup you have. I have hardcoded the height (`28px`) but the width of the event elements can be variable. The end result is something like this: [![enter image description here](https://i.stack.imgur.com/E9nf0.png)](https://i.stack.imgur.com/E9nf0.png) A few requirements for this solution to work: * The `left` property needs to be defined in the HTML markup of each event (as in your example), like: ``` • Entry 1 ``` * The events need to be in order, with each event element's `left` property equal to, or greater, than the previous element's `left` property **`arrangeEvents()`** Accepts a selector for the event elements as an argument, then loops through them and applies a `top` property as needed depending on the end of the longest previous event and start of the current event. In short, if the start time of the current event is less than the end of a previous event, the current event is positioned below the previous events. If the start of the current event is greater than the end of the previous events, the current event is positioned at the top. ```js const arrangeEvents = (els) => { let offset = 1; let end = 0; Array.from(els).forEach((event, index) => { const posLeft = parseInt(event.style.left); offset = posLeft >= end ? 0 : ++offset; end = Math.max(end, posLeft + event.offsetWidth); event.style.top = `-${28 * (index - offset)}px`; }); } arrangeEvents(document.querySelectorAll('.event')); ``` ```css #events { position: relative; } .event { display: inline-block; float: left; clear: both; border: 1px solid lightgray; padding: 4px; height: 28px; box-sizing: border-box; } ``` ```html • Entry 1 • Entry 2 • #3 • A Really Long Entry 4 • Entry5 • And Even Longer Entry 6 • #7 • Entry 8 • Entry 9 • Long Entry 10 • Entry 11 • Entry 12 • Entry 13 ``` Upvotes: 0
2018/03/18
1,882
8,363
<issue_start>username_0: So i was playing around in java once again and while doing so, i ran into an interesting problem. I was trying to write my self a little registration service. If an object of a certain type is instantiated via its constructor it would retrieve an id from my registration service and is added to the services list of objects. Here is an example object ``` public class Test { private final Long id; public Test() { this.id = TestRegistration.register(this); throw new IllegalAccessError(); } public Long getId() { return this.id; } } ``` And here is an example service ``` public class TestRegistration { private final static Map registration = new HashMap<>(); protected final static long register(final Test pTest) { if (pTest.getId() != null) { throw new IllegalStateException(); } long freeId = 0; while (registration.containsKey(freeId)) { freeId = freeId + 1; } registration.put(freeId, pTest); return freeId; } protected final static Test get(final long pId) { return registration.get(pId); } } ``` Now as you can see, the constructor of my class `Test` can't successfully execute at all since it always throws an `IllegalAccessError`. But the method `register(...)` of my `TestRegistration` class is called in the constructor before this error is thrown. And inside this method it is added to the registrations `Map`. So if i would run for example this code ``` public static void main(final String[] args) { try { final Test t = new Test(); } catch (final IllegalAccessError e) { } final Test t2 = TestRegistration.get(0); System.out.println(t2); } ``` My `TestRegistration` does in fact contain the object created when the constructor of my `Test` class was called and i can (here using variable `t2`) access it, even tho it wasn't successfully created in the first place. **My question is, can i somehow detect from within my TestRegistration class if the constructor of Test was executed successfully without any exceptions or other interruptions?** And before you ask why i throw this exception in the first place here is my answer. Test may have potential subclasses i don't know of yet but still will be registered in my TestRegistration class. But since i don't have influence on the structure of those subclasses i can't tell if their constructor will throw an exception or not.<issue_comment>username_1: Weather or not the constructor comples does not influence whether or not the object is created. All instance variables will be created the super() will still be called and memory will still be allocated. In reality the exception will always be thrown, every object in your registration service will have thrown an exception. As children will have to call super() in order to be registered and following registration an exception is thrown. Upvotes: 0 <issue_comment>username_2: **It does not *appear* to be possible.** I've included the best I can gather from the JLS below. As can be seen from that, the execution of the body of the constructor is the very last step in the creation of an object. Thus I don't see any evidence to suggest that raising an exception would result in anything *not* happening which you could've checked to see whether the execution was successful (apart from the rest of the body of the constructor, obviously). This may not seem particularly convincing, although I'm not convinced that you'd find anything more concrete than this (it is, after all, notoriously difficult to prove that something doesn't exist). --- I would recommend putting the logic that modifies external data somewhere else. It wouldn't be entirely unreasonable to require that a `register` method (either in the TestRegistration class, or in the object itself) be explicitly called after construction of an object. It could also work to, instead of calling the constructors directly, have a class containing methods to return objects (which sounds a lot like the *Factory Design Pattern*), where you can then put this external modification logic. --- From the JLS: > > [15.9.4. Run-Time Evaluation of Class Instance Creation Expressions](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.9.4) > ---------------------------------------------------------------------------------------------------------------------------------------------- > > > At run time, evaluation of a class instance creation expression is as follows. > > > First, if the class instance creation expression is a qualified class instance creation expression, the qualifying primary expression is evaluated. If the qualifying expression evaluates to null, a NullPointerException is raised, and the class instance creation expression completes abruptly. If the qualifying expression completes abruptly, the class instance creation expression completes abruptly for the same reason. > > > Next, space is allocated for the new class instance. If there is insufficient space to allocate the object, evaluation of the class instance creation expression completes abruptly by throwing an OutOfMemoryError. > > > The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value (§4.12.5). > > > Next, the actual arguments to the constructor are evaluated, left-to-right. If any of the argument evaluations completes abruptly, any argument expressions to its right are not evaluated, and the class instance creation expression completes abruptly for the same reason. > > > **Next, the selected constructor of the specified class type is invoked.** This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (§8.8) and is specified in detail in §12.5. > > > The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created. > > > --- > > [12.5. Creation of New Class Instances](https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.5) > --------------------------------------------------------------------------------------------------------------- > > > ... > > > Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure: > > > 1. Assign the arguments for the constructor to newly created parameter variables for this constructor invocation. > 2. If this constructor begins with an explicit constructor invocation (§8.8.7.1) of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5. > 3. This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4. > 4. Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5. > 5. **Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.** > > > Upvotes: 2 [selected_answer]
2018/03/18
776
3,023
<issue_start>username_0: I am rendering local web content on a `WKWebView` using a local server of `GCDWebServer`, but I have a cross-origin request due to cookies sitting in the backend. how could I configure a proxy that will solve this problem. NOTE: I have try'd to implement something on GitHub called `CorsProxy` but it's outdated and frankly doesn't solve my problem, creating a proxy. I have come across answers addressing a similar problem, however I am running my webView on a GCDWebServer and I don't know how to create such a proxy on this particular local server? Any help? Here's my code: ``` class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler { var wkWebView: WKWebView! var webServer = GCDWebServer() var contentController = WKUserContentController() func initWebServer() { let folderPath = Bundle.main.path(forResource: "www", ofType: nil) webServer.addGETHandler(forBasePath: "/", directoryPath: folderPath!, indexFilename: "index.html", cacheAge: 0, allowRangeRequests: true) webServer.start(withPort: 8080, bonjourName: "GCD Web Server") } public override func viewDidLoad() { super.viewDidLoad() initWebServer() let userScript = WKUserScript(source: "helloMsg2(\"boooo hoo hoo hoooo\")", injectionTime: .atDocumentEnd, forMainFrameOnly: true) contentController.addUserScript(userScript) contentController.add(self, name: "callback") let config = WKWebViewConfiguration() config.userContentController = contentController wkWebView = WKWebView(frame: view.bounds, configuration: config) wkWebView.scrollView.bounces = false wkWebView.uiDelegate = self wkWebView.navigationDelegate = self view.addSubview(wkWebView!) wkWebView.load(URLRequest(url: webServer.serverURL!)) } func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if message.name == "callback" { print("message from javaScript is: \(message.body)") } else { print("message from javaScript is: \(message.body)") } } } ```<issue_comment>username_1: This may help [support CORS](https://github.com/swisspol/GCDWebServer/issues/306). Just add `Access-Control-Allow-Origin: *` into the response headers. Upvotes: 0 <issue_comment>username_2: You will need to roll your own implementation of `-addGETHandlerForBasePath...`to add the `Access-Control-Allow-Origin: *` header since this API doesn't allow customization of the headers. See the source code in <https://github.com/swisspol/GCDWebServer/blob/master/GCDWebServer/Core/GCDWebServer.m#L1015>. Upvotes: 1 <issue_comment>username_3: Just do: ``` GCDWebServerResponse * yourResponse = [GCDWebServerResponse new]; [yourResponse setValue:@"*" forAdditionalHeader:@"Access-Control-Allow-Origin"]; ``` Upvotes: 0
2018/03/18
282
985
<issue_start>username_0: How could I transform a number with commas like 123,245 to a number without commas like this 123245, I know that you could already put commas in number without them but how to do that in reverse? pure JAVASCRIPT please!<issue_comment>username_1: This may help [support CORS](https://github.com/swisspol/GCDWebServer/issues/306). Just add `Access-Control-Allow-Origin: *` into the response headers. Upvotes: 0 <issue_comment>username_2: You will need to roll your own implementation of `-addGETHandlerForBasePath...`to add the `Access-Control-Allow-Origin: *` header since this API doesn't allow customization of the headers. See the source code in <https://github.com/swisspol/GCDWebServer/blob/master/GCDWebServer/Core/GCDWebServer.m#L1015>. Upvotes: 1 <issue_comment>username_3: Just do: ``` GCDWebServerResponse * yourResponse = [GCDWebServerResponse new]; [yourResponse setValue:@"*" forAdditionalHeader:@"Access-Control-Allow-Origin"]; ``` Upvotes: 0
2018/03/18
749
2,791
<issue_start>username_0: Suppose I had this layout below: ``` class Navigation extends React.Component { primaryFun() { console.log('funn') } secondaryFun() { this.primaryFun(); } } ``` I'd of expected this to then call primary but instead I get an undefined, Ok. So I thought I'd add a constructor to bind the function to this: ``` constructor(props) { super(props) this.primaryFun = this.primaryFun.bind(this); } ``` but primary fun is still undefined. In my real project I'm calling these on a mouseOut event. Feels like the above should work and tbh the documentation for React is all over the shot so couldn't find much here.<issue_comment>username_1: You also need to bind the `secondaryFun` function to use `this` inside that. Without that, the `this` inside the function `secondaryFun` will refers to the function scope which is `secondaryFun` Upvotes: 2 <issue_comment>username_2: Are you looking for something like this calling one function inside the other ```js import React, { Component } from 'react'; import './App.css' class App extends Component { constructor(){ super() this.mouseClick = this.mouseClick.bind(this); this.primaryFun = this.primaryFun.bind(this); this.secondaryFun = this.secondaryFun.bind(this); } primaryFun(){ console.log('primaryFun funn') } secondaryFun(){ console.log('secondaryFun funn') this.primaryFun() } mouseClick(){ this.secondaryFun() } render() { return ( Hello World! ); } } export default App; ``` Here when you click on "Hello world" **secondaryFun** is called and inside **secondaryFun** , **primaryFun** is been triggered Upvotes: 4 [selected_answer]<issue_comment>username_3: Make sure both functions have the correct `this` scope. If you are using class properties, see <https://babeljs.io/docs/plugins/transform-class-properties/>. Which already present on the babel-preset-react-app used by create-react-app, you can use that and write those as arrow functions, as seen on the babel link. And avoid having to use `.bind` on the constructor. Upvotes: 0 <issue_comment>username_4: You need to bind this in your mouseOut ``` onMouseOut={this.secondaryFun.bind(this)} ``` Or a as best practice use the Lambda syntax. It'll bind this for you ``` onMouseOut={()=>this.secondaryFun()} ``` Upvotes: 2 <issue_comment>username_5: You must bind() both two functions. You should that: ``` class Navigation extends React.Component { constructor(props) { super(props) this.primaryFun = this.primaryFun.bind(this); this.secondaryFun = this.secondaryFun.bind(this); } primaryFun() { console.log('funn') } secondaryFun() { this.primaryFun(); } } ``` Upvotes: 0
2018/03/18
1,029
3,434
<issue_start>username_0: I got Twitter and Google login with Django all-auth. Having issues with Facebook now. Tried every single combination between localhost/127.0.0.1/etc (also went extreme routes by changing my hosts to local.domain.com - even got an SSL thing going as Facebook apparently blocks http access (since March 2018). Got this far... now I get this error Can anyone lead me into the right direction? I'm about to pull my hair out. > > > ``` > KeyError at /accounts/facebook/login/token/ 'access_token' Request Method: POST Request > > ``` > > URL: <https://localhost:8000/accounts/facebook/login/token/> Django > Version: 2.0.3 Exception Type: KeyError Exception Value: > > 'access\_token' > > > ``` {'error': {'code': 5, 'fbtrace_id': 'Bs4PHOvc+rZ', 'message': "This IP can't make requests for that application.", 'type': 'OAuthException'}} ``` Addition details: <http://localhost:8000/accounts/facebook/login/callback> ``` SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'js_sdk', 'SCOPE': ['email', 'public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time', ], 'LOCALE_FUNC': lambda request: 'en_GB', 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': False, 'VERSION': 'v2.5', } } ```<issue_comment>username_1: Django 1.4.15, django-allauth 0.18.0, Facebook upgrade API v2.8 Since Mars 2018, Facebook sets "Use Strict Mode for Redirect URls" YES by default. My problem was in the Facebook App configuration, not in django-allauth. Working again App settings: **Settings Basic** - App Domains: "AnySite.com" - Privacy policy URL: "<https://AnySite.com/myprivacy/>" - Website: "<https://AnySite.com/>" **Settings Advanced** - Server IP Whitelist: let it blank - Domain Manager: let it blank **Facebook login Settings** Yes Client OAuth Login Yes Web OAuth Login Yes (new: forced) Use strict Mode for redicect URLs Yes Embeded Browser OAuth Login Yes Enforce HTTPS Valid OAuth Redirect URLs: "**<https://AnySite.com/accounts/facebook/login/callback/>**" (mandatory) Hope it helps. Upvotes: 3 [selected_answer]<issue_comment>username_2: Update in case anyone else is struggling with this in 2020: In facebook developers: 1. create a test app from your main app 2. settings -> basic, add localhost and 127.0.0.1 to app domains. set site url to https://localhost:8000 3. Products -> facebook login -> settings. client, wen login enabled. Embedded Browser OAuth Login enabled. Add all of these into Valid OAuth Redirect URIs: <https://127.0.0.1:8000/> <https://127.0.0.1:8000/accounts/facebook/login/callback> https://localhost:8000/ https://localhost:8000/accounts/facebook/login/callback In django: 1. `pip install django-sslserver` 2. add sslserver to INSTALLED\_APPS 3. `python manage.py runsslserver` In admin: 1. Create 2 sites, <https://127.0.0.1:8000/> and https://localhost:8000/ 2. Add a social application, facebook, add in your test app id and key. Register the 2 sites above into it. Upvotes: 1
2018/03/18
699
2,282
<issue_start>username_0: striving to make jquery and li working in this context: ``` ### Statistics * Stat 1 * Stat 2 ``` s ``` $(function() { $("#statLateralMenu li").click(function() { alert( "A" ); $("#statLateralMenu li").removeClass("selected"); $(this).addClass("selected"); }); } ); ``` I am pretty sure the error is very stupid also because I've already implemented this code in another area of my page and it works perfectly, but this time really I can't make it working. Any clue please? **EDIT:** I am not able even to fire the alert, my problem is not (yet) to change the class's `li`. JQuery is loaded as in the same page I have another ul/li complex and it works perfectly **EDIT 2:** At this point maybe I am messing up a bit, but using my code here it doesn't work as well: <https://jsfiddle.net/nakjyyaj/4/><issue_comment>username_1: try to change `$("#statLateralMenu li").removeClass("selected");` to ``` $(this).removeClass("selected"); ``` like that ``` $(function() { $("#statLateralMenu li").click(function() { alert( "A" ); $(this).removeClass("selected"); $(this).addClass("selected"); }); } ); ``` but if you want only to change design elements you can use **:hover** ``` li:hover { background-color: yellow; } ``` Upvotes: 0 <issue_comment>username_2: It seems to work : ```js $(function() { $("li").click(function() { $("li").removeClass("selected"); $(this).addClass("selected"); }); }); ``` ```css .selected{background:yellow} ``` ```html * azerty * bzerty * czerty ``` To deal with dynamic content you can use event delegation : ```js $(function() { $("ul").on("click", "li", function() { $("li").removeClass("selected"); $(this).addClass("selected"); }); }); setTimeout(function () { $("p").remove(); $("ul").html("" + "- azerty " + "- bzerty " + "- czerty " ); }, 1000); ``` ```css .selected{background:yellow} ``` ```html Wait 1 second. ``` Further reading : <https://stackoverflow.com/a/46251110/1636522>. Upvotes: 3 [selected_answer]<issue_comment>username_3: In your JSFiddle, you forgot to load JQuery framework. You don't need script tag in JSFiddle (no need and ). Upvotes: 0
2018/03/18
1,601
6,137
<issue_start>username_0: My main objective is to conditionally render a "Create profile" button if the user does not have a profile in firebase, or an "Edit profile" button if the user has a profile. I am not having issues rendering the edit profile button. I am checking if the user has a profile by comparing the auth users "uid" with the profile's "uid." If they match, then the edit button will render. My problem is that, when the edit button renders, the create button still appears as well, but it should disappear since I am conditionally rendering the two. What am I missing here? > > EDIT 3/23/2018 > -------------- > > > I've figured out the problem but I still don't have a solution. The problem is that the map function is looping through the 'Profiles' array and is looking for a 'uid' equal to to the logged in users 'uid'. But if the 'uid' doesn't match the logged in users 'uid,' the create button will still render since there are other profiles in the 'Profiles' array which have uid's not equal to the logged in users 'uid.' So i guess my other question would be, how can I check if a logged in user does not have data in an array and/or Firebase db? -------------------------------------------------------------------------------------- Here's my code: I have database named 'Profiles' which I am pulling information from. ``` "Profiles" : { "-L7p-wZNcvgBBTkvmn7I" : { "about" : "I'm a full stack web developer with many skills", "email" : "<EMAIL>", "frameworkOne" : "react", "frameworkThree" : "bootstrap", "frameworkTwo" : "javascript", "name" : "<NAME>", "projectInfo" : "You're on it!", "projectLink" : "https://hiremoredevs.com", "projectName" : "HireMoreDevs", "uid" : "ABCDEFG1234567" } ``` } The react component: ``` class ProfileButtonToggle extends Component { constructor(props){ super(props); this.state = { authUser:null, Profiles:[] } } componentDidMount(){ const profilesRef = firebase.database().ref('Profiles'); profilesRef.once('value', (snapshot) => { let Profiles = snapshot.val(); let newState = []; for (let profile in Profiles){ newState.push({ id: profile, uid:Profiles[profile].uid, }); } this.setState({ Profiles: newState }); }); firebase.auth().onAuthStateChanged((authUser) => { if (authUser) { this.setState({ authUser }); } }); } render() { return ( {this.state.authUser ? {this.state.Profiles.map((profile) => { return( {profile.uid === this.state.authUser.uid ? Edit Profile : Create Profile } ); })} : null } ); } } export default ProfileButtonToggle; ```<issue_comment>username_1: After weeks of hair pulling, I've finally figured out a solution. It turns out I don't even need a 'create' button. ***componentDidUpdate*** fires after the DOM is rendered which is exaclty what I needed. I then check if a child of '*Profiles*' has a **uid** equal to the logged in users **uid**, if not ***push()*** that current users **uid** to '*Profiles*' and reload the page. And it actually worked! In other words, it will automatically create a Profile, if one does not exist for this user. ``` componentDidUpdate() { firebase.database().ref("Profiles").orderByChild("uid").equalTo(this.state.authUser.uid).once("value",snapshot => { const userData = snapshot.val(); if (userData){ console.log("exists!"); } else { const profilesRef = firebase.database().ref('Profiles'); const Profiles = { uid: this.state.authUser.uid } profilesRef.push(Profiles); window.location.reload(); } }); } ``` I changed my conditional render to this: ``` {this.state.authUser ? {this.state.Profiles.map((profile) => { return( {profile.uid === this.state.authUser.uid ? Edit Profile : null } ); })} : null } ``` After the page reloaded the edit button rendered as expected. The full component ================== ``` class ProfileButtonToggle extends Component { constructor(props){ super(props); this.state = { authUser:null, Profiles:[], } } componentDidMount(){ const profilesRef = firebase.database().ref('Profiles'); profilesRef.once('value', (snapshot) => { let Profiles = snapshot.val(); let newState = []; for (let profile in Profiles){ newState.push({ id: profile, uid:Profiles[profile].uid, }); } this.setState({ Profiles: newState }); }); firebase.auth().onAuthStateChanged((authUser) => { if (authUser) { this.setState({ authUser }); } }); } componentDidUpdate() { firebase.database().ref("Profiles").orderByChild("uid").equalTo(this.state.authUser.uid).once("value",snapshot => { const userData = snapshot.val(); if (userData){ console.log("exists!"); } else { const profilesRef = firebase.database().ref('Profiles'); const Profiles = { uid: this.state.authUser.uid } profilesRef.push(Profiles); window.location.reload(); } }); } render() { return ( {this.state.authUser ? {this.state.Profiles.map((profile) => { return( {profile.uid === this.state.authUser.uid ? Edit Profile : null } ); })} : null } ); } } export default ProfileButtonToggle; ``` Upvotes: 2 <issue_comment>username_2: Just a quick tip, your conditional render could use the `&&` logical operator since it doesn't return anything in the else part of the ternary operator ``` {this.state.authUser && {this.state.Profiles.map((profile) => { return( {profile.uid === this.state.authUser.uid ? Edit Profile : null } ); })} } ``` So It would render either the items after the `&&` or null if `this.state.authUser` is unavailable Upvotes: 1
2018/03/18
836
2,390
<issue_start>username_0: I need the textarea to stretch across the width of the web page. Here's what the developer tools Source in Chromes gives. ``` Musak [Application name](/) * [Home](/) * [API](/Help) Musak ----- textarea { width: 800px; height: 100px; background-color: black; font-size: 1em; font-weight: bold; font-family: Verdana, Arial, Helvetica, sans-serif; border: 1px solid black; color: green; } Enter command ------------- --- © 2018 - My ASP.NET Application var uriDump = 'api/dump'; var uriKey = 'api/key'; var uriKey2 = 'api/key2'; var uriDbase = 'api/dbase'; function find() { var id = $('#command').val().toLowerCase(); var res = id.split(" "); if (res.length > 0) { switch (res[0]) { case "dump": $.getJSON(uriDump + '/') .done(function (data) { var box = $("#alltext"); box.val(box.val() + data); }) .fail(function (jqXHR, textStatus, err) { var box = $("#alltext"); box.val(box.val() + err); }); break; case "dbase": $.getJSON(uriDbase + '/') .done(function (data) { var box = $("#alltext"); box.val(box.val() + data); }) .fail(function (jqXHR, textStatus, err) { var box = $("#alltext"); box.val(box.val() + err); }); break; case "key": $.getJSON(uriKey + '/' + res[1] + '/') .done(function (data) { var box = $("#alltext"); box.val(box.val() + data); }) .fail(function (jqXHR, textStatus, err) { var box = $("#alltext"); box.val(box.val() + err); }); break; case "key2": $.getJSON(uriKey2 + '/' + res[1] + '/' + res[2] + '/') .done(function (data) { var box = $("#alltext"); box.val(box.val() + data); }) .fail(function (jqXHR, textStatus, err) { var box = $("#alltext"); box.val(box.val() + err); }); break; default: break; } } } ``` **EDIT** I found the piece of offending CSS.. In my site.css file: ``` /* Set width on the form input elements since they're 100% wide by default */ input, select, textarea { max-width: 280px; } ```<issue_comment>username_1: You should set the width to 100% using css. By doing that the textarea will get stretched as per the width of your browser tab. ``` ``` or make the following changes ``` textarea{ width:100% } ``` Upvotes: 0 <issue_comment>username_2: Make the following changes in your code: 1. Remove the `cols="800"` attribute from your textarea. 2. Set the value of width property to 100% in css. Upvotes: -1
2018/03/18
1,432
5,098
<issue_start>username_0: How to insert a new node(create with javascript) under the clicked node?. At the moment it crosses the original div, I do not want that it crosses, it should remain in its origin ```js let parent = document.getElementById("parent"); parent.addEventListener("click", function(event) { var currentSelection, currentRange, currentNode, newDiv, newContent; currentSelection = window.getSelection(); currentRange = currentSelection.getRangeAt(0); currentNode = currentRange.startContainer; console.log(currentNode.nodeValue); newDiv = document.createElement("div"); newDiv.className = 'nuevo'; newContent = document.createTextNode("holanda"); newDiv.appendChild(newContent); this.appendChild(newDiv) }); ``` ```css .nuevo { width: auto; height: auto; background: red; display: inline-block; margin-top: 1em; z-index: 3; } #parent>div { float: left; z-index: 1; } ``` ```html hello \*\*\* world ``` result: when clicked the word `world` [![enter image description here](https://i.stack.imgur.com/dJ748.png)](https://i.stack.imgur.com/dJ748.png) when clicked the word `***` [![enter image description here](https://i.stack.imgur.com/wVTQi.png)](https://i.stack.imgur.com/wVTQi.png)<issue_comment>username_1: Utilizing the `offsetLeft` property to locate new append elements: ```js let parent = document.getElementById("parent"); let rootElements = document.querySelectorAll("div.root"); for (let i = 0; i < rootElements.length; i++ ) { rootElements[i].addEventListener("click", function(event) { var currentSelection, currentRange, currentNode, newDiv, newContent; currentSelection = window.getSelection(); currentRange = currentSelection.getRangeAt(0); currentNode = currentRange.startContainer; // console.log(currentNode.nodeValue); newDiv = document.createElement("div"); newDiv.className = 'nuevo'; newContent = document.createTextNode("holanda"); newDiv.appendChild(newContent); let xPos = event.currentTarget.offsetLeft; let newEle = parent.appendChild(newDiv); newEle.style.left = xPos + "px"; }); } ``` ```css #parent { position: relative; left: 0px; } .nuevo { display: block; width: fit-content; height: auto; background: red; position: relative; } .root { vertical-align: top; display: inline-block; } ``` ```html hello \*\*\* world ``` **Update: one more way to achieve the goal** Append every new stack which actually has the same number of elements as first line. Utilize `display: flex` property on every new stack, and then give the inner elements corresponding width as same as their ancestor by `flex-basis` (why not width? this is another problem because of characteristic of `flex` property). And let content of that only element which we want for visibly appending to extend the space for itself. ```js let parent = document.getElementById("parent"); let rootElements = document.querySelectorAll("div.root"); for (let i = 0; i < rootElements.length; i++ ) { rootElements[i].addEventListener("click", function(event) { newStack = document.createElement("div"); newStack.className = 'stack'; for (let j = 0; j < rootElements.length; j++) { let grid = document.createElement("div"); grid.className = 'flexItem'; grid.setAttribute("style", "flex-basis:" + rootElements[j].getBoundingClientRect().width + "px"); if (i===j) { grid.className += ' nuevo'; grid.textContent = 'holanda'; } newStack.appendChild(grid) } parent.appendChild(newStack); }); } ``` ```css #parent { font-size: 0px; // For eliminating gap between inline-blocks } .stack { display: flex; } .flexItem { flex: 0 1; } .nuevo { height: auto; background: red; position: relative; font-size: 16px; } .root { display: inline-block; font-size: 16px; } ``` ```html hello \*\*\*\*\*\*\* world ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Attach the event listener to each one of the divs inside `parent` so that you can use them to append your elements, also, change the display property of `nuevo` to `block` ```js let items = document.querySelectorAll("#parent > div"); for (var i = 0; i < items.length; i++) { var item = items[i]; item.addEventListener("click", function(event) { var newDiv = document.createElement("div"); newDiv.className = 'nuevo'; newDiv.appendChild(document.createTextNode("holanda")); newDiv.style.left = this.offsetLeft + 'px'; this.parentNode.appendChild(newDiv); }); } ``` ```css .nuevo { width: auto; height: auto; background: red; display: block; clear: both; position: relative; } #parent>div { float: left; } #parent { position: relative; left: 0px; } ``` ```html hello \*\*\* world ``` Upvotes: -1
2018/03/18
969
3,985
<issue_start>username_0: I created a custom control class which inherits from `Button`. The reason I did that is I need to create the same Button and I don't want to do everything every single time. Also, I want a DropDown list selector for the properties that I add, accessible from the Properties Grid in the Form Designer. For example, I want three different colors and no other, so I want a DropDown selector on for this new Property. I used an Enum for that and it worked, but the problem is when I select for example `Red`, it doesn't change the color. My code is: ``` public class CustomButton : Button { public NormalColor CLR { get; set; } public enum NormalColor { Red, Blue, Yellow } public CustomButton() { if (CLR == NormalColor.Blue) { BackColor = Color.Blue; } else if (CLR == NormalColor.Red) { BackColor = Color.Red; } else if (CLR == NormalColor.Yellow) { BackColor = Color.Yellow; } else { BackColor = Color.FromArgb(18, 18, 18); } ForeColor = Color.White; FlatAppearance.BorderSize = 0; FlatStyle = FlatStyle.Flat; Size = new Size(100, 100); MouseEnter += CustomButton_MouseEnter; MouseLeave += CustomButton_MouseLeave; MouseClick += CustomButton_MouseClick; } } ```<issue_comment>username_1: In a control Constructor you can define its base (default) properties, not its behaviour or how a Control responds to user settings. Your Public Properties are delegated to this task. > > Note that I've inserted the `InitializeComponent()` procedure, so the > Control can be dropped in a container from the ToolBox. > > > If you want to hide your Control's `BackColor` Property in the Property window at Design Time, override the property and hide it with: `[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]` You could change your `CustomButton` this way: (With the current settings, when you drop your control on a Form from the Toolbox, it will be drawn with a red `BackColor` and a white `ForeColor`). ``` public class CustomButton : Button { private NormalColor CurrentColorSelection = 0; public NormalColor CLR { get { return CurrentColorSelection; } set { SetBackColor(value); } } public enum NormalColor { Red, Blue, Yellow } public CustomButton() => InitializeComponent(); private void InitializeComponent() { SetBackColor(CurrentColorSelection); this.ForeColor = Color.White; this.FlatAppearance.BorderSize = 0; this.FlatStyle = FlatStyle.Flat; this.Size = new Size(100, 100); this.MouseEnter += this.CustomButton_MouseEnter; this.MouseLeave += this.CustomButton_MouseLeave; this.MouseClick += this.CustomButton_MouseClick; } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public override Color BackColor { get { return base.BackColor; } set { base.BackColor = value; } } private void SetBackColor(NormalColor value) { this.CurrentColorSelection = value; this.BackColor = Color.FromName(value.ToString()); } //(...) //Event Handlers } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: When you instantiate the button class `constructor` is executed first, so in your code flow make sure that CLR is set while instantiating **Do following** ``` public class CustomButton : Button { public NormalColor CLR { get; private set; } public enum NormalColor { Red, Blue, Yellow } #region Constructor public CustomButton(NormalColor backgroundColor) { CLR = backgroundColor; if (CLR == NormalColor.Blue) { BackColor = Color.Blue; } /*Your other code*/ } } ``` Upvotes: 0
2018/03/18
533
1,487
<issue_start>username_0: i know that my question maybe down voted and amateur/basic but I'll take it gladly for the sake of learning. how do i fill my 2d array from numbers 1-9 using loop? no vectors pls, im still in the basic ty. ``` #include using namespace std; int main(){ int ar[3][3]= {0}; for(int i =1;i<=9;i++){ //this is the part i think im wrong and i cant figure it out ar[3][3] = i; } for(int i = 0; i<3; i++){ for(int j = 0;j<3; j++){ cout< ```<issue_comment>username_1: A very simple way to do it would be just to use a counter with two `for()` loops. You can assign the counter to the location specified by the `for()` loops and then increment the counter. It might look something like this: ``` int counter = 1; for(size_t i = 0; i < 3; ++i) { for(size_t j = 0; j < 3; ++j) { arr[i][j] = counter; ++counter; } } ``` Your other option is to explicitly initialize the array when you declare it. You can do this as follows: ``` int array[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Use two nested loops to fill the array, same as for printing it. Use a counter to count from 1 to 9 by incrementing it in the inner loop. ``` #include using namespace std; int main(){ int ar[3][3]; int a = 1; for(int i = 0; i<3; i++){ for(int j = 0;j<3; j++){ ar[i][j] = a; a++; } } for(int i = 0; i<3; i++){ for(int j = 0;j<3; j++){ cout< ``` Upvotes: 0
2018/03/18
1,476
5,224
<issue_start>username_0: I'm able to know whether a user has an active subscription for a given product: ``` $subscribed = WC_Subscriptions_Manager::user_has_subscription($userId, $productId, $status); ``` But I'm not managing to figure out how many subscriptions to this product that user has… *(Woocommerce Subscriptions plugin now supports a user buying multiple subscriptions)*. Anyone know how to do this?<issue_comment>username_1: This custom function will give you **the count of active subscriptions** in a very light SQL query, for a defined used ID and a specific subscription product ID: ``` function get_user_active_subscriptions_count( $product_id, $user_id = null ) { global $wpdb; // if the user_id is not set in function argument we get the current user ID if( null == $user_id ) $user_id = get_current_user_id(); // return the active subscriptions for a define user and a defined product ID return $wpdb->get_var(" SELECT COUNT(p.ID) FROM {$wpdb->prefix}posts as p LEFT JOIN {$wpdb->prefix}posts AS p2 ON p.post_parent = p2.ID LEFT JOIN {$wpdb->prefix}postmeta AS pm ON p2.ID = pm.post_id LEFT JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON pm.post_id = woi.order_id LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id WHERE p.post_type LIKE 'shop_subscription' AND p.post_status LIKE 'wc-active' AND p2.post_type LIKE 'shop_order' AND woi.order_item_type LIKE 'line_item' AND pm.meta_key LIKE '_customer_user' AND pm.meta_value = '$user_id' AND woim.meta_key = '_product_id' AND woim.meta_value = '$product_id' "); } ``` Code goes in function.php file of your active child theme (or active theme). Tested and works. --- **Usage for a defined product ID `9` and:** 1. A user ID as a dynamic variable `$user_id` : echo 'Subscription count: ' . get\_user\_active\_subscriptions\_count( '9', $user\_id ) . ' '; 2. A defined user ID *(Here user ID is **`15`**)*: echo 'Subscription count: ' . get\_user\_active\_subscriptions\_count( '9', '15' ) . ' '; 3. The current user ID: echo 'Subscription count: ' . get\_user\_active\_subscriptions\_count( '9' ) . ' '; The product ID can also be dynamic using a variable instead of an integer (for the product ID) --- Update: To get **the total count of a product subscription** in active subscriptions for a defined used ID (in a very light SQL query): ``` function get_user_active_product_subscriptions_count( $product_id, $user_id = null ) { global $wpdb; // if the user_id is not set in function argument we get the current user ID if( null == $user_id ) $user_id = get_current_user_id(); // return the active subscriptions for a define user and a defined product ID return $wpdb->get_var(" SELECT sum(woim2.meta_value) FROM {$wpdb->prefix}posts as p LEFT JOIN {$wpdb->prefix}posts AS p2 ON p.post_parent = p2.ID LEFT JOIN {$wpdb->prefix}postmeta AS pm ON p2.ID = pm.post_id LEFT JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON pm.post_id = woi.order_id LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim2 ON woim.order_item_id = woim2.order_item_id WHERE p.post_type LIKE 'shop_subscription' AND p.post_status LIKE 'wc-active' AND p2.post_type LIKE 'shop_order' AND woi.order_item_type LIKE 'line_item' AND pm.meta_key LIKE '_customer_user' AND pm.meta_value = '$user_id' AND woim.meta_key = '_product_id' AND woim.meta_value = '$product_id' AND woim2.meta_key = '_qty' "); } ``` Code goes in function.php file of your active child theme (or active theme). Tested and works. **The usage** is the same than above, but the result will be different as you will get the sum of the defined product subscription in active subscriptions (for a defined user ID (So it will sum the quantities of all items corresponding to the defined product ID in the subscriptions made by a user ID)… Upvotes: 2 <issue_comment>username_2: Meanwhile, I think that this works. I have no idea how efficient it is, but the answer seems to be right – given a particular user and particular product, this will return the quantity of subscriptions the user has for this product. *(Make sure to provide the Wordpress user\_id in the $user\_id variable, and the Woocommerce product id in the $product\_id variable.)* ``` $allSubscriptions = WC_Subscriptions_Manager::get_users_subscriptions($user_id); $item_quantity = 0; foreach ($allSubscriptions as $subscription){ if (($subscription['status'] == 'active' || $subscription['status'] == 'pending-cancel') == false) continue; $order = wc_get_order($subscription['order_id']); // Iterating through each line-item in the order foreach ($order->get_items() as $item_id => $item_data) { if ($item_data->get_product()->get_id() != $product_id) continue; $item_quantity += $item_data->get_quantity(); } } echo 'Quantity: ' . $item_quantity . ' '; ``` Upvotes: 0
2018/03/18
664
2,536
<issue_start>username_0: I'm new to Jquery and i've been working on a checkout form. I've placed a check box " Shipping address different from billing address? " and upon checkbox checked the fields are set to empty using the following code. ``` $(document).on('change', '#ship_to_different_address', function() { if(this.checked) { $("#fname").val(""); $("#lname").val(""); $('#shipping_company').val(""); this.checked = true; }else{ //What to write here to fetch old values? } }); ``` I'm using Laravel framework. Please guide.<issue_comment>username_1: I assume you're trying to use the checkbox to toggle between clearing the form and restoring the values from before it was cleared. If you want to be able to fetch the old values, you need to store them somewhere before clearing them. Here I stash them in a data attribute on each input element, for example: ```js $(document).on('change', '#ship_to_different_address', function() { // Since we're doing the same thing to all three elements, let's make an array loop: for (var theId of ['#fname', '#lname', '#shipping_company']) { var thisEl = $(theId); if (this.checked) { thisEl.data("oldval", thisEl.val()) // stash the current value .val(""); // clear it } else { thisEl.val(thisEl.data("oldval")) // retrieve the stash .data("oldval",""); // clear the stash } } }); ``` ```html Fill these: Then toggle this: ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Well if you are making a checkout form, I think you will need both the shipping and billing address... So if user select that ***Shipping address is different from billing address*** you will need a shipping address block with same values filled at billing address and if not just empty those fields ```js $(".radio").on("change", function() { if ($(this).val() === "1") { $("#s_fname").val($("#b_fname").val()).prop("disabled", true); $("#s_lname").val($("#b_lname").val()).prop("disabled", true); $("#shipping_company").val($("#billing_company").val()).prop("disabled", true); } else { $("#s_fname").val("").prop("disabled", false); $("#s_lname").val("").prop("disabled", false); $("#shipping_company").val("").prop("disabled", false); } }) ``` ```css body { font: 13px Verdana; } ``` ```html #### Billing address **Shipping address different from billing address?** Yes No #### Shipping address ``` Upvotes: 1
2018/03/18
869
3,027
<issue_start>username_0: I am unable to print a grid. This is what I am trying to do: 1. Take the grid size as an input from the user. 2. Dynamically create the grid based on the input. Below is a part of the code. ```js $(document).ready(function() { $("#grid-input").click(function() { $(".drawing-area").empty(); var rows = $("#row").val(); var cols = $("#col").val(); if (rows > 0 && cols > 0) { for (var i = 1; i <= rows; i++) { var rowClassName = 'row' + i; $('| ').addClass(rowClassName).appendTo('.drawing-area'); //Adding dynamic class names whenever a new table row is created for (var j = 1; j <= cols; j++) { var colClassName = 'col' + j; $(' |').addClass(colClassName).appendTo('.rowClassName'); } } } else { alert("You haven't provided the grid size!"); } }); }); }); ``` ```html ```<issue_comment>username_1: You can try to save the dynamic table row to a variable `$tr` first and then add the dynamic table column to that `$tr` variable like: ```js $("#grid-input").click(function() { $(".drawing-area").empty(); var rows = $("#row").val(); var cols = $("#col").val(); if (rows > 0 && cols > 0) { for (var i = 1; i <= rows; i++) { var rowClassName = 'row' + i; // Saving dynamic table row variable var $tr = $('| ').addClass(rowClassName).appendTo('.drawing-area'); for (var j = 1; j <= cols; j++) { var colClassName = 'col' + j; $(' '+ (i \* j) +' |').addClass(colClassName) // Append the new td to this $tr .appendTo($tr); } } } else { alert("You haven't provided the grid size!"); } }); ``` ```css .drawing-area{font-family:"Trebuchet MS",Arial,Helvetica,sans-serif;border-collapse:collapse;width:100%} .drawing-area td,.drawing-area th{border:1px solid #ddd;padding:8px} .drawing-area tr:nth-child(even){background-color:#f2f2f2} .drawing-area tr:hover{background-color:#ddd} ``` ```html Row: Col: Save ``` Upvotes: 0 <issue_comment>username_2: There is an error in your code, Last brackets are not required. Append dom at the end of your code, Try following code ``` $(document).ready(function() { $("#grid-input").click(function() { $(".drawing-area").empty(); var rows = $("#row").val(); var cols = $("#col").val(); if (rows > 0 && cols > 0) { for (var i = 1; i <= rows; i++) { var rowClassName = 'row' + i; var tr = $('|').addClass(rowClassName); tr.appendTo('.drawing-area'); //Adding dynamic class names whenever a new table row is created for (var j = 1; j <= cols; j++) { var colClassName = 'col' + j; $(' ').addClass(colClassName).appendTo(tr); } } } else { alert("You haven't provided the grid size!"); } }); }); | ``` Upvotes: 2 [selected_answer]
2018/03/18
437
1,646
<issue_start>username_0: I'm saving part of my variables in MySQL fields instead of files How can I recover it of a part of new PHP file? And using a similar functions like **include()** but for variables. As an idea of theoretical code: ```html php $var = '$nom = "NOMBRE"; $cognom = "APELLIDO"; '; // something like this but for variable include ($var); echo $nom; echo $cognom; // Result: NOMBRE APELLIDO ? ```<issue_comment>username_1: You need to use [`eval`](http://php.net/manual/en/function.eval.php) to execute a string as PHP code. Simply change: ``` include ($var); ``` to ``` eval($var); ``` Upvotes: 2 <issue_comment>username_2: It is very bad approach and application design to store code in the database. Now, it might looks much easier to rapidly develop the application however in the future you will face to huge obstacles to do even simple changes in the app and its data. Imagine that you will have a table of users and you will need to fine all users with the same last name... In well structured database you will simply run code like: ``` SELECT * FROM users WHERE surname 'Doe'; ``` However if the database will keep the code with variables holding the variable `$name="John";$surname="Doe";` it will be much more tricky to search correct substring not speaking about the issues with indexing, performance and weird logic at all. ``` SELECT * FROM codes WHERE code LIKE ; ``` Not speaking about sorting, calculations, agregations and other useful functionality providing us the database. So store atomic values in well structured database table such id, name, surname, nick, etc. Upvotes: 1
2018/03/18
2,135
6,220
<issue_start>username_0: I have the following program that I am compiling using Microsoft's Visual C++ command line compiler. ``` #include void foo(int, int); void main(void) { foo(5,4); } void foo(int a, int b) { printf("%u\n", sizeof(int)); printf("%u\n", &a); printf("%u\n", &b); } ``` When I print out the addresses I get addresses like -: ``` 3799448016 3799448024 ``` The gap is always 8 byes between addresses, while `sizeof(int) = 4` **There is always an extra 4 byte gap between the parameters** (*The size of int on my machine is 4 bytes*). **Why ?** What is the extra 4 bytes of space for ? I am on a 64-bit Windows 8.1 machine with VS 2013.<issue_comment>username_1: Because your OS is 64-bit, so addresses are too. Parameters are passed with `push` instruction. This instruction pushes operand into stack and decreases `esp` based on stack frame size. In 64-bit OS, `esp` is decreased by 8 for next address. In 32-bit OS, you will see 4 byte difference only. If it was not function argument, you would not have seen this behavior. For example, in the following code you should see 4 byte difference in addresses: ``` void foo() { int a = 0; int b = 0; printf("%u\n", sizeof(int)); printf("%u\n", &a); printf("%u\n", &b); } ``` **EDIT:** When you pass parameters, they are allocated on stack, so this following example: ``` struct _asd { int a; int b; char c[6]; }; void foo2(struct _asd a, int b) { printf("%u\n", sizeof(struct _asd)); printf("%u\n", &a); printf("%u\n", &b); } ``` In this case, `sizeof(struct _asd)==16`, so you see a result like this: ``` 16 3754948864 3754948880 ``` and as you see difference is 16. Just remember that you need to test this when you build **Release** mode, in **Debug** mode you see something like this: ``` 16 3754948864 3754948884 ``` a 20 byte difference, Because in **Debug** mode, compiler allocates more memory for structures. Now if you write your code like this: ``` struct _asd { int a; int b; char c[6]; }; void foo2(struct _asd *a, int b) { printf("%u\n", sizeof(struct _asd)); printf("%u\n", a); printf("%u\n", &b); } ``` Result will be like this: ``` 16 827849528 827849520 ``` Only 8 bytes difference, because now only addresses is sent to function which is only 8 bytes long. As a side note, in 64-bit OS, arguments are mostly passed by registers. For example first 4 parameters are normally passed by registers when you compile your code in MSVC. But in current topic, parameters are accessed by address and this will be meaningless for registers. So I think compiler automatically passed such parameters by pushing them into stack. Upvotes: 0 <issue_comment>username_2: Well, I cannot check the code produced by VS 2013, but Godbolt does support some CL version; the assembly below is an excerpt of what it [generated](https://godbolt.org/g/BhXR6s): ``` main PROC sub rsp, 40 ; 00000028H mov edx, 4 mov ecx, 5 call void __cdecl foo(int,int) ... main ENDP a$ = 48 b$ = 56 foo PROC mov DWORD PTR [rsp+16], edx mov DWORD PTR [rsp+8], ecx sub rsp, 40 ; 00000028H mov edx, 4 lea rcx, OFFSET FLAT:$SG4875 call printf lea rdx, QWORD PTR a$[rsp] lea rcx, OFFSET FLAT:$SG4876 call printf lea rdx, QWORD PTR b$[rsp] lea rcx, OFFSET FLAT:$SG4877 call printf add rsp, 40 ; 00000028H ret 0 foo ENDP ``` First of all, the parameters are *not* passed on stack, but in registers - first in `*CX` and second in `*DX` - as these are 32-bit, they're passed in `EDX` and `ECX` . Thus, the parameters do not have addresses, and would *not* stored in memory, **unless** they have their address taken. Since the `&` operator is used within the function, these now have to be stored on stack. I don't have any *good* explanation though on why they're stored with a 4-byte gap (`[rsp+16]` and `[rsp+8]`) - but they are. \*\*EDIT: [Here's the relevant Visual Studio documentation](https://learn.microsoft.com/en-us/cpp/build/stack-allocation) - from [<NAME>'s comment](https://stackoverflow.com/questions/49350395/why-is-there-a-4-byte-gap-between-the-parameters-on-microsoft-vc/49350418?noredirect=1#comment85701327_49350395) - it clearly shows that VS 2013 uses a fixed layout to store the parameters wherever needed - despite their types. This is unlike my Linux GCC, which would generate code that stores them in adjacent 32-bit locations: ``` foo: .LFB1: push rbp mov rbp, rsp sub rsp, 16 mov DWORD PTR -4[rbp], edi mov DWORD PTR -8[rbp], esi ``` ... ---- And the conversion specification for printing pointers is `%p` and for `size_t` you *should* use `%zu`. [But since VS 2013 does not have a standards-compliant C compiler, you cannot use `z`](https://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx) - therefore cast it to `unsigned long long` and print with `%llu` or get a C compiler. Upvotes: 1 <issue_comment>username_3: > > The gap is always 8 byes between addresses, while sizeof(int) = 4 > > > 1) This is compiler and implementation depended. The C standard does not specify memory arrangement for the individual integers. 2) To print addresses use `"%p"` format after casting it to `(void *)`. The `size_t` should be print with `"%zu"` format. For example: ``` #include struct my\_struct { int a; int b; int c; int d; }; void foo(int a, int b, struct my\_struct f, struct my\_struct g ) { printf("%zu\n", sizeof(int)); printf("&a= %p\n", (void \*) &a); printf("&b= %p\n", (void \*) &b); printf("&f= %p\n", (void \*) &f); printf("&g= %p\n", (void \*) &g); } int main(void) { int c=0; int d=1; struct my\_struct e,f; foo(5, 4, e, f); printf("&c= %p\n", (void \*) &c); printf("&d= %p\n", (void \*) &d); return 0; } ``` Output: ``` 4 &a= 0x7fff88da09fc &b= 0x7fff88da09f8 &f= 0x7fff88da09e0 &g= 0x7fff88da09d0 &c= 0x7fff88da0a18 &d= 0x7fff88da0a1c ``` Upvotes: 0
2018/03/18
2,161
6,471
<issue_start>username_0: **CODE:** ``` Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt rem odit quis quaerat. In dolorem praesentium velit ea esse consequuntur cum fugit sequi voluptas ut possimus voluptatibus deserunt nisi eveniet!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem voluptates vel dolorum autem ex repudiandae iste quasi. Minima explicabo qui necessitatibus porro nihil aliquid deleniti ullam repudiandae dolores corrupti eaque ``` jsfiddle: <https://jsfiddle.net/g2anpehk/5/> Code is to present 250 \* 250 picture and picture's subject. (`#subject-text`) But subject text is too much and overflow the max-height of `#max2lines-div` and `text-overflow: ellipsis`is useless. **Question:** What I want to make is that only showing 2 lines maximum with `text-overflow: ellipsis;`. So subject should be ended with `...` How can I fix it? I'm using bootstrap 3.3.7.<issue_comment>username_1: Because your OS is 64-bit, so addresses are too. Parameters are passed with `push` instruction. This instruction pushes operand into stack and decreases `esp` based on stack frame size. In 64-bit OS, `esp` is decreased by 8 for next address. In 32-bit OS, you will see 4 byte difference only. If it was not function argument, you would not have seen this behavior. For example, in the following code you should see 4 byte difference in addresses: ``` void foo() { int a = 0; int b = 0; printf("%u\n", sizeof(int)); printf("%u\n", &a); printf("%u\n", &b); } ``` **EDIT:** When you pass parameters, they are allocated on stack, so this following example: ``` struct _asd { int a; int b; char c[6]; }; void foo2(struct _asd a, int b) { printf("%u\n", sizeof(struct _asd)); printf("%u\n", &a); printf("%u\n", &b); } ``` In this case, `sizeof(struct _asd)==16`, so you see a result like this: ``` 16 3754948864 3754948880 ``` and as you see difference is 16. Just remember that you need to test this when you build **Release** mode, in **Debug** mode you see something like this: ``` 16 3754948864 3754948884 ``` a 20 byte difference, Because in **Debug** mode, compiler allocates more memory for structures. Now if you write your code like this: ``` struct _asd { int a; int b; char c[6]; }; void foo2(struct _asd *a, int b) { printf("%u\n", sizeof(struct _asd)); printf("%u\n", a); printf("%u\n", &b); } ``` Result will be like this: ``` 16 827849528 827849520 ``` Only 8 bytes difference, because now only addresses is sent to function which is only 8 bytes long. As a side note, in 64-bit OS, arguments are mostly passed by registers. For example first 4 parameters are normally passed by registers when you compile your code in MSVC. But in current topic, parameters are accessed by address and this will be meaningless for registers. So I think compiler automatically passed such parameters by pushing them into stack. Upvotes: 0 <issue_comment>username_2: Well, I cannot check the code produced by VS 2013, but Godbolt does support some CL version; the assembly below is an excerpt of what it [generated](https://godbolt.org/g/BhXR6s): ``` main PROC sub rsp, 40 ; 00000028H mov edx, 4 mov ecx, 5 call void __cdecl foo(int,int) ... main ENDP a$ = 48 b$ = 56 foo PROC mov DWORD PTR [rsp+16], edx mov DWORD PTR [rsp+8], ecx sub rsp, 40 ; 00000028H mov edx, 4 lea rcx, OFFSET FLAT:$SG4875 call printf lea rdx, QWORD PTR a$[rsp] lea rcx, OFFSET FLAT:$SG4876 call printf lea rdx, QWORD PTR b$[rsp] lea rcx, OFFSET FLAT:$SG4877 call printf add rsp, 40 ; 00000028H ret 0 foo ENDP ``` First of all, the parameters are *not* passed on stack, but in registers - first in `*CX` and second in `*DX` - as these are 32-bit, they're passed in `EDX` and `ECX` . Thus, the parameters do not have addresses, and would *not* stored in memory, **unless** they have their address taken. Since the `&` operator is used within the function, these now have to be stored on stack. I don't have any *good* explanation though on why they're stored with a 4-byte gap (`[rsp+16]` and `[rsp+8]`) - but they are. \*\*EDIT: [Here's the relevant Visual Studio documentation](https://learn.microsoft.com/en-us/cpp/build/stack-allocation) - from [<NAME>'s comment](https://stackoverflow.com/questions/49350395/why-is-there-a-4-byte-gap-between-the-parameters-on-microsoft-vc/49350418?noredirect=1#comment85701327_49350395) - it clearly shows that VS 2013 uses a fixed layout to store the parameters wherever needed - despite their types. This is unlike my Linux GCC, which would generate code that stores them in adjacent 32-bit locations: ``` foo: .LFB1: push rbp mov rbp, rsp sub rsp, 16 mov DWORD PTR -4[rbp], edi mov DWORD PTR -8[rbp], esi ``` ... ---- And the conversion specification for printing pointers is `%p` and for `size_t` you *should* use `%zu`. [But since VS 2013 does not have a standards-compliant C compiler, you cannot use `z`](https://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx) - therefore cast it to `unsigned long long` and print with `%llu` or get a C compiler. Upvotes: 1 <issue_comment>username_3: > > The gap is always 8 byes between addresses, while sizeof(int) = 4 > > > 1) This is compiler and implementation depended. The C standard does not specify memory arrangement for the individual integers. 2) To print addresses use `"%p"` format after casting it to `(void *)`. The `size_t` should be print with `"%zu"` format. For example: ``` #include struct my\_struct { int a; int b; int c; int d; }; void foo(int a, int b, struct my\_struct f, struct my\_struct g ) { printf("%zu\n", sizeof(int)); printf("&a= %p\n", (void \*) &a); printf("&b= %p\n", (void \*) &b); printf("&f= %p\n", (void \*) &f); printf("&g= %p\n", (void \*) &g); } int main(void) { int c=0; int d=1; struct my\_struct e,f; foo(5, 4, e, f); printf("&c= %p\n", (void \*) &c); printf("&d= %p\n", (void \*) &d); return 0; } ``` Output: ``` 4 &a= 0x7fff88da09fc &b= 0x7fff88da09f8 &f= 0x7fff88da09e0 &g= 0x7fff88da09d0 &c= 0x7fff88da0a18 &d= 0x7fff88da0a1c ``` Upvotes: 0
2018/03/18
659
2,400
<issue_start>username_0: I'm still a beginner in reactJS (using nodeJS backend) and I have to create a website to manage my collections. I don't know if what I'm going to ask you is feasible, but it probably is. So I'm using a react component, react-photo-gallery. It's a component where you can use url links and it mixes them together to create a beautiful gallery. <https://github.com/neptunian/react-photo-gallery> I'm using nodeJS to get the information from the database, where I get the urls of all the pictures. For example I have a collection of cards, and an url of the image which represents the collection. **What I want to do is get the link of the picture that I'm clicking on so I can use it in another component.** ```js import React from 'react'; import { render } from 'react-dom'; import Gallery from 'react-photo-gallery'; import Photo from './Photo'; class PhotoGallery extends React.Component { constructor(props){ super(props); this.onClick = this.onClick.bind(this); this.state = { urlImages: [] }; } async componentDidMount() { var getUrlImages = 'http://localhost:3004'; const response = await fetch(getUrlImages+"/getUrlImages"); const newList = await response.json(); this.setState(previousState => ({ ...previousState, urlImages: newList, })); } galleryPhotos() { if(this.state.urlImages) { return this.state.urlImages.map(function(urlimage) { return { src: urlimage.urlimage, width: 2, height: 2 } }) } } onClick() { alert(this.galleryPhotos().value); } render() { return ( ) } } const photos = []; export default PhotoGallery; ``` ```html ``` Basically what I want to do is get the source link of the picture in the onClick function. Is that possible? Thanks in advance!<issue_comment>username_1: The onClick event of the Gallery component has a number of arguments: 1. the event 2. an object containing the selected index and the original photo object You can use this in your onClick handler: ``` onClick(e, obj) { const src = obj.photo.src // do whatever you need with the src (setState, etc) } ``` Upvotes: 2 <issue_comment>username_2: Check the `onClick` event. ``` onClick(event) { alert(event.target.src) } ``` The **[DEMO](https://codesandbox.io/s/x3063kpm7z)** Upvotes: 3 [selected_answer]
2018/03/18
1,050
3,032
<issue_start>username_0: I created a racetrack shaped curve in three.js with the following code: ``` var path = new THREE.Path(); path.moveTo(150,50); path.lineTo(150,150); path.quadraticCurveTo(150,175,100,175); path.quadraticCurveTo(50,175,50,150); path.lineTo(50,50); path.quadraticCurveTo(50,25,100,25); path.quadraticCurveTo(150,25,150,50); var pathPoints = path.getPoints(); var pathGeometry = new THREE.BufferGeometry().setFromPoints(pathPoints); var pathMaterial = new THREE.LineBasicMaterial({color:0xFF1493}); var raceTrack = new THREE.Line(pathGeometry,pathMaterial); scene.add(raceTrack); } ``` Right now, the track is just a single line, and I wanted to know if it was possible to make the track into a geometry with a width (still 2D) so that I can add a texture to it. Currently, the path looks something like this: ![1px wide path](https://i.stack.imgur.com/PI9n3.jpg) What I'd like is to be able to draw the same shape, but just increase the width of the line: ![5px wide path](https://i.stack.imgur.com/DNia4.jpg)<issue_comment>username_1: With `R91`, `three.js` added support for triangulated lines. This approach enables line width greater than 1px in a reliable way. Demo: <https://threejs.org/examples/webgl_lines_fat.html> There are no textures applied on the example but uv-coordinates are generated for the underlying geometry. Upvotes: 3 [selected_answer]<issue_comment>username_2: With regular `Line`-objects, there is no way to achieve this. Here are a few options you can try: * create your complete "race-track" as a geometry, including both the inner and the outer line. I have no idea what you need this for, but this is probably the most "correct" way to do something like this (using this approach, the race-track can have different width at different points, you have control over how bends and turns behave and so on). A quick example: ``` const shape = new THREE.Shape(); shape.moveTo(150, 50); shape.lineTo(150, 150); shape.quadraticCurveTo(150, 175, 100, 175); shape.quadraticCurveTo(50, 175, 50, 150); shape.lineTo(50, 50); shape.quadraticCurveTo(50, 25, 100, 25); shape.quadraticCurveTo(150, 25, 150, 50); const innerShape = new THREE.Path(); innerShape.moveTo(140, 40); innerShape.lineTo(140, 140); innerShape.quadraticCurveTo(140, 165, 90, 165); innerShape.quadraticCurveTo(60, 165, 60, 140); innerShape.lineTo(60, 50); innerShape.quadraticCurveTo(60, 35, 110, 35); innerShape.quadraticCurveTo(140, 35, 140, 60); shape.holes.push(innerShape); var raceTrack = new THREE.Mesh( new THREE.ShapeGeometry(shape), new THREE.MeshBasicMaterial({ color: 0xff1493 }) ); ``` full code here: <https://codepen.io/usefulthink/pen/eMBgmE> * alternatively, you can use the new fat-lines implementation shown here: <https://threejs.org/examples/?q=line#webgl_lines_fat> or the MeshLine implementation from here: <https://github.com/spite/THREE.MeshLine>, but I have the feeling those do not what you are looking for... Upvotes: 2
2018/03/18
968
3,017
<issue_start>username_0: I want to check if a given point on a map (with its latitude and longitude) is inside a certain polygon. I have the vertex coords (in lat/long) of the polygon. I thought of creating a Polygon and check if point is inside, but it gives me that the point is always outside... Maybe the polygon does not work with georeferential coords? ``` Double[] xCoords = {40.842226, 40.829498, 40.833394, 40.84768, 40.858716} Double[] yCoords = {14.211753, 14.229262, 14.26617, 14.278701, 14.27715} Double[] myPoint = {40.86141, 14.279932}; Path2D myPolygon = new Path2D.Double(); myPolygon.moveTo(xCoords[0], yCoords[0]); //first point for(int i = 1; i < xCoords.length; i ++) { myPolygon.lineTo(xCoords[i], yCoords[i]); //draw lines } myPolygon.closePath(); //draw last line if(myPolygon.contains(myPoint{0}, myPoint{1})) { //it's inside; } ``` This is how it looks like in google maps [![enter image description here](https://i.stack.imgur.com/xcAq3.jpg)](https://i.stack.imgur.com/xcAq3.jpg) It always return false... but the point it's inside the polygon...<issue_comment>username_1: That point can't possibly be contained in that polygon, no matter what shape the polygon has. Your right-most coordinate is at `40.858716` while the point has an x value of `40.86141`, this means that the point lies on the right of your polygon. Same for y, max y coordinate in the polygon is `14.278701` while the point is at `14.279932`. This means that the point is *outside*. Also, you're inverting the coordinates, the coordinates of our beloved city are `40.8518° N, 14.2681° E`, this means that `40` is the `y` and `14` the `x`. `Path2D` will do just fine. My observation just tells you that the point is not in the polygon but checking the extremes is not a general solution for verifying that a point is inside a polygon. Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` public class CoordinatesDTO { private Long id; private double latitude; private double longnitude; ``` } ``` public static boolean isLocationInsideTheFencing(CoordinatesDTO location, List fencingCoordinates) { //this is important method for Checking the point exist inside the fence or not. boolean blnIsinside = false; List lstCoordinatesDTO = fencingCoordinates; Path2D myPolygon = new Path2D.Double(); myPolygon.moveTo(lstCoordinatesDTO.get(0).getLatitude(), lstCoordinatesDTO.get(0).getLongnitude()); // first // point for (int i = 1; i < lstCoordinatesDTO.size(); i++) { myPolygon.lineTo(lstCoordinatesDTO.get(i).getLatitude(), lstCoordinatesDTO.get(i).getLongnitude()); // draw // lines } myPolygon.closePath(); // draw last line // myPolygon.contains(p); Point2D P2D2 = new Point2D.Double(); P2D2.setLocation(location.getLatitude(), location.getLongnitude()); if (myPolygon.contains(P2D2)) { blnIsinside = true; } else { blnIsinside = false; } return blnIsinside; } ``` Upvotes: -1
2018/03/18
643
1,857
<issue_start>username_0: I would like to calculate the correlation coefficient between two columns of a pandas data frame after making a column boolean in nature. The original `table` had two columns: a `Group` Column with one of two treatment groups, now boolean, and an `Age` Group. Those are the two columns I'm looking to calculate the correlation coefficient. I tried the `.corr()` method, with: ``` table.corr(method='pearson') ``` but have this returned to me: [![enter image description here](https://i.stack.imgur.com/co6cM.jpg)](https://i.stack.imgur.com/co6cM.jpg) I have pasted the first 25 rows of boolean `table` below. I don't know if I'm missing parameters, or how to interpret this result. It's also strange that it's 1 as well. Thanks in advance! ``` Group Age 0 1 50 1 1 59 2 1 22 3 1 48 4 1 53 5 1 48 6 1 29 7 1 44 8 1 28 9 1 42 10 1 35 11 0 54 12 0 43 13 1 50 14 1 62 15 0 64 16 0 39 17 1 40 18 1 59 19 1 46 20 0 56 21 1 21 22 1 45 23 0 41 24 1 46 25 0 35 ```<issue_comment>username_1: Calling `.corr()` on the entire DataFrame gives you a full correlation matrix: ``` >>> table.corr() Group Age Group 1.0000 -0.1533 Age -0.1533 1.0000 ``` You can use the separate Series instead: ``` >>> table['Group'].corr(table['Age']) -0.15330486289034567 ``` This should be faster than using the full matrix and indexing it (with `df.corr().iat['Group', 'Age']`). Also, this should work whether `Group` is bool or int dtype. Upvotes: 6 [selected_answer]<issue_comment>username_2: my data frame consists of many columns. the correlation between any 2 colums is ``` **df.corr().loc['ColA','ColB']** ``` we get matrix b/w both columns Upvotes: -1
2018/03/18
415
1,502
<issue_start>username_0: I have a Fortran 95 code that I want to compile to a Python library using f2py. In a matter of fact I've already done it, and it works beautifully. Does the resulting .pyd (.so) depend on numpy after compilation? Could it be used without numpy installation and are they some other options to embed the needed parts inside the final library so it has no dependencies? I am considering this to be a library accompanying a commercial product and I want the end user to have as little as possible to install on his system, so suggesting to my future customers to install numpy does not suit me. I've searched extensively for an answer, but I cannot seem to find one. In case it is not possible, could you please refer me to a dependence free way to wrap Fortran code using Python.<issue_comment>username_1: Calling `.corr()` on the entire DataFrame gives you a full correlation matrix: ``` >>> table.corr() Group Age Group 1.0000 -0.1533 Age -0.1533 1.0000 ``` You can use the separate Series instead: ``` >>> table['Group'].corr(table['Age']) -0.15330486289034567 ``` This should be faster than using the full matrix and indexing it (with `df.corr().iat['Group', 'Age']`). Also, this should work whether `Group` is bool or int dtype. Upvotes: 6 [selected_answer]<issue_comment>username_2: my data frame consists of many columns. the correlation between any 2 colums is ``` **df.corr().loc['ColA','ColB']** ``` we get matrix b/w both columns Upvotes: -1
2018/03/18
1,190
4,610
<issue_start>username_0: This is my first time to use a List. I have a Class named Foods and I want to make a dynamic list out of it. I wrote the first line that you can see below and then there are a lot of methods that just popped out that I need to override. What should I write in each method? Or is this the right way to make an instance of a list? ``` public List food = new List() { //then these list of methods just popped out// @Override public int size() { return 0; } @Override public boolean isEmpty() { return false; } @Override public boolean contains(Object o) { return false; } @NonNull @Override public Iterator iterator() { return null; } @NonNull @Override public Object[] toArray() { return new Object[0]; } @NonNull @Override public T[] toArray(@NonNull T[] ts) { return null; } @Override public boolean add(Foods foods) { return false; } @Override public boolean remove(Object o) { return false; } @Override public boolean containsAll(@NonNull Collection collection) { return false; } @Override public boolean addAll(@NonNull Collection extends Foods collection) { return false; } @Override public boolean addAll(int i, @NonNull Collection extends Foods collection) { return false; } @Override public boolean removeAll(@NonNull Collection collection) { return false; } @Override public boolean retainAll(@NonNull Collection collection) { return false; } @Override public void clear() { } @Override public Foods get(int i) { return null; } @Override public Foods set(int i, Foods foods) { return null; } @Override public void add(int i, Foods foods) { } @Override public Foods remove(int i) { return null; } @Override public int indexOf(Object o) { return 0; } @Override public int lastIndexOf(Object o) { return 0; } @NonNull @Override public ListIterator listIterator() { return null; } @NonNull @Override public ListIterator listIterator(int i) { return null; } @NonNull @Override public List subList(int i, int i1) { return null; } }; ```<issue_comment>username_1: You probably don't need to override any methods, just create a `List` like this: ``` private List list = new ArrayList<>(); ``` `List` is an `interface`, it cannot be instantiated (none of its methods are implemented). `ArrayList` is one implementation of the `List` interface, it uses an internal array to store its elements. By writing `List`, you are declaring that this `List` will hold elements of type `Foods`. You generally should not make fields `public`, use `private` and if you need to access them from another class, add a `getter`/`setter` method. Upvotes: 1 <issue_comment>username_2: `List` is an `Interface`, if you use `new` directly, you have to implement it as an anonymous class(above code). Instead, you can use the implementions `java.util` package provided, such as ArrayList and LinkedList, you can initiate it like this: ``` public List food = new ArrayList<>(): ``` or ``` public List food = new LinkedList<>(): ``` Upvotes: 2 <issue_comment>username_3: List<> is the interface that other list types such ArrayList and LinkedList implement. When you initialise your List, you want to use one of these other List types that already have the methods that popped up for you implemented. For example: ``` public List food = new ArrayList<>() ``` Upvotes: 2 <issue_comment>username_4: List is an interface, so if you call it directly, of course you have to override its methods. The proper way to instantiate a List is to instantiate one of the classes which implement it, the most commonly used are ArrayList and LinkedList: `List food = new LinkedList<>();` or `List food = new ArrayList<>();` The first is an ordered list, the second has random access. I suggest you to read the [javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/List.html) of List interface (and of any java object you are not familiar with): you can find useful information on the object you are using, such as if it is a class or an interface and in the last case there is a section called "All Known Implementing Classes" where you can find all the classes that implement it, so you can decide which is the implementation you need. Upvotes: 1 <issue_comment>username_5: If there is anything different from `ArrayList` or `LinkedList` you would like to implement (something that is special for your food list), then yes, you have to specify these methods. Otherwise, as suggested in previous posts, use this approach: `public List food = new ArrayList<>();` Upvotes: 0
2018/03/18
401
1,055
<issue_start>username_0: I am trying to filter my output to display only files created in "Jan" and "Feb". Is there a way to do this without using grep? Would need to be able to switch from "Jan" and "Feb" to "Jan" and "Mar" etc..<issue_comment>username_1: Try this : ``` find . -newermt "31 Dec 2017" -not -newermt "28 Feb 2018" ``` or for your specific need: ``` find . -newermt "31 Dec 2017" -not -newermt "28 Feb 2018" -size +30M -printf '%s %p\n' | numfmt --to=iec | sort -h ``` or if you want to keep your command : ``` find . -newermt "31 Dec 2017" -not -newermt "28 Feb 2018" -size +30M -print0 | xargs -0 ls -lh | sort -h ``` Check : ``` man find | less +/'-newerXY reference' ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` touch -d 1/1/2018 jan touch -d 3/1/2018 mar find . -type f -cnewer jan ! -cnewer mar -ls ``` ls is only used for control purpose. -type f might be a wanted restriction or not. `xargs -ls lh` can be omitted by using finds -printf format, see the manpage for the multiple options. Upvotes: 0
2018/03/18
582
1,519
<issue_start>username_0: I have a data set in Excel similar to the following: ``` A B 1: 07:42:07 2 2: 07:42:08 3 3: 07:42:09 4 4: 07:42:10 5 5: 07:42:11 6 6: 07:42:12 7 7: 07:42:13 8 ``` Given a particular time, I would like to extract the value which is diagonal to the specific time. For example, given the value 07:42:10 (at cell A4), I would like to get the value 4 (at cell B3), which is in the previous row and in the next column. I need to be able to pass the time value to the function, so that the respective value in column B will be shown as explained in the example. Is there a function which will allow me to do this please? Thank you<issue_comment>username_1: Try this : ``` find . -newermt "31 Dec 2017" -not -newermt "28 Feb 2018" ``` or for your specific need: ``` find . -newermt "31 Dec 2017" -not -newermt "28 Feb 2018" -size +30M -printf '%s %p\n' | numfmt --to=iec | sort -h ``` or if you want to keep your command : ``` find . -newermt "31 Dec 2017" -not -newermt "28 Feb 2018" -size +30M -print0 | xargs -0 ls -lh | sort -h ``` Check : ``` man find | less +/'-newerXY reference' ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` touch -d 1/1/2018 jan touch -d 3/1/2018 mar find . -type f -cnewer jan ! -cnewer mar -ls ``` ls is only used for control purpose. -type f might be a wanted restriction or not. `xargs -ls lh` can be omitted by using finds -printf format, see the manpage for the multiple options. Upvotes: 0
2018/03/18
968
3,673
<issue_start>username_0: We are trying to debug a crash that happens for some users, but can't figure out exactly what it is. In Google Play console, we see this: ``` java.lang.RuntimeException: at android.app.ActivityThread.handleReceiver (ActivityThread.java:3331) at android.app.ActivityThread.-wrap20 (ActivityThread.java) at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1734) at android.os.Handler.dispatchMessage (Handler.java:102) at android.os.Looper.loop (Looper.java:154) at android.app.ActivityThread.main (ActivityThread.java:6688) at java.lang.reflect.Method.invoke (Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1468) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1358) Caused by: java.lang.ClassNotFoundException: at dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:56) at java.lang.ClassLoader.loadClass (ClassLoader.java:380) at java.lang.ClassLoader.loadClass (ClassLoader.java:312) at android.app.ActivityThread.handleReceiver (ActivityThread.java:3326) ``` We have Crashlytics set up in the project, and it is the first thing that loads when the app starts running. I suspect that perhaps one of the classes is missing from the manifest, but we looked at it (even disasemmbled the APK just to make sure) and they are all there. We suspect that perhaps it is a class that one of the activities use during initialization, but some of them are 3rd party SDKs so we do not have access to their source. Is there a way to see the class name that wasn't found? The errors don't show up on crashlytics and we are unable to reproduce it on any of the devices / emulators that we have. Thanks! **Edit : Partial Resolution** The problem ended up being a notification package that we are using, that requires vendor-specific entries (which we do not have in our test devices) in the AndroidManifest.xml. After reintegrating almost all of our 3rd party services, we eventually saw the crash report disappear. We were not able to achieve our general goal (get the exception text, not just the exception stack trace, from exceptions logged to Google Play Developer Console), so there is no "good" way (as far as we are aware) to find out which class was missing. Quite disappointing TBH.<issue_comment>username_1: So not all users experience this exception. Clearly, at the run time, for those users, there is no such class known to the loader. My thought is that you are using a lib (like lib.so, either your own native code or a 3rd party lib) which its native code does not support a certain architecture (like MIPS, or Intel) and therefore such devices get the exception. Just something to investigate. There are emulators for different architectures so you might not even need real hardware to test if this is the root cause. Upvotes: 1 <issue_comment>username_2: Crashlytics will not update immediately. That crash will report in Crashlytics once the user open app again after crash. **Possible cases** 1. Your crashed device may not open the app after the crash 2. May be uninstalled after crash Upvotes: 0 <issue_comment>username_3: **Try this in build.gradle:** ``` android { defaultConfig { ... minSdkVersion 15 targetSdkVersion 26 multiDexEnabled true } ... } dependencies { compile 'com.android.support:multidex:1.0.1' } ``` and in **application** class: ``` public class MyApplication extends Application { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } } ``` Upvotes: 0
2018/03/18
563
2,067
<issue_start>username_0: In Shiny, we have `downloadButton()` and `fileInput()` buttons for downloading and uploading data respectively. However it happens that, with `downloadButton()` there is *download* icon, and however with `fileInput()` no icon is attached. In my Shiny app, I have both buttons. However since one of them has icon attached, it brings some kind of visual inconsistency in my App. So, I either want to remove such icon from `downloadButton()`, or add some *upload* button with `fileInput()` to bring consistency. However, it appears that there is not any direct approach to perform either of them. So can anybody suggest here if there is any way to : Either remove icon from `downloadButton()` Or, attach some *upload* icon with `fileInput()` Any pointer is highly appreciated. Thanks,<issue_comment>username_1: If you look at the source code of `downloadButton`, you will see that changing/removing the button is pretty straightforward ``` downloadButton ## function (outputId, label = "Download", class = NULL, ...) ## { ## aTag <- tags$a(id = outputId, class = paste("btn btn-default shiny-download-link", ## class), href = "", target = "_blank", download = NA, ## icon("download"), label, ...) ## } ## ``` You just need to replace `icon("download")` with `NULL`. Here is a complete example ``` myDownloadButton <- function(outputId, label = "Download"){ tags$a(id = outputId, class = "btn btn-default shiny-download-link", href = "", target = "_blank", download = NA, NULL, label) } shinyApp( fluidPage(myDownloadButton("download")), function(input, output, session){ output$download = downloadHandler( "file.rds", function(file){ saveRDS(mtcars, file) } ) } ) ``` Upvotes: 2 <issue_comment>username_2: To add an icon to fileInput(), add a list to the buttonLabel. e.g. ``` shinyApp( fluidPage( fileInput("myFileInput",label="Test",buttonLabel=list(icon("folder"),"TestyMcTestFace")) ), function(input, output, session){ } ) ``` Upvotes: 4 [selected_answer]
2018/03/18
1,027
3,442
<issue_start>username_0: I will try to keep this as brief as possible as I tried to find an answer and I couldn't. I am trying to create a simple till system. I am using a CSV file to store the description, price and stock of the product. If the user logs in as a manager they will be able to change the stock of a particular product. I find it very difficult to understand how to change the new stock. i forgot to mention that I use lists to store each category Let's say I have the following file ``` apples,1,11 grape,1.2,1 chocolate,0.75,15 bananas,1.35,27 ``` And the following code to create the lists: ``` Products = [] Prices = [] Prices= [] import csv with open('listlist.csv') as csvfile: readCSV = csv.reader(csvfile,delimiter=',') for row in readCSV: print(row) item = row[0] price = row[1] stock = row[2] Products.append(item) Prices.append(price) Stock.append(int(stock)) ``` If the manager wants to change the stock of the item 'grape' from 1 to 11, how should I approach this in the easiest way?<issue_comment>username_1: you could do it using pandas for example, and you wouldnt need to deal with different lists ``` 0 1 2 0 apples 1.00 11 1 grape 1.20 1 2 chocolate 0.75 15 3 bananas 1.35 27 import pandas df = pandas.read_csv(csv_file_path, header=None) df.loc[df[0] == "apples", 2] = new_stock ``` the [0] and 2 can be changed by the name of the columns if you add column names to the file Upvotes: 0 <issue_comment>username_2: Since this appears to be a homework assignment or exercise, this isn't a full answer, but should get you started. Reading your file, using list of dictionaries to store the items: ``` items_in_store = [] import csv with open('listlist.csv') as csvfile: readCSV = csv.reader(csvfile,delimiter=',') for row in readCSV: item = dict(name=row[0], price=row[1], stock=row[2]) items_in_store.append(item) ``` Looping over the resulting list, changing a specific target item: ``` tgt_item = 'apple' tgt_stock = 5 for item in items_in_store: if item['name'] == tgt_item: # we found our item, change it item['stock'] = tgt_stock ``` To [persist your changes](https://docs.python.org/3.6/library/csv.html#csv.writer) to the file (note this time we open the file in write mode): ``` with open('listlist.csv', 'w') as csvfile: writeCSV = csv.writer(csvfile, delimiter=',') for item in items_in_store: row = [item['name'], item['price'], item['stock']] writeCSV.writerow(row) ``` --- Alternative approach, again reading the file, but this time storing in a dictionary containing dictionaries: ``` items_in_store = {} # create empty dictionary import csv with open('listlist.csv') as csvfile: readCSV = csv.reader(csvfile,delimiter=',') for row in readCSV: # use item name as key in first dictionary # and store a nested dictionary with price and stock items_in_store[row[0]] = dict(price=row[1], stock=row[2]) ``` Having our data stored this way, we do not need to loop to change the stock, we can just access the desired item with its key right away: ``` tgt_item = 'apple' tgt_stock = 5 items_in_store[tgt_item]['stock'] = tgt_stock ``` In all the above example snippets, you could ask for user input to fill your `tgt_item` and `tgt_stock`. Upvotes: 1
2018/03/18
582
1,878
<issue_start>username_0: I am new to fedora and just creating process in fedora using c++ code. I want to make 2 process from the parent process. I am doing so in my code but the When process 2 is created and I check its parent id it differ from the original parent Id can some tell why this code is showing this behavior thank you. ``` #include #include #include #include #include #include using namespace std; int main() { cout<<"Begning of the program"<0) { pid\_t child2=fork(); if(child2>0) { cout<<"Parrent of Child1 and Child2"< ``` Results: ``` Begning of the program Parrent of Child1 and Child2 Child1 Process Process ID: 2186 Parrent ID: 2059 End Process ID: 2187 Parrent ID: 2186 End Child2 Creadted Process ID: 2188 Parrent ID: 1287 End ```<issue_comment>username_1: Before your forked child process output its parent process id, the real parent (where `fork()` was called) already exited. The child process is reattached to the group parent process, which pid is output by the child. You could call `pstree -p` to see which process is 1303. I advise to replace lines ``` cout<<"Process ID: "< ``` with ``` cout << getpid() << ": Parent ID: "<< getpid() << endl; ``` This would help to separate possible mixed outputs (since the output order is undetermined.) Example output: ``` 2186: Parent ID: 2059 ``` Upvotes: 2 <issue_comment>username_2: you should apply wait after creating the process 2 like I do in the code. So that parent remain alive until the child 2 executes. In you r code parent dies after creating child2 which make child 2 a zombie process. ``` #include #include #include #include #include #include using namespace std; int main() { cout<<"Begning of the program"<0) { pid\_t child2=fork(); wait(NULL); if(child2>0) { cout<<"Parrent of Child1 and Child2"< ``` Upvotes: 1 [selected_answer]
2018/03/18
1,320
3,918
<issue_start>username_0: I have to catch "hover" and after call JS function. I call it from html. But nothing happen. I tried also to use mouseover - also doesn't work from html. I have to catch "hover",but can't make event listener in JS file on "hover".I can put event listener on "mouseover" but it doesn't work correct when mouse moves fast). What mistake I do that I don't have any reaction on changeDef(event)? ```js function changeDef(event){ console.log(event.target); } ``` ```html ![](./img/footer1.png) ```<issue_comment>username_1: There is no "hover" event. You do use the **[`mouseover`](https://developer.mozilla.org/en-US/docs/Web/Events/mouseover)** event, which (when using HTML attributes to set up) is referenced with `on` in front of the event name. There won't be a problem with this event triggering even if the mouse is moving fast. ```js function changeDef(event){ console.log(event.target); } ``` ```html ![](./img/footer1.png) ``` But, you really should not use the 25+ year old technique of setting up event handlers via HTML attributes (which introduces **[a variety of issues](https://stackoverflow.com/questions/43459890/javascript-function-doesnt-work-when-link-is-clicked/43459991#43459991)**) and, instead, follow modern standards and best practices by separating the JavaScript from the HTML: ```js // Get a reference to the element that you want to work with var img = document.querySelector("img.img-default"); // Set up an event handler. Notice that we don't use "on" in front // of the event name when doing it this way. img.addEventListener("mouseover", changeDef); function changeDef(event){ console.log(event.target); } ``` ```css img { width:50px; } ``` ```html ![](http://cdn.schoolstickers.com/products/en/819/GREEN-SMILE-00.png) ``` Now, in CSS, there is a hover "state" that an element can be in, and if you just want to change styling of the element, you don't need any JavaScript at all: ```css img { width:50px; border:2px solid rgba(0,0,0,0); } img:hover { border:2px solid red; } ``` ```html ![](http://cdn.schoolstickers.com/products/en/819/GREEN-SMILE-00.png) ``` Upvotes: 4 <issue_comment>username_2: To actually mimic the CSS hover with script, you'll need two event handlers, `mouseover` and `mouseout`, here done with `addEventListener`. *Updated based on a comment, showing how to toggle a class that is using `transition`, and with that make use of its transition effect to make the "hover" look good.* Stack snippet *(one using JS, one using CSS)* ```js var images = document.querySelector('.images.js'); images.addEventListener('mouseover', changeDefOver); images.addEventListener('mouseout', changeDefOut); function changeDefOver(e) { e.target.classList.toggle('opacity-toggle'); } function changeDefOut(e) { e.target.classList.toggle('opacity-toggle'); } ``` ```css .images { position: relative; } .images2 { position: absolute; left: 0; top: 0; } .images2 img { transition: opacity 1s; } .images2 img.opacity-toggle { opacity: 0; } /* CSS hover */ .css .images2 img:hover { opacity: 0; } ``` ```html This use JS ![](http://placehold.it/100x100/f00) ![](http://placehold.it/100x100/ff0) ![](http://placehold.it/100x100/f0f) ![](http://placehold.it/100x100/0ff) ![](http://placehold.it/100x100/00f) ![](http://placehold.it/100x100) ![](http://placehold.it/100x100) ![](http://placehold.it/100x100) ![](http://placehold.it/100x100) ![](http://placehold.it/100x100) This use CSS (hover) ![](http://placehold.it/100x100/f00) ![](http://placehold.it/100x100/ff0) ![](http://placehold.it/100x100/f0f) ![](http://placehold.it/100x100/0ff) ![](http://placehold.it/100x100/00f) ![](http://placehold.it/100x100) ![](http://placehold.it/100x100) ![](http://placehold.it/100x100) ![](http://placehold.it/100x100) ![](http://placehold.it/100x100) ``` Upvotes: 4 [selected_answer]
2018/03/18
631
1,883
<issue_start>username_0: Im using str\_match in dyplr in R to extract a string from a column and put it into a new column. The full strings look like: ``` Chemical: (BETA-CYFLUTHRIN = 118831) ``` I just want 'BETA-CYFLUTHRIN' so I'm trying to use regex to get the value between ( and = but I've been getting ``` (BETA-CYFLUTHRIN = ``` I know this is probably a really silly question but I've been struggling with this for a while and still can't see to get it. This is what I have so far: any suggestions? thanks! ``` ru2 <- ru2%>%mutate(chem2 = str_extract(chem, "[(](.*?) =")) ```<issue_comment>username_1: Use `str_match` instead, and grab the second value. You don't have to change your pattern at all: ``` x <- "Chemical: (BETA-CYFLUTHRIN = 118831)" str_match(x, "[(](.*?) =") [,1] [,2] # [1,] "(BETA-CYFLUTHRIN =" "BETA-CYFLUTHRIN" str_match(x, "[(](.*?) =")[1,2] # [1] "BETA-CYFLUTHRIN" ``` This works because `str_match` was designed to extract capturing groups (things inside `()`), which is a very useful addition to the regex functions in R indeed. Upvotes: 1 <issue_comment>username_2: You may still use `str_extract`, but you need to use *zero-width assertions* to only grab a piece of a pattern inside some context: ``` str_extract(chem, "(?<=\\().*?(?= =)") ``` The pattern matches: * `(?<=\\()` - there must be a `(` char immediately to the left of the current location * `.*?` - matches any 0+ chars other than line break chars, as few as possible * `(?= =)` - there must be a space and `=` immediately to the right of the current location. **[See the regex demo](https://regex101.com/r/e4Ikay/1)** A base R equivalent could look like ``` regmatches(x, regexpr("(?<=\\().*?(?= =)", x, perl=TRUE)) # => [1] "BETA-CYFLUTHRIN" ``` See an [R demo online](https://ideone.com/pagVgr). Upvotes: 3 [selected_answer]
2018/03/18
3,428
10,607
<issue_start>username_0: I have made a tic-tac-toe game , where i make 9 buttons and then mark the button `x` or `o` by turn and change the color for the mark. I also have a `checkIsWinner` function that checks the winning combinations. If the combination is a winner then i use a variable and check it true if there is a combination, i use this variable so that i can perform `System.exit(0)`, to exit from the program. But this variable trick doesn't seem to work. Please help. I want to stop the program when there is a winner. ```html var table = []; var blocks = 9; var player1, player2, boardId; var elem, Id; var chance = 1; var tie = 10; var isWinner = false; var checkTie = false; var buttonKey; var outputArray = []; var array1, array2, array3, array4, array5, array6, array7, array8, array9, array10, array11, array12; var array13, array14, array15, array16, array17, array0; winningCombinations = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7] ]; $(document).ready(function() { buttonId = 1; for (var index = 0; index < blocks; index++) { buttonKey = document.createElement("button"); if ((index == 3 || index == 6)) { lineBreak = document.createElement('br'); document.body.appendChild(lineBreak); } buttonKey.innerHTML = " + "; buttonKey.id = buttonId; buttonKey.setAttribute("value", buttonId); buttonKey.setAttribute("text", buttonId); // button.setAttribute("onclick",selectColor()); buttonKey.style.fontFamily = "Times New Roman"; buttonKey.style.backgroundSize = "50px"; buttonKey.style.backgroundColor = "#C0C0C0"; buttonKey.style.fontSize = "25px"; buttonKey.style.marginBottom = "10px"; buttonKey.style.marginLeft = "5px"; buttonKey.style.marginRight = "5px"; document.body.appendChild(buttonKey); buttonId++; buttonKey.addEventListener("click", function(event) { selectMark(event, event.srcElement); checkIsWinner(); if (isWinner == true || checkTie == true) { return false; } }); } }); function selectMark(currentObject, currentType) { if (chance % 2 != 0) { player1 = 'x'; outputArray.push([currentType.id, player1]); document.getElementById(currentType.id).innerHTML = player1; document.getElementById(currentType.id).style.backgroundColor = '#238EE1'; } else { player2 = 'o'; outputArray.push([currentType.id, player2]); document.getElementById(currentType.id).innerHTML = player2; document.getElementById(currentType.id).style.backgroundColor = '#FF1010'; } chance++; } function checkIsWinner(currentObject, currentType) { winningCombinations = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7] ]; if (chance == 2) { array1 = outputArray[0][0]; array2 = outputArray[0][1]; console.log("array1=" + array1 + " array2=" + array2) } if (chance == 3) { array3 = outputArray[1][0]; array4 = outputArray[1][1]; console.log("array3 = " + array3 + " array4 = " + array4); } if (chance == 4) { array5 = outputArray[2][0]; array6 = outputArray[2][1]; console.log("array5 = " + array5 + " array6 = " + array6); } if (chance == 5) { array7 = outputArray[3][0]; array8 = outputArray[3][1]; console.log("array7 = " + array7 + " array8 = " + array8); } if (chance == 6) { array9 = outputArray[4][0]; array10 = outputArray[4][1]; console.log("array9 =" + array9 + " array10 = " + array10); } if (chance == 7) { array11 = outputArray[5][0]; array12 = outputArray[5][1]; console.log("array11 =" + array11 + " array12 = " + array12); } if (chance == 8) { array13 = outputArray[6][0]; array14 = outputArray[6][1]; console.log("array13 =" + array13 + " array14 = " + array14); } if (chance == 9) { array15 = outputArray[7][0]; array16 = outputArray[7][1]; console.log("array15 =" + array15 + " array16 = " + array16); } if (chance == 10) { array17 = outputArray[8][0]; array18 = outputArray[8][1]; console.log("array17 = " + array17 + " array18 = " + array18); } for (var row = 0; row < 8; row++) { // console.log("array[row]="+outputArray[row]); answer1 = winningCombinations[row][0]; answer2 = winningCombinations[row][1]; answer3 = winningCombinations[row][2]; if (((array1 == answer1 || array1 == answer2 || array1 == answer3) && (array5 == answer1 || array5 == answer2 || array5 == answer3) && (array9 == answer1 || array9 == answer2 || array9 == answer3))) { console.log("player 1 is the Winner"); isWinner = true; break; } if ((array1 == answer1 || array1 == answer2 || array1 == answer3) && (array5 == answer1 || array5 == answer2 || array5 == answer3) && (array13 == answer1 || array13 == answer2 || array13 == answer3)) { isWinner = true; console.log("player 1 is the Winner"); break; } if ((array1 == answer1 || array1 == answer2 || array1 == answer3) && (array5 == answer1 || array5 == answer2 || array5 == answer3) && (array17 == answer1 || array17 == answer2 || array17 == answer3)) { console.log("player 1 is the Winner"); isWinner = true; break; } if ((array1 == answer1 || array1 == answer2 || array1 == answer3) && (array9 == answer1 || array9 == answer2 || array9 == answer3) && (array13 == answer1 || array13 == answer2 || array13 == answer3)) { console.log("player 1 is the Winner"); isWinner = true; break; } if ((array1 == answer1 || array1 == answer2 || array1 == answer3) && (array9 == answer1 || array9 == answer2 || array9 == answer3) && (array17 == answer1 || array17 == answer2 || array17 == answer3)) { console.log("player 1 is the Winner"); isWinner = true; break; } if ((array9 == answer1 || array9 == answer2 || array9 == answer3) && (array5 == answer1 || array5 == answer2 || array5 == answer3) && (array13 == answer1 || array13 == answer2 || array13 == answer3)) { console.log("player 1 is the Winner"); isWinner = true; break; } if ((array9 == answer1 || array9 == answer2 || array9 == answer3) && (array5 == answer1 || array5 == answer2 || array5 == answer3) && (array17 == answer1 || array17 == answer2 || array17 == answer3)) { console.log("player 1 is the Winner"); isWinner = true; break; } if ((array9 == answer1 || array9 == answer2 || array9 == answer3) && (array13 == answer1 || array13 == answer2 || array13 == answer3) && (array17 == answer1 || array17 == answer2 || array17 == answer3)) { console.log("player 1 is the Winner"); isWinner = true; break; } if ((array1 == answer1 || array1 == answer2 || array1 == answer3) && (array13 == answer1 || array13 == answer2 || array13 == answer3) && (array17 == answer1 || array17 == answer2 || array17 == answer3)) { console.log("player 1 is the Winner"); winner = true; break; } if ((array13 == answer1 || array13 == answer2 || array13 == answer3) && (array5 == answer1 || array5 == answer2 || array5 == answer3) && (array17 == answer1 || array17 == answer2 || array17 == answer3)) { console.log("player 1 is the Winner"); isWinner = true; break; } if ((array3 == answer1 || array3 == answer2 || array3 == answer3) && (array7 == answer1 || array7 == answer2 || array7 == answer3) && (array11 == answer1 || array11 == answer2 || array11 == answer3)) { console.log("player 2 is the Winner"); isWinner = true; break; } if ((array3 == answer1 || array3 == answer2 || array3 == answer3) && (array7 == answer1 || array7 == answer2 || array7 == answer3) && (array15 == answer1 || array15 == answer2 || array15 == answer3)) { console.log("player 2 is the Winner"); isWinner = true; break; } if ((array3 == answer1 || array3 == answer2 || array3 == answer3) && (array15 == answer1 || array15 == answer2 || array15 == answer3) && (array11 == answer1 || array11 == answer2 || array11 == answer3)) { console.log("player 2 is the Winner"); isWinner = true; break; } if ((array15 == answer1 || array15 == answer2 || array15 == answer3) && (array7 == answer1 || array7 == answer2 || array7 == answer3) && (array11 == answer1 || array11 == answer2 || array11 == answer3)) { console.log("player 2 is the Winner"); isWinner = true; break; } } tie--; if (tie <= 1) { console.log("Its a tie. Game Over !"); checkTie = true; } } ```<issue_comment>username_1: There's no such thing in in-browser Javascript as "exit the program", other than closing the browser window or navigating to a new page. You can't call Java functions in Javascript because the two languages have nothing to do with one another, other than a highly unfortunate branding decision back in the day. You already have an `isWinner` boolean to keep track of whether the game is supposed to be over, but currently you're not doing anything with it: ``` buttonKey.addEventListener("click", function(event) { selectMark(event, event.srcElement); checkIsWinner(); if (isWinner == true || checkTie == true) { return false; } }); ``` `return false` from an event handler prevents the event from bubbling to parent elements, which is not at all what you want to do here. One rather bare-bones solution would be to have that function check whether the game is over before doing anything: ``` buttonKey.addEventListener("click", function(event) { if (isWinner == true || checkTie == true) { console.log("The game is already over, no more moves.") } else { selectMark(event, event.srcElement); // you might also want to check whether the button is already marked here, before letting the user re-set it; or remove the click handler from each button as it's used checkIsWinner(); } }); ``` Upvotes: 1 <issue_comment>username_2: If you are executing the script in a web browser, you can try to use `window.close()`, which closes the current browser window (or the current tab if the window has more than two tabs). But be careful: > > This method is only allowed to be called for windows that were opened > by a script using the window.open() method. If the window was not > opened by a script, an error similar to this one appears in the > console: `Scripts may not close windows that were not opened by script`. > > > See MDN web docs at [link](https://developer.mozilla.org/en-US/docs/Web/API/Window/close). Instead, if you want to re-run the game or show a final screen that states that the game is over, consider modifying your DOM elements in the page, as closing the window/tab is not the best solution in this case. Upvotes: 0
2018/03/18
381
999
<issue_start>username_0: on condition that string may be is "password Rtt3<PASSWORD>6" (without "is"). ``` (?<=password\ is|password\ ).* ``` That regexp doesn't work, because always return "is Rtt3Ved36" (but i need "Rtt3Ved36"). How to keep order in OR condition?<issue_comment>username_1: You may use ``` password(?: is)?\s*(.*) ``` and grab Group 1 value. See the [regex demo](http://regexstorm.net/tester?p=password%28%3F%3A%20is%29%3F%5Cs*%28.*%29&i=password%20Rtt3<PASSWORD>6%0D%0Apassword%20is%20Rtt3Ved36). **Details** * `password` - a literal substring * `(?: is)?` - an optional substring space + `is` * `\s*` - 0+ whitespace * `(.*)` - Group 1: any 0+ chars other than a newline. In C#: ``` var m = Regex.Match(s, @"password(?: is)?\s*(.*)"); var result = string.Empty; if (m.Success) { result = m.Groups[1].Value; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: According to this site: <https://regex101.com/> your regex does work and returns "Rtt3Ved36". Upvotes: -1
2018/03/18
389
1,181
<issue_start>username_0: In my code, if i click the `add_box` icon, it will add another input form below so that I could input more values, but this is the problem shown in this link <http://g.recordit.co/R0iifhd6Wd.gif> and this is my code ### Component.ts ```js instrumentsData = { particulars: '' } addParticular() { this.particulars.push(''); } ``` ### Component.html ```html *add\_box* * ```<issue_comment>username_1: the problem is simple. your are using the same ngModel for all your inputs, that's why you can see that behavior in your app if particular is a array then you can do it like ``` *add\_box* * ``` Upvotes: 0 <issue_comment>username_2: The reason why you get this issue is you always bind 1 value in ngModel instrumentsData.particular You could resolve your issue by doing like this: HTML: ``` *add\_box* * ``` Component.ts: ``` ... particulars: any[] = []; addParticular() { this.particulars.push(''); } trackByFn(index, item) { return index; } ... ``` Here is your plunker: <https://plnkr.co/edit/98mLfBla5KQqx4hpNne2?p=preview> Or it could be another array then you don't need trackBy in \*ngFor Upvotes: 1
2018/03/18
1,118
3,866
<issue_start>username_0: I am writing a Sudoku generator/solver in Haskell as a learning exercise. My `solve` function takes in a `UArray` but returns a `State Int (UArray ...)` so that it can also return the maximum difficulty level that it found while solving. This is my function so far (still in the very experimental early stage): ``` import Control.Monad.State (State, put) import Control.Monad.Trans.Class (lift) import Data.Array.MArray (thaw) import Data.Array.ST (runSTUArray) import Data.Array.Unboxed (UArray) -- ... type Cell = Word16 solve :: UArray (Int, Int) Cell -> State Int (UArray (Int, Int) Cell) solve grid = do return $ runSTUArray $ do arr <- thaw grid lift $ put 42 return arr ``` It does not really do anything with the mutable array yet. I am simply trying to get it to type check with the `put 42`, but currently get the following error: ``` • Couldn't match kind ‘*’ with ‘* -> *’ When matching the kind of ‘ST’ • In a stmt of a 'do' block: lift $ put 42 In the second argument of ‘($)’, namely ‘do arr <- thaw grid lift $ put 42 return arr’ In the second argument of ‘($)’, namely ‘runSTUArray $ do arr <- thaw grid lift $ put 42 return arr’ | 128 | lift $ put 42 | ^^^^^^^^^^^^^ ```<issue_comment>username_1: `solve grid` has form `return $ ...`. This means that `State Int (UArray (Int, Int) Cell)` is just specialized `Monad m => m (UArray (Int, Int) Cell)` - the `...` does not have access to the features of this specific monad, it's just a `UArray (Int, Int) Cell` value that you return. Upvotes: 0 <issue_comment>username_2: `runSTUArray ...` is a pure value, it does not know anything about "outer monad". And `State` cares about how you use it, you cannot pass it opaquely into ST. What you could do: **Option1**: change the whole program to move more logic to ST side. Instead of State you'd use STRef then: ``` solve :: ST s (STRef Int) -> ST s (UArray (Int, Int) Cell) -> ST s () ... ``` **Option2**: manually extract it and pass it to ST, then get back and put explicitly. But there is complication. `runSTUArray` does not allow getting another value together with the array. I don't know how it can be done safely with current array functions. Unsafely you could re-implement better `runSTUArray` which can pass another value. You could also add fake cells and encode the new state there. The way to export another value exists in the vector package, there is (in new versions) `createT` function which can take not bare vector but a structure containing it (or even several vectors). So, overall, your example would be like: ``` import Control.Monad.State (State, put, get) import Data.Word (Word16) import qualified Data.Vector.Unboxed as DVU type Cell = Word16 solve :: DVU.Vector Cell -> State Int (DVU.Vector Cell) solve grid = do oldState <- get let (newState, newGrid) = DVU.createT (do arr <- DVU.thaw grid pure (oldState + 42, arr)) put newState pure newGrid ``` vectors are one-dimensional only, unfortunately Upvotes: 1 <issue_comment>username_3: I was able to get a slight variation to compile and run after changing the `State` monad to a tuple `(Int, Grid)`: ``` import Control.Monad.ST (ST, runST) import Data.Array.MArray (freeze, thaw, writeArray) import Data.Array.ST (STUArray) import Data.Array.Unboxed (UArray) import Data.Word (Word16) type Cell = Word16 type Grid = UArray (Int, Int) Cell solve :: Grid -> (Int, Grid) solve grid = runST $ do mut <- thaw grid :: ST s (STUArray s (Int, Int) Cell) writeArray mut (0, 0) 0 -- test that I can actually write frozen <- freeze mut return (42, frozen) ``` This works fine for my application. Upvotes: 1 [selected_answer]
2018/03/18
923
2,743
<issue_start>username_0: I would like to share with you my thoughts about this code: ``` for (var i = 1, max = 5; i < max; i++) { let random = Math.random(); let expression = (random < 1 / (i + 1)); if (expression){ console.log('random is: ' + random + ' and the expression is: ' + expression + ', i is: ' + i); }else{ console.log('random was: ' + random + ' and the expression was: ' + expression + ', i was: ' + i); } } ``` I was studying this example taken from GitHub: <https://github.com/chuckha/ColorFlood> And I had trouble trying to know what was the meaning of the expression inside the if(). I used the JS repl: <https://jscomplete.com/repl/> The context of this example is that this function would take a random index from 0 to 5, to map a random color to a Node. Here we have a sample output from the repl: ``` "random was: 0.7118559117992413 and the expression was: false, i was: 1" "random was: 0.478919411809795 and the expression was: false, i was: 2" "random was: 0.4610390397998597 and the expression was: false, i was: 3" "random was: 0.7051121468181564 and the expression was: false, i was: 4" ```<issue_comment>username_1: I first thought that it would be evaluated random < 1 so then as random uses Math.random() which gets a number between 0 and 1, excluding the one; I thought that part of the expression would be alway true. But in fact after putting it into the repl I discovered that the 1 / (i+1) part is done first, and then it is done all together: random / result. I have also read: <https://www.w3schools.com/js/js_comparisons.asp> <https://www.w3schools.com/js/js_arithmetic.asp> <https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/random> Please note that in the original post I simplified the code, the original code is: ``` var randomIndexFromCollection = function randomIndexFromCollection(collection) { var index = 0; for (var i = 1, max = collection.length; i < max; i++) { if (Math.random() < 1 / (i + 1)) { index = i; debugger; } } return index; }; ``` Upvotes: 0 <issue_comment>username_2: The syntax: ``` let expression = (random < 1 / (i + 1)); ``` Means: * `(i + 1)` first add 1 to var `i` * Next, `1 / (i + 1)` divide 1 by the sum `(i + 1)` + Let say `result = 1 / (i + 1)` * `random < result`, if the random value less than above division `result` than return true, else false. So, something simple like: ```js for (var i = 1, max = 5; i < max; i++) { let random = Math.random(); let expression = (random < 1 / (i + 1)); console.log( i, random.toFixed(2), (1 / (i + 1)).toFixed(2), expression ) } ``` Upvotes: 2 [selected_answer]
2018/03/18
835
2,574
<issue_start>username_0: I have an array : ``` myData: [{ name: "", lastName: "", historicalData: [{ data1: '', data2: 0, }, { data1: '', data2: 30, } ] }, { name: "", lastName: "", historicalData: [{ data1: '', data2: 6, }, { data1: '', data2: 1, } ] } ] ``` I want to iterate through this array, filter it to have all the data where data2 > 2. And then sort that result by data1. Since it is a nested array of object within an array of objects, I'm unsure of how to iterate and filter in es6. Any suggestions ? ``` myData.filter(oneData => historicalData.data1 > 2) ``` But initially I would have to map through the historical data too. Expected result: ``` myData: [{ name: "", lastName: "", historicalData: [{ data1: '', data2: 30, }] },{ name: "", lastName: "", historicalData: [{ data1: '', data2: 6, }] }] ``` Once I have this result then I can sort accordingly. THanks<issue_comment>username_1: I first thought that it would be evaluated random < 1 so then as random uses Math.random() which gets a number between 0 and 1, excluding the one; I thought that part of the expression would be alway true. But in fact after putting it into the repl I discovered that the 1 / (i+1) part is done first, and then it is done all together: random / result. I have also read: <https://www.w3schools.com/js/js_comparisons.asp> <https://www.w3schools.com/js/js_arithmetic.asp> <https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math/random> Please note that in the original post I simplified the code, the original code is: ``` var randomIndexFromCollection = function randomIndexFromCollection(collection) { var index = 0; for (var i = 1, max = collection.length; i < max; i++) { if (Math.random() < 1 / (i + 1)) { index = i; debugger; } } return index; }; ``` Upvotes: 0 <issue_comment>username_2: The syntax: ``` let expression = (random < 1 / (i + 1)); ``` Means: * `(i + 1)` first add 1 to var `i` * Next, `1 / (i + 1)` divide 1 by the sum `(i + 1)` + Let say `result = 1 / (i + 1)` * `random < result`, if the random value less than above division `result` than return true, else false. So, something simple like: ```js for (var i = 1, max = 5; i < max; i++) { let random = Math.random(); let expression = (random < 1 / (i + 1)); console.log( i, random.toFixed(2), (1 / (i + 1)).toFixed(2), expression ) } ``` Upvotes: 2 [selected_answer]
2018/03/18
960
2,957
<issue_start>username_0: I am setting up a aws server for Django Server. I have successfully installed python3.5.1, pip and django. Following aws documentation i am running the following command : > > pip install awsebcli > > > I get this Error: ``` Collecting awsebcli Using cached awsebcli-3.12.4.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "/tmp/pip-build-1eejewt6/awsebcli/setup.py", line 46, in long\_description=open('README.rst').read() + open('CHANGES.rst').read(), File "/usr/lib/python3.5/encodings/ascii.py", line 26, in decode return codecs.ascii\_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4092: ordinal not in range(128) ---------------------------------------- Command "python setup.py egg\_info" failed with error code 1 in /tmp/pip-build-1eejewt6/awsebcli/ ``` like error occurs when trying to opean and read rst files. Eb repo can be found [here](https://pypi.python.org/packages/45/fd/f0f7ff9cba9a2ab803881d7d910ea06985834eee5ce28a09329b6c1a51e3/awsebcli-3.12.4.tar.gz) . I tried fixing the error in package and run manually but no success. Why is there an error in official repo? Am i missing something?<issue_comment>username_1: I manually installed an older version (3.10.0) located [here](https://pypi.python.org/packages/23/f6/b73be78b302037e3bbc01c3be9d8d3936e2fc4a61087d6fb41018c420b07/awsebcli-3.10.0.tar.gz) and this one is working fine. Upvotes: 4 [selected_answer]<issue_comment>username_2: In awsebcli package for version >= 3.10.3, some changes were added in CHANGES.rst which had a unicode character 'ã' on Line 156. This is causing the mentioned error while installing in some os versions. If awsebcli version >= 3.10.3 is required, then install the package the manually till there is no official resolution from aws. Follow [this answer](https://stackoverflow.com/questions/13270877/how-to-manually-install-a-pypi-module-without-pip-easy-install/13271241#13271241) of how to install a package manually. Before installing remove the unicode character in CHANGES.rst file. It will work fine. Upvotes: 2 <issue_comment>username_3: The error is in changes.rst and/or readme file. they are not required for the installation. so open the files, delete its contents and save. manually install it by going to the folder and executing `python setup.py install` Upvotes: 0 <issue_comment>username_4: In my case, I found that I had to install the setuptools first by doing `pip install setuptools` then the installation of awsebcli went successfully. Upvotes: 0 <issue_comment>username_5: From <https://forums.aws.amazon.com/thread.jspa?messageID=897654&tstart=0> I decided to try `export LC_ALL=en_US.UTF-8` and loading the README.rst and CHANGES.rst files no longer threw the encoding error. This avoids manually manipulating the package files. Upvotes: 1
2018/03/18
1,270
4,217
<issue_start>username_0: I have created an API using Go. It's working fine in postman but not when consumed using javascript. When I post request using javascript I'm getting an error saying that Access-Control-Allow-Origin is set to null. go API code: ``` package main import ( "fmt" "encoding/json" "github.com/gorilla/mux" "log" "net/http" ) type Calculate struct { Operand1 string `json:"Operand1,omitempty"` Operand2 string `json:"Operand2,omitempty"` Operator string `json:"Operator,omitempty"` } type Answer struct { Res string `json:"Res,omitempty"` } func do_Calculation(w http.ResponseWriter, r *http.Request) { var cal Calculate var ans Answer fmt.Println("Request Reached") w.Header().Set("Access-Control-Allow-Headers", "Content-Type") w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.Header().Set("Access-Control-Allow-Origin", "*") w.WriteHeader(http.StatusOK) json.NewDecoder(r.Body).Decode(&cal) // my stuff // res := do_Operations(convertToFloat(cal.Operand1),convertToFloat(cal.Operand2),cal.Operator) // ans = Answer{Res: floattostrwithprec(res, 4)} json.NewEncoder(w).Encode(ans) } // main function to boot up everything func main() { router := mux.NewRouter() router.HandleFunc("/calculate", do_Calculation).Methods("POST") fmt.Println("Server online at port :8000") log.Fatal(http.ListenAndServe(":8000", router)) } ``` javascript code: ``` var data = JSON.stringify({ "Operand1": "2.6", "Operand2": "2.4", "Operator": "+" }); var xhr = new XMLHttpRequest(); xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { console.log(this.responseText); } }); xhr.open("POST", "http://localhost:8000/calculate"); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("Cache-Control", "no-cache"); xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); xhr.setRequestHeader("Access-Control-Allow-Methods", "POST"); xhr.withCredentials = true; xhr.send(data); ``` error: > > Failed to load <http://127.0.0.1:8000/calculate>: Response to preflight > request doesn't pass access control check: The value of the > 'Access-Control-Allow-Origin' header in the response must not be the > wildcard '\*' when the request's credentials mode is 'include'. Origin > 'null' is therefore not allowed access. The credentials mode of > requests initiated by the XMLHttpRequest is controlled by the > withCredentials attribute. > > ><issue_comment>username_1: I manually installed an older version (3.10.0) located [here](https://pypi.python.org/packages/23/f6/b73be78b302037e3bbc01c3be9d8d3936e2fc4a61087d6fb41018c420b07/awsebcli-3.10.0.tar.gz) and this one is working fine. Upvotes: 4 [selected_answer]<issue_comment>username_2: In awsebcli package for version >= 3.10.3, some changes were added in CHANGES.rst which had a unicode character 'ã' on Line 156. This is causing the mentioned error while installing in some os versions. If awsebcli version >= 3.10.3 is required, then install the package the manually till there is no official resolution from aws. Follow [this answer](https://stackoverflow.com/questions/13270877/how-to-manually-install-a-pypi-module-without-pip-easy-install/13271241#13271241) of how to install a package manually. Before installing remove the unicode character in CHANGES.rst file. It will work fine. Upvotes: 2 <issue_comment>username_3: The error is in changes.rst and/or readme file. they are not required for the installation. so open the files, delete its contents and save. manually install it by going to the folder and executing `python setup.py install` Upvotes: 0 <issue_comment>username_4: In my case, I found that I had to install the setuptools first by doing `pip install setuptools` then the installation of awsebcli went successfully. Upvotes: 0 <issue_comment>username_5: From <https://forums.aws.amazon.com/thread.jspa?messageID=897654&tstart=0> I decided to try `export LC_ALL=en_US.UTF-8` and loading the README.rst and CHANGES.rst files no longer threw the encoding error. This avoids manually manipulating the package files. Upvotes: 1
2018/03/18
615
2,425
<issue_start>username_0: I want to make a program which plans park positions for incoming aircrafts at airport in C#. To do that, I need to consider aircrafts' type (big plane or small), domestic or international, terminal 1, or 2 or 3... etc. I can use many if statements such as: --- ``` if(aircraft is terminal 1){ if(aircraft is domestic){ if(aircraft is big){ if(.....) }else if(){ ...... } }else if(){.....} }else if(){....} ``` --- But I don't see this way efficient. My question is that what can I use to check multiple conditions except using long sequences of ifs? Or how should I approach this problem? I would be very glad if you can give me any ideas about this.<issue_comment>username_1: It is a bit hard to tell with so little information as you have given, but one approach would be the following: Define a new class called `ParkingPosition` which contains requirements that an aircraft should meet in order to park there. Create a list of instances of that class, with such requirements. Then, once you have an aircraft that needs to park, loop through all available parking positions, and for each parking position: * See if the aircraft matches the requirements of that parking position, and if so, park it there. Upvotes: 3 [selected_answer]<issue_comment>username_2: If you have a collection of 'gates' for your airport, which have the required properties, you could use LINQ to find what you want quickly. For example, if you have a `Gate` which has the properties you need to check (like `SupportedSize`, `International`, and `TerminalNo`) and your aircraft had similar properties (`Size`, `International` and `Terminal`) then you could do something like this: ``` //(For this example you should have a class defined which has the properties of the parking positions, and one for the aircraft. Here I've used Gate and Plane respectively.) //This is a list of the Gate object. Contains every gate and the properties about them. var Gates = List; Plane aircraft; //This will find spaces compatible with the supplied aircraft IEnumerable usableGates= Gates.Where(gate => gate.SupportedSize==aircraft.Size && gate.International==aircraft.International && gate.Terminal==aircraft.Terminal); //Now any items which appear in usableGates should be usable for that aircraft ``` You can now iterate through `usableGates`, or just pick the first one, and 'park up' there. Upvotes: 1
2018/03/18
479
1,917
<issue_start>username_0: I just have a little question here. How can I make this arrow to back to previous activity? I mean, I know how to code it, but i can't find this arrow. Is it something, that is in e.g. android studio or is it something that i have to make by myself?[![enter image description here](https://i.stack.imgur.com/G3M18.png)](https://i.stack.imgur.com/G3M18.png)<issue_comment>username_1: Use below code to back your previous Activity. Code is Here : ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onSupportNavigateUp(){ finish(); return true; } } ``` Upvotes: 0 <issue_comment>username_2: There are many ways to achieve that, here is what I suggest: Layout: ``` ``` Activity: ``` Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // back button pressed finish(); } }); ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: To show top back arrow you have to enable the display home button `getSupportActionBar().setDisplayHomeAsUpEnabled(true)` and you will get the arrow click event at `onOptionsItemSelected` method. ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item){ if(item.getItemId() == android.R.id.home){ // do your task on arrow click return true; } return super.onOptionsItemSelected(item) } ``` Upvotes: 0
2018/03/18
979
2,830
<issue_start>username_0: Can someone explain how Babel in React supports fat arrow functions as class properties? Using Babel [Try it out](https://babeljs.io/repl/#?babili=false&browsers=&build=&builtIns=false&code_lz=MYGwhgzhAECKCuBTCAXAlgewHbQN4Ch9poBbATwAUAnDAB2gF5oAKASkYD48jjorEU8KjgDkACUQgQGADTQA7hiogAJgEIRAbh4BfHj3IAxeFmBtuvPgKGiJU2QqWqN24nuL49QA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&lineWrap=false&presets=react&prettier=true&targets=&version=6.26.0&envVersion=1.6.2) I can see they are not supported: ``` class Question { // Property (not supported) myProp = () => { return 'Hello, world!'; } // Method (supported) myFunc() { return 'Hello, world!'; } } ``` Class properties are not supported in ES6 (correct me if I'm wrong) but then in React (with Babel) they work. I can see the difference between methods and properties using TypeScript [Playground](https://www.typescriptlang.org/play/index.html#src=class%20Question%20%7B%0D%0A%0D%0A%20%20myProp%20%3D%20()%20%3D%3E%20%7B%0D%0A%20%20%20%20return%20'Hello%2C%20world!'%3B%0D%0A%20%20%7D%0D%0A%20%20%0D%0A%20%20myFunc()%20%7B%0D%0A%20%20%20%20return%20'Hello%2C%20world!'%3B%0D%0A%20%20%7D%0D%0A%20%20%0D%0A%7D%0D%0A) but I can't clearly understand if Babel is supporting them or not. Is there some plug-in? UPDATE: I can see they are supported using [`"babel-preset-stage-0"`](https://babeljs.io/docs/plugins/preset-stage-0/).<issue_comment>username_1: As @illiteratewriter suggested class properties are supported from [Stage 0 preset](https://babeljs.io/docs/plugins/preset-stage-0/). For the time being, they are supported until [Stage 2 preset](https://babeljs.io/docs/plugins/preset-stage-2/): > > The proposal must now additionally have a formal description of the syntax and semantics of the feature (using the formal language of the ECMAScript specification). The description should be as complete as possible, but can contain todos and placeholders. Two experimental implementations of the feature are needed, but one of them can be in a transpiler such as Babel. > > > Upvotes: 0 <issue_comment>username_2: To support class properties, you need to install and add [`babel-plugin-transform-class-properties`](https://babeljs.io/docs/plugins/transform-class-properties/) to the `plugins` setting of your `.babelrc` (or in your `webpack` config). Note that this plugin is also included in * [`babel-preset-stage-0`](https://babeljs.io/docs/plugins/preset-stage-0/) * [`babel-preset-stage-1`](https://babeljs.io/docs/plugins/preset-stage-1) * [`babel-preset-stage-2`](https://babeljs.io/docs/plugins/preset-stage-2) So if you use one of those, you don't need to install `babel-plugin-transform-class-properties` by yourself. Upvotes: 3 [selected_answer]
2018/03/18
480
1,537
<issue_start>username_0: Are both methods alternative to each other or they have any specific role in while adding element in vector in the middle like performance wise?<issue_comment>username_1: `insertElementAt()` will add the new element to the vector preserving the previous elements. `set()` will overwrite the element at the given index. ``` Vector vector = new Vector<>(); vector.add("A"); // A vector.add("B"); // A B vector.insertElementAt("C", 1); // A C B vector.set(1, "D"); // A D B ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: [`insertElementAt`](https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html#insertElementAt-E-int-) inserts the given element at the given index, and shifts all the elements after it. E.g., if you were to insert an element in index 2, the element that was at index 2 before the insertion would now be in index 3, the element at index 3 would now be in 4, etc. [`set`](https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html#set-int-E-), on the other hand, just overwrites the element at the given index. Consider the following snippet: ``` Vector vec = new Vector<>(Arrays.asList("a", "b", "c", "d")); System.out.println(vec); vec.insertElementAt("e", 2); System.out.println(vec); vec.set(2, "f"); System.out.println(vec); ``` The call to `insertElementAt` inserts an "e" between the "b" and the "c". The call to `set` overwrites that "e" with an "f". I.e., the resulting output would be: ``` [a, b, c, d] [a, b, e, c, d] [a, b, f, c, d] ``` Upvotes: 2
2018/03/18
567
1,868
<issue_start>username_0: The problem =========== Is it possible to send a POST request with `Content-Type: application/json` on AMP applications? More context ============ I have a form on my App and I need to perform a POST request on my API with `Content-type: application/json`. I've checked the [amp-form](https://www.ampproject.org/pt_br/docs/reference/components/amp-form) component in order to do it, but I've noticed that it sends a request with the header `content-type: multipart/form-data; boundary=----WebKitFormBoundaryoYJsC0JKaBczGL1z` as you may see [here](https://ampbyexample.com/playground/#url=https%3A%2F%2Fampbyexample.com%2Fcomponents%2Famp-form%2Fsource%2F). [![enter image description here](https://i.stack.imgur.com/VA0Ag.png)](https://i.stack.imgur.com/VA0Ag.png) So, is it possible to change this to `application/json` or the API needs to handle the `content-type: multipart/form-data;` requests as well?<issue_comment>username_1: I've checked the [link](https://ampbyexample.com/playground/#url=https%3A%2F%2Fampbyexample.com%2Fcomponents%2Famp-form%2Fsource%2F) you've provided and I got a `content-type: application/json`. [![Check this image.](https://i.stack.imgur.com/sps7P.png)](https://i.stack.imgur.com/sps7P.png) Based from this [documentation](https://www.ampproject.org/pt_br/docs/reference/components/amp-form#success/error-response-rendering), both success and error responses should have a `Content-Type: application/json` header. `submit-success` will render for all responses that has a status of `2XX`, all other statuses will render `submit-error`. Upvotes: -1 <issue_comment>username_2: I think you need the API to handle it. The fetch event [seems to always going to have multipart/form-data](https://github.com/ampproject/amphtml/blob/master/src/service/xhr-impl.js#L223). Regards, Upvotes: 3 [selected_answer]
2018/03/18
488
1,446
<issue_start>username_0: I am trying to parse json response from an API. ``` response = requests.post('https://analysis.lastline.com/analysis/get_completed', files=files) my = response.json() print my ``` **Output:** ``` {u'data': {u'tasks': [], u'more_results_available': 0, u'after': u'2018-03-18 22:00:20', u'before': u'2018-03-18 17:00:22'}, u'success': 1} ``` Here `my` is a dictionary. Now I want to get values against the keys. I have tried this: ``` print my['tasks'] ``` It gives me `KeyError`.<issue_comment>username_1: I've checked the [link](https://ampbyexample.com/playground/#url=https%3A%2F%2Fampbyexample.com%2Fcomponents%2Famp-form%2Fsource%2F) you've provided and I got a `content-type: application/json`. [![Check this image.](https://i.stack.imgur.com/sps7P.png)](https://i.stack.imgur.com/sps7P.png) Based from this [documentation](https://www.ampproject.org/pt_br/docs/reference/components/amp-form#success/error-response-rendering), both success and error responses should have a `Content-Type: application/json` header. `submit-success` will render for all responses that has a status of `2XX`, all other statuses will render `submit-error`. Upvotes: -1 <issue_comment>username_2: I think you need the API to handle it. The fetch event [seems to always going to have multipart/form-data](https://github.com/ampproject/amphtml/blob/master/src/service/xhr-impl.js#L223). Regards, Upvotes: 3 [selected_answer]
2018/03/18
1,651
6,686
<issue_start>username_0: When .NET first came out, I was one of many who complained about .NET's lack of deterministic finalization (class destructors being called on an unpredictable schedule). The compromise Microsoft came up with at the time was the `using` statement. Although not perfect, I think using `using` is important to ensuring that unmanaged resources are cleaned up in a timely manner. However, I'm writing some ADO.NET code and noticed that almost every class implements `IDisposable`. That leads to code that looks like this. ``` using (SqlConnection connection = new SqlConnection(connectionString)) using (SqlCommand command = new SqlCommand(query, connection)) using (SqlDataAdapter adapter = new SqlDataAdapter(command)) using (SqlCommandBuilder builder = new SqlCommandBuilder(adapter)) using (DataSet dataset = new DataSet()) { command.Parameters.AddWithValue("@FirstValue", 2); command.Parameters.AddWithValue("@SecondValue", 3); adapter.Fill(dataset); DataTable table = dataset.Tables[0]; foreach (DataRow row in table.Rows) // search whole table { if ((int)row["Id"] == 4) { row["Value2"] = 12345; } else if ((int)row["Id"] == 5) { row.Delete(); } } adapter.Update(table); } ``` I *strongly* suspect I do not need all of those `using` statements. But without understanding the code for each class in some detail, it's hard to be certain which ones I can leave out. The results is kind of ugly and detracts from the main logic in my code. Does anyone know why all these classes need to implement `IDisposable`? (Microsoft has many [code examples online](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommandbuilder(v=vs.110).aspx) that don't worry about disposing many of these objects.) Are other developers writing `using` statements for all of them? And, if not, how do you decide which ones can do without?<issue_comment>username_1: If a class implements `IDisposable`, then you should always make sure that it gets disposed, without making any assumptions about its implementation. I think that's the minimal amount of code that you could possibly write that ensures that your objects will be disposed. I see absolutely no problem with it, and it does not distract me at all from the main logic of my code. If reducing this code is of paramount importance to you, then you can come up with your own replacement (wrapper) of `SqlConnection` whose child classes do not implement `IDisposable` and instead get automatically destroyed by the connection once the connection is closed. However, that would be a huge amount of work, and you would lose some precision with regards to when something gets disposed. Upvotes: 2 <issue_comment>username_2: One part of the problem here is that ADO.NET is an abstract provider model. We *don't know* what a specific implementation (a specific ADO.NET provider) will need with regards to disposal. Sure, we can reasonably assume the connection and transaction need to be disposed, but the command? Maybe. Reader? Probably, not least because one of the command-flags options allows you to associate a connection's lifetime to the reader (so the connection closes when the reader does, which should logically extend to disposal). So overall, I think it is probably fine. Most of the time, people aren't messing with ADO.NET by hand, and any ORM tools (or micro-ORM tools, such as "Dapper") will get this right *for you* without you having to worry about it. --- I will openly confess that on the few occasions when I've used `DataTable` (seriously, it is 2018 - that shouldn't be your default model for representing data, except for some niche scenarios): I haven't disposed them. That one kinda makes no sense :) Upvotes: 3 [selected_answer]<issue_comment>username_3: Yes. almost anything in ADO.Net is implementing `IDisposable`, whether that's actually needed - in case of, say, `SqlConnection`([because of connection pooling](https://stackoverflow.com/questions/48210258/how-to-keep-single-sql-server-connection-instance-open-for-multiple-request-in-c/48210460#48210460)) or not - in case of, say, `DataTable` ([Should I Dispose() DataSet and DataTable?](https://stackoverflow.com/questions/913228/should-i-dispose-dataset-and-datatable) ). The problem is, as noted in the question: > > without understanding the code for each class in some detail, it's hard to be certain which ones I can leave out. > > > I think that this alone is a good enough reason to keep everything inside a `using` statement - in one word: Encapsulation. In many words: It shouldn't be necessary to get intimately familiar, or even remotely familiar for that matter, with the implementation of every class you are working with. You only need to know the surface area - meaning public methods, properties, events, indexers (and fields, if that class has public fields). from the user of a class point of view, anything other then it's public surface area is an implementation detail. Regarding all the `using` statements in your code - You can write them only once by creating a method that will accept an SQL statement, an `Action` and a params array of parameters. Something like this: ``` void DoStuffWithDataTable(string query, Action action, params SqlParameter[] parameters) { using (SqlConnection connection = new SqlConnection(connectionString)) using (SqlCommand command = new SqlCommand(query, connection)) using (SqlDataAdapter adapter = new SqlDataAdapter(command)) using (SqlCommandBuilder builder = new SqlCommandBuilder(adapter)) using (var table = new DataTable()) { foreach(var param in parameters) { command.Parameters.Add(param); } // SqlDataAdapter has a fill overload that only needs a data table adapter.Fill(table); action(); adapter.Update(table); } } ``` And you use it like that, for all the actions you need to do with your data table: ``` DoStuffWithDataTable( "Select...", table => { // of course, that doesn't have to be a lambda expression here... foreach (DataRow row in table.Rows) // search whole table { if ((int)row["Id"] == 4) { row["Value2"] = 12345; } else if ((int)row["Id"] == 5) { row.Delete(); } } }, new SqlParameter[] { new SqlParameter("@FirstValue", 2), new SqlParameter("@SecondValue", 3) } ); ``` This way your code is "safe" with regards of disposing any `IDisposable`, while you have only written the plumbing code for that just once. Upvotes: 1
2018/03/18
1,436
5,453
<issue_start>username_0: I'm working on a project that calculates the derivative of the speed and the integral of the acceleration. my problem is that I have a lot of acceleration points and speed over time and I can not find the right program for that. example: * acceleration from 0 km / h to 40 km / h in 5 seconds * from 5 to 10 seconds, the speed is constant 40km/h; * from 10 to 17 seconds there is a deceleration from 40 km / h to 20 km / h So dv/dt = (v2-v1)/(t2-t1) but I don't know how to declare multiple variables for v1 v2 t1 t2 ``` function a=acc(v1,v2,t1,t2) a= (v2-v1)/(t2-t1) endfunction v1= v2= t1= t2= disp(acc(v1,v2,t1,t2),'acc = ') ``` and the same for the integral of (dv/dt)\*dt please help me guys<issue_comment>username_1: If a class implements `IDisposable`, then you should always make sure that it gets disposed, without making any assumptions about its implementation. I think that's the minimal amount of code that you could possibly write that ensures that your objects will be disposed. I see absolutely no problem with it, and it does not distract me at all from the main logic of my code. If reducing this code is of paramount importance to you, then you can come up with your own replacement (wrapper) of `SqlConnection` whose child classes do not implement `IDisposable` and instead get automatically destroyed by the connection once the connection is closed. However, that would be a huge amount of work, and you would lose some precision with regards to when something gets disposed. Upvotes: 2 <issue_comment>username_2: One part of the problem here is that ADO.NET is an abstract provider model. We *don't know* what a specific implementation (a specific ADO.NET provider) will need with regards to disposal. Sure, we can reasonably assume the connection and transaction need to be disposed, but the command? Maybe. Reader? Probably, not least because one of the command-flags options allows you to associate a connection's lifetime to the reader (so the connection closes when the reader does, which should logically extend to disposal). So overall, I think it is probably fine. Most of the time, people aren't messing with ADO.NET by hand, and any ORM tools (or micro-ORM tools, such as "Dapper") will get this right *for you* without you having to worry about it. --- I will openly confess that on the few occasions when I've used `DataTable` (seriously, it is 2018 - that shouldn't be your default model for representing data, except for some niche scenarios): I haven't disposed them. That one kinda makes no sense :) Upvotes: 3 [selected_answer]<issue_comment>username_3: Yes. almost anything in ADO.Net is implementing `IDisposable`, whether that's actually needed - in case of, say, `SqlConnection`([because of connection pooling](https://stackoverflow.com/questions/48210258/how-to-keep-single-sql-server-connection-instance-open-for-multiple-request-in-c/48210460#48210460)) or not - in case of, say, `DataTable` ([Should I Dispose() DataSet and DataTable?](https://stackoverflow.com/questions/913228/should-i-dispose-dataset-and-datatable) ). The problem is, as noted in the question: > > without understanding the code for each class in some detail, it's hard to be certain which ones I can leave out. > > > I think that this alone is a good enough reason to keep everything inside a `using` statement - in one word: Encapsulation. In many words: It shouldn't be necessary to get intimately familiar, or even remotely familiar for that matter, with the implementation of every class you are working with. You only need to know the surface area - meaning public methods, properties, events, indexers (and fields, if that class has public fields). from the user of a class point of view, anything other then it's public surface area is an implementation detail. Regarding all the `using` statements in your code - You can write them only once by creating a method that will accept an SQL statement, an `Action` and a params array of parameters. Something like this: ``` void DoStuffWithDataTable(string query, Action action, params SqlParameter[] parameters) { using (SqlConnection connection = new SqlConnection(connectionString)) using (SqlCommand command = new SqlCommand(query, connection)) using (SqlDataAdapter adapter = new SqlDataAdapter(command)) using (SqlCommandBuilder builder = new SqlCommandBuilder(adapter)) using (var table = new DataTable()) { foreach(var param in parameters) { command.Parameters.Add(param); } // SqlDataAdapter has a fill overload that only needs a data table adapter.Fill(table); action(); adapter.Update(table); } } ``` And you use it like that, for all the actions you need to do with your data table: ``` DoStuffWithDataTable( "Select...", table => { // of course, that doesn't have to be a lambda expression here... foreach (DataRow row in table.Rows) // search whole table { if ((int)row["Id"] == 4) { row["Value2"] = 12345; } else if ((int)row["Id"] == 5) { row.Delete(); } } }, new SqlParameter[] { new SqlParameter("@FirstValue", 2), new SqlParameter("@SecondValue", 3) } ); ``` This way your code is "safe" with regards of disposing any `IDisposable`, while you have only written the plumbing code for that just once. Upvotes: 1
2018/03/18
1,339
3,963
<issue_start>username_0: I have a mongodb db with 18625 collections. It has following keys: ``` "_id" : ObjectId("5aab14d2fc08b46adb79d99c"), "game_id" : NumberInt(4), "score_phrase" : "Great", "title" : "NHL 13", "url" : "/games/nhl-13/ps3-128181", "platform" : "PlayStation 3", "score" : 8.5, "genre" : "Sports", "editors_choice" : "N", "release_year" : NumberInt(2012), "release_month" : NumberInt(9), "release_day" : NumberInt(11) ``` Now, i wish to create another dimension/ collection with only genres. If i use the following query : ``` db.ign.aggregate([ {$project: {"genre":1}}, { $out: "dimen_genre" } ]); ``` It generates 18625 collections, even though there are only 113 distinct genres. How to apply distinct here and get the collection for genres with only the distinct 113 values. I googled, bt it showed that aggregate and distinct don't work together in mongo. I also tried : db.dimen\_genre.distinct('genre').length this showed that in dimension\_genre, there are 113 distinct genres. Precisely, how to make a collection from existing one with only distinct values. I am really new to NoSQLs.<issue_comment>username_1: You can use [$addToSet](https://docs.mongodb.com/manual/reference/operator/update/addToSet/) to group unique values in one document and then [$unwind](https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/index.html) to get back multiple docs: ``` db.ign.aggregate([ { $group: { _id: null, genre: { $addToSet: "$genre" } } }, { $unwind: "$genre" }, { $project: { _id: 0 } }, { $out: "dimen_genre" } ]); ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: You can try ``` db.names.aggregate( [ { $group : { _id : "$genre", books: { $push: "$$ROOT" } } } ] ) ``` I have tried with Test and Sports as genre It gives you output something like this ``` { "_id" : "Test", "books" : [ { "_id" : ObjectId("5aaea6150cc1403ee9a02e0c"), "game_id" : 4, "score_phrase" : "Great", "title" : "NHL 13", "url" : "/games/nhl-13/ps3-128181", "platform" : "PlayStation 3", "score" : 8.5, "genre" : "Test", "editors_choice" : "N", "release_year" : 2012, "release_month" : 9, "release_day" : 11 } ] } /* 2 */ { "_id" : "Sports", "books" : [ { "_id" : ObjectId("5aaea3be0cc1403ee9a02d97"), "game_id" : 4, "score_phrase" : "Great", "title" : "NHL 13", "url" : "/games/nhl-13/ps3-128181", "platform" : "PlayStation 3", "score" : 8.5, "genre" : "Sports", "editors_choice" : "N", "release_year" : 2012, "release_month" : 9, "release_day" : 11 }, { "_id" : ObjectId("5aaea3c80cc1403ee9a02d9b"), "game_id" : 4, "score_phrase" : "Great", "title" : "NHL 13", "url" : "/games/nhl-13/ps3-128181", "platform" : "PlayStation 3", "score" : 8.5, "genre" : "Sports", "editors_choice" : "N", "release_year" : 2012, "release_month" : 9, "release_day" : 11 }, { "_id" : ObjectId("5aaea3cf0cc1403ee9a02d9f"), "game_id" : 4, "score_phrase" : "Great", "title" : "NHL 13", "url" : "/games/nhl-13/ps3-128181", "platform" : "PlayStation 3", "score" : 8.5, "genre" : "Sports", "editors_choice" : "N", "release_year" : 2012, "release_month" : 9, "release_day" : 11 } ] } ``` Upvotes: 2
2018/03/18
1,240
4,745
<issue_start>username_0: I have a db with structure like in the image below: [![enter image description here](https://i.stack.imgur.com/7Hcm1.png)](https://i.stack.imgur.com/7Hcm1.png) Here, I need to have multiple brands, and also multiple sub brands under each brand. I tried with 'maps' before, but it was really messy and also learned that it's better to have multiple documents. I am very new to this and has been struggling with it for 3-4 days now. Any help would be much appreciated. ``` firebaseFirestore.collection("Coffee").addSnapshotListener(new EventListener() { @Override public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) { if (e != null) { Log.d(TAB, "Error : " + e.getMessage()); } for (DocumentChange doc : documentSnapshots.getDocumentChanges()) { if (doc.getType() == DocumentChange.Type.ADDED) { Log.d("Brand Name: ",doc.getDocument().getId()); // how to retrieve documents of subCollection here? something like doc.getDocument().collection?? } } } }); ``` Thank you.<issue_comment>username_1: This is really simple and easy try this. ``` firebaseFirestore.collection("Coffee").addSnapshotListener(new EventListener() { @Override public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) { if (e != null) { Log.d("", "Error : " + e.getMessage()); } for (DocumentChange doc : documentSnapshots.getDocumentChanges()) { if (doc.getType() == DocumentChange.Type.ADDED) { Log.d("Brand Name: ", doc.getDocument().getId()); doc.getDocument().getReference().collection("SubBrands").addSnapshotListener(new EventListener() { @Override public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) { if (e != null) { Log.d("", "Error : " + e.getMessage()); } for (DocumentChange doc : documentSnapshots.getDocumentChanges()) { if (doc.getType() == DocumentChange.Type.ADDED) { Log.d("SubBrands Name: ", doc.getDocument().getId()); } } } }); } } }}); ``` **Note**: i have updated the answer. It is obvious that you can't fetch sub collections within the collection's document with a single request. Upvotes: 3 [selected_answer]<issue_comment>username_2: I see that is already an accepted answer but I want to provide you a more elegant way of structuring your database. This means that you'll also able to retrieve the data more easily. Before that, as I understand from your question, you only want to retrieve data but in order to achieve this, just use a `get()` call. `addSnapshotListener()` is used to retrieve `real time` data. This is the database structure that I suggest you use for your app: ``` Firestore-root | --- coffee (collection) | --- coffeeId (document) | --- coffeeBrand: "Nescafe" | --- coffeeSubBrand: "Sunrise" | --- coffeeName: "CoffeeName" | --- quantity | --- 50g: true | --- 100g: true | --- 150g: true ``` While username_1's code might work on your actual database structure, this new structure will provide you the ability to avoid nested loops. To get all the coffees, just use the following code: ``` FirebaseFirestore rootRef = FirebaseFirestore.getInstance(); CollectionReference coffeeRef = rootRef.collection("coffee"); coffeeRef.get().addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { for (DocumentSnapshot document : task.getResult()) { String coffeeName = document.getString("coffeeName"); Log.d("TAG", coffeeName); } } } }); ``` If you want to display only the `Nescafe coffee`, instead of using a `CollectionReference`, you need to use a `Query`: ``` Query query = coffeeRef.whereEqualTo("coffeeBrand", "Nescafe"); ``` If you want to display only the coffee SubBrands then use the following Query: ``` Query query = coffeeRef.whereEqualTo("coffeeSubBrand", "Sunrise"); ``` If you want to display the coffees Brands and SubBrands, you can chain methods like this: ``` Query query = coffeeRef .whereEqualTo("coffeeSubBrand", "Sunrise") .whereEqualTo("coffeeBrand", "Nescafe"); ``` If you want to display only the coffee with the quantity of `100g`, then just use the following query: ``` Query query = coffeeRef.whereEqualTo("quantity.100g", true); ``` If you want to learn more about Cloud Firestore database structures, you can take a look on one of my **[tutorials](https://www.youtube.com/playlist?list=PLn2n4GESV0AmXOWOam729bC47v0d0Ohee)**. Upvotes: 1
2018/03/18
347
1,433
<issue_start>username_0: The following code ``` class A { public: A() {} // default constructor A(int i) {} // second constructor }; int main() { A obj({}); } ``` calls the second constructor. Probably the empty `initializer_list` is treated as one argument and is converted to `int`. But when you remove the second constructor from the class, it calls the default constructor. Why? Also, I understand why `A obj { {} }` will always call a constructor with one argument as there we are passing one argument which is an empty `initializer_list`.<issue_comment>username_1: It's because the `{}` in `A obj({});` ends up being interpreted as of type `int`. So the code ends up being similar to `A obj(0);`. Upvotes: 0 <issue_comment>username_2: The presence of the parentheses surrounding the braces in `A obj({});` indicates the single argument constructor will be called, if possible. In this case it is possible because an empty initializer list, or *braced-init-list*, can be used to value initialize an `int`, so the single argument constructor is called with `i=0`. When you remove the single argument constructor, `A obj({});` can no longer call the default constructor. However, the `{}` can be used to default construct an `A` and then the copy constructor can be called to initialize `obj`. You can confirm this by adding `A(const A&) = delete;`, and the code will fail to compile. Upvotes: 4 [selected_answer]
2018/03/18
1,184
5,774
<issue_start>username_0: I'm trying to test a async Python function using pytest. My test is passing with a warning, when it *should* be failing. This is my test: ``` import asynctest import pytest from Foo.bar import posts @pytest.mark.asyncio async def test_get_post_exists(): returned_post = await posts.get_post('0') assert returned_post.id == 0 assert returned_post.text == 'Text for the post body.' assert True == False ``` It passes with the following message: ``` ================================== test session starts =================================== platform darwin -- Python 3.6.4, pytest-3.4.2, py-1.5.2, pluggy-0.6.0 rootdir: /path/path/path/path, inifile: collected 1 item tests/unit/route_logic/test_post_helpers.py . [100%] ==================================== warnings summary ==================================== tests/unit/route_logic/test_post_helpers.py::test_get_post_exists /usr/local/lib/python3.6/site-packages/_pytest/python.py:155: RuntimeWarning: coroutine 'test_get_post_exists' was never awaited testfunction(**testargs) -- Docs: http://doc.pytest.org/en/latest/warnings.html ========================== 1 passed, 1 warnings in 0.10 seconds ========================== ```<issue_comment>username_1: Here is the working demo using `pytest` and `pytest-asyncio`: `Foo/bar/posts.py`: ```py from collections import namedtuple Post = namedtuple('Post', 'id text') async def get_post(id: str): return Post(id=int(id), text='Text for the post body.') ``` `test_post_helpers.py`: ```py import pytest from Foo.bar import posts @pytest.mark.asyncio async def test_get_post_exists(): returned_post = await posts.get_post('0') assert returned_post.id == 0 assert returned_post.text == 'Text for the post body.' assert True == False ``` Unit test result: ```sh ========================================================================================================================================================================= test session starts ========================================================================================================================================================================== platform darwin -- Python 3.7.5, pytest-5.3.1, py-1.8.0, pluggy-0.13.1 rootdir: /Users/ldu020/workspace/github.com/mrdulin/python-codelab plugins: asyncio-0.10.0 collected 1 item src/stackoverflow/49350821/test_post_helpers.py F [100%] =============================================================================================================================================================================== FAILURES =============================================================================================================================================================================== _________________________________________________________________________________________________________________________________________________________________________ test_get_post_exists _________________________________________________________________________________________________________________________________________________________________________ @pytest.mark.asyncio async def test_get_post_exists(): returned_post = await posts.get_post('0') assert returned_post.id == 0 assert returned_post.text == 'Text for the post body.' > assert True == False E assert True == False src/stackoverflow/49350821/test_post_helpers.py:11: AssertionError ========================================================================================================================================================================== 1 failed in 0.15s =========================================================================================================================================================================== ``` `assert True == False` cause the assertion fails as you wish. Source code: <https://github.com/mrdulin/python-codelab/tree/master/src/stackoverflow/49350821> Upvotes: 3 <issue_comment>username_2: **You have to install [pytest-asyncio](https://pypi.org/project/pytest-asyncio/).** ``` pip install pytest-asyncio ``` You don't have to import it anywhere. Just decorate the async def tests with `@pytest.mark.asyncio`. It was mentioned by in the @hoefling comments, I'm posting this answer just to make it more visible: > > `coroutine 'my_coro' was never awaited` means that the coroutine object was never put into the event loop, so I suppose you are either missing pytest-asyncio that puts tests into event loop. > > > Without pytest-asyncio, pytest doesn't know that it should `await` the async test. It just runs it as a non-async function, which is not enough to actually execute the async function body: ``` $ python3 Python 3.7.3 (default, Apr 3 2019, 05:39:12) >>> async def foo(): ... raise Excepion('this is never raised') ... >>> foo() >>> exit() sys:1: RuntimeWarning: coroutine 'foo' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback ``` Upvotes: 3
2018/03/18
1,005
5,210
<issue_start>username_0: I would like to make a class which looks like a `String` to VBA. That is, if I make a function with a string argument, and pass this object instead, I won't get any errors. I thought `Implements String` would work, but apparently it's not even an option! Why is it not possible, and is there any way to get the behaviour I'm after? (Of course I could just make my own `IString` interface and specify my functions to request that, but I don't want to do that) --- I'm trying to make a file-selection dialogue, which I can pass to any functions that require string-filepaths as arguments. This would be a neat self contained way of retro-fitting file-selection to existing functions.<issue_comment>username_1: Here is the working demo using `pytest` and `pytest-asyncio`: `Foo/bar/posts.py`: ```py from collections import namedtuple Post = namedtuple('Post', 'id text') async def get_post(id: str): return Post(id=int(id), text='Text for the post body.') ``` `test_post_helpers.py`: ```py import pytest from Foo.bar import posts @pytest.mark.asyncio async def test_get_post_exists(): returned_post = await posts.get_post('0') assert returned_post.id == 0 assert returned_post.text == 'Text for the post body.' assert True == False ``` Unit test result: ```sh ========================================================================================================================================================================= test session starts ========================================================================================================================================================================== platform darwin -- Python 3.7.5, pytest-5.3.1, py-1.8.0, pluggy-0.13.1 rootdir: /Users/ldu020/workspace/github.com/mrdulin/python-codelab plugins: asyncio-0.10.0 collected 1 item src/stackoverflow/49350821/test_post_helpers.py F [100%] =============================================================================================================================================================================== FAILURES =============================================================================================================================================================================== _________________________________________________________________________________________________________________________________________________________________________ test_get_post_exists _________________________________________________________________________________________________________________________________________________________________________ @pytest.mark.asyncio async def test_get_post_exists(): returned_post = await posts.get_post('0') assert returned_post.id == 0 assert returned_post.text == 'Text for the post body.' > assert True == False E assert True == False src/stackoverflow/49350821/test_post_helpers.py:11: AssertionError ========================================================================================================================================================================== 1 failed in 0.15s =========================================================================================================================================================================== ``` `assert True == False` cause the assertion fails as you wish. Source code: <https://github.com/mrdulin/python-codelab/tree/master/src/stackoverflow/49350821> Upvotes: 3 <issue_comment>username_2: **You have to install [pytest-asyncio](https://pypi.org/project/pytest-asyncio/).** ``` pip install pytest-asyncio ``` You don't have to import it anywhere. Just decorate the async def tests with `@pytest.mark.asyncio`. It was mentioned by in the @hoefling comments, I'm posting this answer just to make it more visible: > > `coroutine 'my_coro' was never awaited` means that the coroutine object was never put into the event loop, so I suppose you are either missing pytest-asyncio that puts tests into event loop. > > > Without pytest-asyncio, pytest doesn't know that it should `await` the async test. It just runs it as a non-async function, which is not enough to actually execute the async function body: ``` $ python3 Python 3.7.3 (default, Apr 3 2019, 05:39:12) >>> async def foo(): ... raise Excepion('this is never raised') ... >>> foo() >>> exit() sys:1: RuntimeWarning: coroutine 'foo' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback ``` Upvotes: 3
2018/03/18
1,036
3,737
<issue_start>username_0: I am to do a presentation on SQL Injection, and what better way to do it than to make my own php queries and show them to the class. The problem is I have my DB and php code running flawlessly, but can't seem to find an exploit on my UPDATE query in an edit form I made. If anyone could take a look at it and tell me how I could insert say a 'DROP TABLE' command or something of the sort, it would be extremely helpful! ``` php session_start(); require_once 'config.php'; error_reporting(E_ALL); ini_set('display_errors', 1); $userid = $_SESSION["userid"]; $fname = $_SESSION["fname"]; $lname = $_SESSION["lname"]; $gender = $_SESSION["gender"]; $email = $_SESSION["email"]; if($_SERVER["REQUEST_METHOD"] == "POST") { $userid = trim($_POST["userid"]); $fname = trim($_POST["fname"]); $lname = trim($_POST["lname"]); $gender = trim($_POST["gender"]); $email = trim($_POST["email"]); $query = "UPDATE user_details SET fname = '$fname', lname = '$lname', gender = '$gender', email = '$email' WHERE userid = '$userid' "; if (mysqli_query($link, $query)) { echo 'Update complete!'; } echo mysqli_error($link); // else { // echo '<p' . 'Woah something went really wrong dude' . '' ; // echo mysqli_error($link); // } } ?> Edit body{ font: 14px sans-serif; } .wrapper{ width: 350px; padding: 20px; } " method="post"> First Name "> Last Name "> Gender "> Email "> UserID "> Submit Back ```<issue_comment>username_1: Not sure I understand you fully, but I will try to tell you why this seems to be a bad idea... if I post to userid ``` $userid="';DROP TABLE XY;SELECT * FROM USER_DETAILS WHERE fname = '" ``` your code would do... ``` $query = "UPDATE user_details SET fname = '$fname', lname = '$lname', gender = '$gender', email = '$email' WHERE userid = '$userid' "; ``` which results in the query: ``` $query = "UPDATE user_details SET fname = '$fname', lname = '$lname', gender = '$gender', email = '$email' WHERE userid = '';DROP TABLE XY;SELECT * FROM USER_DETAILS WHERE fname = '' "; ``` The queries would be ``` UPDATE user_details SET fname = '$fname', lname = '$lname', gender = '$gender', email = '$email' WHERE userid = '' DROP TABLE XY SELECT * FROM USER_DETAILS WHERE fname = '' ``` Each one of them is valid...now create a table XY and run the original query of your example with this posted injection... I am missing something? Edit: as @RaymondNijland pointed out the mysql function used in the example seems to block this kind of an attack. I am still considering it to be a dangerous code style, where only a driver creates security. Maybe there are future updates allowing batch sql, I would sleep better knowing my code doesn't open this kind of a door... Upvotes: 0 <issue_comment>username_2: In the most of the cases mysqli prevents multiple queries and MySQL itself has certain in-built security measures to prevent accidental deletion of tables and databases. So your `DROP TABLE` won't work. But you can demonstrate a successful login attempt using MySQL injections. Create a login form and pass data to the validation page. There write your query as, ``` query = "SELECT * FROM `user` WHERE `username` = '." username ".' AND `password` = '." password ".'"; ``` Now, in the login form enter username as `' OR '1'='1` and password as `' OR '1'='1`. so at the end the complete query would look like this, ``` SELECT * FROM `user` WHERE `username`='' OR '1'='1' AND `password`='' OR '1'='1'; ``` this will return all the user records in the `user` table, and simply the application would login by using the very first record. Upvotes: 3 [selected_answer]
2018/03/18
2,264
6,591
<issue_start>username_0: I am attempting to use a corporate SQL Server as the backend for my Django project with Python 3.5.2. I have installed Django 2.0.3, pyodbc==4.0.22, django-pyodbc-azure 2.0.3, pypiwin32==219 (pip freeze below). I have also configured DATABASES in my site's settings.py (see below). When attempting to run the server I get the following error: No module named 'sql\_server'. I referenced other questions, the most relevant of which appeared to be: [No module named sql\_server.pyodbc.base](https://stackoverflow.com/questions/32745408/no-module-named-sql-server-pyodbc-base), which concluded that the django-pyodbc-azure and Django versions needed to be identical. This did not solve my problem, however; the same error persists. ``` Traceback (most recent call last): File "manage.py", line 24, in execute\_from\_command\_line(sys.argv) File "C:\Users\K5SH\venv\lib\site-packages\django\core\management\\_\_init\_\_.py" , line 338, in execute\_from\_command\_line utility.execute() File "C:\Users\K5SH\venv\lib\site-packages\django\core\management\\_\_init\_\_.py" , line 312, in execute django.setup() File "C:\Users\K5SH\venv\lib\site-packages\django\\_\_init\_\_.py", line 18, in se tup apps.populate(settings.INSTALLED\_APPS) File "C:\Users\K5SH\venv\lib\site-packages\django\apps\registry.py", line 108, in populate app\_config.import\_models(all\_models) File "C:\Users\K5SH\venv\lib\site-packages\django\apps\config.py", line 198, i n import\_models self.models\_module = import\_module(models\_module\_name) File "C:\Users\K5SH\AppData\Local\Programs\Python\Python35-32\lib\importlib\\_\_ init\_\_.py", line 126, in import\_module return \_bootstrap.\_gcd\_import(name[level:], package, level) File "", line 986, in \_gcd\_import File "", line 969, in \_find\_and\_load File "", line 958, in \_find\_and\_load\_unlocked File "", line 673, in \_load\_unlocked File "", line 665, in exec\_module File "", line 222, in \_call\_with\_frames\_removed File "C:\Users\K5SH\venv\lib\site-packages\django\contrib\auth\models.py", lin e 41, in class Permission(models.Model): File "C:\Users\K5SH\venv\lib\site-packages\django\db\models\base.py", line 139 , in \_\_new\_\_ new\_class.add\_to\_class('\_meta', Options(meta, \*\*kwargs)) File "C:\Users\K5SH\venv\lib\site-packages\django\db\models\base.py", line 324 , in add\_to\_class value.contribute\_to\_class(cls, name) File "C:\Users\K5SH\venv\lib\site-packages\django\db\models\options.py", line 250, in contribute\_to\_class self.db\_table = truncate\_name(self.db\_table, connection.ops.max\_name\_length( )) File "C:\Users\K5SH\venv\lib\site-packages\django\db\\_\_init\_\_.py", line 36, in \_\_getattr\_\_ return getattr(connections[DEFAULT\_DB\_ALIAS], item) File "C:\Users\K5SH\venv\lib\site-packages\django\db\utils.py", line 240, in \_ \_getitem\_\_ backend = load\_backend(db['ENGINE']) File "C:\Users\K5SH\venv\lib\site-packages\django\db\utils.py", line 129, in l oad\_backend raise ImproperlyConfigured(error\_msg) django.core.exceptions.ImproperlyConfigured: 'sql\_server.pyodbc' isn't an availa ble database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'base', 'mysql', 'oracle', 'postgresql\_psycopg2', 'sqlite3' Error was: No module named 'sql\_server' ``` Installed packages: ``` chardet==2.3.0 configparser==3.5.0 cycler==0.10.0 diff-match-patch==20121119 Django==2.0.3 django-crispy-forms==1.7.2 django-csvimport==2.4 django-debug-toolbar==1.9.1 django-import-export==1.0.0 django-money==0.9.1 django-mssql==1.8 django-pyodbc-azure==2.0.3.0 djangorestframework==3.6.3 et-xmlfile==1.0.1 jdcal==1.3 matplotlib==1.5.3 mysqlclient==1.3.12 numpy==1.11.2rc1+mkl openpyxl==2.4.8 pandas==0.18.1 psycopg2==2.7.3.2 pymssql==2.1.2 pyodbc==4.0.22 pyparsing==2.1.9 pypiwin32==219 pypyodbc==1.3.3 python-dateutil==2.5.3 pytz==2016.6.1 scipy==0.18.1 seaborn==0.7.1 six==1.10.0 sqlalchemy==1.1.4 sqlparse==0.2.4 tablib==0.10.0 virtualenv==15.0.3 xlrd==1.0.0 xlwt==1.2.0 ``` Databases: ``` DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'my_db_name', 'USER': '', 'PASSWORD': '', 'HOST': 'my_sql_host', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, }, } ``` (Note: I have attempted this both with and without the 'OPTIONS' setting).<issue_comment>username_1: I started fresh on Windows using Python 3.6.0 and virtualenv 15.1.0. These should be close enough that this should work. First I created and activated a `virtualenv`, and installed `django-pyodbc-azure`, which in turn installed Django and pyodbc as dependencies: ``` virtalenv djangowin djangowin\Scripts\activate.bat pip install django-pyodbc-azure ``` Then I started a fresh Django project: ``` django-admin startproject sqltest ``` Then I edited `sqltest\sqltest\settings.py` and updated my `DATABASES` definition to use a freshly created database: ``` DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'cdw-sql0101.wharton.upenn.edu', 'PORT': '1433', 'NAME': 'flipperpa', 'USER': 'flipperpa', 'PASSWORD': '', 'AUTOCOMMIT': True, 'OPTIONS': { 'driver': 'SQL Server', 'unicode_results': True, 'host_is_server': True, }, } } ``` ...and it worked like a charm: ``` (djangowin) C:\Users\tallen\sqltest>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). March 23, 2018 - 16:39:51 Django version 2.0.3, using settings 'sqltest.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. ``` Is there some step along this path that didn't work for you? Are you sure your `virtualenv` is active? The command `djangowin\Scripts\activate.bat` is very important - you're going to do that each time you open a new terminal window. Upvotes: 1 <issue_comment>username_2: Default virtual environment doesn't work properly on azure. Activate command seems has no effect. But if you create your own virtual environment on azure it works properly. I faced the same kind of problem for my project then I installed virtual environment for myself and edited the auto deployment configurations scripts. Now it is working perfectly. Upvotes: 0 <issue_comment>username_3: I found this issue mainly due to Version of django I replaced my Django version with django==2.1.15 then it worked. django-pyodbc-azure==2.1.0.0 pyodbc=4.0 Upvotes: 0
2018/03/18
1,029
3,798
<issue_start>username_0: I am working on my first Django project. But I get following errors: **edit\_file template** ``` {% csrf\_token %} {{ form.errors }} {{ form.non\_field\_errors }} {% for hidden\_field in form.hidden\_fields %} {{ hidden\_field.errors }} {{ hidden\_field }} {% endfor %} File Name {% render\_field form.name|add\_class:"form-control" %} File Path {% render\_field form.directory\_path|add\_class:"form-control" %} {% render\_field form.script\_code|add\_class:"form-control" %} ``` {{ form.script_code }} ``` Save Changes [Back]({% url 'list_files_from_version' file.version_id %}) ``` **Views.py** ``` def edit_file(request, id): instance = get_object_or_404(File, id=id) if request.method == "POST": form = EditFileForm(request.POST, instance=instance) if form.is_valid(): print('Form validation => True') form.save() return HttpResponse(' database updated! ================== ') else: print('Form validation => False') file = File.objects.latest('id') context = {'file': file, "form": form} return render(request, 'edit_file.html', context) else: instance = get_object_or_404(File, id=id) form = EditFileForm(request.POST or None, instance=instance) file = File.objects.latest('id') context = {'file': file, "form": form} return render(request, 'edit_file.html', context) ``` **forms.py** ``` class EditFileForm(ModelForm): # field_order = ['field_1', 'field_2'] class Meta: print("forms.py 1") model = File fields = ('name', 'script_code', 'directory_path','version') def clean(self): print("forms.py 2") cleaned_data = super(EditFileForm, self).clean() name = cleaned_data.get('name') print("cleaned data: ", cleaned_data) ``` **Models:** Version id point to a version which contains multiple files. ``` class File(models.Model): # Incrementing ID (created automatically) name = models.CharField(max_length=40) script_code = models.TextField() # max juiste manier? directory_path = models.CharField(max_length=200) version = models.ForeignKey('Version', on_delete=models.CASCADE) class Meta(object): db_table = 'file' # table name class Version(models.Model): # Incrementing ID (created automatically) version_number = models.CharField(max_length=20) pending_update = models.BooleanField(default=False) creation_date = models.DateTimeField(auto_now_add=True, null=True, editable=False) modification_date = models.DateTimeField(auto_now_add=True, null=True) connecthor = models.ForeignKey('ConnecThor', on_delete=models.CASCADE) def __str__(self): return self.connecthor_id ``` ***The problem:*** form.is\_valid() keeps failing. My view returns one error. **\*version: This field is required.** But I don't know how to fix this. Users should only be able to update 3 of the 5 data fields. So there is no reason to show the PK or FK in the template.<issue_comment>username_1: You've included version in the list of fields in your form, but you aren't outputting it in the template so there is no means of providing it. Since the model field does not specify blank=True, it is a required field, hence the error. If you don't want users to be able to modify this field, you should remove it from that list of fields under Meta. Upvotes: 3 [selected_answer]<issue_comment>username_2: You do not have version in your template. Your model field for version does not say it can have null values. Hence your form validation fails. Include it in your template or remove the field from EditFileForm class's Meta class in forms.py Upvotes: 0
2018/03/18
548
2,383
<issue_start>username_0: ``` new Thread(new Runnable(){ @Override public void run () { Intent firstServiceIntent=new Intent(getApplicationContext(),MyService.class); } }).start(); ``` I have to perform background location updates in the service. I've used LocationListner in the service and it calls onLocationChanged() frequently, which can block my UI thread. If I use create thread in onLocationChanged(), every-time this method is called a new thread would be spawned. So, I'm thinking of creating the entire service in new thread instead of creating thread in onLocationChanged() . Is this a good solution or what should be the best way? Any help is appreciated.<issue_comment>username_1: A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise. However, launching a service from a different thread looks ugly. You can create a new thread inside the service. Upvotes: 1 <issue_comment>username_2: If you are using `IntentService` component of android , it will automatically take care of your background processing in `onHandleIntent(...)` you can try... ``` class YourService extends IntentService ``` [IntentService](https://developer.android.com/training/run-background-service/create-service.html) else if you use `Service` like ``` class YourService extends Service ``` you can use your *custom thread* in `onCreate()` **ELSE** The service will run in the `MainThread` [Service](https://developer.android.com/guide/components/services.html) Upvotes: 1 <issue_comment>username_3: If you want your service to run on a background thread, then you have two options: 1. Use an `IntentService` which automatically is run on a background thread by the Android OS. Everything you do inside the `IntentService` will be run on the background thread. You don't need to do any threading. 2. Use a standard Android `Service` and instantiate a `new Thread()` inside the service where you want to perform the work. The standard Android `Service` is run by default on the main thread so it will block your UI. That's why you have to handle the threading yourself. More information here: [Android Services](https://developer.android.com/guide/components/services.html) Upvotes: 3 [selected_answer]
2018/03/18
1,225
4,738
<issue_start>username_0: I'm trying to create a stopwatch function within Google Sheets, and I'm having some trouble in getting `var diff` to show the difference in seconds:milleseconds between `var currentTime` and `var previousTiming`. For some reason, I'm only retrieving a 'NaN' value. The thought is that there will be an image on the "Timer" sheet, which users will click to start timings, along with a "lap" function which moves the active cell down 1 row from the current to capture the next time. Right now, I have it placing the current time it captures in the activeCell(), but would like to change it to the `var diff` value, if I can get it to have the right format. Any help/advice you all could provide would be greatly appreciated. ``` function timer() { // Getting Active Sheet Details var spreadsheetName = SpreadsheetApp.getActive().getName(); var spreadsheetTimeZone = SpreadsheetApp.getActive().getSpreadsheetTimeZone(); var currentTime = Utilities.formatDate(new Date(), spreadsheetTimeZone, "MM/dd/yyyy' 'HH:mm:ss:ms"); var ss = SpreadsheetApp.getActive(); var dataSheet = ss.getActiveSheet(); var sheetName = dataSheet.getName().toString(); // If the active sheet name contains "tim", continue if (sheetName.indexOf("Tim") > -1) { var totalBreakpoints = dataSheet.getRange("A2:A").getValues().filter(function(row) { return row[0]; }); var headers = dataSheet.getRange("C1:1").getValues().filter(function(row) { return row[0]; }); // Get the total number of rows/columns to look at var numberRows = totalBreakpoints.length; var numberColumns = ss.getLastColumn(); // Get the range that can accept times var valuesRange = dataSheet.getRange(2, 3, numberRows, numberColumns); // Getting Active Cell Details var activeCell = dataSheet.getActiveCell(); var activeRow = activeCell.getRow(); var activeColumn = activeCell.getColumn(); var cellAbove = activeCell.offset(-1, 0).getValue(); var previousTiming if (activeRow <= 2 || cellAbove == '') { previousTiming = currentTime; } else { previousTiming = Utilities.formatDate(new Date(cellAbove), spreadsheetTimeZone, "MM/dd/yyyy' 'HH:mm:ss:ms"); }; // Check to see if within range if (activeCell.getRow() >= valuesRange.getRow() && activeCell.getRow() <= valuesRange.getLastRow() && activeCell.getColumn() >= valuesRange.getColumn() && activeCell.getColumn() <= valuesRange.getLastColumn()) { activeCell.setValue(currentTime); dataSheet.getRange(activeRow + 1, activeColumn).activate(); var diff = Math.abs(currentTime - previousTiming); } } } ```<issue_comment>username_1: ``` function calcTimeDifference(Start,End) { if(Start && End) { var second=1000; var t1=new Date(Start).valueOf(); var t2=new Date(End).valueOf(); var d=t2-t1; var seconds=Math.floor(d/second); var milliseconds=Math.floor(d%seconds); return 'ss:ms\n' + seconds + ':' + milliseconds; } else { return 'Invalid Inputs'; } } ``` Note: valueOf() just returns the numerical value in milliseconds. Play around with this a bit. ``` function ttestt(){ var dt1=new Date(); var dt2=dt1.valueOf()-100000; Logger.log('dt1=%s dt1-dt2=%s',dt1.valueOf(),dt1.valueOf()-dt2.valueOf()); } ``` Upvotes: 2 <issue_comment>username_2: The reason you get `NaN` as the value for diff is because [`Utilities.formatDate()`](https://developers.google.com/apps-script/reference/utilities/utilities#formatdatedate-timezone-format) returns a String - you are subtracting two strings, which is most certainly not a number. The solution is to only apply the formatting when printing to the cell, and let `currentTime` and `previousTime` remain native `Date` objects, e.g. ``` activeCell.setValue(Utilities.formatDate(....)); ``` Probably a better solution is to apply a datetime number format to the cells which hold the timing information, and write the actual number (not a formatted string) to the cells in question. This way you can be sure that when you read the value of the previous row's cell, that it is read as a number and can be used as such. e.g. ``` // Time in col A, differential in col B function lapImageClicked() { var now = new Date(); var sheet = SpreadsheetApp.getActiveSheet(); var last = sheet.getRange(sheet.getLastRow(), 1, 1, 2); // Write date into A, and milliseconds differential in B last.offset(1, 0).setValues([ [now, now - last.getValues()[0][0]] ]); } ``` Upvotes: 2 [selected_answer]
2018/03/18
727
2,317
<issue_start>username_0: I'm using [jss](http://cssinjs.org/react-jss?v=v8.3.5) and [TransitionGroup](https://reactcommunity.org/react-transition-group/). How can I set the step-enter-active class in jss? css ``` .step-enter { opacity: 0; } .step-enter.step-enter-active { opacity: 1; transition-duration: 100ms; transition-timing-function: cubic-bezier(0.175, 0.665, 0.320, 1), linear; } ``` current jss ``` const styles = { step: { background: props => props.color }, } const Button = ({classes}) => ( test ) ```<issue_comment>username_1: With TransitionGroup, you don't need to explicitly add the -enter and -enter-active classes to the component. This is managed automatically by the CSSTransition component. The CSSTransition component will use the class name to apply to the enter classes. In your case if you use: ``` ``` `step-enter` and `step-enter-active` will be applied by the component. So your button component could be something like: ``` const Button = ({classes}) => ( test ) ``` You'll need to import the css file containing the step-enter and step-enter-active classes. The react-transition-group docs have pretty good examples around this (<https://codesandbox.io/s/yv645oq21x?from-embed>) To declare the step-enter classes using JSS you could use the jss-global plugin. This allows you to declare global css classes, with predetermined class names. It would like something like: ``` const styles = { '@global': { '.step-enter': { opacity: 0; } }, step: { background: props => props.color }, } ``` More details on jss-global can be found at: <http://cssinjs.org/jss-global> Upvotes: 0 <issue_comment>username_2: Have a look at the source file [here](https://github.com/reactjs/react-transition-group/blob/master/src/CSSTransition.js). According to that, you can either have a string value for the `classNames` prop or an object of the following shape: ``` classNames={{ appear: 'my-appear', appearActive: 'my-active-appear', enter: 'my-enter', enterActive: 'my-active-enter', enterDone: 'my-done-enter, exit: 'my-exit', exitActive: 'my-active-exit', exitDone: 'my-done-exit, }} ``` Which means you can pass all your JSS generated class names into it. ``` const Button = ({classes}) => ( test ) ``` Upvotes: 3
2018/03/18
609
2,115
<issue_start>username_0: A problem occurred configuring project ':app': > > Failed to notify project evaluation listener. > > Could not initialize class com.android.sdklib.repository.AndroidSdkHandler > > > I am trying to build a project for class and have been getting this error while running the test. What went wrong?<issue_comment>username_1: With TransitionGroup, you don't need to explicitly add the -enter and -enter-active classes to the component. This is managed automatically by the CSSTransition component. The CSSTransition component will use the class name to apply to the enter classes. In your case if you use: ``` ``` `step-enter` and `step-enter-active` will be applied by the component. So your button component could be something like: ``` const Button = ({classes}) => ( test ) ``` You'll need to import the css file containing the step-enter and step-enter-active classes. The react-transition-group docs have pretty good examples around this (<https://codesandbox.io/s/yv645oq21x?from-embed>) To declare the step-enter classes using JSS you could use the jss-global plugin. This allows you to declare global css classes, with predetermined class names. It would like something like: ``` const styles = { '@global': { '.step-enter': { opacity: 0; } }, step: { background: props => props.color }, } ``` More details on jss-global can be found at: <http://cssinjs.org/jss-global> Upvotes: 0 <issue_comment>username_2: Have a look at the source file [here](https://github.com/reactjs/react-transition-group/blob/master/src/CSSTransition.js). According to that, you can either have a string value for the `classNames` prop or an object of the following shape: ``` classNames={{ appear: 'my-appear', appearActive: 'my-active-appear', enter: 'my-enter', enterActive: 'my-active-enter', enterDone: 'my-done-enter, exit: 'my-exit', exitActive: 'my-active-exit', exitDone: 'my-done-exit, }} ``` Which means you can pass all your JSS generated class names into it. ``` const Button = ({classes}) => ( test ) ``` Upvotes: 3
2018/03/18
797
2,697
<issue_start>username_0: This seems like a simple question, but I can't find the solution on here. I have a data frame with over 900 columns. The precise number of columns can increase over time, but the first 10 are always the same and the last 10 are always the same. I'd like to move the last 10 columns to just after the first 10, hence they'd occupy positions 11 through 20. My thought was to use `nrow` to get the total number of columns and use some basic arithmetic: ``` endcol <- df[,ncol(df)] endcol_start <- endcol-9 midcol_end <- endcol_start-1 ``` ... to get the index values to re-order. Then something like: ``` df2 <- df[,c(1:10, endcol_start:endcol, 11:midcol_end)] ``` ... to reorder accordingly to the index values set above. But I just get a vector of column indices without the rows being preserved. How to preserve the rows in this so the data frame is actually reordered? Thanks.<issue_comment>username_1: With TransitionGroup, you don't need to explicitly add the -enter and -enter-active classes to the component. This is managed automatically by the CSSTransition component. The CSSTransition component will use the class name to apply to the enter classes. In your case if you use: ``` ``` `step-enter` and `step-enter-active` will be applied by the component. So your button component could be something like: ``` const Button = ({classes}) => ( test ) ``` You'll need to import the css file containing the step-enter and step-enter-active classes. The react-transition-group docs have pretty good examples around this (<https://codesandbox.io/s/yv645oq21x?from-embed>) To declare the step-enter classes using JSS you could use the jss-global plugin. This allows you to declare global css classes, with predetermined class names. It would like something like: ``` const styles = { '@global': { '.step-enter': { opacity: 0; } }, step: { background: props => props.color }, } ``` More details on jss-global can be found at: <http://cssinjs.org/jss-global> Upvotes: 0 <issue_comment>username_2: Have a look at the source file [here](https://github.com/reactjs/react-transition-group/blob/master/src/CSSTransition.js). According to that, you can either have a string value for the `classNames` prop or an object of the following shape: ``` classNames={{ appear: 'my-appear', appearActive: 'my-active-appear', enter: 'my-enter', enterActive: 'my-active-enter', enterDone: 'my-done-enter, exit: 'my-exit', exitActive: 'my-active-exit', exitDone: 'my-done-exit, }} ``` Which means you can pass all your JSS generated class names into it. ``` const Button = ({classes}) => ( test ) ``` Upvotes: 3
2018/03/18
461
1,569
<issue_start>username_0: I can't figure out how to make visible the bottom part of the slider in this row where i used clip-path to make the background with angled top and bottom. I tried z-index, overflow and position:relative in combination with all elements but nothing helped: <http://sport.fusionidea.com/test-page/> ![](https://i.stack.imgur.com/5msvS.jpg)<issue_comment>username_1: As I commented above here is an alternative to create the background without the use of clip-path which is also better supported and easier to manage: ```css .slide { --s: 40px; /* Change this to control the angle*/ height: 300px; background: linear-gradient(to top left ,purple 50%,#0000 51%) top, linear-gradient(purple 0 0) center, linear-gradient(to bottom right ,purple 50%,#0000 51%) bottom; background-size: 100% var(--s),100% calc(100% - 2*var(--s)); background-repeat: no-repeat; } ``` ```html ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use a pseudo element to create this effect. Give the parent div a width and `position: relative` then create a pseudo element with `position: absolute`, `width:100%` and `height: 100%` that sits behind it (using `z-index`). This will let you creative the effect of a "container" div that allows children elements to escape its bounds. The upside to this method, versus the linear gradient method, is that you can use background-images, actual linear-gradients, etc. on your slanted shape — you're not limited to a single color. <https://jsfiddle.net/9swLf86p/1/> Upvotes: 3