date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/22
1,433
4,695
<issue_start>username_0: I have a rather simple Pascal program, that is to call some C functions I have written. My C code: ``` void connect_default(int* errorcode) { // Connects the default user and places any error code in errorcode } void connect(char user[129], char password[129], int* errorcode) { // Connects the given user and places any error code in errorcode } ``` I'm trying to call these two functions in my Pascal application. This works fine: ``` program pascaltest(INPUT, OUTPUT); procedure connect_default(var errorcode: integer); external; var errorcode : integer := 0; begin connect_default(errorcode); if errorcode <> 0 then writeln('Failed to connect with error code ', errorcode); end. ``` But I have a hard time finding out what data type to use in Pascal, that corresponds to a null terminated char array in C. A Pascal string does not seem to be it, because this passes nothing to the C function. ``` program pascaltest(INPUT, OUTPUT); procedure connect(user : string, password : string, var errorcode: integer); external; var errorcode : integer := 0; begin connect('MyUser', 'MyPassword', errorcode); if errorcode <> 0 then writeln('Failed to connect with error code ', errorcode); end. ``` What datatype in Pascal corresponds to a null terminated C char array? My environment is a HP OpenVMS machine and not Free Pascal, meaning that I do not have access to the types pchar and ansistring that I have read about. The C functions need to stay as general as possible and I cannot make any changes to them, creating custom structs (like what is described here [Declaring Pascal-style strings in C](https://stackoverflow.com/questions/7648947/declaring-pascal-style-strings-in-c)), as the C functions are already successfully called by similar programs written in C, Fortran and Cobol, where I managed to find the data types needed.<issue_comment>username_1: As you can see in official HP documentation, you Pascal version supports null-terminated strings: <http://h41379.www4.hpe.com/doc/82final/6083/6083pro_005.html#null_strings> > > 2.7 Null-Terminated Strings > > > HP Pascal includes routines and a built-in type to better coexist with null-terminated strings in the C language. > The C\_STR\_T datatype is equivalent to: > > > > > > > C\_STR\_T = ^ ARRAY [0..0] OF CHAR; > > > > > > > > > C\_STR\_T is a pointer to an ARRAY OF > CHARs. It does not allocate memory for any character data. C\_STR\_T > behaves like a normal pointer type in that you can assign NIL into it > and the optional pointer checking code will check for dereferencing of > a NIL pointer. The individual characters can be used by dereferencing > the pointer and using an array index. > > > In these cases, no bounds > checking will be performed even if array bounds checking is enabled. > However, you cannot dereference a C\_STR\_T pointer without also > indexing a single character. If you want to access an entire > null-terminated string, see the PAS\_STR function. > > > Then you can use that C-style strings as a read-only references or convert them into standalone Pascal strings via `PAS_STR` function: <http://h41379.www4.hpe.com/doc/82final/6083/6083pro_016.html#pas_str_func> And `PAS_STRCPY` would do opposite thing right away: <http://h41379.www4.hpe.com/doc/82final/6083/6083pro_016.html#pas_strcpy> Upvotes: 2 <issue_comment>username_2: I found a workaround for now that does not affect my C code at all, but is not very dynamic. In my specific case, the user name and password are hard-coded. I simply use a character array in Pascal, and set the characters one by one. It is however not a good solution in the general case, and I want to accept username_1's answer as the correct one. That is the intended use. I cannot, however, since I never got it to work. I will update this thread if I find out why. ``` program pascaltest(INPUT, OUTPUT); type username = array [0..6] of char; type password = array [0..10] of char; procedure connect(var user : username, var pass : password, var errorcode: integer); external; var errorcode : integer := 0; user : username; pass : password; begin user[0] := 'M'; user[1] := 'y'; user[2] := 'U'; user[3] := 's'; user[4] := 'e'; user[5] := 'r'; user[6] := chr(0); pass[0] := 'M'; pass[1] := 'y'; pass[2] := 'P'; pass[3] := 'a'; pass[4] := 's'; pass[5] := 's'; pass[6] := 'w'; pass[7] := 'o'; pass[8] := 'r'; pass[9] := 'd'; pass[10] := chr(0); connect(user, pass, errorcode); if errorcode <> 0 then writeln('Failed to connect with error code ', errorcode); end. ``` Upvotes: 1
2018/03/22
556
2,159
<issue_start>username_0: In my project, I use `RxJS` to handle HTTP request. I came into a confusing point about the error handling part as following: ``` .switchMap((evt: any) => { return http.getComments(evt.params) .map(data => ({ loading: false, data })) .catch(() => { console.log('debugging here'); return Observable.empty(); }); }) ``` in the above code, inside the `switchMap` operator, I use the `http.getComments` function to send request, which is defined by myself as following: ``` getComments(params) { return Observable.fromPromise( this.io.get(path, { params }) ); } ``` in this function, I use `fromPromise` operator convert the returned Promise to observable. The problem is when HTTP request failed, the `catch` operator inside `switchMap` can not work, the debugging console can't output. So what's wrong with my code.<issue_comment>username_1: Your code should work. Here a simplified simulation, where http calls are substituted by a function which raises an error. ``` import {Observable} from 'rxjs'; function getComments(params) { return Observable.throw(params); } const params = 'abc'; Observable.of(null) .switchMap(_ => { return getComments(params) .map(data => ({ loading: false, data })) .catch(err => { console.log('debugging here', err); return Observable.empty(); }); }) .subscribe( console.log, error => console.error('This method is not called since the error is already caught', error), () => console.log('DONE') ) ``` Upvotes: 0 <issue_comment>username_2: Do you really need to catch the error inside the `switchMap` anyway? You can handle your error in your source if you want. ``` .switchMap((evt: any) => http.getComments(evt.params).map(data => ({ loading: false, data })) }) .subscribe(console.log, console.error); ``` Any way, your source code does not look to have any error, maybe your promise is not been rejected when the http fails and is just resolving with an error as a response (this is a guess because I've seen that before) Upvotes: 2 [selected_answer]
2018/03/22
1,398
5,516
<issue_start>username_0: Let's say we have two classes – `Car` and `Engine`. The question is would it be more reasonable to inherit `Car` from `Engine` to use `Engine`'s methods (e.g. `start()`) or to use `Engine` as an attribute of a `Car`? First approach (obvious): ``` class Car(Engine): # do smth with inherited methods ``` Second approach: ``` class Car(): def __init__(self, engine) self.engine = engine def start(self): return self.engine.start() class EngineV4(): def start(self): pass class EngineV8(): def start(self): pass # usage engine = EngineV8() car = Car(engine) ``` Also a version – to subclass a `Car`: ``` class V8Car(EngineV8, Car): pass ``` The first approach at some point looks good but leads to inheritance of literally everything a car has (e.g. `Car(Engine, Lights, Wheels)`. I guess, it's not a purpose of inheritance in OOP, not to mention that lights are not car in common sense to be inherited from. The second approach allows a car to use different engines, for example. The third approach leads to the same problem as the first one, except it's on the other level of abstraction. So, what is the most logical way of implementing such things? I understand that the question is more about OOP basics than Python and curios where to read more about such cases.<issue_comment>username_1: As Khelwood mentions in a comment, ask yourself: "is a car a type of engine ?". Semantically, inheritance describes a "is a" relationship - if "B" inherits from "A", then "B" is a "A" (cf [liskov's substitution principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle)). From this point of view, a "car" is not an "engine", it has an engine, so you want composition ("has a" relationship). Technically - specially in dynamically typed languages like Python where you don't strictly need inherance for subtyping -, inheritance (implementation inheritance I mean) is also a restricted and static form of composition/delegation so you might see code using inheritance mostly for implementation reuse, but this is still debatable from a design POV ( (this might be ok when factoring out common stuff in a TestCase suite but that's about it) and does definitly not apply to your example. As a general rule, only use inheritance when you really have a "is a" relationship, else use composition/delegation. Edit: I just noticed this in your question: ``` class V8Car(EngineV8, Car): pass ``` This is exactly what you want to avoid, both semantically and technically. Some of the problems you will get with this design: 1/ A car's engine is a replaceable part so you should be able to change it without changing the car itself. How will you deal with this when your customer asks you to add this "little feature" that was "so obvious" that it wasn't part of the initial requirements ? 2/ You are going to need one subclass for possible each car / engine combination, and you will need to create a new car subclass each time you add a new engine type. Good luck maintaining this... Now add wheels and a few other features and and figure out how many classes you end up with. 3/ if you add a new attribute/method to Engine that happens to shadow an existing Car attribute, all you client code will break - in an obvious way if you're lucky, but often in a more subtle way that might not be systematic nor immediatly detected. Then once you find out you broke something, you will have to edit all impacted classes to make sure the attribute is correctly resolved on `Car`, not on `Engine`, and remember to port this fix to all new car/engine combinations too. And that's in the lucky case where there's no other implication - you might have (well, you *probably* have) some method in Engine that uses this attribute for some computation, but then those methods will start using the Car's attribute instead and then how are you going to fix this ? Some of the above points may look like strawmen arguments, but I've seen such things happening IRL and fixing them was a real mess - and a huge net loss for the company. Now compare with what you get by making Engine a component of Car: ``` class Engine(): # ... class Car(): def __init__(self, engine): self.engine = engine car = Car(engine=Engine()) ``` 1/ A car's engine is a replaceable part so you should be able to change it without changing the car itself ``` # Yeah we got this even better engine! car.engine = V8SuperEngine() ``` 2/ You are going to need one subclass for possible each car / engine combination, and you will need to create a new car subclass each time you add a new engine type ``` # don't need a new class... newcar = Car(engine=V8SuperEngine()) ``` 3/ if you add a new attribute/method to Engine that happens to shadow an existing Car attribute, all you client code will break ``` # Well, now this just cannot happen, period. Something else ? ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Aggregation is more useful approach for this task because it allows construct concrete car dynamically, like this: ``` class Car(): def __init__(self, engine, wheels): self.engine = engine self.wheels = wheels ... some_car = Car(concrete_engine, concrete_wheels) ``` work with aggregated objects (for higher cohesion), like this method: ``` def speed(self): if self.wheels.is_locked(): return 0 return self.engine.swiftness() * self.factor ``` Upvotes: 2
2018/03/22
656
2,143
<issue_start>username_0: A client uses an external CRM platform to manage customers that I connected to his website using a dedicated plugin provided by this CRM company. With this plugin I can display on the website informations that my client fill in this external platform. I can't change the html code of this plugin (because is syncronized every 10 mins with the CRM platform) but I need to hide some of these informations coming from the CRM via Plugin. In the specific this Plugin generates in the pages this kind of code ``` #### Headline one Copy Text 1 #### Headline Two Copy Text 2 #### Headline Three Copy Text 3 #### Headline Four Copy Text 4 #### Headline Five Copy Text 5 #### Headline Six Copy Text 6 ``` Has you can see every headline has class `cx_h4` and the copy-text instead is a simple paragraph. The headlines with class `cx_h4` **never changes in the content**. But the paragraph `p` always change. My question is: How can I hide for example **only** these informations? ``` #### Headline Two Copy Text 2 #### Headline Five Copy Text 5 #### Headline Six Copy Text 6 ``` if I can't define classes or id for them? Can I achieve this with CSS or jQuery? **Does this works cross-browsers?** Do you have any tips? :)<issue_comment>username_1: What about the use of [nth-of-type](https://developer.mozilla.org/en-US/docs/Web/CSS/%3Anth-of-type): ```css .entry-content h4:nth-of-type(2), /*Select second h4 element */ .entry-content p:nth-of-type(2), /*Select second p element */ .entry-content h4:nth-of-type(5), .entry-content p:nth-of-type(5), .entry-content h4:nth-of-type(6), .entry-content p:nth-of-type(6){ display:none } ``` ```html #### Headline one Copy Text 1 #### Headline Two Copy Text 2 #### Headline Three Copy Text 3 #### Headline Four Copy Text 4 #### Headline Five Copy Text 5 #### Headline Six Copy Text 6 ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: With CSS ``` .cx_h4, .cx_h4~p{ display: none; } ``` With jQuery ``` $('.cx_h4, .cx_h4~p').hide(); ``` Upvotes: -1
2018/03/22
684
2,937
<issue_start>username_0: I have a simple search bar which uses a react-autosuggest. When I create a suggestion, I want to attach an onClick handler. This onClick has been passed down from a parent class. When the suggestion is rendered however, `this` is undefined and therefore the click handler is not attached. I have attached the component below, the logic which is not working is in the `renderSuggestion` method. ``` import Autosuggest from 'react-autosuggest' import React from 'react' export class SearchBar extends React.Component { static getSuggestionValue(suggestion) { return suggestion; } static escapeRegexCharacters(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } constructor(props) { super(props); this.state = { value: '', suggestions: [], listOfValues: this.props.tickers }; } onChange = (event, { newValue, method }) => { this.setState({ value: newValue }); }; onSuggestionsFetchRequested = ({ value }) => { this.setState({ suggestions: this.getSuggestions(value) }); }; onSuggestionsClearRequested = () => { this.setState({ suggestions: [] }); }; renderSuggestion(suggestion) { return ( this.props.clickHandler(suggestion)}>{suggestion} ); } getSuggestions(value) { const escapedValue = SearchBar.escapeRegexCharacters(value.trim()); if (escapedValue === '') { return []; } const regex = new RegExp('^' + escapedValue, 'i'); return this.state.listOfValues.filter(ticker => regex.test(ticker)); } render() { const { value, suggestions } = this.state; const inputProps = { placeholder: "Search for stocks...", value, onChange: this.onChange }; return ( ); } } ```<issue_comment>username_1: In the scope of `renderSuggestion`, `this` isn't referring to the instance of the class. Turning `renderSuggestion` into an arrow function like you've done elsewhere will ensure that `this` refers to the instance of the class. ``` renderSuggestion = (suggestion) => { return ( this.props.clickHandler(suggestion)}>{suggestion} ); } ``` Upvotes: 0 <issue_comment>username_2: This is becuase you need to bind "this" to your function. If you add this code to your constructor ``` constructor(props) { super(props); this.state = { value: '', suggestions: [], listOfValues: this.props.tickers }; //this line of code binds this to your function so you can use it this.renderSuggestion = this.renderSuggestion.bind(this); } ``` It should work. More info can be found at <https://reactjs.org/docs/handling-events.html> Upvotes: 1
2018/03/22
1,127
4,040
<issue_start>username_0: I have a basic cordova app running on android that loads my main web app in a webview. When running my web app via cordova it will not download any pdf's over https that are located in the same hosting subscription as my app. Downloading pdf's over https from other websites work fine - including other hosting subscriptions on the same server. Downloading pdf's over http work fine no matter where the are hosted. All other files (including txt files) download ok no matter where they are hosted (either by http or https). **EXAMPLE:** <https://mywebsite.com/test.txt> (DOWNLOADS OK) **<https://mywebsite.com/test.pdf> (DOES NOT DOWNLOAD)** <http://mywebsite.com/test.pdf> (DOWNLOADS OK) <https://anyanotherwebsite.com/test.txt> (DOWNLOADS OK) <https://anyanotherwebsite.com/test.pdf> (DOWNLOADS OK) <http://anyanotherwebsite.com/test.pdf> (DOWNLOADS OK) **MY CODE:** This is my cordova "index.html" file: ``` Loading ``` This is my cordova "index.js" file: ``` var app = { initialize: function() { document.addEventListener('deviceready', this.onDeviceReady.bind(this), false); }, onDeviceReady: function() { var targetUrl = "https://cordova1.mydevelopmentserver.com/"; window.location.replace(targetUrl); }, }; app.initialize(); ``` This is my cordova "config.xml" file: ``` xml version='1.0' encoding='utf-8'? My Awesome App Apache Cordova Team ``` Have also trying change the config.xml settings to below but it still does not work: ``` ``` **DOWNLOAD SAMPLE CORDOVA PROJECT:** <https://drive.google.com/file/d/1Z3TZudstF5WqquW6M-bv-8cit3nUFNcI/view?usp=sharing> The sample cordova project redirects to <https://cordova1.mydevelopmentserver.com> which contains the following html file which can be used to test the issue. I have also setup <https://cordova2.mydevelopmentserver.com> exactly the same & the issue still occurs with that domain as well. ``` Hello World <https://cordova1.mydevelopmentserver.com/test.txt> <https://cordova1.mydevelopmentserver.com/test.pdf> <http://cordova1.mydevelopmentserver.com/test.pdf> --- <https://cordova2.mydevelopmentserver.com/test.txt> <https://cordova2.mydevelopmentserver.com/test.pdf> <http://cordova2.mydevelopmentserver.com/test.pdf> ``` **OTHER NOTES:** I don't think that it is not an issue with the server as links to a pdf from another website on the same server works ok. I don't think that it is not an issue with the SSL certificate as other links to hosting subscription with the same SSL work ok. I'm new to cordova but think it may be an issue with my configuration somewhere but have already ripped out as much of the config as I can. Cordova version: 7.0 Android version: 7.0 Phone: Samsung S8+ Also tested it on a Samsung S4 running Android 5.0.1 but have the same issue.<issue_comment>username_1: Using your example I could reproduce your issue & it looks like it is related to using the WebView. If I use the InAppBrowser I can open PDF's over https fine (no matter where they are). Hopefully you can at least use the InAppBrowser until a proper solution is found. Upvotes: 3 [selected_answer]<issue_comment>username_2: If you are sure of **SSL** validity try to set properly **content security policy** or cordova **allow origin** of **whitelist plugin**: <https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/> For suspect invalid **SSL** certificate take a look here: <http://ivancevich.me/articles/ignoring-invalid-ssl-certificates-on-cordova-android-ios/> From my experience i think is somekind of issue related to trust your cert from cordova webview, in the above link you may try to implement **onReceivedSslError** handle and look if **SSL** cert have a problem. Try to test your **SSL** cert here to make sure it not have issues: <https://www.ssllabs.com/ssltest/> In **Handshake Simulation** report you are able to verify many mobile platform and webviews version to check if certificate is trusted or not. Hope it helps. Upvotes: 0
2018/03/22
442
1,842
<issue_start>username_0: I have a database (structured according to dplyr principle) giving an overview of a literature database. One of the columns is "language", and another one is "tag", a deprecated column I'd like to clean up as it contains multiple information. It also contains "language" information. Each book entry has its language in that "tag" entry (along with other information, separated by commas). How can I copy each of these language strings contained in "tag" to the respective language column (currently empty). I.e., how can I do "if tag column contains string "English" then move "English" to column "language"?<issue_comment>username_1: Using your example I could reproduce your issue & it looks like it is related to using the WebView. If I use the InAppBrowser I can open PDF's over https fine (no matter where they are). Hopefully you can at least use the InAppBrowser until a proper solution is found. Upvotes: 3 [selected_answer]<issue_comment>username_2: If you are sure of **SSL** validity try to set properly **content security policy** or cordova **allow origin** of **whitelist plugin**: <https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/> For suspect invalid **SSL** certificate take a look here: <http://ivancevich.me/articles/ignoring-invalid-ssl-certificates-on-cordova-android-ios/> From my experience i think is somekind of issue related to trust your cert from cordova webview, in the above link you may try to implement **onReceivedSslError** handle and look if **SSL** cert have a problem. Try to test your **SSL** cert here to make sure it not have issues: <https://www.ssllabs.com/ssltest/> In **Handshake Simulation** report you are able to verify many mobile platform and webviews version to check if certificate is trusted or not. Hope it helps. Upvotes: 0
2018/03/22
331
892
<issue_start>username_0: I want to modify lines in a file using awk and print the new lines with the following line. My file is like this ``` Name_Name2_ Name3_Name4 ASHRGSJFSJRGDJRG Name5_Name6_Name7_Name8 ADGTHEGHGTJKLGRTIWRK ``` I want ``` Name-Name2 ASHRGSJFSJRGDJRG Name5-Name6 ADGTHEGHGTJKLGRTIWRK ``` I have sued awk to modify my file: ``` awk -F'_' {print $1 "-" $2} file > newfile ``` but I don't know how to tell to print also the line just after (ABDJRH) sure is it possible with awk x=NR+1 NR<=x thanks<issue_comment>username_1: Following `awk` may help you on same. ``` awk -F"_" '/_/{print $1"-"$2;next} 1' Input_file ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: assuming your structure in sample (no separation in line with "data" letter ) ``` awk '$0=$1' Input_file # or with sed sed 's/[[:space:]].*//' Input_file ``` Upvotes: 0
2018/03/22
1,234
3,627
<issue_start>username_0: So, basically I need to print out a 2d array as a table and put indexes "around" it. ``` Random rnd = new Random(); int[][] array = new int[5][5]; for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length; col++) { array[row][col] = rnd.nextInt(6); } } for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length; col++) { if (col < 1) { System.out.print(row+" "); System.out.print(" " + array[row][col] + " "); } else { System.out.print(" " + array[row][col] + " "); } } System.out.println(); } ``` } I get this: ``` 0 2 4 0 2 4 1 1 2 0 2 2 2 0 1 5 4 0 3 4 2 1 4 1 4 2 4 3 1 3 ``` So the first (left) column are indexes and I need to put another column of indexes (0,1,2,3,4) on top of the "table" with "counting" starting from the second column...something like this: ``` 0 1 2 3 4 0 2 4 0 2 4 1 1 2 0 2 2 2 0 1 5 4 0 3 4 2 1 4 1 4 2 4 3 1 3 ``` Sorry for any mistakes, its my first time asking here.<issue_comment>username_1: You are only missing another for before the nested fors in which you print the table, where to print out first an empty character, after which the indexes needed. Otherwise, the code seems correct. ``` System.out.print(" "); for(int i=0;i ``` Upvotes: 0 <issue_comment>username_2: Your final printed tabs has a size bigger by one than your array. So first, loop for the length of array + 1. To do this change `<` condition by `<=`. Then you can simply identify the different cases you are going through : 1. Top right corner is identify by `row==0` and `col==0`. In this case just print a space 2. First row is identify by `row==0` and `col!=0`. In this case just print the column number in your array : `col-1` 3. First column is identify by `col==0` and `row!=0`. In this case just print the row number in your array : `row-1` 4. All other values, just print them from your array : `array[col-1][row-1]`. You should obtain this : ``` for (int row = 0; row <= ROWS; row++) { for (int col = 0; col <= COLUMNS; col++) { if (col == 0 && row == 0) { //Top right corner System.out.print(" "); } else if (row == 0) { //First row System.out.print(" " + (col-1)); } else if (col == 0) { //First column System.out.print(" " + (row-1)); } else { //All other cases System.out.print(" " + array[row-1][col-1]); } } System.out.println(); } ``` Upvotes: 1 [selected_answer]<issue_comment>username_3: Make a for loop before the nested for loop: ``` Random rnd = new Random(); final int COLUMNS = 5; final int ROWS = 5; int[][] array = new int[COLUMNS][ROWS]; for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length; col++) { array[row][col] = rnd.nextInt(6); } } System.out.print(" "); for (int row = 0; row < array.length; row++) { System.out.print(" " + row ); } System.out.println(); for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length; col++) { if (col < 1) { System.out.print(row); System.out.print(" " + array[row][col]); } else { System.out.print(" " + array[row][col]); } } System.out.println(); } ``` output: ``` 0 1 2 3 4 0 2 3 1 0 2 1 0 1 1 5 2 2 1 0 3 3 5 3 1 4 0 5 2 4 1 0 3 3 3 ``` Upvotes: 1
2018/03/22
1,060
4,386
<issue_start>username_0: Suppose that I have a Directive decorator which adds a static method to it's target called factory: ``` function Directive(constructor: T) { return class extends constructor { static factory(...args): ng.IDirectiveFactory { const c: any = () => { return constructor.apply(this, args); }; c.prototype = constructor.prototype; return new c(...args); } }; } ``` I also add the type via an interface: ``` interface BaseDirective extends ng.IDirective { factory(): ng.IDirectiveFactory; } ``` Why in my class declaration of: ``` @Directive class FocusedDirective implements BaseDirective {.... ``` I get a `Class 'FocusedDirective' incorrectly implements interface 'BaseDirective'. Property 'factory' is missing in type 'FocusedDirective'.` Am I wrong to expect from `@Directive` to add this missing property for me?<issue_comment>username_1: Decorators can't change the type of the class, you can invoke your decorator as a function and store the new class which will contain the method and use the new class instead of the original: ``` const FocusedDirectiveWithDirective = Directive(FocusedDirective); ``` You can do away with the intermediate class altogether by using class expressions: ``` const FocusedDirective = Directive(class implements BaseDirective{ }); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You have two problems. The first has little to do with decorators: `factory` is a static method in your implementation, but a regular method in your interface: ``` interface BaseDirective { factory(): ng.IDirectiveFactory; } ``` That's going to be a problem for you. For now I'm going to convert the implementation to a regular method, since it's simpler to implement. ``` function Directive(constructor: T) { return class extends constructor { factory(...args: any[]): ng.IDirectiveFactory { const c: any = () => { return constructor.apply(this, args); }; c.prototype = constructor.prototype; return new c(...args); } }; } ``` --- The second issue: decorators do not mutate the class signature the way you're expecting. This is an [oft-requested feature](https://github.com/Microsoft/TypeScript/issues/4881) and there are some interesting issues around why it's not a simple problem to solve. Importantly, it's not easy to figure out how to support having the implementation of the class refer to the mutated type. In your case: would the stuff inside your `{....` know about `factory()` or not? Most people seem to expect it would, but the decorator hasn't been applied yet. The workaround is not to use decorator syntax at all, but instead to use the decorator function as a regular function to create a new class. The syntax looks like this: ``` class FocusedDirective extends Directive(class { // any impl that doesn't rely on factory prop: string = "hey"; foo() { this.prop; // okay // this.factory(); // not okay } }) implements BaseDirective { // any impl that relies on factory bar() { this.prop; // okay this.foo(); // okay this.factory(); // okay } } ``` This also solves the "does the implementation know about the decorator" issue, since the stuff inside the decorator function does not, and the stuff outside does, as you see above. --- Back to the static/instance issue. If you want to enforce a constraint on the static side of a class, you can't do it by having the class implement anything. Instead, you need to enforce the static side on the class constructor itself. Like this: ``` interface BaseDirective { // any actual instance stuff here } interface BaseDirectiveConstructor { new(...args: any[]): BaseDirective; factory(): ng.IDirectiveFactory; } class FocusedDirective extends Directive(class { // impl without BaseDirectiveConstructor }) implements BaseDirective { // impl with BaseDirectiveConstructor bar() { FocusedDirective.factory(); // okay } } function ensureBaseDirectiveConstructor(t: T): void {} ensureBaseDirectiveConstructor(FocusedDirective); ``` The `ensureBaseDirectiveConstructor()` function makes sure that the `FocusedDirective` class constructor has a static `factory()` method of the right type. That's where you'd see an error if you failed to implement the static side. --- Okay, hope that helps. Good luck. Upvotes: 1
2018/03/22
490
1,608
<issue_start>username_0: I've two tables: ``` `orders` order_id order_office_id order_invoice_id 1 1 1 2 2 2 3 2 2 4 2 3 5 1 4 `invoices` inv_id inv_order_id inv_amount 1 1 500.00 2 0 320.00 3 3 740.00 4 4 160.00 ``` With this query: ``` SELECT SUM(inv_amount) matrah, order_office_id FROM `invoices` LEFT JOIN orders ON order_invoice_id = inv_id OR inv_order_id = order_id WHERE order_id IS NOT NULL GROUP BY order_office_id ``` It is multiplying some amounts. What I want to get sum of amounts by office: ``` office_id sum 1 660.00 2 1060.00 ``` How to get proper amounts by single query?<issue_comment>username_1: This query may help you out: ``` SELECT SUM(i.inv_amount) matrah, o.order_office_id FROM `invoices` AS i LEFT JOIN `orders` AS o ON o.order_invoice_id = i.inv_id GROUP BY order_office_id ``` OR statement in your ON condition caused the problem. Upvotes: 0 <issue_comment>username_2: This does what you want, I think ``` select sum(inv_amount) as matrah, (select order_office_id from orders where order_invoice_id = inv_id limit 1) as office from invoices group by office; ``` I've removed the OR, because you were getting two office ids for one of the orders, so it was ambiguous. I've included a subquery to make sure that only one office is applied to each order. Upvotes: 2 [selected_answer]
2018/03/22
358
1,345
<issue_start>username_0: I'm trying to understand how an OS figures out what thread is a current one (for example, when the thread calls `gettid()` or `GetCurrentThreadId()`). Since a process address space is shared between all threads, keeping a thread id there is not an option. It must be something unique to each thread (i.e. stored in its context). If I was an OS developer, I would store it in some internal CPU register readable only in kernel mode. I googled a lot but haven't found any similar question (as if it was super obvious). So how is it implemented in real operating systems like Linux or Windows?<issue_comment>username_1: This query may help you out: ``` SELECT SUM(i.inv_amount) matrah, o.order_office_id FROM `invoices` AS i LEFT JOIN `orders` AS o ON o.order_invoice_id = i.inv_id GROUP BY order_office_id ``` OR statement in your ON condition caused the problem. Upvotes: 0 <issue_comment>username_2: This does what you want, I think ``` select sum(inv_amount) as matrah, (select order_office_id from orders where order_invoice_id = inv_id limit 1) as office from invoices group by office; ``` I've removed the OR, because you were getting two office ids for one of the orders, so it was ambiguous. I've included a subquery to make sure that only one office is applied to each order. Upvotes: 2 [selected_answer]
2018/03/22
1,139
3,135
<issue_start>username_0: I am trying to group items an array of items by a property and then reindex the result starting from `0`. The following function returns a grouped set of items. ``` groupItemBy(array, property) { let hash = {}, props = property.split('.'); for (let i = 0; i < array.length; i++) { let key = props.reduce( (acc, prop) => { return acc && acc[prop]; }, array[i]); if (!hash[key]) hash[key] = []; hash[key].push(array[i]); } return hash; } ``` The result is an array of arrays, and something like: ``` [{ "1193312":[ { "description":"Item 1", "number": "1193312" } ], "1193314":[ { "itemDesc":"Item 2"}, "number": "1193314" { "description":"Item 3", "number": "1193314" } ], etc... }] ``` From here I'd like to map `1193312` to `0`, and `1193314` to `1`, etc. I tried `.filter(val => val)` on the result, but that seemed to have no effect.<issue_comment>username_1: If you can use `ES6`: ```js var arr = [{ "1193312":[ { "time":"2018-02-20", "description":"Item 1" } ], "1193314":[ { "time":"2018-02-21", "itemDesc":"Item 2"}, { "time":"2018-02-21", "description":"Item 3" } ] }]; var data = arr[0]; var res = Object.entries(data).map(([key, value]) => ({[key]: value})); console.log(res); ``` Upvotes: 0 <issue_comment>username_2: ```js var data = [{ "1193312":[ { "description":"Item 1", "number": "1193312" } ], "1193314":[ { "itemDesc":"Item 2", "number": "1193314"}, { "description":"Item 3", "number": "1193314" } ] }] var newData = Object.keys(data[0]).map(function(key,index){ var newObj={}; newObj[index] = data[0][key]; return newObj; }); console.log(newData); ``` Upvotes: 1 <issue_comment>username_3: You need to use an intermediate key replacement: ``` function groupItemBy(array, property) { let hash = {} let props = property.split('.') let keys = [] for (let i = 0; i < array.length; i++) { let key = props.reduce((acc, prop) => { return acc && acc[prop]; }, array[i]); let subst = keys.indexOf(key) if (subst === -1) { keys.push(key) subst = keys.length - 1 } if (!hash[subst]) hash[subst] = []; hash[subst].push(array[i]); } return hash; } ``` [ <https://jsfiddle.net/05t9141p/> ] Upvotes: 3 [selected_answer]<issue_comment>username_4: You could use `map` for the array part, and `Object.values` and reduce for the renumber part. ```js const data = [{ "1193312":[ { "time":"2018-02-20", "description":"Item 1", "number": "1193312" } ], "1193314":[ { "time":"2018-02-21", "itemDesc":"Item 2", "number": "1193314" },{ "time":"2018-02-21", "description":"Item 3", "number": "1193314" } ] }]; const renumbered = data.map((m) => Object.values(m).reduce((a,v,ix) => (a[ix] = v, a), {})); console.log(renumbered); ``` Upvotes: 2
2018/03/22
689
2,666
<issue_start>username_0: I have tried downloading small files from google Colaboratory. They are easily downloaded but whenever I try to download files which have a large sizes it shows an error? What is the way to download large files?<issue_comment>username_1: Google colab doesn't allow you to download large files using `files.download()`. But you can use one of the following methods to access it: 1. The easiest one is to use github to commit and push your files and then clone it to your local machine. 2. You can mount google-drive to your colab instance and write the files there. Upvotes: 0 <issue_comment>username_2: This is how I handle this issue: ``` from google.colab import auth from googleapiclient.http import MediaFileUpload from googleapiclient.discovery import build auth.authenticate_user() ``` Then click on the link, authorize Google Drive and paste the code in the notebook. ``` drive_service = build('drive', 'v3') def save_file_to_drive(name, path): file_metadata = { 'name': name, 'mimeType': 'application/octet-stream' } media = MediaFileUpload(path, mimetype='application/octet-stream', resumable=True) created = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute() print('File ID: {}'.format(created.get('id'))) return created ``` Then: ``` save_file_to_drive(destination_name, path_to_file) ``` This will save whatever files to your Google Drive, where you can download or sync them or whatever. Upvotes: 4 <issue_comment>username_3: If you have created a large zip file, say my\_archive.zip, then you can download it as following: 1. Mount your Google drive from your Google colab Notebook. You will be asked to enter a authentication code. ``` from google.colab import drive drive.mount('/content/gdrive',force_remount=True) ``` 2. Copy the zip file to any of your google drive folder (e.g. downloads folder). You may also copy the file on 'My Drive' which is a root folder. ``` !cp my_archive.zip '/content/gdrive/My Drive/downloads/' !ls -lt '/content/gdrive/My Drive/downloads/' ``` Finally, you can download the zip file from your Google drive to your local machine. Upvotes: 4 <issue_comment>username_4: I tried many different solutions. The only way that was effective and quick is to zip the file/folder and then download it directly: ``` !zip -r model.zip model.pkl ``` And to download: [![enter image description here](https://i.stack.imgur.com/EKs30.png)](https://i.stack.imgur.com/EKs30.png) Upvotes: 1
2018/03/22
1,203
4,380
<issue_start>username_0: I do not know exactly what I am looking for, that is the reason why I am opening a new question. If there is another question which is answered, please mark this question as a duplicate. > > Please understand I am new to IOS development, so if I write something > that is not quite right, feel free to correct me. > > > So I have an array in my swift code with six indexes. Every index has a value of four different variables. For example in my `QuestionBank` class: ``` var list = [Question]() init() { list.append(Question(text: "some Text", answerA: "answer a"), answerB: "answer b", selectedQuestionNumber: 1) list.append(Question(text: "some Text", answerA: "answer a"), answerB: "answer b", selectedQuestionNumber: 2) list.append(Question(text: "some Text", answerA: "answer a"), answerB: "answer b", selectedQuestionNumber: 3) list.append(Question(text: "some Text", answerA: "answer a"), answerB: "answer b", selectedQuestionNumber: 4) list.append(Question(text: "some Text", answerA: "answer a"), answerB: "answer b", selectedQuestionNumber: 5) list.append(Question(text: "some Text", answerA: "answer a"), answerB: "answer b", selectedQuestionNumber: 6) } ``` I added the `selectedQuestionNumber` to have a unique identifier for each index. I do not want to use the default number of every index (`allQuestions.list[questionNumber].questionText`) So my question is the following: How can I get the values of the first index using the `selectedQuestionNumber` as the identifier? So far i got this: ``` if allQuestions.list[questionNumber].storyNumber == 1 { storyTextView.text = allQuestions.list[questionNumber].questionText topButton.setTitle(allQuestions.list[questionNumber].answerA, for: .normal) bottomButton.setTitle(allQuestions.list[questionNumber].answerB, for: .normal) } ``` I evaluate if the storyNumber is 1 but the text and the answers won't be evaluated by the same factor. I would like to have everything evaluated by the storyNumber. That means that the `[questionNumber]` must be replaced with something else and give me the text and the answers that belong to storyNumber 1. If you need more information about the code and the variables that are not defined (at least here, on my project they are defined), feel free to ask. Best regards<issue_comment>username_1: You’re looking to use `first(where: )`. It’s done like this: ``` let question = list.first(where: { $0.selectedQuestionNumber == 1 }) ``` You can also sort the array by `selectedQuestionNumber` like this: ``` let orderedList = list.sorted { $0.selectedQuestionNumber < $1.selectedQuestionNumber } ``` Or, the mutating version: ``` list.sort { $0.selectedQuestionNumber < $1.selectedQuestionNumber } ``` To which you can then access them by their array index. And on top of all of that, there is filter: ``` let question = list.filter { $0.selectedQuestionNumber == 3 } ``` But be aware, since you’re using it in this context, that the result will still be an array. There may be none, one, or multiple values that remain. Upvotes: 2 [selected_answer]<issue_comment>username_2: using `first(where: {$0.selectionNumber == VALUE})` is indeed what you are looking for if you just want to head straight forward. Since you want to index the array yourself, i would suggest doing it this way tho. I rewrote your Question struct to represent my design: ``` public struct Question { let text: String let answerA: String let answerB: String init(_ text: String, _ answerA: String, _ answerB: String) { self.text = text self.answerA = answerA self.answerB = answerB } } class Test { var list: [Int : Question] = [:] init() { list[0] = Question("some text", "answer A", "Answer B") list[1] = Question("some text", "answer A", "Answer B") list[2] = Question("some text", "answer A", "Answer B") list[3] = Question("some text", "answer A", "Answer B") list[4] = Question("some text", "answer A", "Answer B") list[5] = Question("some text", "answer A", "Answer B") } } ``` This way you will use an `dictionary` that you can index yourself and fetch the same way as an array. This way you don't have to zero index it either, but you can start at 15 and go up, or you can use negative values if you so wish. Upvotes: 0
2018/03/22
928
3,408
<issue_start>username_0: I need to get a `UILabel` to go to more than one line if text requires with autolayout. In code and also in storyboard for good measure I have set numberOfLines to 0 and wordwrapping on and I've also called `sizeToFit`. The full amount of text will display on multiple lines if I set the height constraint for the label to a large enough value such = 200. But with short text, it does not contract, leaving a lot of white space. But if I set the height constraint to a lower value such as >=21 then it shows only one line and cuts off everything else. The view hierarchy is View-Scrollview-Contentview-elements I set a bottom constant for the lowest element with a priority of 250 so it should adjust. Autolayout shows no errors Nothing, however, short of creating a huge height constraint for the label lets the label extend to multiple lines. Would appreciate any suggestions on how to solve this issue. In viewwillappear: ``` _myLabel.lineBreakMode = UILineBreakModeWordWrap;//deprecated but I threw it in too _myLabel.lineBreakMode = NSLineBreakByWordWrapping; _myLabel.numberOfLines = 0; [_myLabel sizeToFit]; // height constraint for label height>=21//text does not extend more than one line height=200//text does extend more than one line but leaves lots of whitespace if text is short ie it does not shrink. ```<issue_comment>username_1: You’re looking to use `first(where: )`. It’s done like this: ``` let question = list.first(where: { $0.selectedQuestionNumber == 1 }) ``` You can also sort the array by `selectedQuestionNumber` like this: ``` let orderedList = list.sorted { $0.selectedQuestionNumber < $1.selectedQuestionNumber } ``` Or, the mutating version: ``` list.sort { $0.selectedQuestionNumber < $1.selectedQuestionNumber } ``` To which you can then access them by their array index. And on top of all of that, there is filter: ``` let question = list.filter { $0.selectedQuestionNumber == 3 } ``` But be aware, since you’re using it in this context, that the result will still be an array. There may be none, one, or multiple values that remain. Upvotes: 2 [selected_answer]<issue_comment>username_2: using `first(where: {$0.selectionNumber == VALUE})` is indeed what you are looking for if you just want to head straight forward. Since you want to index the array yourself, i would suggest doing it this way tho. I rewrote your Question struct to represent my design: ``` public struct Question { let text: String let answerA: String let answerB: String init(_ text: String, _ answerA: String, _ answerB: String) { self.text = text self.answerA = answerA self.answerB = answerB } } class Test { var list: [Int : Question] = [:] init() { list[0] = Question("some text", "answer A", "Answer B") list[1] = Question("some text", "answer A", "Answer B") list[2] = Question("some text", "answer A", "Answer B") list[3] = Question("some text", "answer A", "Answer B") list[4] = Question("some text", "answer A", "Answer B") list[5] = Question("some text", "answer A", "Answer B") } } ``` This way you will use an `dictionary` that you can index yourself and fetch the same way as an array. This way you don't have to zero index it either, but you can start at 15 and go up, or you can use negative values if you so wish. Upvotes: 0
2018/03/22
1,051
2,858
<issue_start>username_0: I have a data table that has entries for every one minute, it's bulky dataset. So I need to get every 2 minutes data retrieving `10 minutes dataset from last valid record`. All these data is used in the graph drawing, so trying to limit the number of records displayed in the chart. eg for a sample looks like this: ``` DateTime 2016-01-01 08:22:00 2016-01-01 08:21:00 2016-01-01 08:20:00 2016-01-01 08:19:00 2016-01-01 08:18:00 2016-01-01 08:17:00 2016-01-01 08:16:00 2016-01-01 08:15:00 2016-01-01 08:14:00 2016-01-01 08:13:00 2016-01-01 08:12:00 2016-01-01 08:11:00 2016-01-01 08:10:00 ``` Expected records result: ``` 2016-01-01 08:21:00 2016-01-01 08:19:00 2016-01-01 08:17:00 2016-01-01 08:15:00 2016-01-01 08:13:00 ``` How can I do it in SQL query?<issue_comment>username_1: You’re looking to use `first(where: )`. It’s done like this: ``` let question = list.first(where: { $0.selectedQuestionNumber == 1 }) ``` You can also sort the array by `selectedQuestionNumber` like this: ``` let orderedList = list.sorted { $0.selectedQuestionNumber < $1.selectedQuestionNumber } ``` Or, the mutating version: ``` list.sort { $0.selectedQuestionNumber < $1.selectedQuestionNumber } ``` To which you can then access them by their array index. And on top of all of that, there is filter: ``` let question = list.filter { $0.selectedQuestionNumber == 3 } ``` But be aware, since you’re using it in this context, that the result will still be an array. There may be none, one, or multiple values that remain. Upvotes: 2 [selected_answer]<issue_comment>username_2: using `first(where: {$0.selectionNumber == VALUE})` is indeed what you are looking for if you just want to head straight forward. Since you want to index the array yourself, i would suggest doing it this way tho. I rewrote your Question struct to represent my design: ``` public struct Question { let text: String let answerA: String let answerB: String init(_ text: String, _ answerA: String, _ answerB: String) { self.text = text self.answerA = answerA self.answerB = answerB } } class Test { var list: [Int : Question] = [:] init() { list[0] = Question("some text", "answer A", "Answer B") list[1] = Question("some text", "answer A", "Answer B") list[2] = Question("some text", "answer A", "Answer B") list[3] = Question("some text", "answer A", "Answer B") list[4] = Question("some text", "answer A", "Answer B") list[5] = Question("some text", "answer A", "Answer B") } } ``` This way you will use an `dictionary` that you can index yourself and fetch the same way as an array. This way you don't have to zero index it either, but you can start at 15 and go up, or you can use negative values if you so wish. Upvotes: 0
2018/03/22
1,264
5,216
<issue_start>username_0: I had a perfectly functional application on the app store for over a year which featured Facebook signup and it all worked without any problems. However, few days ago I got few complaints from users who say that Facebook login causes the app to get stuck on login screen. I've investigated the behaviour and it seems that the callback from Facebook after clicking on login button does not work when you use Facebook app to authenticate. Going through Safari works. I've updated my Cocoapod libs to the latest version and in my AppDelegate I have the following: ``` func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) return true } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(app, open: url as URL!, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) } func applicationDidBecomeActive(_ application: UIApplication) { FBSDKAppEvents.activateApp() } ``` All my Plist files are in order, Facebook didn't suspend my app or anything similar, and again it works when I try to sign in using Safari. Version of iOS is 11 and i'm using Swift 3.<issue_comment>username_1: I think you've done a log in via Facebook and this may cause some problems It is best to use the latest update for Facebook sdk using pod or download facebook framework latest version ``` pod 'FacebookCore' pod 'FacebookLogin' pod 'FacebookShare' ``` see facebook [LoginBehavior](https://github.com/facebook/facebook-sdk-swift/blob/master/Sources/Login/LoginBehavior.swift) based on last update for facebook sdk It should appear this way [![enter image description here](https://i.stack.imgur.com/KN52U.png)](https://i.stack.imgur.com/KN52U.png) And check plist info same this ``` CFBundleURLTypes CFBundleURLSchemes fb{your-app-id} FacebookAppID {your-app-id} FacebookDisplayName {your-app-name} LSApplicationQueriesSchemes fbapi fb-messenger-share-api fbauth2 fbshareextension ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Try to catch any response from Facebook to get a better idea where your request it's being stopped. For example Facebook changes the policies for readPermissions from time to time (is not usual) but that may cause an error on your request. I try to get a better idea when i make a request like this: ``` loginManager.logIn(readPermissions: [.email, .publicProfile, .userFriends, .userBirthday], viewController: parentVC) { (result) in //Check the response switch result { case .failed(let error): #if DEBUG print("Failed login: ", error.localizedDescription) #endif completionHandler(.connectionError) break case .cancelled: completionHandler(.cancelledError) break case .success(_, _, _): //We have success, make graph Request self.makeGraphRequest(completionHandler: completionHandler) break }//Check the pemrmissions response }// Ends loginManager.logIn ``` Upvotes: 0 <issue_comment>username_3: As mentioned above by @username_1, Facebook Login SDK Documentation neglected to include this in the plist snippet. This fully resolved the crash for me. Thanks @username_1 ``` CFBundleTypeRole ///ADD THIS Editor ///AND THIS CFBundleURLSchemes flex fb323015428110219 ``` Upvotes: 2 <issue_comment>username_4: Works For FBSDK version 5.0.0 and later in AppDelegate ``` func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions) return true } ``` after that, you can add ``` func applicationDidBecomeActive(_ application: UIApplication) { AppEvents.activateApp() } ``` and then ``` func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { return ApplicationDelegate.shared.application(app, open: (url as URL?)!, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplication.OpenURLOptionsKey.annotation]) } ``` by following that, should works with you. Upvotes: 2 <issue_comment>username_5: ``` Try FBSDKLoginButton and use the Delegate method of that. It will help you. If you want to login with your browser only and want to remove "Login with the Facebook App" then remove LSApplicationQueriesSchemes array of strings from your info.plist. It will remove the app login option. ``` ```html LSApplicationQueriesSchemes fbapi fb-messenger-share-api fbauth2 fbshareextension ``` Upvotes: 0
2018/03/22
811
2,712
<issue_start>username_0: I have installed Jupiter notebook and I only have python 2 as a default kernel. I want to change it from python 2 to python 3. How could I do that?[![Here is the screenshot.](https://i.stack.imgur.com/F0Cbi.png)](https://i.stack.imgur.com/F0Cbi.png)<issue_comment>username_1: In case you installed the python/jupyter with anaconda, simply update the python from 2.\* to 3.\* Upvotes: 0 <issue_comment>username_2: ``` https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-python.html ``` Follow the link for managing python. If you use python 2, then install python 3 by using this command. ``` conda create -n py36 python=3.6 anaconda ``` After installing python 3, activate python 3 by using this command ``` activate py36 ``` Then open jupyter notebook, you will find python on your kernel. Upvotes: 5 [selected_answer]<issue_comment>username_3: You can do this with the following steps: 1. `conda create -n py36 'python=3.6' ipykernel #Replace 3.6 with desired version.` 2. To activate installed jupyter kernal you need run, `source activate py36` 3. `python -m ipykernel install --user` 4. The interesting part: if you want to switch between kernels (py2-py3) in the same notebook, you need to run, `conda install nb_conda` However, if at any point you realize that some of the modules are not available, for that you need to check Anaconda Python version. ``` python - version ``` if it is not python 3.x, you need to run ``` conda create -n py36 python=3.6 anaconda source active py36 ``` I hope it helps and enjoy switching python versions in the same notebook. You can try to print something in both python2 and python 3. Upvotes: 3 <issue_comment>username_4: You can do this with the following steps: 1. Create new env by using python3. virtualenv -p /usr/bin/python3.7 jupyter\_environment 2. Activate env source jupyter\_environment/bin/activate 3. Start jupyter jupyter notebook --allow-root Then open Jupyter notebook, you will find python3 by default on your kernel. Upvotes: 0 <issue_comment>username_5: I have succeeded to add Python 3.9 to Jupyter as follows. ``` # cd /usr/share/jupyter/kernels # ls python3 # cp python3 python3.9 # cd python3.9 ``` and changed `python3` in the `kernel.json` file to `python3.9`: ``` # cat kernel.json { "argv": [ "/usr/bin/python3.9", "-m", "ipykernel_launcher", "-f", "{connection_file}" ], "display_name": "Python 3.9", "language": "python" ``` After this, the kernel may be changed through `Kernel->Change kernel` in Jupyter. Python 3.9 was installed separately, simply with package manager (zypper in my case). I think, this should work with Python 2 as well. Upvotes: 0
2018/03/22
972
3,344
<issue_start>username_0: I am working on a game where I use different sized objects - such as houses, trees etc. My question is, which way should I determine is the place I am going to place my object free or not? World is generated randomly every time the game is launched. (I'm only using x and z coordinates) For example, I have tree in a item pool with a size of 10x10, in the location 10, 0, 10 and I am going to add a stone which is size 5x5 for example. So how do I tell the stone "hey you can't place yourself to coordinates from 5 to 15 on x axis and 5 to 15 on z axis, place somewhere else". Yes a simple way would be to just write down all the coordinates which are taken (5,6,7 ... 14,15), but what if I have 1000 trees? Is there any better and faster way to locate free spot for the item other than looping through a list of coordinates which have also looped to be written in taking a slot?<issue_comment>username_1: In case you installed the python/jupyter with anaconda, simply update the python from 2.\* to 3.\* Upvotes: 0 <issue_comment>username_2: ``` https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-python.html ``` Follow the link for managing python. If you use python 2, then install python 3 by using this command. ``` conda create -n py36 python=3.6 anaconda ``` After installing python 3, activate python 3 by using this command ``` activate py36 ``` Then open jupyter notebook, you will find python on your kernel. Upvotes: 5 [selected_answer]<issue_comment>username_3: You can do this with the following steps: 1. `conda create -n py36 'python=3.6' ipykernel #Replace 3.6 with desired version.` 2. To activate installed jupyter kernal you need run, `source activate py36` 3. `python -m ipykernel install --user` 4. The interesting part: if you want to switch between kernels (py2-py3) in the same notebook, you need to run, `conda install nb_conda` However, if at any point you realize that some of the modules are not available, for that you need to check Anaconda Python version. ``` python - version ``` if it is not python 3.x, you need to run ``` conda create -n py36 python=3.6 anaconda source active py36 ``` I hope it helps and enjoy switching python versions in the same notebook. You can try to print something in both python2 and python 3. Upvotes: 3 <issue_comment>username_4: You can do this with the following steps: 1. Create new env by using python3. virtualenv -p /usr/bin/python3.7 jupyter\_environment 2. Activate env source jupyter\_environment/bin/activate 3. Start jupyter jupyter notebook --allow-root Then open Jupyter notebook, you will find python3 by default on your kernel. Upvotes: 0 <issue_comment>username_5: I have succeeded to add Python 3.9 to Jupyter as follows. ``` # cd /usr/share/jupyter/kernels # ls python3 # cp python3 python3.9 # cd python3.9 ``` and changed `python3` in the `kernel.json` file to `python3.9`: ``` # cat kernel.json { "argv": [ "/usr/bin/python3.9", "-m", "ipykernel_launcher", "-f", "{connection_file}" ], "display_name": "Python 3.9", "language": "python" ``` After this, the kernel may be changed through `Kernel->Change kernel` in Jupyter. Python 3.9 was installed separately, simply with package manager (zypper in my case). I think, this should work with Python 2 as well. Upvotes: 0
2018/03/22
289
1,050
<issue_start>username_0: I'm trying to run java program from mac terminal. I need to refer the library path before compilation.i keep getting import error because its not referring to the jar files.i cant get this to work. Any advise on this would be helpful. **Please find the below commands used:** ``` export CLASSPATH=/Users/Documents//IOS/lib/Parser.jar, /Users/Documents/IOS/lib/Collector.jar javac samplejava.java ``` Also, i need to run the whole thing as shell script(like how we run a batch job in windows). Please help me with a working sample.<issue_comment>username_1: Please try: ``` export CLASSPATH=/Users/Documents//IOS/lib/Parser.jar:/Users/Documents/IOS/lib/Collector.jar javac samplejava.java ``` classpath separator is : (colon) in \*nix and there should be no space. Upvotes: 3 [selected_answer]<issue_comment>username_2: create a .bash\_profile file in your home directory with `export CLASSPATH=/Users/Documents//IOS/lib/Parser.jar, /Users/Documents/IOS/lib/Collector.jar export PATH=${JAVA_HOME}/bin/` Upvotes: 0
2018/03/22
1,246
4,889
<issue_start>username_0: I have two combo boxes. When select the first combo box's first element the second combo box's elements need to change accordingly. ``` { xtype: 'combobox', fieldLabel: 'Type', name: 'type', store: 'type', displayField: 'name', valueField: 'id', queryMode: 'local', }, { xtype: 'combobox', fieldLabel: 'State', name: 'state', store: state, displayField: 'name', valueField: 'id', queryMode: 'local', } ``` So if I select first element of type combo box the state combo box need to have the element which are in state. Otherwise It should have to contain the elements in states. ``` var states = Ext.create('Ext.data.Store', { fields: ['id', 'name'], data: [{ 'id': 1, 'name': 'A' }, { 'id': 2, 'name': 'B' }, { 'id': 3, 'name': 'C' }, { 'id': 4, 'name': 'D' }, { 'id': 5, 'name': 'E' } ] }); var state = Ext.create('Ext.data.Store', { fields: ['id', 'name'], data: [{ 'id': 1, 'name': 'A' }, { 'id': 2, 'name': 'B' } ] }); ``` That means my second combo box's store part need to be changed dynamically.<issue_comment>username_1: Bind a change event to your first combo box. Load the store data in that function for second combo box by passing the selected value of first combobox. ``` { xtype: 'combobox', fieldLabel: 'Type', name: 'type', store: 'type', displayField: 'name', valueField: 'id', queryMode: 'local', listeners: { change: function(this,newVal,oldVal,eOpts){ var store = Ext.getStore('state'); store.load( params: { /* parameters to pass*/ }, callback : function(records, operation, success) { /* perform operations on the records*/ }); } } } ``` Upvotes: 1 <issue_comment>username_2: You want to use a change listener on the first `combobox` and use the `bindStore` function on the second `combobox` to bind the correct store: ``` listeners: { change: function(combo, nV) { if(nV=="A") combo.nextSibling().bindStore(state); if(nV=="B") combo.nextSibling().bindStore(states); } } ``` <https://fiddle.sencha.com/#view/editor&fiddle/2eoh> Upvotes: 3 [selected_answer]<issue_comment>username_3: For this you can use [`combo.setStore(store)`](https://docs.sencha.com/extjs/5.0.0/api/Ext.form.field.ComboBox.html#method-setStore). In this **[FIDDLE](https://fiddle.sencha.com/#view/editor&fiddle/2eoi)**, I have created a demo using [`combo`](https://docs.sencha.com/extjs/5.0.0/api/Ext.form.field.ComboBox.html). I hope this will help/guide you to achieve your requirement. **CODE SNIPPET** ``` Ext.application({ name: 'Fiddle', launch: function () { //Store Type Ext.define('StoreType', { extend: 'Ext.data.Store', alias: 'store.storetype', fields: ['text', 'value'], data: [{ text: 'Store1', value: 'store1' }, { text: 'Store2', value: 'store2' }] }); //Store 1 Ext.create('Ext.data.Store', { storeId: 'store1', fields: ['text', 'value'], data: [{ text: 'A', value: 'A' }] }); //Store 2 Ext.create('Ext.data.Store', { storeId: 'store2', fields: ['text', 'value'], data: [{ text: 'B', value: 'B' }] }); Ext.create('Ext.panel.Panel', { title: 'Combobox store change ', renderTo: Ext.getBody(), items: [{ xtype: 'combobox', fieldLabel: 'Select Store', store: { type: 'storetype' }, queryMode: 'local', listeners: { select: function (cmp, record) { var combo = cmp.up('panel').down('#myStore'); if (combo.isDisabled()) { combo.setDisabled(false); } combo.reset(); combo.setStore(record[0].get('value')); } } }, { xtype: 'combobox', itemId: 'myStore', fieldLabel: 'Select value', disabled: true }] }); } }); ``` Upvotes: 2
2018/03/22
1,080
4,265
<issue_start>username_0: I am trying to remove the h1 title on my about page in my functions.php file. Here is my code: ``` function remove_about_page_title() { if (is_page('about')) { remove_action('storefront_page', 'storefront_page_header', 10); } } add_action('init', 'remove_about_page_title'); ``` If I do a var dump on `is_page('about')` then I get `false` even though it is the about page. If I change my `add_action()` function to run the `remove_about_page_title()` function from init to `storefront_page` then `is_page()` prints true but the remove\_action function no longer works. Is this due to being out of the scope chain? Is there a way to remove the page header inside the `functions.php` file without CSS and #ids?<issue_comment>username_1: Bind a change event to your first combo box. Load the store data in that function for second combo box by passing the selected value of first combobox. ``` { xtype: 'combobox', fieldLabel: 'Type', name: 'type', store: 'type', displayField: 'name', valueField: 'id', queryMode: 'local', listeners: { change: function(this,newVal,oldVal,eOpts){ var store = Ext.getStore('state'); store.load( params: { /* parameters to pass*/ }, callback : function(records, operation, success) { /* perform operations on the records*/ }); } } } ``` Upvotes: 1 <issue_comment>username_2: You want to use a change listener on the first `combobox` and use the `bindStore` function on the second `combobox` to bind the correct store: ``` listeners: { change: function(combo, nV) { if(nV=="A") combo.nextSibling().bindStore(state); if(nV=="B") combo.nextSibling().bindStore(states); } } ``` <https://fiddle.sencha.com/#view/editor&fiddle/2eoh> Upvotes: 3 [selected_answer]<issue_comment>username_3: For this you can use [`combo.setStore(store)`](https://docs.sencha.com/extjs/5.0.0/api/Ext.form.field.ComboBox.html#method-setStore). In this **[FIDDLE](https://fiddle.sencha.com/#view/editor&fiddle/2eoi)**, I have created a demo using [`combo`](https://docs.sencha.com/extjs/5.0.0/api/Ext.form.field.ComboBox.html). I hope this will help/guide you to achieve your requirement. **CODE SNIPPET** ``` Ext.application({ name: 'Fiddle', launch: function () { //Store Type Ext.define('StoreType', { extend: 'Ext.data.Store', alias: 'store.storetype', fields: ['text', 'value'], data: [{ text: 'Store1', value: 'store1' }, { text: 'Store2', value: 'store2' }] }); //Store 1 Ext.create('Ext.data.Store', { storeId: 'store1', fields: ['text', 'value'], data: [{ text: 'A', value: 'A' }] }); //Store 2 Ext.create('Ext.data.Store', { storeId: 'store2', fields: ['text', 'value'], data: [{ text: 'B', value: 'B' }] }); Ext.create('Ext.panel.Panel', { title: 'Combobox store change ', renderTo: Ext.getBody(), items: [{ xtype: 'combobox', fieldLabel: 'Select Store', store: { type: 'storetype' }, queryMode: 'local', listeners: { select: function (cmp, record) { var combo = cmp.up('panel').down('#myStore'); if (combo.isDisabled()) { combo.setDisabled(false); } combo.reset(); combo.setStore(record[0].get('value')); } } }, { xtype: 'combobox', itemId: 'myStore', fieldLabel: 'Select value', disabled: true }] }); } }); ``` Upvotes: 2
2018/03/22
1,214
4,411
<issue_start>username_0: How can I use the `first()` method on a relation in an Eloquent query builder? I only want to return the first section and the first subsection within that section. I have the following query in my Assessment service: ``` public function firstSubsection() { return $this->model->with(['sections.subsections' => function ($q) { $q->take(1); }])->first(); } ``` This returns multiple sections: ``` { "id": 1, "name": "Assessment 1", "description": "Some description ", "created_at": "2018-03-09 17:14:43", "updated_at": "2018-03-09 17:14:43", "sections": [ { "id": 5, "name": "Section 1", "description": null, "parent": null, "created_at": "2018-03-09 17:14:52", "updated_at": "2018-03-09 17:14:52", "pivot": { "assessment_id": 1, "section_id": 5 }, "subsections": [ { "id": 6, "name": "Subsection 1", "description": "Lorem ipsum dolor sit amet \r\n ", "parent": 5, "position": 6, "created_at": "2018-03-09 17:15:08", "updated_at": "2018-03-21 11:40:10" } ] }, { "id": 10, "name": "Section 2", "description": null, "parent": null, "position": 10, "created_at": "2018-03-20 14:34:50", "updated_at": "2018-03-20 14:34:50", "pivot": { "assessment_id": 1, "section_id": 10 }, "subsections": [] } ] } ``` Any idea how I can achieve this? I have the following relationships in my Eloquent models: ``` class Section extends Model { use BelongsToSortedManyTrait, SortableTrait; public $fillable = [ 'id', 'name', 'description', 'parent', 'position' ]; public static $rules = [ // create rules 'name' => 'required' ]; public function assessments() { return $this->belongsToSortedMany('App\Models\Assessment'); } public function subsections() { return $this->hasMany(self::class, 'parent')->sorted(); } } class Assessment extends Model { public $fillable = [ 'id', 'name', 'description' ]; public static $rules = [ // create rules ]; public function sections() { return $this->belongsToMany('App\Models\Section')->whereNull('parent')->sorted(); } } ```<issue_comment>username_1: ``` public function firstSubsection() { return $this->model->with(['sections.subsections' => function ($q) { $q->take(1)->first(); }])->first(); } ``` Upvotes: 0 <issue_comment>username_2: I am not sure this will work or not, but you can try this logic: If you want to eager load the first section and subsection of your model you should create a new relationship in your model : ``` public function firstSectionOnly() { return $this->hasOne(Section::class)->orderBy('id', 'asc'); } ``` And in **Section** model define ``` public function firstSubSectionOnly() { return $this->hasOne(Subsection::class)->orderBy('id', 'asc'); } ``` Then you can eager load it in your current model: ``` public function firstSubsection() { return $this->model->with(['firstSectionOnly.firstSubSectionOnly'])->first(); } ``` After trying this. Tell me it is working or have errors. Upvotes: 1 <issue_comment>username_3: `Take(1)` and `first()` doing same thing right now. But still its not a problem. Remove `take(1)` and add `->get()` after `first()` Give it a try. Upvotes: 0 <issue_comment>username_4: In the end I had to do it like this: ``` public function firstSubsection() { return $this->model->with(['sections' => function ($q) { $q->with(['subsections' => function ($q) { $q->first(); } ])->first(); }])->first(); } ``` Thanks to @ab\_in for leading me in the right direction. Upvotes: 3 [selected_answer]
2018/03/22
1,595
5,827
<issue_start>username_0: I am studying about Haskell. And i am trying to make a while loop that everytime it runs it makes the value 'a' 2 times smaller with flooring after that. this works fine: ``` func a = if a > 0 then func (a/2) else print (a) ``` Now adding floor function to it. ``` func a = if a > 0 then func (floor (a/2)) else print (a) ``` now running it ``` func 5 ``` And there is an error: ``` Ambiguous type variable ‘t0’ arising from a use of ‘func’ prevents the constraint ‘(Show t0)’ from being solved. Probable fix: use a type annotation to specify what ‘t0’ should be. These potential instances exist: instance Show Ordering -- Defined in ‘GHC.Show’ instance Show Integer -- Defined in ‘GHC.Show’ instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’ ...plus 22 others ...plus 12 instances involving out-of-scope types (use -fprint-potential-instances to see them all) • In the expression: func 1 In an equation for ‘it’: it = func 1 ``` The two questions i have is: question 1:Why is this error occuring? question 2:And how can i fix it? I am using "repl.it" haskell. I'll appreciate every helps :)!<issue_comment>username_1: The problem is that the function `floor` returns an `Integral` type, while the `/` function (the fractional divide-by operator) returns a `Fractional` type. So you need `a` to be of a type that is both `Integral` and `Fractional`, which I believe does not exist (other Haskellers: feel free to correct me on this). One way to fix this is to let the `Integral` returned by `floor` free to become any type of number: ``` func a = if a > 0 then func $ fromIntegral (floor (a/2)) else print (a) ``` Either way, it is a good practice to specify the type of your functions. The signature below would make your error clearer if you had tried it before using `fromIntegral`: ``` func :: Double -> IO () ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: @username_1's answer is correct in getting the code to work, but the error message itself is actually because of a different cause: [defaulting rules](https://www.haskell.org/onlinereport/haskell2010/haskellch4.html#x10-790004.3.4). Let's look at what your original function's type would be if inferred by GHC: ``` func a = if a > 0 then func (a/2) else print (a) ``` You use `/2` (which requires `Fractional`) and `print` (which requires `Show`), which means that GHC would infer that `func` has the type: ``` func :: (Fractional a, Show a) => a -> IO () ``` This is a perfectly fine type. But, when you want to actually *call* `func`, you have to pick a *specific type* to call it with. You can't call `(Fractional a, Show a) => a -> IO ()`; you have to call `Double -> IO ()`, or `Float -> IO ()`, etc. So, how does GHC know which one you "want" to call, when you do `func 5`? This is where **defaulting** kicks in. By default, Haskell tries out all of the possible candidate types: 1. Integer 2. Double this list is hard-coded into GHC (and the Haskell language spec). It tries them out, in order, and it defaults the type variable to the first one that would compile. In this case, it'd try out `Integer`, see that it doesn't work, and then try out `Double`, and then see that it does work, and calls `func :: Double -> IO ()`. Now, your second function: ``` func a = if a > 0 then func (floor (a/2)) else print (a) ``` Now, because you call `floor (a/2)`, `a` now is inferred to have a `RealFrac` instance. And because you call `func` with the result, `a` is now inferred to have an `Integral` instance. So, the inferred type signature is: ``` func :: (RealFrac a, Integral a, Show a) => a -> IO () ``` This, too, is a perfectly fine type. This is why *defining* the function was fine, and no errors happened. But, what happens when you call `func 5`? GHC again tries out all of the defaulting candidates in order. Integer fails, Double fails, so...defaulting can't resolve the ambiguity, so you get a compile-time error. Note that the error is **not** because there is no type that is an instance of all three typeclasses. This can never cause an error in Haskell, because typeclasses are global. This would create weird situations where instances being declared in modules for types that aren't being used will cause code to compile or not compile. So, a value that fails if there are *no* instances of a given typeclass is not allowed or sound in Haskell. So, **even if** there was an instance of all Integral, RealFrac, and Show that existed, you would *still get an error*. Imagine there was a type `Foo` that had all three necessary instances. *Even in this case*, there would still be an error, because `Foo` is not in the list of defaulting types that GHC tries out. The problem is that GHC needs help to figure out what type you want, since its list of defaults is exhausted. So, you can do something like: ``` func (5 :: Foo) ``` which will work, provided `Foo` has an instance of `RealFrac`, `Integral`, *and* `Show`. The problem isn't that no instance exists --- the problem is that GHC doesn't know which one to pick. In general, this is what "Ambiguous type ..." errors mean: **not** that no instances exist, but that GHC needs your help to pick which type you want to instantiate a function as, since GHC can't infer from type inference. The actual fix to get your code to work comes from the fact that you probably wanted things to work with `Double` in the first place. If you give `func` a type signature, then the error will turn into `No instance for Integral Double`, which is the "actual" fundamental issue with your code. Upvotes: 2
2018/03/22
1,038
3,608
<issue_start>username_0: How can I have an object property from an array of objects (`inputArray`) added to another array (`output`). ``` var inputArray = [ { subject: 'Maths', integervalue: '40', booleanvalue: null }, { subject: 'Science', integervalue: '50', booleanvalue: null }, { subject: 'Chemi', integervalue: '35', booleanvalue: null }, { subject: 'Stats', integervalue: null, booleanvalue: true }, { subject: 'Other', integervalue: null, booleanvalue: false }, { subject: 'History', integervalue: null, booleanvalue: true }, ]; ``` `output` should be added to when the `subject` property matches from each object. If match is on `'Chemi'`, `output.suba` should be equal to the `integerValue` property of `inputArray` where the `subject` is `'Chemi'`. Ergo, will be set to the value of ``` inputArray[2].integervalue. ``` If `integerValue` is null, then it should be set to the `booleanValue` property from `inputArray`. So `output` would look like this: ``` var output = { suba: inputArray[n].integervalue, subb: inputArray[n].integervalue; subc: inputArray[n].integervalue; subd: inputArray[n].booleanvalue; sube: inputArray[n].booleanvalue; sudf: inputArray[n].booleanvalue; } ``` Thanks in advance.<issue_comment>username_1: Solution which uses number index not letter index, if you need letter index i could improve this. ``` const output = inputArray.reduce( ( _output, e, _index ) => { const query = `WHERE subject is = ${e.subject} set ${e.integervalue || e.booleanvalue}` _output[ `sub${_index}` ] = query; return _output; }, {} ) ``` [![enter image description here](https://i.stack.imgur.com/xBgTl.png)](https://i.stack.imgur.com/xBgTl.png) Upvotes: 0 <issue_comment>username_2: username_1's solution can be modified to have letters index like this: ``` const output = inputArray.reduce( ( _output, e, _index ) => { const query = `WHERE subject is = ${e.subject} set ${e.integervalue || e.booleanvalue}` const charIndex = String.fromCharCode(97 + _index); _output[ `sub${charIndex }` ] = query; return _output; }, {} ) ``` Upvotes: 0 <issue_comment>username_3: You can use `array#map` to generate an array of objects of your new string. Then using `Object.assign()` you can create a new object with all the key-value. ```js var inputArray = [ { subject: 'Maths', integervalue: '40', booleanvalue: null }, { subject: 'Science', integervalue: '50', booleanvalue: null }, { subject: 'Chemi', integervalue: '35', booleanvalue: null }, { subject: 'Stats', integervalue: null, booleanvalue: true }, { subject: 'Other', integervalue: null, booleanvalue: false }, { subject: 'History', integervalue: null, booleanvalue: true }], output = Object.assign(...inputArray.map(({subject,integervalue, booleanvalue}) => ({[subject]:integervalue || booleanvalue}))); console.log(output); ``` Upvotes: 2 [selected_answer]<issue_comment>username_4: ```js var inputArray = [ { subject: 'Maths', integervalue: '40', booleanvalue: null }, { subject: 'Science', integervalue: '50', booleanvalue: null }, { subject: 'Chemi', integervalue: '35', booleanvalue: null }, { subject: 'Stats', integervalue: null, booleanvalue: true }, { subject: 'Other', integervalue: null, booleanvalue: false }, { subject: 'History', integervalue: null, booleanvalue: true }, ]; var myOutput = inputArray.reduce( function(output, currentValue) { output[currentValue.subject] = currentValue.integervalue || currentValue.booleanvalue; return output }, {}); console.log(myOutput); ``` Upvotes: 1
2018/03/22
585
2,025
<issue_start>username_0: im trying to make a "sleep" function for real time updating my UI display with updating variables. using xcode 9.2 swift 4 ``` //sleep function for UI display func sleep(time: Double, closure: @escaping (Timer) -> (Void) ) { var timer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(closure), userInfo: nil, repeats: false) timer.invalidate() } ``` i get this error: > > Use of unresolved identifier 'self' > > > thanks a million!<issue_comment>username_1: A selector statically identifies a function. You can't make a selector out of an argument. Perhaps something like this would be better: ``` func sleep(time: Double, closure: @escaping (Timer) -> (Void) ) { _ = Timer.scheduledTimer(withTimeInterval: time, repeats: false) { timer in closure(timer) } } ``` Upvotes: 1 <issue_comment>username_2: Regarding your error this function is might be outside of a class that is why `self` is `unresolved identifier`. Function should be inside the class body. Next point is you are making selector in wrong way. Selector will be a method defined in same class. Another point is you are `invalidating` the timer in next line so it will never execute. **If your app supports `iOS Version >= 10.0`.** ``` func sleep(time: Double, closure: @escaping (Timer) -> (Void) ) { Timer.scheduledTimer(withTimeInterval: time, repeats: false) { (timer) in closure(timer) } } ``` **If your app supports `iOS Version < 10.0`** In your class make few properties: ``` typealias TimerCallBack = (_ timer: Timer) -> Void var timer: Timer! var callBack: TimerCallBack! ``` Then ``` func sleep(time: Double, closure: @escaping TimerCallBack) { self.callBack = closure self.timer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(timerFired(_:)), userInfo: nil, repeats: false) } @objc func timerFired(_ timer: Timer) { if callBack != nil { callBack(self.timer) } } ``` Upvotes: 0
2018/03/22
626
2,402
<issue_start>username_0: I use fetch() to post json data as below ``` var data = { name: this.state.name, password: <PASSWORD> } fetch('http://localhost:3001/register/paitent', { method: 'POST', body: JSON.stringify(data), mode: 'no-cors', headers: new Headers({ 'Content-Type': 'application/json' }) }) .then(res => res.json()) ``` I always get {} in request.body in my express server router, and I figure out the problem is in sending request, it's always 'text/plain'. Why this happens? [![enter image description here](https://i.stack.imgur.com/HY9CA.png)](https://i.stack.imgur.com/HY9CA.png)<issue_comment>username_1: You set the mode to `no-cors`. Setting the Content-Type to `application/json` requires permission from CORS… > > The only allowed values for the Content-Type header [without triggering a preflight CORS request] are: > > > * application/x-www-form-urlencoded > * multipart/form-data > * text/plain > > > — [mdn](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) …which you told `fetch` not to ask for. Since you don't ask for permission, you don't get permission, so fetch reverts to `text/plain`. Upvotes: 2 <issue_comment>username_2: I was stuck on same issue for hours now figure out exact solution for this as mentioned in documentation of expressjs @username_1 has pointed towards exact issue. Here I am posting some more details so it may help someone else to resolve this issue quickly. When you are posting JSON object with `'Content-Type':'application/json'` fetch or any other method browser will request for CORS setting first for security reason then if it receives CORS options which is very easy to achieve. Then it will post original object to server as NodeJS server is waiting for `'Content-Type':'application/json'` You can check documentation of CORS setting on expressjs.com. You just need to install CORS package and add this line in your file: ``` app.options("/data",cors()); ``` This will setup preflight CORS response for your browser for specific `/data` path. Your method will look like this: ``` app.post('/data',cors(),function(req,res){} ``` Now you can post data with `'Content-Type':'application/json'`. I recommend you to read CORS article on MDN for better understanding. Upvotes: 0
2018/03/22
338
979
<issue_start>username_0: Sorry, this is tricky for me to find through search ``` ? ? Question ? X Y ? Answer 1 Answer 2 Answer 3 ``` Where X and Y are numbers from 0 to 100; How to stack X on top of Y like a fraction, in good way? EDIT: It's example, markup can be added/changed.<issue_comment>username_1: Try this: ``` X⁄Y ``` Output: X⁄Y Reference: <http://changelog.ca/log/2008/07/01/writing_fractions_in_html> Upvotes: 3 <issue_comment>username_2: You can place one number vertically over the other but you need to use CSS in tandem. Declare in HTML: ``` 1 X/Y. ``` Then CSS: ``` span.frac { display: inline-block; font-size: 50%; text-align: center; } span.frac > sup { display: block; border-bottom: 1px solid; font: inherit; } span.frac > span { display: none; } span.frac > sub { display: block; font: inherit; } ``` The span allows the text rendered in html for the client without CSS. Hope this can help you. Upvotes: 0
2018/03/22
547
1,775
<issue_start>username_0: I have next models: ``` class User(models.Model): id = models.IntegerField(primary_key=True) class UserMarketSubscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) market = models.ForeignKey('Market', on_delete=models.CASCADE) date_in = models.DateField(default=year_back) date_out = models.DateField(default=year_back) class Market(models.Model): name = models.CharField(max_length=50) ``` Shortly to say, I have User that can be subscripted on several markets. At the end I want to get QuerySet that contains all users and their information about subscription(1 user per row). So i want to get nearely next field\_names('id', 'market1\_date\_in', 'market1\_date\_out', 'market2\_date\_in' ..., 'marketN\_date\_out) I have tried annotations, but it does not work since, it requires exact field name on annotation, and i can't do it in cylce over each Market. 'values\_list' method returns many objects of one user with different subscription details, I want all details in one object. How can i do this?<issue_comment>username_1: Try this: ``` X⁄Y ``` Output: X⁄Y Reference: <http://changelog.ca/log/2008/07/01/writing_fractions_in_html> Upvotes: 3 <issue_comment>username_2: You can place one number vertically over the other but you need to use CSS in tandem. Declare in HTML: ``` 1 X/Y. ``` Then CSS: ``` span.frac { display: inline-block; font-size: 50%; text-align: center; } span.frac > sup { display: block; border-bottom: 1px solid; font: inherit; } span.frac > span { display: none; } span.frac > sub { display: block; font: inherit; } ``` The span allows the text rendered in html for the client without CSS. Hope this can help you. Upvotes: 0
2018/03/22
2,127
7,470
<issue_start>username_0: Below is a snippet of the decision tree as it is pretty huge. [![enter image description here](https://i.stack.imgur.com/lks6d.png)](https://i.stack.imgur.com/lks6d.png) How to make the tree stop growing when the lowest **value** in a node is under 5. Here is the code to produce the decision tree. On [SciKit - Decission Tree](http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html) we can see the only way to do so is by **min\_impurity\_decrease** but I am not sure how it specifically works. ``` import numpy as np import pandas as pd from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier X, y = make_classification(n_samples=1000, n_features=6, n_informative=3, n_classes=2, random_state=0, shuffle=False) # Creating a dataFrame df = pd.DataFrame({'Feature 1':X[:,0], 'Feature 2':X[:,1], 'Feature 3':X[:,2], 'Feature 4':X[:,3], 'Feature 5':X[:,4], 'Feature 6':X[:,5], 'Class':y}) y_train = df['Class'] X_train = df.drop('Class',axis = 1) dt = DecisionTreeClassifier( random_state=42) dt.fit(X_train, y_train) from IPython.display import display, Image import pydotplus from sklearn import tree from sklearn.tree import _tree from sklearn import tree import collections import drawtree import os os.environ["PATH"] += os.pathsep + 'C:\\Anaconda3\\Library\\bin\\graphviz' dot_data = tree.export_graphviz(dt, out_file = 'thisIsTheImagetree.dot', feature_names=X_train.columns, filled = True , rounded = True , special_characters = True) graph = pydotplus.graph_from_dot_file('thisIsTheImagetree.dot') thisIsTheImage = Image(graph.create_png()) display(thisIsTheImage) #print(dt.tree_.feature) from subprocess import check_call check_call(['dot','-Tpng','thisIsTheImagetree.dot','-o','thisIsTheImagetree.png']) ``` Update ====== I think `min_impurity_decrease` can in a way help reach the goal. As tweaking `min_impurity_decrease` does actually prune the tree. Can anyone kindly explain min\_impurity\_decrease. I am trying to understand the equation in scikit learn but I am not sure what is the value of right\_impurity and left\_impurity. ``` N = 256 N_t = 256 impurity = ?? N_t_R = 242 N_t_L = 14 right_impurity = ?? left_impurity = ?? New_Value = N_t / N * (impurity - ((N_t_R / N_t) * right_impurity) - ((N_t_L / N_t) * left_impurity)) New_Value ``` Update 2 -------- Instead of pruning at a certain value, we prune under a certain condition. such as We do split at 6/4 and 5/5 but not at 6000/4 or 5000/5. Let's say if one value is under a certain percentage in comparison with its adjacent value in the node, rather than a certain value. ``` 11/9 / \ 6/4 5/5 / \ / \ 6/0 0/4 2/2 3/3 ```<issue_comment>username_1: **Edit :** This is not correct as @SBylemans and @Viktor point out in the comments. I'm not deleting the answer since someone else may also think this is the solution. Set `min_samples_leaf` to 5. `min_samples_leaf` : > > The minimum number of samples required to be at a leaf node: > > > **Update :** I think it cannot be done with `min_impurity_decrease`. Think of the following scenario : ``` 11/9 / \ 6/4 5/5 / \ / \ 6/0 0/4 2/2 3/3 ``` According to your rule, you do not want to split node `6/4` since 4 is less than 5 but you want to split `5/5` node. However, splitting `6/4` node has 0.48 information gain and splitting `5/5` has 0 information gain. Upvotes: 2 <issue_comment>username_2: Directly restricting the lowest value (number of occurences of a particular class) of a leaf cannot be done with min\_impurity\_decrease or any other built-in stopping criteria. I think the only way you can accomplish this without changing the source code of scikit-learn is to **post-prune** your tree. To accomplish this, you can just traverse the tree and remove all children of the nodes with minimum class count less that 5 (or any other condition you can think of). I will continue your example: ``` from sklearn.tree._tree import TREE_LEAF def prune_index(inner_tree, index, threshold): if inner_tree.value[index].min() < threshold: # turn node into a leaf by "unlinking" its children inner_tree.children_left[index] = TREE_LEAF inner_tree.children_right[index] = TREE_LEAF # if there are shildren, visit them as well if inner_tree.children_left[index] != TREE_LEAF: prune_index(inner_tree, inner_tree.children_left[index], threshold) prune_index(inner_tree, inner_tree.children_right[index], threshold) print(sum(dt.tree_.children_left < 0)) # start pruning from the root prune_index(dt.tree_, 0, 5) sum(dt.tree_.children_left < 0) ``` this code will print first `74`, and then `91`. It means that the code has created 17 new leaf nodes (by practically removing links to their ancestors). The tree, which has looked before like [![enter image description here](https://i.stack.imgur.com/8TsTi.jpg)](https://i.stack.imgur.com/8TsTi.jpg) now looks like [![enter image description here](https://i.stack.imgur.com/AbDhI.png)](https://i.stack.imgur.com/AbDhI.png) so you can see that is indeed has decreased a lot. Upvotes: 6 [selected_answer]<issue_comment>username_3: Interestingly, `min_impurity_decrease` doesn't look as if it would allow growth of any of the nodes you have shown in the snippet you provided (the sum of impurities after splitting equals the pre-split impurity, so there is no **impurity decrease**). However, while it won't give you exactly the result you want (terminate node if lowest value is under 5), it may give you something similar. If my testing is right, the official docs make it look more complicated than it actually is. Just take the lower value from the potential parent node, then subtract the sum of the lower values of the proposed new nodes - this is the **gross** impurity reduction. Then divide by the total number of samples in the **whole tree** - this gives you the **fractional impurity decrease** achieved if the node is split. If you have 1000 samples, and a node with a lower value of 5 (i.e. 5 "impurities"), 5/1000 represents the maximum impurity decrease you could achieve if this node was perfectly split. So setting a `min_impurity_decrease` of of 0.005 would approximate stopping the leaf with <5 impurities. It would actually stop most leaves with a bit more than 5 impurities (depending upon the impurities resulting from the proposed split), so it is only an approximation, but as best I can tell its the closest you can get without post-pruning. Upvotes: 1 <issue_comment>username_4: In Scikit learn library, you have parameter called `ccp_alpha` as parameter for `DescissionTreeClassifier`. Using this you can do post-compexity-pruning for DecessionTrees. Check this out <https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html> Upvotes: 1
2018/03/22
1,401
4,810
<issue_start>username_0: I am very new to coding in PHP/MySQL, for fun I've been downloading some World of Worldcraft data from their API to test what I've learnt about PHP. Sorry for the long post, I'm trying to give as much info as needed, whilst being concise :) The short version is "my code takes 25 minutes to run. Can I do anything (things) better to speed this up? LONG VERSION BELOW Blizzard have a lot of data held about their servers, in a JSON format & there's a JSON file per server (I've a list 123 servers in total). I've written a basic JSON file that holds the name & URL of the 123 servers (serv\_gb.json). The code should run as follows:- * Read serv\_gb.json to count the number of rows to use in a For loop. * Record a start time for my own check. * The For loop starts, and it reads & accesses the URL's in serv\_gb.json. * The URL holds a JSON file for that server, it's parsed and held in an array. The URL when opened in a web browser takes on average 20 seconds to load & holds approx 100k rows. * It then uses the foreach to read & send the data to my database. * The end time is recorded & a duration calculated. There is more data in the JSON file than I need. I've tried two ways to filter this. a) Just try to send all of the data in the JSON & if it fails to & would normally error, hide it with "error\_reporting(0);". (Lazy, yes, because this is a pet project just for me, I thought I'd try it!). b) Adding the following If loop around the SQL to only send the correct data to the database. ``` foreach($auctions as $val) if ($val['item'] == 82800) { { $sql = "INSERT INTO `petshop`.`ah` (datedatacollected, seller, petSpeciesId, server, buyout, region, realrealm) VALUES('".$cTime."','".$val['owner']."','".$val['petSpeciesId']."', '".$servername."', '".$val['buyout']."','gb','".$val['ownerRealm']."')"; $mysqli->query($sql); } } ``` Idea A is about 15% slower than Idea B. Idea B takes the 25 minutes to run through all 123 JSON's. I run this on a local machine (my own desktop pc) running Apache2.4, MySQL57 & PHP Version 5.6.32 Any advice is appreciated, I think the following are good questions that I need help learning more about. * Is there any ways to making the loops or reads faster (or am I at the mercy of Blizzard's servers)? * Is it the writing to the DB that's bottle necking the process? * Would splitting the URLs up & triggering multiple JSON reads at the same time speed this up? If you've got this far in the post. A huge THANK YOU for taking the time to read it, I hope it was clear and made sense! MY PHP CODE ``` $servjson = '../servers/serv_gb.json'; $servcontents = file_get_contents($servjson); $servdata = json_decode($servcontents,true); $jrc = count($servdata['servers']); echo "Json Row Count: ".$jrc.""; $sTime = (new \DateTime())->format('Y-m-d H:i:s'); for($i=0; $i<$jrc; $i++){ $json = $servdata['servers'][$i]['url']; $contents = file\_get\_contents($json); $data = json\_decode($contents,true); $servername = $data['realms'][0]['slug']; $auctions = $data['auctions']; foreach($auctions as $val) { $sql = "INSERT INTO `petshop`.`ah` (datedatacollected, seller, petSpeciesId, server, buyout, region, realrealm) VALUES('".$cTime."','".$val['owner']."','".$val['petSpeciesId']."', '".$servername."', '".$val['buyout']."','gb','".$val['ownerRealm']."')"; $mysqli->query($sql); } } $eTime = (new \DateTime())->format('Y-m-d H:i:s'); $dTime = abs(strtotime($eTime) - strtotime($sTime)); ```<issue_comment>username_1: There are at least two topics here: A) you are downloading feeds from remote servers to your local machine. This may take some time of course. Compressing content by the server should be used if possible. This limits the amount of data which needs to be transfered to the client. However this is not straightforward with built-in `PHP` functions. You need to take a look at `PHP cURL`: [curl\_setopt](http://php.net/manual/en/function.curl-setopt.php) with `CURLOPT_ENCODING`. If remote server can compress data, request it to do so. B) database performance. As far as `MySQL` you can choose `MyISAM` or `InnoDB` engine. Inserting thousands of records could work better with `InnoDB` and a transaction, which you commit as soon as all queries are successful. Tuning your `PHP` and `MySQL` is a serious topic and it cannot be fully covered here. Upvotes: 1 <issue_comment>username_2: Please `echo` a sample `INSERT` statement. There may be some issues with it. Around the `INSERT` loop, add `BEGIN` and `COMMIT`. This will put all the inserts into a single transaction, thereby making it faster. I prefer `microtime(true)` for measuring time. 25 minutes? How long does it take if you comment out the `INSERTs`? This is to see whether it is MySQL or not. Upvotes: 0
2018/03/22
217
824
<issue_start>username_0: I have a server listening for messages on a port running in a different thread. Now once it receives a message I need it to be displayed in a textbox. 1. Is there method like runOnUiThread() (which is in android) or equivalent in Vala, GTK? 2. Or else what are the alternatives?<issue_comment>username_1: In contrast to many other Operating Systems, apparently you could perform UI operations from a non UI thread. I could successfully change the text of an `Entry` from the server thread. Not sure if this is recommended though. Upvotes: -1 <issue_comment>username_2: Use [GLib.Idle.add](https://valadoc.org/glib-2.0/GLib.Idle.add.html) to schedule something in the event dispatch thread: ``` Idle.add(() => { textbox.Entry = "foo"; return Source.REMOVE; }); ``` Upvotes: 3 [selected_answer]
2018/03/22
289
976
<issue_start>username_0: My React app has the following render definition ``` ReactDOM.render( , document.getElementById('react') ) ``` All URLs look as such ``` http://localhost:8080/myApp#/dashboard http://localhost:8080/myApp#/about ``` I want to add a trailing slash before the `#` so the URLs look a *little* less ugly, like so ``` http://localhost:8080/myApp/#/dashboard http://localhost:8080/myApp/#/about ``` Any ideas on how to do so?<issue_comment>username_1: In contrast to many other Operating Systems, apparently you could perform UI operations from a non UI thread. I could successfully change the text of an `Entry` from the server thread. Not sure if this is recommended though. Upvotes: -1 <issue_comment>username_2: Use [GLib.Idle.add](https://valadoc.org/glib-2.0/GLib.Idle.add.html) to schedule something in the event dispatch thread: ``` Idle.add(() => { textbox.Entry = "foo"; return Source.REMOVE; }); ``` Upvotes: 3 [selected_answer]
2018/03/22
404
1,284
<issue_start>username_0: This is my input structure. All the fields here are optional because it can have zero or more elements in this json string. I am fine to use liftweb or regular scala. ``` { "fname" : String, "lname" : String, "age" : String, "gender" : String, "phone" : String, "mstatus" : String } ``` Input: (Note here "mstatus" is not available and "gender" is empty) ``` { "fname" : "Thomas", "lname" : "Peter", "age" : "20", "gender" : "", "phone" : "12345 } ``` I want to read this Json string and to check whether the key is present and its value is not null then add into a map. My output map would like below. ``` val inputMap = Map( "fname" -> "Thomas" "lname" -> "Peter" "age" -> "20", "phone" -> "12345) ```<issue_comment>username_1: In contrast to many other Operating Systems, apparently you could perform UI operations from a non UI thread. I could successfully change the text of an `Entry` from the server thread. Not sure if this is recommended though. Upvotes: -1 <issue_comment>username_2: Use [GLib.Idle.add](https://valadoc.org/glib-2.0/GLib.Idle.add.html) to schedule something in the event dispatch thread: ``` Idle.add(() => { textbox.Entry = "foo"; return Source.REMOVE; }); ``` Upvotes: 3 [selected_answer]
2018/03/22
912
2,820
<issue_start>username_0: I'm learning PHP and I found useful tutorials online, so I'm trying to build my very first site in PHP. I have a problem with CSS implementation. I keep my tab with localhost always on so I dont have to run it every single time when I change something. Problem is, when I code some CSS it loads on my registration form, but when i refresh the page, it's like I never coded CSS for that page. (sorry for bad english I hope You guys understand what I wanted to say..) Here's the signup.php code : ``` ### EPO - Sistem - Registracija Veb aplikacija za evidenciju predispitnih obaveza. ### Dobrodosli, <NAME>, unesite podatke za registraciju. E-mail: Firstname: Lastname: Password: ``` And here's the Index page: ``` EPO - Pocetna stranica [EPO Aplikacija](#) * [Pocetna stranica](#index) * [Ulogujte se](#login) * [Prijavite se](#signup) Index Login php include("./user/signup.php"); ? ``` And here's the css code: ``` body{ background-color: darkgray; font-size: 22px; margin: 0; padding: 0; } .crud{ width:auto; color: #605d5d !important; font-size: 25px; font-weight: 800; } .sub_msg{ text-align: center; padding: 10px 0px 20px 0px; } .signup{ border: 1px solid #c40707; text-align: center; width: 60%; height: auto; margin: auto; } .input_group{ margin: 0px 20px 20px 20px; } .input_group input{ height: 40px; font-size: 20px; } input[type="submit"]{ height: 40px; font-size: 20px; font-weight: bold; background-color: #c40707; color: #605d5d !important; } ``` I'm stuck her for over two hours, and I'm pretty sure it's some beginners silly mistake but I can't find it..<issue_comment>username_1: In the code below href attribute has unneeded space in it. ``` ``` Should be: ``` ``` Also sometimes you may need to clear cache for the changes in your css to appear. In this case, cause it can become tiresome pressing the refresh button, rather than do a refresh, I add a random value at the end of the css url to make it appear like a new url so no caching will happen. Like ``` ``` Upvotes: 0 <issue_comment>username_2: Check by adding version number like ``` ``` Upvotes: 0 <issue_comment>username_3: Correct the path of from to If still not work then [force your browser to refresh the stylesheet](https://stackoverflow.com/a/12718566). Upvotes: 1 <issue_comment>username_4: Try to change this line (assuming that your **css** folder in in the same level as you **index.php**) ``` ``` To this this ``` ``` Remove the `php echo time(); ?` once you go on production as it meant on for development so you don't need to clear the cache or the hard reload if the changes in your css are not reflected in the browser. Upvotes: 0
2018/03/22
586
2,195
<issue_start>username_0: I have been trying to move the marquee text from right to left in Android, using ellipsize. It does move, but the issue is it moves only if the text size is smaller than screen view. For that reason, I even added extra spaces both left and right of my text, to make the text size greater than screen size. Now after the text scrolls out of the screen, there is a small delay before it could come again from the right end of the screen. I want it to come up immediately, as soon as the text goes out of the screen. Following is the customized Ticker I have created for the marquee. ``` public class Ticker extends AppCompatTextView { public Ticker(Context context, AttributeSet attrs) { super(context, attrs); initialize(); } private void initialize() { setSelected(true); setMarqueeRepeatLimit(-1); setEllipsize(TextUtils.TruncateAt.MARQUEE); setFreezesText(true); setSingleLine(true); setHorizontallyScrolling(true); } } ``` and the text is "\t \t \t \t \t \t \t \t sometext \t \t \t \t \t \t \t \t"<issue_comment>username_1: In the code below href attribute has unneeded space in it. ``` ``` Should be: ``` ``` Also sometimes you may need to clear cache for the changes in your css to appear. In this case, cause it can become tiresome pressing the refresh button, rather than do a refresh, I add a random value at the end of the css url to make it appear like a new url so no caching will happen. Like ``` ``` Upvotes: 0 <issue_comment>username_2: Check by adding version number like ``` ``` Upvotes: 0 <issue_comment>username_3: Correct the path of from to If still not work then [force your browser to refresh the stylesheet](https://stackoverflow.com/a/12718566). Upvotes: 1 <issue_comment>username_4: Try to change this line (assuming that your **css** folder in in the same level as you **index.php**) ``` ``` To this this ``` ``` Remove the `php echo time(); ?` once you go on production as it meant on for development so you don't need to clear the cache or the hard reload if the changes in your css are not reflected in the browser. Upvotes: 0
2018/03/22
656
2,380
<issue_start>username_0: I have setup all these steps and bundle id on Firebase Dashboard and tried crash many times but not getting any report. 1. pod 'Fabric', '~> 1.7.6' 2. pod 'Crashlytics', '~> 3.10.1' 3. In Build phase added run Script : **"${PODS\_ROOT}/Fabric/run"** 4. Debug Inforation Format : DWARF with dSYM File 5. running in simulator with following steps * (IBAction)crashButtonTapped:(id)sender { [[Crashlytics sharedInstance] crash]; } * Click play\_arrow Build and then run the current scheme in Xcode to build your app on a device or simulator. * Click stop Stop running the scheme or action in Xcode to close the initial instance of your app. This initial instance includes a debugger that interferes with Crashlytics. * Open your app again from the simulator or device. Touch Crash to crash the app. **@Alexizamerican** my app's bundle id is "com.lawcrossing.apps". Also when i went into my pods/Fabric/ and click on "run" CLI. It clearly says > > Firebase mode detected. warning: unable to find > GoogleService-Info.plist in app bundle, dSYMs will not be uploaded > > > BUT actually plist is present. I had tried it deleting it and re-added the plist file. I also tried with the Firebase.configure (withoptions) by explicit defining the path and filename of plist.<issue_comment>username_1: In the code below href attribute has unneeded space in it. ``` ``` Should be: ``` ``` Also sometimes you may need to clear cache for the changes in your css to appear. In this case, cause it can become tiresome pressing the refresh button, rather than do a refresh, I add a random value at the end of the css url to make it appear like a new url so no caching will happen. Like ``` ``` Upvotes: 0 <issue_comment>username_2: Check by adding version number like ``` ``` Upvotes: 0 <issue_comment>username_3: Correct the path of from to If still not work then [force your browser to refresh the stylesheet](https://stackoverflow.com/a/12718566). Upvotes: 1 <issue_comment>username_4: Try to change this line (assuming that your **css** folder in in the same level as you **index.php**) ``` ``` To this this ``` ``` Remove the `php echo time(); ?` once you go on production as it meant on for development so you don't need to clear the cache or the hard reload if the changes in your css are not reflected in the browser. Upvotes: 0
2018/03/22
640
2,025
<issue_start>username_0: I'm facing some difficulties executing GET request with access token via python. For some reason when I execute the request from POSTMAN I get the expected result, however, when using python I get connection error : ``` A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond ``` I believe that my script is being blocked by the server to prevent scrapping attempts, but I'm not sure. This is what I'm running via **POSTMAN** : ``` https://www.operation.io/web/alerts?access_token=6ef06fee265de1fa640b6a444ba47--z&envId=<PASSWORD>&folderId=active&sortBy=status ``` And this is what I'm running from inside the **script** : ``` response = requests.get('https://www.operation.io/web/alerts', headers={'Authorization': 'access_token 6ef06fee265de1fa640b6a444ba47--z'}) ``` Please notice that the url and the access token are not real, so please don't try to use. How can I make it work via the script and not only via postman? Thank you for your help/<issue_comment>username_1: Since via postman you're sending the token as query param(as opposed to header), you can try this : ``` response = requests.get('https://www.operation.io/web/alerts', params={'access_token': '6ef06fee265de1fa640b6a444ba47--z'}) ``` Assuming the API you're using accepts it as query param rather than as headers (which is my guess from the postman request) Upvotes: 0 <issue_comment>username_2: It's hard to tell without actually being able to test the solutions, but I would suggest 2 hacks that worked for me in the past: 1. Change "Authorization" to "authorization" 2. Change "6ef06fee265de1fa<PASSWORD>" to "Token <PASSWORD>" (add a space as well) Put it all together: ``` response = requests.get('https://www.operation.io/web/alerts', headers={'authorization': 'Token <PASSWORD>'}) ``` Upvotes: 2 [selected_answer]
2018/03/22
438
1,314
<issue_start>username_0: I am using "**java-client-5.0.4**" version, I am unable to select image from gallery. Here is my code ``` List galleryElements = driver.findElementsByClassName("android.widget.ImageView"); TouchAction t = new TouchAction(driver); t.tap(galleryElements.get(0)).perform(); ``` [![enter image description here](https://i.stack.imgur.com/VtBeR.png)](https://i.stack.imgur.com/VtBeR.png)<issue_comment>username_1: Since via postman you're sending the token as query param(as opposed to header), you can try this : ``` response = requests.get('https://www.operation.io/web/alerts', params={'access_token': '<PASSWORD>'}) ``` Assuming the API you're using accepts it as query param rather than as headers (which is my guess from the postman request) Upvotes: 0 <issue_comment>username_2: It's hard to tell without actually being able to test the solutions, but I would suggest 2 hacks that worked for me in the past: 1. Change "Authorization" to "authorization" 2. Change "<PASSWORD>65de1fa640b6a444ba47--z" to "Token <PASSWORD>" (add a space as well) Put it all together: ``` response = requests.get('https://www.operation.io/web/alerts', headers={'authorization': 'Token <PASSWORD>--z'}) ``` Upvotes: 2 [selected_answer]
2018/03/22
4,658
13,345
<issue_start>username_0: I initially wanted to migrate a JAVA EE project into maven. However, I ran into a dispatching error. I got this stack trace in the file : C:\Program Files using(x86)\IBM\WebSphere\AppServer\profiles\AppSrv01\logs\My\_SERVER\SystemOut.log ``` > [22/03/18 07:46:32:755 VET] 00000020 XmlConfigurat I > com.opensymphony.xwork2.util.logging.commons.CommonsLogger info > Parsing configuration file [struts-default.xml] [22/03/18 07:46:32:766 > VET] 00000020 XmlConfigurat I > com.opensymphony.xwork2.util.logging.commons.CommonsLogger info > Parsing configuration file [struts-plugin.xml] [22/03/18 07:46:32:812 > VET] 00000020 XmlConfigurat I > com.opensymphony.xwork2.util.logging.commons.CommonsLogger info > Parsing configuration file [struts.xml] [22/03/18 07:46:32:814 VET] > 00000020 DefaultConfig I > com.opensymphony.xwork2.util.logging.commons.CommonsLogger info > Overriding property struts.i18n.reload - old value: false new value: > true [22/03/18 07:46:32:814 VET] 00000020 DefaultConfig I > com.opensymphony.xwork2.util.logging.commons.CommonsLogger info > Overriding property struts.configuration.xml.reload - old value: false > new value: true [22/03/18 07:46:32:858 VET] 00000020 Dispatcher E > com.opensymphony.xwork2.util.logging.commons.CommonsLogger error > Dispatcher initialization failed > java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at > com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:295) > at > com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector.construct(ContainerImpl.java:431) > at > com.opensymphony.xwork2.inject.ContainerBuilder$5.create(ContainerBuilder.java:207) > at com.opensymphony.xwork2.inject.Scope$2$1.create(Scope.java:51) at > com.opensymphony.xwork2.inject.ContainerBuilder$3.create(ContainerBuilder.java:93) > at > com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:487) > at > com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:484) > at > com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:574) > at > com.opensymphony.xwork2.inject.ContainerBuilder.create(ContainerBuilder.java:484) > at > com.opensymphony.xwork2.config.impl.DefaultConfiguration.createBootstrapContainer(DefaultConfiguration.java:252) > at > com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:193) > at > com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:66) > at > org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:371) at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:415) > at > org.apache.struts2.dispatcher.FilterDispatcher.init(FilterDispatcher.java:190) > at > com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.init(FilterInstanceWrapper.java:140) > at > com.ibm.ws.webcontainer.filter.WebAppFilterManager._loadFilter(WebAppFilterManager.java:509) > at > com.ibm.ws.webcontainer.filter.WebAppFilterManager.loadFilter(WebAppFilterManager.java:423) > at > com.ibm.ws.webcontainer.filter.WebAppFilterManager.getFilterInstanceWrapper(WebAppFilterManager.java:282) > at > com.ibm.ws.webcontainer.filter.WebAppFilterManager.getFilterChain(WebAppFilterManager.java:340) > at > com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:812) > at > com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:917) > at > com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor.invokeFilters(DefaultExtensionProcessor.java:924) > at > com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor.handleRequest(DefaultExtensionProcessor.java:852) > at > com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3610) > at > com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:274) > at > com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:926) > at > com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1557) > at > com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:173) > at > com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:455) > at > com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:384) > at > com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:83) > at > com.ibm.ws.ssl.channel.impl.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1772) > at > com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165) > at > com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217) > at > com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161) > at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138) at > com.ibm.io.async.ResultHandler.complete(ResultHandler.java:202) at > com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:766) > at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:896) at > com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1527) Caused by: > java.lang.reflect.InvocationTargetException at > sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at > sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:45) > at > sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37) > at java.lang.reflect.Method.invoke(Method.java:599) at > com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:293) > ... 40 more Caused by: java.lang.NoClassDefFoundError: > ognl.OgnlRuntime (initialization failure) at > java.lang.J9VMInternals.initialize(J9VMInternals.java:140) at > com.opensymphony.xwork2.ognl.OgnlValueStackFactory.setContainer(OgnlValueStackFactory.java:85) > ... 45 more > > [22/03/18 07:46:32:860 VET] 00000020 webapp E > com.ibm.ws.webcontainer.webapp.WebApp logError SRVE0293E: [Erreur du > servlet]-[ognl.OgnlRuntime (initialization failure)] : > java.lang.reflect.InvocationTargetException - Class: > com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector File: > ContainerImpl.java Method: inject Line: 295 - > com/opensymphony/xwork2/inject/ContainerImpl.java:295:-1 at > org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:428) at > org.apache.struts2.dispatcher.FilterDispatcher.init(FilterDispatcher.java:190) > at > com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.init(FilterInstanceWrapper.java:140) > at > com.ibm.ws.webcontainer.filter.WebAppFilterManager._loadFilter(WebAppFilterManager.java:509) > at > com.ibm.ws.webcontainer.filter.WebAppFilterManager.loadFilter(WebAppFilterManager.java:423) > at > com.ibm.ws.webcontainer.filter.WebAppFilterManager.getFilterInstanceWrapper(WebAppFilterManager.java:282) > at > com.ibm.ws.webcontainer.filter.WebAppFilterManager.getFilterChain(WebAppFilterManager.java:340) > at > com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:812) > at > com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:917) > at > com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor.invokeFilters(DefaultExtensionProcessor.java:924) > at > com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor.handleRequest(DefaultExtensionProcessor.java:852) > at > com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3610) > at > com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:274) > at > com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:926) > at > com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1557) > at > com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:173) > at > com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:455) > at > com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:384) > at > com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:83) > at > com.ibm.ws.ssl.channel.impl.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1772) > at > com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165) > at > com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217) > at > com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161) > at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138) at > com.ibm.io.async.ResultHandler.complete(ResultHandler.java:202) at > com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:766) > at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:896) at > com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1527) Caused by: > java.lang.RuntimeException: > java.lang.reflect.InvocationTargetException at > com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:295) > at > com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector.construct(ContainerImpl.java:431) > at > com.opensymphony.xwork2.inject.ContainerBuilder$5.create(ContainerBuilder.java:207) > at com.opensymphony.xwork2.inject.Scope$2$1.create(Scope.java:51) at > com.opensymphony.xwork2.inject.ContainerBuilder$3.create(ContainerBuilder.java:93) > at > com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:487) > at > com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:484) > at > com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:574) > at > com.opensymphony.xwork2.inject.ContainerBuilder.create(ContainerBuilder.java:484) > at > com.opensymphony.xwork2.config.impl.DefaultConfiguration.createBootstrapContainer(DefaultConfiguration.java:252) > at > com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:193) > at > com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:66) > at > org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:371) at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:415) > ... 27 more Caused by: java.lang.reflect.InvocationTargetException > at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at > sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:45) > at > sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37) > at java.lang.reflect.Method.invoke(Method.java:599) at > com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:293) > ... 40 more Caused by: java.lang.NoClassDefFoundError: > ognl.OgnlRuntime (initialization failure) at > java.lang.J9VMInternals.initialize(J9VMInternals.java:140) at > com.opensymphony.xwork2.ognl.OgnlValueStackFactory.setContainer(OgnlValueStackFactory.java:85) > ... 45 more > > [22/03/18 07:46:32:873 VET] 00000020 srt W > com.ibm.ws.webcontainer.srt.SRTServletResponse addHeader WARNING: > Cannot set header. Response already committed. [22/03/18 07:46:32:874 > VET] 00000020 srt W > com.ibm.ws.webcontainer.srt.SRTServletResponse setHeader WARNING: > Cannot set header. Response already committed. [22/03/18 07:46:32:875 > VET] 00000020 srt W > com.ibm.ws.webcontainer.srt.SRTServletResponse setHeader WARNING: > Cannot set header. Response already committed. [22/03/18 07:46:32:875 > VET] 00000020 srt W > com.ibm.ws.webcontainer.srt.SRTServletResponse setDateHeader WARNING: > Cannot set header. Response already committed. ``` I added this dependency to my POM.xml (I thought that it's missing) ``` org.apache.struts.xwork xwork-core 2.2.1 ``` But I still have the error. Can anyone tell me what I'm missing? Is it perhaps because I'm using Eclipse NEON1? I have JDK1.7.0\_71 and Websphere 7.0.0. ``` JAVA_HOME=C:\Program Files (x86)\Java\jdk1.7.0_71 MAVEN_HOME=D:\Maven\apache-maven-3.3.9 ```<issue_comment>username_1: ``` Caused by: java.lang.NoClassDefFoundError: ognl.OgnlRuntime (initialization failure) at ``` You have missing OGNL dependencies on class path at run time. The `xwork-core` is transitive dependency for `struts2-core` artifact. OGNL is also transitive dependency. Regarding the second error: ``` Response has been already commuted. ``` Struts is trying to return error result by using servlet response internally or forward to the error page by it can't do it if response has been commuted. The response becomes commuted as soon as the buffer is flushed. You should check the size of buffer on the response object and how much bytes has written to it. Upvotes: 2 <issue_comment>username_2: javassist dependency was messing. I added this dependeny on the POM file : ``` javassist javassist 3.12.1.GA ``` and it works for me. Upvotes: 1 [selected_answer]
2018/03/22
513
1,908
<issue_start>username_0: I am building an Android MVVM application using RxJava2. What I want is to expose an `Observable` in my ViewModel, which I also can receive the last emitted value (like a `BehaviourSubject`). I don't want to expose a `BehaviourSubject` because I don't want the View to be able to call `onNext()`. For example, in my `ViewModel` I expose a date. I now want to subscribe a `TextView` to changes, but I also need to be able to access the current value if I want to show a `DatePickerDialog` with this date as initial value. What would be the best way to achieve this?<issue_comment>username_1: > > I don't want to expose a [`BehaviourSubject`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/subjects/BehaviorSubject.html) > > > [`Subject`](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/subjects/Subject.html), by definition, is *"an `Observer` and an `Observable` at the same time"*. Therefore, instead of exposing `BehaviorSubject` itself just expose `Observable`, thus client (in this case the view) won't be able to perform `onNext()`, but will be able to receive last emitted value. As an alternative to subject approach you can use `replay(1).autoConnect()` approach. See more details concerning this approach in ["RxJava by example" presentation](https://www.youtube.com/watch?v=wxx9hEi_E8c) by <NAME>. Also, consider `cache()` operator (see difference of `cache` and `replay().autoConnect()` [here](https://github.com/ReactiveX/RxJava/issues/5704)). Upvotes: 2 <issue_comment>username_2: Delegate: ``` class TimeSource { final BehaviorSubject lastTime = BehaviorSubject.createDefault( System.currentTimeMillis()); public Observable timeAsObservable() { return lastTime; } public Long getLastTime() { return lastTime.getValue(); } /\*\* internal only \*/ void updateTime(Long newTime) { lastTime.onNext(newTime); } } ``` Upvotes: 2
2018/03/22
1,298
3,727
<issue_start>username_0: Let's say we want to add a value to "favorites" in a Vue store: * If it's already there REMOVE * Otherwise ADD I know that the code below is probably neither a correct nor an optimal way of doing it, so I'm wondering what would be a proper way to do it? component: ---------- --- `item` is an object, e.g: ``` { "value": false, "name": "Program Files", "path": "C:\\Program Files", "stat": { "dev": 1990771843, "mode": 16676, "nlink": 1, "uid": 0, "gid": 0, "rdev": 0, "ino": 10133099161787836, "size": 0, "atimeMs": 1520444327295.1216, "mtimeMs": 1520444327295.1216, "ctimeMs": 1520444327295.1216, "birthtimeMs": 1506692793335.212, "atime": "2018-03-07T17:38:47.295Z", "mtime": "2018-03-07T17:38:47.295Z", "ctime": "2018-03-07T17:38:47.295Z", "birthtime": "2017-09-29T13:46:33.335Z" } } ``` --- ```html fa-bookmark far fa-bookmark ... computed: { inFavorites(item) { let favorited = this.$store.state.AppData.favorites.includes(item) return favorited ? 'true' : 'false' } }, methods: { addToFavorites(item) { let favorited = this.$store.state.AppData.favorites.includes(item) if (!favorited) { this.$store.commit('addToFavorites', item) } else { this.$store.commit('removeFromFavorites', item) } } ``` store: ------ ``` const state = { favorites: [] } const mutations = { addToFavorites (state, favorites) { state.favorites = favorites }, removeFromFavorites (state, favorites) { state.favorites.find(favorites).splice(favorites) } } ... ```<issue_comment>username_1: You will need to find the `item`'s position in the `state.favorites` array, and then remove it by position. The tricky part is finding the position, but you already seem to have this logic in the `includes` method in: ``` this.$store.state.AppData.favorites.includes(item) ``` So, considering it works, your `removeFromFavorites` mutation would be: ``` removeFromFavorites (state, item) { var itemIndex = state.favorites.indexOf(item); state.favorites.splice(itemIndex, 1); } ``` Using a unique property (e.g. `path`) to identify if favorited ============================================================== Instead of: ``` let favorited = this.$store.state.AppData.favorites.includes(item) ``` Do: ``` let favorited = !!this.$store.state.AppData.favorites.find((i) => i.path === item.path); ``` And, instead of: ``` removeFromFavorites (state, item) { var itemIndex = state.favorites.indexOf(item); state.favorites.splice(itemIndex, 1); } ``` Do: ``` removeFromFavorites (state, item) { var itemIndex = state.favorites.findIndex((i) => i.path === item.path); state.favorites.splice(itemIndex, 1); } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I managed to make it work with the following code, though I'm not sure if it's the best way, there are surely better ways to do it: UPDATED ------- ``` fa-bookmark far fa-bookmark ... methods: { addToFavorites(item) { let favorited = this.$store.state.AppData.favorites.find((i) => i.path === item.path) favorited ? this.$store.commit('removeFromFavorites', selectedItem) : this.$store.commit('addToFavorites', selectedItem) }, inFavorites(item) { let favorited = this.$store.state.AppData.favorites.find((i) => i.path === item.path) return favorited ? true : false } } ``` store: ------ ``` const state = { favorites: [] } const mutations = { addToFavorites (state, item) { state.favorites.push(item) }, removeFromFavorites (state, item) { var itemIndex = state.favorites.findIndex((i) => i.path === item.path) state.favorites.splice(itemIndex, 1) } } ... ``` Upvotes: 0
2018/03/22
1,153
4,559
<issue_start>username_0: PROBLEM: Use one single viewModel with two different views. I have a `Window` with a control `ContentControl` which is binded to a property in the `DataContext`, called `Object MainContent {get;set;}`. Base on a navigationType `enum` property, I assign other ViewModels to it to show the correct `UserControl`. I need to merge two views into one ViewModel, and because I'm assigning a ViewModel to the `ContentControl` mentioned before, the `TemplateSelector` is not able to identify which is the correct view as both shares the same viewModel If I assign the view instead the ViewModel to the `ContentControl`, the correct view is shown, however, non of the commands works. Any Help? Thanks in advance. SOLUTION: based on @mm8 answer and <https://stackoverflow.com/a/5310213/2315752>: ManagePatientViewModel.cs ``` public class ManagePatientViewModel : ViewModelBase { public ManagePatientViewModel (MainWindowViewModel inMainVM) : base(inMainVM) {} } ``` ViewHelper.cs ``` public enum ViewState { SEARCH, CREATE, } ``` MainWindowViewModel.cs ``` public ViewState State {get;set;} public ManagePatientViewModel VM {get;set;} private void ChangeView(ViewState inState) { State = inState; // This is need to force the update of Content. var copy = VM; MainContent = null; MainContent = copy; } public void NavigateTo (NavigationType inNavigation) { switch (inNavigationType) { case NavigationType.CREATE_PATIENT: ChangeView(ViewState.CREATE); break; case NavigationType.SEARCH_PATIENT: ChangeView(ViewState.SEARCH); break; default: throw new ArgumentOutOfRangeException(nameof(inNavigationType), inNavigationType, null); } } ``` MainWindow.xaml ``` ``` TemplateSelector.cs ``` public class TemplateSelector : DataTemplateSelector { public DataTemplate SearchViewTemplate {get;set;} public DataTemplate CreateViewTemplate {get;set;} } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (!(item is SelectLesionViewModel vm)) { return null; } switch (vm.ViewType) { case ViewState.CREATE: return CreateViewTemplate; case ViewState.SEARCH: return SearchViewTemplate; default: return null; } } } ```<issue_comment>username_1: How is the `TemplateSelector` supposed to know which template to use when there are two view types mapped to a single view model type? This makes no sense I am afraid. You should use two different types. You could implement the logic in a common base class and then define two marker types that simply derive from this implementation and add no functionality: ``` public class ManagePatientViewModel { */put all your code in this one*/ } //marker types: public class SearchPatientViewModel { } public class CreatePatientViewModel { } ``` Also, you don't really need a template selector if you remove the `x:Key` attributes from the templates: ``` ... ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Maybe the requirement is to switch out the views and retain the one viewmodel. Datatemplating is just one way to instantiate a view. You could instead set the datacontext of the contentcontrol to the instance of your viewmodel and switch out views as the content. Since views are rather a view responsibility such tasks could be done completely in the view without "breaking" mvvm. Here's a very quick and dirty approach illustrating what I mean. I build two usercontrols, UC1 and UC2. These correspond to your various patient views. Here's the markup for one: ``` ``` I create a trivial viewmodel. ``` public class OneViewModel { public string HelloString { get; set; } = "Hello from OneViewModel"; } ``` My mainwindow markup: ``` ``` The click events switch out the content: private void UC1\_Click(object sender, RoutedEventArgs e) { parent.Content = new UC1(); } ``` private void UC2_Click(object sender, RoutedEventArgs e) { parent.Content = new UC2(); } ``` The single instance of oneviewmodel is retained and the view shown switches out. The hellostring binds and shows ok in both. In your app you will want a more sophisticated approach to setting that datacontext but this sample is intended purely as a proof of concept to show you another approach. Here's the working sample: <https://1drv.ms/u/s!AmPvL3r385QhgpgMZ4KgfMWUnxkRzA> Upvotes: 2
2018/03/22
691
2,548
<issue_start>username_0: I have this image: [![image](https://i.stack.imgur.com/rxDQT.png)](https://i.stack.imgur.com/rxDQT.png) What I'm trying to do is, the cells have different colors. main action=1 green and action=0 red color. I have this html code: ``` | {{item.alarmdesc}} {{getProductName(item.device\_serial)}} {{item.datetime\_device | date:'d/MM/yyyy'}}main action: {{item.acted}} | | ```<issue_comment>username_1: How is the `TemplateSelector` supposed to know which template to use when there are two view types mapped to a single view model type? This makes no sense I am afraid. You should use two different types. You could implement the logic in a common base class and then define two marker types that simply derive from this implementation and add no functionality: ``` public class ManagePatientViewModel { */put all your code in this one*/ } //marker types: public class SearchPatientViewModel { } public class CreatePatientViewModel { } ``` Also, you don't really need a template selector if you remove the `x:Key` attributes from the templates: ``` ... ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Maybe the requirement is to switch out the views and retain the one viewmodel. Datatemplating is just one way to instantiate a view. You could instead set the datacontext of the contentcontrol to the instance of your viewmodel and switch out views as the content. Since views are rather a view responsibility such tasks could be done completely in the view without "breaking" mvvm. Here's a very quick and dirty approach illustrating what I mean. I build two usercontrols, UC1 and UC2. These correspond to your various patient views. Here's the markup for one: ``` ``` I create a trivial viewmodel. ``` public class OneViewModel { public string HelloString { get; set; } = "Hello from OneViewModel"; } ``` My mainwindow markup: ``` ``` The click events switch out the content: private void UC1\_Click(object sender, RoutedEventArgs e) { parent.Content = new UC1(); } ``` private void UC2_Click(object sender, RoutedEventArgs e) { parent.Content = new UC2(); } ``` The single instance of oneviewmodel is retained and the view shown switches out. The hellostring binds and shows ok in both. In your app you will want a more sophisticated approach to setting that datacontext but this sample is intended purely as a proof of concept to show you another approach. Here's the working sample: <https://1drv.ms/u/s!AmPvL3r385QhgpgMZ4KgfMWUnxkRzA> Upvotes: 2
2018/03/22
1,438
5,611
<issue_start>username_0: I know everything is passed by value in Go, meaning if I give a slice to a function and that function appends to the slice using the builtin `append` function, then the original slice will not have the values that were appended in the scope of the function. For instance: ``` nums := []int{1, 2, 3} func addToNumbs(nums []int) []int { nums = append(nums, 4) fmt.Println(nums) // []int{1, 2, 3, 4} } fmt.Println(nums) // []int{1, 2, 3} ``` This causes a problem for me, because I am trying to do recursion on an accumulated slice, basically a `reduce` type function except the reducer calls itself. Here is an example: ``` func Validate(obj Validatable) ([]ValidationMessage, error) { messages := make([]ValidationMessage, 0) if err := validate(obj, messages); err != nil { return messages, err } return messages, nil } func validate(obj Validatable, accumulator []ValidationMessage) error { // If something is true, recurse if something { if err := validate(obj, accumulator); err != nil { return err } } // Append to the accumulator passed in accumulator = append(accumulator, message) return nil } ``` The code above gives me the same error as the first example, in that the `accumulator` does not get all the appended values because they only exist within the scope of the function. To solve this, I pass in a pointer struct into the function, and that struct contains the accumulator. That solution works nicely. My question is, is there a better way to do this, and is my approach idiomatic to Go? **Updated solution** (thanks to icza): I just return the slice in the recursed function. Such a facepalm, should have thought of that. ``` func Validate(obj Validatable) ([]ValidationMessage, error) { messages := make([]ValidationMessage, 0) return validate(obj, messages) } func validate(obj Validatable, messages []ValidationMessage) ([]ValidationMessage, error) { err := v.Struct(obj) if _, ok := err.(*validator.InvalidValidationError); ok { return []ValidationMessage{}, errors.New(err.Error()) } if _, ok := err.(validator.ValidationErrors); ok { messageMap := obj.Validate() for _, err := range err.(validator.ValidationErrors) { f := err.StructField() t := err.Tag() if v, ok := err.Value().(Validatable); ok { return validate(v, messages) } else if _, ok := messageMap[f]; ok { if _, ok := messageMap[f][t]; ok { messages = append(messages, ValidationMessage(messageMap[f][t])) } } } } return messages, nil } ```<issue_comment>username_1: Slice grows dynamically as required if the current size of the slice is not sufficient to append new value thereby changing the underlying array. If this new slice is not returned, your append change will not be visible. Example: ``` package main import ( "fmt" ) func noReturn(a []int, data ...int) { a = append(a, data...) } func returnS(a []int, data ...int) []int { return append(a, data...) } func main() { a := make([]int, 1) noReturn(a, 1, 2, 3) fmt.Println(a) // append changes will not visible since slice size grew on demand changing underlying array a = returnS(a, 1, 2, 3) fmt.Println(a) // append changes will be visible here since your are returning the new updated slice } ``` Result: ``` [0] [0 1 2 3] ``` Note: 1. You don't have to return the slice if you are updating items in the slice without adding new items to slice Upvotes: 4 <issue_comment>username_2: When appending data into slice, if the underlying array of the slice doesn't have enough space, a new array will be allocated. Then the elements in old array will be copied into this new memory, accompanied with adding new data behind Upvotes: 2 <issue_comment>username_3: If you want to pass a slice as a parameter to a function, and have that function modify the original slice, then you have to pass a pointer to the slice: ``` func myAppend(list *[]string, value string) { *list = append(*list, value) } ``` I have no idea if the Go compiler is naive or smart about this; performance is left as an exercise for the comment section. For junior coders out there, please note that this code is provided without error checking. For example, this code will panic if `list` is `nil`. Upvotes: 6 <issue_comment>username_4: Slice you passed is an reference to an array, which means the size is fixed. If you just modified the stored values, that's ok, the value will be updated outside the called function. But if you added new element to the slice, it will reslice to accommodate new element, in other words, a new slice will be created and old slice will not be overwritten. As a summary, if you need to extend or cut the slice, pass the pointer to the slice.Otherwise, use slice itself is good enough. ### Update --- I need to explain some important facts. For adding new elements to a slice which was passed as a value to a function, there are 2 cases: #### A the underlying array reached its capacity, a new slice created to replace the origin one, obviously the origin slice will not be modified. #### B the underlying array has not reached its capacity, and was modified. **BUT** the field `len` of the slice was **not** overwritten because the slice was passed by value. As a result, the origin slice will not aware its len was modified, which result in the slice not modified. Upvotes: 4
2018/03/22
209
657
<issue_start>username_0: ``` ``` This my code. How I can remove padding to error text? [img with error](https://i.stack.imgur.com/cc2PO.jpg) [img with error](https://i.stack.imgur.com/b6Hmi.jpg)<issue_comment>username_1: You have to remove this line ``` android:layout_marginStart="-5dp" ``` or if you need that margin, please give in parentView -`android.support.design.widget.TextInputLayout` like ``` ``` Upvotes: -1 <issue_comment>username_2: `TextInputLayout` is a `LinearLayout`, so you should be able to specify a negative margin or padding, e.g. ``` android:layout_marginLeft="-2dp" android:layout_marginStart="-2dp" ``` Upvotes: -1
2018/03/22
298
988
<issue_start>username_0: Does Create-React-App (or Webpack used by Create-React-App) at any stage (development, staging or production) optimise your node\_modules? That is, if I had an import like this: `import _ from 'lodash'` and only use the `map` function in my project. Would my build bundle for production have all of lodash or would it strip out all other functions and keep the ones that are being referenced in my code?<issue_comment>username_1: CRA use `UglifyJsPlugin` in the [webpack.config.prod.js](https://github.com/facebook/create-react-app/blob/c6375edc079a71bd9addd50c58441cbca8839945/packages/react-scripts/config/webpack.config.prod.js#L293) which supports dead code removal. But you should only import what you need for this to work: <https://webpack.js.org/guides/tree-shaking/> Upvotes: 2 [selected_answer]<issue_comment>username_2: For anyone who stumbled here in 2021, create-react-app also do tree-shaking when you use `import * as _ from 'lodash` Upvotes: 0
2018/03/22
262
836
<issue_start>username_0: Is there any way to know when to use Promises vs Async/Await? I am asking that because it's not so clear for me to know which one performs better, or also is better readable, is there any advantages using each one of them or it doesn't matter? Thanks!<issue_comment>username_1: CRA use `UglifyJsPlugin` in the [webpack.config.prod.js](https://github.com/facebook/create-react-app/blob/c6375edc079a71bd9addd50c58441cbca8839945/packages/react-scripts/config/webpack.config.prod.js#L293) which supports dead code removal. But you should only import what you need for this to work: <https://webpack.js.org/guides/tree-shaking/> Upvotes: 2 [selected_answer]<issue_comment>username_2: For anyone who stumbled here in 2021, create-react-app also do tree-shaking when you use `import * as _ from 'lodash` Upvotes: 0
2018/03/22
247
799
<issue_start>username_0: I know how to use hasAnyAuthority directive in jhipster for HTML part. But i am searching how can i do this in typescript part like if user has role farmer navigate to farmer profile, for admin navigate to dashboard.<issue_comment>username_1: CRA use `UglifyJsPlugin` in the [webpack.config.prod.js](https://github.com/facebook/create-react-app/blob/c6375edc079a71bd9addd50c58441cbca8839945/packages/react-scripts/config/webpack.config.prod.js#L293) which supports dead code removal. But you should only import what you need for this to work: <https://webpack.js.org/guides/tree-shaking/> Upvotes: 2 [selected_answer]<issue_comment>username_2: For anyone who stumbled here in 2021, create-react-app also do tree-shaking when you use `import * as _ from 'lodash` Upvotes: 0
2018/03/22
1,074
4,159
<issue_start>username_0: I want to dynamically add http-headers via [CloudFlare workers](https://blog.cloudflare.com/introducing-cloudflare-workers/) ONLY for the first time visitors. For example these headers: ``` Link: ; rel=preload; as=style; nopush Link: ; rel=preload; as=script; nopush ``` So, what I need is the following, via JavaScript, in CloudFlare Workers: 1. Check if a specific cookie exists on the client's side. 2. If the cookie doesn't exist add http-headers and then set that specific cookie. 3. If the cookie does exist do nothing. You can play with the code [here](https://cloudflareworkers.com/#272d3b58117355d84353d5dd57f6e129:https://tutorial.cloudflareworkers.com). Here's a general example (involving cookie and headers) from the CF's blog: ``` // A Service Worker which skips cache if the request contains // a cookie. addEventListener('fetch', event => { let request = event.request if (request.headers.has('Cookie')) { // Cookie present. Add Cache-Control: no-cache. let newHeaders = new Headers(request.headers) newHeaders.set('Cache-Control', 'no-cache') event.respondWith(fetch(request, {headers: newHeaders})) } // Use default behavior. return }) ```<issue_comment>username_1: Here's a Cloudflare Worker that implements what you describe: ``` addEventListener('fetch', event => { event.respondWith(handle(event.request)) }) async function handle(request) { // Check for cookie. let cookies = request.headers.get('Cookie') || "" if (cookies.includes("returning=true")) { // User has been here before. Just pass request through. return fetch(request) } // Forward request to origin, get response. let response = await fetch(request) // Copy Response object so that we can edit headers. response = new Response(response.body, response) // Add headers. response.headers.append("Link", "; rel=preload; as=style; nopush") response.headers.append("Link", "; rel=preload; as=script; nopush") // Set cookie so that we don't add the headers // next time. response.headers.set("Set-Cookie", "returning=true") // Return on to client. return response } ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: I've managed to modify the worker and provide a solution where `Cache-Control` header is removed if the user has commented on the website. ``` addEventListener('fetch', event => { event.respondWith(addHeaders(event.request)) }) async function addHeaders(request) { // Forward request to origin, get response. let response = await fetch(request) if (response.headers.has("Content-Type") && !response.headers.get("Content-Type").includes("text/html")) { // File is not text/html. Pass request through. return fetch(request) } // Copy Response object so that we can edit headers. response = new Response(response.body, response) // Check for cookie. let cookies = request.headers.get('Cookie') || "" if (cookies.includes("returning=true")) { if (cookies.includes("comment_") && response.headers.has("Cache-Control")) { // User has commented. Delete "cache-control" header. response.headers.delete("Cache-Control") // Return on to client. return response } // User has been here before but has not commented. // Just pass request through. return fetch(request) } // Add headers. response.headers.set("Link", "; rel=preload; as=style; nopush") response.headers.append("Link", "; rel=preload; as=script; nopush") // Set cookie so that we don't add the headers next time. response.headers.set("Set-Cookie", "returning=true") // Return on to client. return response } ``` However, if you're trying to delete a header which is set by Cloudflare in the first place (in this case `Cache-Control`) you'll encounter an unknown error 1101 which will make your site inaccessible. Also you can't modify a header set by Cloudflare. Apparently you can ONLY manipulate headers set by origin and eventually add new headers. Upvotes: 2
2018/03/22
955
3,838
<issue_start>username_0: I am uploading an image directly to AWS bucket which works perfectly fine from my location (India). The same code fails to upload an image when the user location is Singapore. Following is the method I'm using to upload the image. ``` func uploadMediaOnS3(contentType: String = "application/octet-stream", mediaData: Data, folderName: String, fileName: String, progressBlock:@escaping (_ uploadProgress: Float, _ uploadStatus: Bool) -> Void) { //Configure Credentials let credentialProvider = AWSStaticCredentialsProvider(accessKey: "my-access-key", secretKey: "my-secret-key") let configuration = AWSServiceConfiguration(region: .APSouth1, credentialsProvider: credentialProvider) AWSServiceManager.default().defaultServiceConfiguration = configuration AWSServiceManager.default().defaultServiceConfiguration.timeoutIntervalForRequest = 90.0 AWSServiceManager.default().defaultServiceConfiguration.timeoutIntervalForResource = 90.0 //Setup Progress Block let expression = AWSS3TransferUtilityUploadExpression() expression.progressBlock = {(task, progress) in DispatchQueue.main.async { print(" ==> \(Float(progress.fractionCompleted * 100))") progressBlock(Float(progress.fractionCompleted * 100), false) } } //Setup Completion Block let uploadCompletionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock = { (task, error) -> Void in DispatchQueue.main.async { if error != nil { progressBlock(-1.0, false) } else { progressBlock(100.0, true) } } } //Upload Data let transferUtility = AWSS3TransferUtility.default() transferUtility.uploadData(mediaData, bucket: "my-bucket-name", key: "\(folderName)\(fileName)", contentType: contentType, expression: expression, completionHandler: uploadCompletionHandler).continueWith { (task) -> Any? in if task.error != nil { progressBlock(-1.0, false) } return nil } } ``` Following are my AWS SDK details : AWSCore (version : 2.6.13) AWSS3 (version : 2.6.13) My guess would be that there is some issue with the region. I found out that my bucket location falls under .APSouth1 (Mumbai, India) and works fine here but when being used from Singapore, it fails due to the fact that it is falling under .APSoutheast1 One more thing to note, may be important, is that the upload fails instantly, as soon as it starts. There is no issue of timeout or anything. It is also possible that I might be missing some settings here. Thanks in advance!<issue_comment>username_1: ``` func sendMultiPartAWS(path: String, imgData: Data, onComplete: @escaping (JSON, NSError?, URLResponse?) -> Void, onError: @escaping (NSError?, URLResponse?) -> Void) { Alamofire.upload(imgData, to: path, method: .put).responseJSON { response in if response.response?.statusCode == 200 { let swiftyJSON = JSON.init(response.data!) onComplete(swiftyJSON, nil, response.response) } else { } } } ``` I have used above code to upload image in AWS, may this help you. Upvotes: 1 <issue_comment>username_2: Bucket name is global, but location is not. The following is quoted from [Bucket Documentation](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html): > > Objects belonging to a bucket that you create in a specific AWS Region never leave that region, unless you explicitly transfer them to another region. For example, objects stored in the EU (Ireland) region never leave it. > > > You can use [cross-region replication](https://docs.aws.amazon.com/AmazonS3/latest/dev/crr.html) facility to have the same content across the regions Upvotes: 0
2018/03/22
436
1,701
<issue_start>username_0: I am creating a new Angular project without downloading the dependencies, like: `ng new sample-app --skip-install` I have all necessary dependencies in node\_modules in a different folder of a different angular app named older-app. I want the newly created sample-app to refer to the node\_modules of older-app. How can I achieve this?<issue_comment>username_1: Well, the easiest way is to create a symbolic link in `sample-app` that points to the other `node_modules`. If you're in windows, ``` cd sample-app mklink /J node_modules "../older-app/node_modules" ``` Not sure about syntax in linux or MacOS, but it will be similar. I don't really recommend this, though, because though updating or adding packages in one directory will affect both (as both `node_modules` are really the same), only the `package.json` file of the directory you are in will be modified. This implies that, if you share the app with another person or put it in another machine, running `npm install` won't guarantee that you get the same packages, which can cause errors, so do this on your own risk. For example, if you go to `older-app` and update Angular to version 6, `sample-app` will be modified, too. So you can change the code, developing against Angular 6. However, if you then upload that app to Github or other repository, whoever downloads it, when they run `npm install` will get Angular 5, which is sure to cause errors. `package.json` files must always be in sync with the `node_modules` directory. Upvotes: 2 <issue_comment>username_2: The only real option seems to be, moving the cli file. as to see here: <https://github.com/angular/angular-cli/issues/3864> Upvotes: 0
2018/03/22
579
2,131
<issue_start>username_0: In the index.html within the "src" folder, I wrote {{ title }} like as follows: ``` {{ title }} ``` In product.components.ts, I defined the title as "Products" as follows, but it wont works. ``` export class ProductComponent implements OnInit { products: Product[] = []; dataInvalid = false; formErrors = []; formSubmitting = false; title = 'Products'; ``` How can I change the title if users clicks on different pages?<issue_comment>username_1: You have to inject Title from platform-browser in your component ``` import {Title} from "@angular/platform-browser"; constructor(private title: Title) { this.title.setTitle('Your title'); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: just add into the routing. so you no need inject title service in every component. for Ex ``` path: ':path', component: ExampleComponent, data: {title:'title'} ``` Upvotes: 1 <issue_comment>username_3: Now you can set the title tag and meta tag with anglar. Just use the services provide into `@angular/platform-browser` Here we go ... ``` import { Title, Meta } from '@angular/platform-browser'; @Component({ selector: 'app-root', template: `My component ` }) export class YourComponent { public constructor(private titleService: Title, private meta: Meta ) { this.setTitle('My title'); this.setDynamicTitle(); this.setMetaTags() } public setTitle( newTitle: string) { // each component this.titleService.setTitle( newTitle ); } public setDynamicTitle() { // via service this.yourService.get('api/url').subscribe((data) => { this.titleService.setTitle( data.title ); }) } public setMetaTags() { this.meta.addTags([{ name: 'description', content: 'Your description' }, { name: 'author', content: 'You' } ]) } } ``` Here another reference: [How to change title of a page using angular(angular 2 or 4) route?](https://stackoverflow.com/questions/44000162/how-to-change-title-of-a-page-using-angularangular-2-or-4-route) Upvotes: 0
2018/03/22
1,093
2,502
<issue_start>username_0: I have a list of data frames: ``` data1 <- data.frame( ID = c(1, 1, 1, 1), Name1 = c(3, 2, 3, 2), Name2 = c(4, 5, 4, 5), Name3 = c(6, 7, 6, 7), Name4 = c(8, 9, 8, 9)) data2 <- data.frame( ID = c(2, 2, 2), Name4 = c(7, 3, 3), Name2 = c(3, 1, 1), Name3 = c(2, 2, 2), Name1 = c(1, 1, 1)) data3 <- data.frame( ID = c(3, 3, 3, 3, 3, 3), Name3 = c(6, 6, 6, 6, 6, 6), Name1 = c(2, 2, 2, 2, 2, 2), Name4 = c(3, 3, 3, 3, 3, 3), Name2 = c(2, 2, 2, 2, 2, 2)) data4 <- data.frame( ID = c(4, 4, 4, 4), Name2 = c(5, 7, 7, 5), Name3 = c(1, 1, 1, 1), Name1 = c(9, 1, 9, 1), Name4 = c(3, 3, 3, 3)) list_data <- list(data1, data2, data3, data4) ``` I also have a list with an equal number of entries, each entry contains a vector of row positions in list\_data: ``` rows1 <- c(1, 4) rows2 <- c(1) rows3 <- c(1, 3, 6) rows4 <- c(2, 3) list_rows <- list(rows1, rows2, rows3, rows4) ``` How can I subset each dataframe in `list_data` using the corresponding vector of row positions in `list_rows`?<issue_comment>username_1: Here a possible solution using lapply: ``` f<-function(df,list_rows) { return(df[unlist(list_rows[df[1,1]]),]) } lapply(list_data,f,list_rows=list_rows) [[1]] ID Name1 Name2 Name3 Name4 1 1 3 4 6 8 4 1 2 5 7 9 [[2]] ID Name4 Name2 Name3 Name1 1 2 7 3 2 1 [[3]] ID Name3 Name1 Name4 Name2 1 3 6 2 3 2 3 3 6 2 3 2 6 3 6 2 3 2 [[4]] ID Name2 Name3 Name1 Name4 2 4 7 1 1 3 3 4 7 1 9 3 ``` Upvotes: 1 <issue_comment>username_2: With corresponding indices, a `base R` direction option is `Map` ``` Map(function(x, y) x[y, ], list_data, list_rows) #[[1]] # ID Name1 Name2 Name3 Name4 #1 1 3 4 6 8 #4 1 2 5 7 9 #[[2]] # ID Name4 Name2 Name3 Name1 #1 2 7 3 2 1 #[[3]] # ID Name3 Name1 Name4 Name2 #1 3 6 2 3 2 #3 3 6 2 3 2 #6 3 6 2 3 2 #[[4]] # ID Name2 Name3 Name1 Name4 #2 4 7 1 1 3 #3 4 7 1 9 3 ``` --- Similar extraction can be done with `map2` from `purrr` ``` library(tidyverse) map2(list_data, list_rows, ~ .x[.y,]) ``` Or ``` map2(list_data, list_rows, `[`, ) ``` Upvotes: 3 [selected_answer]
2018/03/22
933
2,727
<issue_start>username_0: On running the below query: `SELECT DISTINCT [RULE], LEN([RULE]) FROM MYTBL WHERE [RULE] LIKE 'Trademarks, logos, slogans, company names, copyrighted material or brands of any third party%'` I am getting the output as: [![enter image description here](https://i.stack.imgur.com/wKoC5.jpg)](https://i.stack.imgur.com/wKoC5.jpg) The column datatype is **NCHAR(120)** and the collation used is **SQL\_Latin1\_General\_CP1\_CI\_AS** The data is inserted with an extra leading space in the end. But using **RTRIM** function also I am not able to trim the extra space. I am not sure which type of leading space(encoded) is inserted here. Can you please suggest some other alternative except RTRIM to get rid of extra white space at the end as the Column is **NCHAR**. Below are the things which I have already tried: 1. RTRIM(LTRIM(CAST([RULE] as VARCHAR(200)))) 2. RTRIM([RULE]) **Update to Question** Please download the Database from here [TestDB](https://drive.google.com/file/d/16TPkrEjeYIbosyuCeMn7iqOkmhaLRnc7/view?usp=sharing) Please use below query for your reference: ``` SELECT DISTINCT [RULE], LEN([RULE]) FROM [TestDB].[BI].[DimRejectionReasonData] WHERE [RULE] LIKE 'Trademarks, logos, slogans, company names, copyrighted material or brands of any third party%' ```<issue_comment>username_1: Here a possible solution using lapply: ``` f<-function(df,list_rows) { return(df[unlist(list_rows[df[1,1]]),]) } lapply(list_data,f,list_rows=list_rows) [[1]] ID Name1 Name2 Name3 Name4 1 1 3 4 6 8 4 1 2 5 7 9 [[2]] ID Name4 Name2 Name3 Name1 1 2 7 3 2 1 [[3]] ID Name3 Name1 Name4 Name2 1 3 6 2 3 2 3 3 6 2 3 2 6 3 6 2 3 2 [[4]] ID Name2 Name3 Name1 Name4 2 4 7 1 1 3 3 4 7 1 9 3 ``` Upvotes: 1 <issue_comment>username_2: With corresponding indices, a `base R` direction option is `Map` ``` Map(function(x, y) x[y, ], list_data, list_rows) #[[1]] # ID Name1 Name2 Name3 Name4 #1 1 3 4 6 8 #4 1 2 5 7 9 #[[2]] # ID Name4 Name2 Name3 Name1 #1 2 7 3 2 1 #[[3]] # ID Name3 Name1 Name4 Name2 #1 3 6 2 3 2 #3 3 6 2 3 2 #6 3 6 2 3 2 #[[4]] # ID Name2 Name3 Name1 Name4 #2 4 7 1 1 3 #3 4 7 1 9 3 ``` --- Similar extraction can be done with `map2` from `purrr` ``` library(tidyverse) map2(list_data, list_rows, ~ .x[.y,]) ``` Or ``` map2(list_data, list_rows, `[`, ) ``` Upvotes: 3 [selected_answer]
2018/03/22
702
1,992
<issue_start>username_0: I am working on a Ionic project that uses the Ionic Native google maps and I want to add to the map some markers and make them invisible. The marker declaration looks something like this: ``` this.map.addMarker({ position: {lat: svLat + Math.abs(neLat - svLat) / 2, lng: svLong + Math.abs(neLong - svLong) / 2}, visible: false, infoWindowAnchor: [-150, 50] }); ``` My problem is that when I build the project for ios, the markers remain visible. The android build is working as expected. Any clues on how to solve this?<issue_comment>username_1: Here a possible solution using lapply: ``` f<-function(df,list_rows) { return(df[unlist(list_rows[df[1,1]]),]) } lapply(list_data,f,list_rows=list_rows) [[1]] ID Name1 Name2 Name3 Name4 1 1 3 4 6 8 4 1 2 5 7 9 [[2]] ID Name4 Name2 Name3 Name1 1 2 7 3 2 1 [[3]] ID Name3 Name1 Name4 Name2 1 3 6 2 3 2 3 3 6 2 3 2 6 3 6 2 3 2 [[4]] ID Name2 Name3 Name1 Name4 2 4 7 1 1 3 3 4 7 1 9 3 ``` Upvotes: 1 <issue_comment>username_2: With corresponding indices, a `base R` direction option is `Map` ``` Map(function(x, y) x[y, ], list_data, list_rows) #[[1]] # ID Name1 Name2 Name3 Name4 #1 1 3 4 6 8 #4 1 2 5 7 9 #[[2]] # ID Name4 Name2 Name3 Name1 #1 2 7 3 2 1 #[[3]] # ID Name3 Name1 Name4 Name2 #1 3 6 2 3 2 #3 3 6 2 3 2 #6 3 6 2 3 2 #[[4]] # ID Name2 Name3 Name1 Name4 #2 4 7 1 1 3 #3 4 7 1 9 3 ``` --- Similar extraction can be done with `map2` from `purrr` ``` library(tidyverse) map2(list_data, list_rows, ~ .x[.y,]) ``` Or ``` map2(list_data, list_rows, `[`, ) ``` Upvotes: 3 [selected_answer]
2018/03/22
1,063
3,780
<issue_start>username_0: I have a select component. I have a input component. When the select component is changed I need to .select() the input component. These are two unrelated components i.e. siblings to the main Vue instance. Both of these components are composed from templates so using the ref attribute is not an option as per the documentation <https://v2.vuejs.org/v2/guide/components.html#Child-Component-Refs> How would I go about doing this? I've composed a simple example in codepen - <https://codepen.io/anon/pen/MVmLVZ> **HTML** ``` <select @change="doStuff"> <option value='1'>Value 1</option> <option value='2'>Value 2</option> </select> <input ref='text-some-input' type='text' value='Some Value'/> ``` **Vue Code** ``` Vue.component('some-input', { template: `#vueTemplate-some-input` }); Vue.component('some-select', { methods: { doStuff: function() { // Do some stuff //TODO: Now focus on input text field //this.$refs['text-some-input'].focus(); // Cant use refs, refs is empty } }, template: `#vueTemplate-some-select` }); var app = new Vue({ el: '#my-app' }); ```<issue_comment>username_1: You need to emit a custom event from you select-component to the parent : [VueJS Custom Events](https://v2.vuejs.org/v2/guide/components.html#Custom-Events) Parent component : ``` ``` Select Component : ``` ``` Upvotes: 1 <issue_comment>username_2: There are several ways you could do this, and the right one depends on what the reasons are for implementing this behavior. It sounds like the value selected is significant to the app, rather than just being relevant to the select component, so it should come from the parent. The parent can also pass that value to the input, which can `watch` it for changes and set focus. That solution might look like this snippet: ```js Vue.component("some-input", { template: `#vueTemplate-some-input`, props: ['watchValue'], watch: { watchValue() { this.$refs['text-some-input'].focus(); } } }); Vue.component("some-select", { props: ['value'], methods: { doStuff: function(event) { this.$emit('input', event.target.value); } }, template: `#vueTemplate-some-select` }); var app = new Vue({ el: "#my-app", data: { selectedValue: null } }); ``` ```html Selected: {{selectedValue}} <select :value="value" @change="doStuff"> <option value='1'>Value 1</option> <option value='2'>Value 2</option> </select> <input ref='text-some-input' type='text' value='Some Value' /> ``` If, on the other hand, you really want to know that the `select` changed, and not just that the value changed, you could pass an event bus to the input so that the parent could relay the change to its child. That might look like this snippet: ```js Vue.component("some-input", { template: `#vueTemplate-some-input`, props: ['changeBus'], mounted() { this.changeBus.$on('change', () => this.$refs['text-some-input'].focus()); } }); Vue.component("some-select", { methods: { doStuff: function(event) { this.$emit('change', event.target.value); } }, template: `#vueTemplate-some-select` }); var app = new Vue({ el: "#my-app", data: { changeBus: new Vue() } }); ``` ```html <select @change="doStuff"> <option value='1'>Value 1</option> <option value='2'>Value 2</option> </select> <input ref='text-some-input' type='text' value='Some Value' /> ``` This keeps things encapsulated: the parent knows only that one child changes and that the other child handles change events. Neither component knows about the other. Upvotes: 3 [selected_answer]
2018/03/22
972
3,650
<issue_start>username_0: From the MSDN docs on `list.Clear()` > > Count is set to 0, and references to other objects from elements of the collection are also released. > > > From what I've been taught (which could be wrong), disposed & released are different things. Disposed means the items is completely removed from memory, released means it's simply not bound to that list by pointer. Does that mean that I need to do ``` foreach (var item in Items) { item.Dispose(); } this.Items.Clear(); ``` If I effectively want to completely destroy/clear/release/dipose a list from existence? To me it should all be as simple as `.Clear()`, but, it's a bit unclear to me (pun intended) if that is enough and correct. Note that we are not overriding `Dispose()` nor `Clear()`, it's all default implementation. Also, the list is a `List`. Edit : As per comment recommendation, I've went and checked, the items are all `IDisposables`, which sheds some light on the fact that they should be disposed Duplicate clarification on [What is IDisposable for?](https://stackoverflow.com/questions/615105/what-is-idisposable-for) : I do not think these two questions are the same, mine is asking a difference between two things, the other is asking for clarification on one of those things. It also did not appear in my search before I decided to write the question, because I was too focused on keywords like "difference dispose vs clear", which will probably also be the case for future developers looking for an answer. I'll concede that the other answer provides some more information and is a good link to add here.<issue_comment>username_1: > > From what I've been taught (which could be wrong), disposed & released are different things. > > > True. > > Disposed means the items is completely removed from memory, released means it's simply not bound to that list by pointer. > > > Wrong. Disposed means that any clean-up required by an object that has nothing to do with managed memory is done. If the elements are `IDisposable` then it is indeed a good idea to `Dispose()` them all before clearing, if they are generally reached through that list and hence nothing else will `Dispose()` them. If they aren't `IDisposable` this not only isn't needed, but it's not possible. If they are `IDisposable` but something else will still be using the elements, then you shouldn't `Dispose()` them as that will break that other use. Upvotes: 2 [selected_answer]<issue_comment>username_2: No, [`List.Clear`](https://msdn.microsoft.com/en-us/library/dwb5h52a(v=vs.110).aspx) does not [dispose](https://stackoverflow.com/a/538238/284240) objects. If you want you can write an extension: ``` public static class IEnumerableExtensions { public static void DisposeAll(this IEnumerable seq) where T : IDisposable { foreach (T d in seq) d?.Dispose(); } } ``` --- ``` var connections = new List(); // ... connections.DisposeAll(); ``` Upvotes: 2 <issue_comment>username_3: As far as I know, `Dispose()` is very helpful in some areas like if you're handling resource and you want to clear those resource in the memory or if there's any exception happens, surely you need to dispose that. Just a tip: You can basically don't need to include `Dispose()` method when you're using statement code this like ``` using(var someResource = new SomeResource()){ // Some galaxy logic here } ``` Since it has Dispose mechanism. If those resources are not manage of [CLR](https://www.c-sharpcorner.com/UploadFile/9582c9/what-is-common-language-runtime-in-C-Sharp/) so just use `using` statement will be an easy option. --- Upvotes: 0
2018/03/22
2,320
6,185
<issue_start>username_0: I want to try to make some more types of regex, so I have been trying to make the following work. Here is my expression: <https://regex101.com/r/VzspFy/4/> On the test strings, the very first 3 are good, so patterns like that must be matched, the problem is the last one, which I don't want to be included, so I tried to do this: <https://regex101.com/r/9HVKTK/2> and this: <https://regex101.com/r/9HVKTK/1> But no luck! The main idea is: ``` `aaa ... bbb ccc` -> must match `ccc ... (aaa|ddd|eee) ... bbb ccc` -> should not match ``` How can I make it work or maybe some better implementation?<issue_comment>username_1: Here's a relatively simple regex for your problem: ``` (?:(?<=[-]\s)(?:ITA\s)?\w{3}\s\w{3}\s[-]\s\w{3}\s\w{3}\s\w{3}\b)|(?:Eng\.sub\.ita) ``` which you can [test out here](https://regex101.com/r/VzspFy/18). REGEX: ------ `(?<=[-]\s)` is a positive look-behind, that makes sure that the match is preceded by a dash and a space (but doesn't match them) `(?:ITA\s)?` is a non-capturing group which tells the regex that if the match is preceded by an "ITA" and space, then match them also. `\w{3}` matches a string of three word characters (letters/numbers/underscore or a combination of them) `\s` means a single space, and `[-]` is just a fancy way of matching a single `-`. `|(?:Eng\.sub\.ita)` tells the regex to match `eng.sub.ita` (case-insensitive) along with the original matches if present in a sentence together. Do Note: -------- If the name of the show contains something along the lines of `- red SEO - two one` or 'dash-space-three\_letters-space-three\_letters-space-dash-space-three\_letters-space-three\_letters', then even the name of the show will be matched. However, the likelihood of a show containing such a format is negligible, so you needn't worry about that. Upvotes: 0 <issue_comment>username_2: You may use ``` var rx = new Regex(@"(?:^|])(?:(?!\b(?:eng|ita)\b)[^]])*\b(eng(?:\W+\w+)?\W+sub\W+ita)\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); ``` See the [regex demo](https://regex101.com/r/VzspFy/17). You need to get Group 1 values. **Pattern details** * `(?:^|])` - either start of string or `]` (add `| RegexOptions.Multiline` if you have a multiline string as input, but I suppose these are all standalone strings) * `(?:(?!\b(?:eng|ita)\b)[^]])*` - any char but `]`, as many as possible, that does not start a whole word `eng` or `ita` (see [tempered greedy token](https://stackoverflow.com/a/37343088/3832970) to understand this construct better) * `\b` - a word boundary * `(eng(?:\W+\w+)?\W+sub\W+ita)` - Group 1: + `eng` - a literal substring + `(?:\W+\w+)?` - an optional sequence of any 1+ non-word chars followed with 1+ word chars (actually, an optional word) + `\W+` - 1+ non-word chars + `sub` - a literal substring + `\W+` - 1+ non-word chars + `ita` - a literal substring * `\b` - a word boundary See the [C# demo](https://ideone.com/ZqBmeZ): ``` var strs = new List { "Lucifer S03e15 [XviD - Eng Mp3 - Sub Ita Eng] DLRip By Pir8 [CURA] Fede e Religioni", "Lucifer S03e15 [XviD - Eng Mp3 - Sub Ita Eng] DLRip By Pir8 [CURA] Fede e Religioni", "Lucifer S03e01-08 [XviD - Eng Mp3 - Sub Ita Eng] DLRip By Pir8 [CURA] Fede e Religioni SEASON PREMIERE", "Young Sheldon S01e13 [SATRip 720p - H264 - Eng Ac3 - Sub Ita] HDTV by AVS", "Young Sheldon S01e08 [Mux 1080p - H264 - Ita Eng Ac3 - Sub Ita Eng] WEBMux Morpheus", "Young Sheldon S01e08 [Mux 1080p - H264 - Ita Eng Ac3 - Sub Ita Eng] WEBMux Morpheus", "Young Sheldon S01e14 [SATRip 720p - H264 - Eng Ac3 - Sub Ita] HDTV by AVS", "Lucifer S03e15 [XviD - Eng Mp3 - Sub Ita Eng] DLRip By Pir8 [CURA] Fede e Religioni", "Lucifer S03e16 [XviD - Eng Mp3 - Sub Ita Eng] DLRip By Pir8 [CURA] Fede e Religioni", "Lucifer S02e01-13 [XviD - Eng Mp3 - Sub Ita] DLRip by Pir8 [CURA] Fede e Religioni FULL ", "Absentia S01e01-10 [Mux 1080p - H264 - Ita Eng Ac3 - Sub Ita Eng] By Morpheus The.Breadwinner.2017.ENG.Sub.ITA.HDRip.XviD-[WEB]" }; var rx = new Regex(@"(?:^|])(?:(?!\b(?:eng|ita)\b)[^]])\*\b(eng(?:\W+\w+)?\W+sub\W+ita)\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); foreach (var s in strs) { Console.WriteLine(s); var result = rx.Match(s); if (result.Success) Console.WriteLine("Matched: {0}", result.Groups[1].Value); else Console.WriteLine("No match!"); Console.WriteLine("=========================================="); } ``` Output: ``` Lucifer S03e15 [XviD - Eng Mp3 - Sub Ita Eng] DLRip By Pir8 [CURA] Fede e Religioni Matched: Eng Mp3 - Sub Ita ========================================== Lucifer S03e15 [XviD - Eng Mp3 - Sub Ita Eng] DLRip By Pir8 [CURA] Fede e Religioni Matched: Eng Mp3 - Sub Ita ========================================== Lucifer S03e01-08 [XviD - Eng Mp3 - Sub Ita Eng] DLRip By Pir8 [CURA] Fede e Religioni SEASON PREMIERE Matched: Eng Mp3 - Sub Ita ========================================== Young Sheldon S01e13 [SATRip 720p - H264 - Eng Ac3 - Sub Ita] HDTV by AVS Matched: Eng Ac3 - Sub Ita ========================================== Young Sheldon S01e08 [Mux 1080p - H264 - Ita Eng Ac3 - Sub Ita Eng] WEBMux Morpheus No match! ========================================== Young Sheldon S01e08 [Mux 1080p - H264 - Ita Eng Ac3 - Sub Ita Eng] WEBMux Morpheus No match! ========================================== Young Sheldon S01e14 [SATRip 720p - H264 - Eng Ac3 - Sub Ita] HDTV by AVS Matched: Eng Ac3 - Sub Ita ========================================== Lucifer S03e15 [XviD - Eng Mp3 - Sub Ita Eng] DLRip By Pir8 [CURA] Fede e Religioni Matched: Eng Mp3 - Sub Ita ========================================== Lucifer S03e16 [XviD - Eng Mp3 - Sub Ita Eng] DLRip By Pir8 [CURA] Fede e Religioni Matched: Eng Mp3 - Sub Ita ========================================== Lucifer S02e01-13 [XviD - Eng Mp3 - Sub Ita] DLRip by Pir8 [CURA] Fede e Religioni FULL Matched: Eng Mp3 - Sub Ita ========================================== Absentia S01e01-10 [Mux 1080p - H264 - Ita Eng Ac3 - Sub Ita Eng] By Morpheus The.Breadwinner.2017.ENG.Sub.ITA.HDRip.XviD-[WEB] Matched: ENG.Sub.ITA ========================================== ``` Upvotes: 2 [selected_answer]
2018/03/22
504
1,814
<issue_start>username_0: How do I make my cursor a prepared statement as well as a dictionary. I have the following. ``` cursor(cursor_class = MySQLCursorPrepared) prints cursor(dictionary = True) prints ``` So I am overwriting the prepared statement with the dictionary. I am using the mysql connector for python3. I have tried ``` cursor(prepared=True,dictionary=True) ``` That errors with ``` Cursor not available with given criteria: dictionary, prepared ``` Interestingly ``` cursor(cursor_class = MySQLCursorPrepared,dictionary = True) ``` I get no errors but the data not of dictionary type.<issue_comment>username_1: I have the same problem. Prepared and Dictionary don't work together. I reported bug: <https://bugs.mysql.com/bug.php?id=92700> Now we wait ;) Upvotes: 4 [selected_answer]<issue_comment>username_2: This naive workaround seems to work for me - if I disable SSL, I can see in 'strace' output that multiple identical queries only get sent to the server once, and I definitely get dictionaries back when I iterate over the cursor's rows: ``` from mysql.connector.cursor import MySQLCursorDict, MySQLCursorPrepared class PreparedDictionaryCursor(MySQLCursorDict, MySQLCursorPrepared): pass ``` Upvotes: 0 <issue_comment>username_3: Zipping `cursor.column_names` with the row values is a good workaround: ``` cursor = connection.cursor(prepared=True) query = 'SELECT foo, bar FROM some_table WHERE a = %s AND b = %s' a = 1 b = 42 cursor.execute(query, [a, b]) rows = cursor.fetchall() for row in rows: result = dict(zip(cursor.column_names, row)) print(result['foo'], result['bar']) ``` See <https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-column-names.html> for documentation on `MySQLCursor.column_names`. Upvotes: 2
2018/03/22
920
2,634
<issue_start>username_0: In Julia, I want to solve a system of ODEs with external forcings `g1(t), g2(t)` like ``` dx1(t) / dt = f1(x1, t) + g1(t) dx2(t) / dt = f2(x1, x2, t) + g2(t) ``` with the forcings read in from a file. I am using this study to learn Julia and the package DifferentialEquations, but I am having difficulties finding the correct approach. I could imagine that using a `callback` could work, but that seems pretty cumbersome. Do you have an idea of how to implement such an external forcing?<issue_comment>username_1: You can use functions inside of the integration function. So you can use something like [Interpolations.jl](https://github.com/JuliaMath/Interpolations.jl) to build an interpolating polynomial from the data in your file, and then do something like: ``` g1 = interpolate(data1, options...) g2 = interpolate(data2, options...) p = (g1,g2) # Localize these as parameters to the model function f(du,u,p,t) g1,g2 = p du[1] = ... + g1[t] # Interpolations.jl interpolates via [] du[2] = ... + g2[t] end # Define u0 and tspan ODEProblem(f,u0,tspan,p) ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Thanks for a nice question and nice answer by @username_1. Below a complete reproducible example of such a problem. Note that Interpolations.jl has changed the indexing to `g1(t)`. ``` using Interpolations using DifferentialEquations using Plots time_forcing = -1.:9. data_forcing = [1,0,0,1,1,0,2,0,1, 0, 1] g1_cst = interpolate((time_forcing, ), data_forcing, Gridded(Constant())) g1_lin = scale(interpolate(data_forcing, BSpline(Linear())), time_forcing) p_cst = (g1_cst) # Localize these as parameters to the model p_lin = (g1_lin) # Localize these as parameters to the model function f(du,u,p,t) g1 = p du[1] = -0.5 + g1(t) # Interpolations.jl interpolates via () end # Define u0 and tspan u0 = [0.] tspan = (-1.,9.) # Note, that we would need to extrapolate beyond ode_cst = ODEProblem(f,u0,tspan,p_cst) ode_lin = ODEProblem(f,u0,tspan,p_lin) # Solve and plot sol_cst = solve(ode_cst) sol_lin = solve(ode_lin) # Plot time_dense = -1.:0.1:9. scatter(time_forcing, data_forcing, label = "discrete forcing") plot!(time_dense, g1_cst(time_dense), label = "forcing1", line = (:dot, :red)) plot!(sol_cst, label = "solution1", line = (:solid, :red)) plot!(time_dense, g1_lin(time_dense), label = "forcing2", line = (:dot, :blue)) plot!(sol_lin, label = "solution2", line = (:solid, :blue)) ``` [![enter image description here](https://i.stack.imgur.com/OS1sC.png)](https://i.stack.imgur.com/OS1sC.png) Upvotes: 2
2018/03/22
583
1,767
<issue_start>username_0: ``` class Parent(models.Model): name = models.CharField(max_length=255, blank=False) class Child(models.Model): parent = models.ForeignKey(Warehouse, related_name="children") name = models.CharField(max_length=255, blank=True) ``` Need to apply search from **Child** by some *term* stating: If **Child**'s *name* is not empty or not NULL then we compare *term* with **Child**'s *name* else - compare *term* with **Parent**'s *name*. Something like: ``` search_result = Child.objects.filter( if Q(name__isnull=True) | Q(name='') then parent__name__icontains=term else name__icontains=term ) ``` so that having: ``` parent = Parent(name="Smith").save() ch1 = Child(parent=parent, name="Smithson").save() ch2 = Child(parent=parent, name="Watson").save() ch3 = Child(parent=parent).save() ``` The search by term "smith" would result: ``` [ch1, ch3] ```<issue_comment>username_1: Not tested but something like this: ``` name = "smith" Child.objects.filter(Q(name__iexact=name) or Q(name=None) & Q(parent__name__iexact=name)) ``` Upvotes: 0 <issue_comment>username_2: You can use multiple of Q objects with `()` signs. ``` from django.db.models import Q search_result = Child.objects.filter( ((Q(name__isnull=True) | Q(name='')) & Q(parent__name__icontains=term)) | (Q(name__isnull=False) & Q(name__icontains=term)) ) ``` Which means either match `((Q(name__isnull=True) | Q(name='')) & Q(parent__name__icontains=term))` this condition or match `(Q(name__isnull=False) & Q(name__icontains=term))` Ref : [Django ORM conditional filter LIKE CASE WHEN THEN](https://stackoverflow.com/questions/48982618/django-orm-conditional-filter-like-case-when-then) Upvotes: 1
2018/03/22
303
1,046
<issue_start>username_0: I have the following code: ``` $orders = Order::all(); $count = $orders->count(); $ordersActive = $orders->during()->count(); //this not working, I get undefined method during ``` I have defined the scope in the model Order: ``` public function scopeDuring($query) { $query->whereNotIn('stat', [1,2,3,4]); } ``` I get undefined method `during`. Any help in resolving this would be greatly appreciated.<issue_comment>username_1: You have alredy get the collection, so you cannot use the method of the model. Instead of this you should do this: ``` $count = Order::count(); $ordersActive = Order::during()->count(); ``` Upvotes: 0 <issue_comment>username_2: Try this code If you want to get all orders use this ``` $orders = Order::all(); ``` If you want to get orders with scope use this ``` $ordersActive = Order::during()->get(); ``` And after that, you will get the count by these queries ``` $count = $orders->count(); $ordersActiveCount = $ordersActive->count(); ``` Upvotes: 3 [selected_answer]
2018/03/22
420
1,354
<issue_start>username_0: In the Bootstrap 4 docs about Jumbotron they show in the example the following: ``` [Learn more](#) ``` What is the need of a paragraph here? And why use the 'lead' class? It seems to do nothing with the button.<issue_comment>username_1: The `lead` class makes the font stand out a little. Here's the actual css rule set used for that: ``` .lead { font-size: 1.25rem; font-weight: 300; } ``` Normal font-size on the body is: ``` font-size: 1rem; font-weight: 400; ``` So, the `lead` class makes the font slightly larger and also a bit thinner which is what makes it stand out slightly. Now, as far as the button is concerned, the `lead` class has absolutely no effect on the text inside the button. So, you are right in that the lead paragraph is not needed for the button. Reference: <https://getbootstrap.com/docs/4.0/content/typography/#lead> Upvotes: 3 [selected_answer]<issue_comment>username_2: > > "What is the need of a paragraph here?" > > > The provides a new line and `margin-bottom` for the button. > > "And why use the 'lead' class?" > > > You're right, the `lead` class doesn't impact the button at all in this case. It's most likely unintentional, and carried over from the other `..` in the same [Jumbotron example](https://getbootstrap.com/docs/4.0/components/jumbotron/). Upvotes: 2
2018/03/22
1,009
3,071
<issue_start>username_0: Help me in solving this issue as i am beginner in android ,i need some help.. Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'. > > java.io.IOException: Can't write [D:\bi.mobile\app\build\intermediates\multi-dex\debug\componentClasses.jar] (Can't read [C:\Users\sort.Vijay.gradle\caches\modules-2\files-2.1\com.google.code.gson\gson\2.8.0\c4ba5371a29ac9b2ad6129b1d39ea38750043eff\gson-2.8.0.jar(;;;;;;\*\*.class)] (Duplicate zip entry [gson-2.8.0.jar:com/google/gson/annotations/Expose.class])) > > > This is my "build.gradle" file ``` apply plugin: 'com.android.application' android { compileSdkVersion 26 defaultConfig { applicationId "com.bimobile" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" multiDexEnabled true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } android { packagingOptions { exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' } // .. } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' //noinspection GradleCompatible,GradleCompatible compile 'com.android.support:appcompat-v7:26.1.0' compile 'com.android.support:design:26.1.0' compile files('libs/android-async-http-1.4.4.jar') compile 'com.google.code.gson:gson:2.8.0' compile 'com.google.android.gms:play-services-maps:11.8.0' compile files('libs/gson-2.8.0.jar') compile 'org.lucasr.twowayview:twowayview:0.1.4' compile "com.daimajia.swipelayout:library:1.2.0@aar" } android { sourceSets { main { res.srcDirs = ['src/main/res', 'src/main/res/anim'] } } } ```<issue_comment>username_1: The `lead` class makes the font stand out a little. Here's the actual css rule set used for that: ``` .lead { font-size: 1.25rem; font-weight: 300; } ``` Normal font-size on the body is: ``` font-size: 1rem; font-weight: 400; ``` So, the `lead` class makes the font slightly larger and also a bit thinner which is what makes it stand out slightly. Now, as far as the button is concerned, the `lead` class has absolutely no effect on the text inside the button. So, you are right in that the lead paragraph is not needed for the button. Reference: <https://getbootstrap.com/docs/4.0/content/typography/#lead> Upvotes: 3 [selected_answer]<issue_comment>username_2: > > "What is the need of a paragraph here?" > > > The provides a new line and `margin-bottom` for the button. > > "And why use the 'lead' class?" > > > You're right, the `lead` class doesn't impact the button at all in this case. It's most likely unintentional, and carried over from the other `..` in the same [Jumbotron example](https://getbootstrap.com/docs/4.0/components/jumbotron/). Upvotes: 2
2018/03/22
876
3,084
<issue_start>username_0: I am joining three tables and taking count [MY SQL FIDDLE](http://sqlfiddle.com/#!9/e34392/25). In this query I want to take one more count like `total_trip` that means I already join the `trip_details` table, in this table take all count that is total trip count, I am not able to write sub query. ``` SELECT COUNT(T.tripId) as Escort_Count, ( SELECT COUNT(*) FROM ( SELECT a.allocationId FROM escort_allocation a INNER JOIN cab_allocation c ON a.allocationId = c.allocationId WHERE c.allocationType = 'Adhoc Trip' GROUP BY a.allocationId ) AS Ad ) AS Adhoc_Trip_Count FROM ( SELECT a.tripId FROM trip_details a INNER JOIN escort_allocation b ON a.allocationId = b.allocationId GROUP BY a.allocationId ) AS T ```<issue_comment>username_1: Is this what you want? ``` SELECT td.tripId, COUNT(*) as total, SUM(ea.allocationType = 'Adhoc Trip') as adhocs FROM trip_details td JOIN escort_allocation ea ON td.allocationId = ea.allocationId GROUP BY td.tripId; ``` Upvotes: -1 <issue_comment>username_2: Use subquery in following: --- **Query:** ``` SELECT COUNT(T.tripId) as Escort_Count, ( SELECT COUNT(*) FROM ( SELECT a.allocationId FROM escort_allocation a INNER JOIN cab_allocation c ON a.allocationId = c.allocationId WHERE c.allocationType = 'Adhoc Trip' GROUP BY a.allocationId ) AS Ad ) AS Adhoc_Trip_Count, (SELECT COUNT(id) FROM trip_details) as Total_Count FROM ( SELECT a.tripId FROM trip_details a INNER JOIN escort_allocation b ON a.allocationId = b.allocationId GROUP BY a.allocationId ) AS T ``` --- **Results:** ``` Escort_Count Adhoc_Trip_Count Total_Trip 5 2 7 ``` --- **Check it out:** `[SQL Fiddle](http://sqlfiddle.com/#!9/25879b/9)` Upvotes: 1 [selected_answer]<issue_comment>username_3: ``` SELECT COUNT(DISTINCT Z.allocationId) Escort_Count,SUM(CASE WHEN allocationType='Adhoc Trip' THEN 1 END) Adhoc_Trip_Count FROM ( SELECT DISTINCT a.allocationId, allocationType FROM escort_allocation a INNER JOIN cab_allocation c ON a.allocationId = c.allocationId INNER JOIN trip_details TD ON a.allocationId = TD.allocationId GROUP BY a.allocationId )Z; ``` **`OR`** ``` SELECT Escort_Count,Adhoc_Trip_Count,Adhoc_Trip_Count+Escort_Count TOTAL FROM( SELECT COUNT(DISTINCT Z.allocationId) Escort_Count,SUM(CASE WHEN allocationType='Adhoc Trip' THEN 1 END) Adhoc_Trip_Count,COUNT(D) FROM ( SELECT DISTINCT a.allocationId, allocationType,SUM(1) D FROM escort_allocation a INNER JOIN cab_allocation c ON a.allocationId = c.allocationId INNER JOIN trip_details TD ON a.allocationId = TD.allocationId GROUP BY a.allocationId )Z )ZZ; ``` You can try above query . Definitely it will help you. Upvotes: 0
2018/03/22
397
1,412
<issue_start>username_0: I use SAP UI5 version 1.52.6. Depending on model data, I would like to enable/disable a sap.ui.table.TreeTable view accordingly. see view: ``` ``` Problem is that there is no method to enable the checkbox in TreeTable, see a similar topic being asked [here](https://stackoverflow.com/questions/43252472/sap-ui-table-table-row-selecter-disable-in-sapui5): How can one disable a checkbox, e.g. if model data of the row has a property called "Enabled" of true? I twould ry to avoid too much jQuery here but did not manage to grab the right attribute of the row anyways.<issue_comment>username_1: You might want to handle the rowSelectionChange event of the table and deselect the not desired rows explicitly, and maybe combine this with a message to the user to inform about the fact. Upvotes: 1 <issue_comment>username_2: Use the below code for disable checkbox in sap.ui.table ```js oTable.addDelegate({ onAfterRendering: function () { var count = this.getVisibleRowCount(); var selectAllId = "#" + this.getId() + "-selall"; $(selectAllId).addClass("disabledbutton"); for (var i = 0; i < count; i++) { var columId = "#" + this.getId() + "-rowsel" + i; $(columId).addClass("disabledbutton"); } } }, oTable); oTable.rerender(); ``` ```css .disabledbutton { pointer-events: none; opacity: 0.4; } ``` Upvotes: 0
2018/03/22
309
1,168
<issue_start>username_0: I have to run a loop in multiple sheets by getting the last column for each sheet. How can I get the last column of every sheet? I tried putting this a function. Can you please suggest on this as I am just a beginner on this. Update: Its working fine now. Tried the code provided by @sktneer. Thanks everyone for your inputs.<issue_comment>username_1: You might want to handle the rowSelectionChange event of the table and deselect the not desired rows explicitly, and maybe combine this with a message to the user to inform about the fact. Upvotes: 1 <issue_comment>username_2: Use the below code for disable checkbox in sap.ui.table ```js oTable.addDelegate({ onAfterRendering: function () { var count = this.getVisibleRowCount(); var selectAllId = "#" + this.getId() + "-selall"; $(selectAllId).addClass("disabledbutton"); for (var i = 0; i < count; i++) { var columId = "#" + this.getId() + "-rowsel" + i; $(columId).addClass("disabledbutton"); } } }, oTable); oTable.rerender(); ``` ```css .disabledbutton { pointer-events: none; opacity: 0.4; } ``` Upvotes: 0
2018/03/22
1,813
4,290
<issue_start>username_0: I am trying to copy the `stochastic` function buffers in the variables. But what I see is that the candles are copied in the array in descending order. ``` double KArray[],DArray[]; ArraySetAsSeries(KArray,true); ArraySetAsSeries(DArray,true); int stochastic_output = iStochastic(_Symbol,PERIOD_M1,5,3,3,MODE_SMA,STO_LOWHIGH); CopyBuffer(stochastic_output,0,0,15,KArray); CopyBuffer(stochastic_output,1,0,15,DArray); for (int i=0;i < Candles_backtest_Stochastic_quantity;i++) { PrintFormat("K %d: %f",i,KArray[i]); PrintFormat("D %d: %f",i,DArray[i]); } ``` This works well and while printing the array values I am getting the `0th` as the current value and the previous values later. ``` 2018.03.22 18:07:23.622 2018.02.01 00:00:00 K 0: 57.291667 2018.03.22 18:07:23.622 2018.02.01 00:00:00 D 0: 63.194444 2018.03.22 18:07:23.622 2018.02.01 00:00:00 K 1: 61.458333 2018.03.22 18:07:23.622 2018.02.01 00:00:00 D 1: 68.754756 2018.03.22 18:07:23.622 2018.02.01 00:00:00 K 2: 70.833333 2018.03.22 18:07:23.622 2018.02.01 00:00:00 D 2: 69.294286 2018.03.22 18:07:23.622 2018.02.01 00:00:00 K 3: 73.972603 2018.03.22 18:07:23.622 2018.02.01 00:00:00 D 3: 57.177428 2018.03.22 18:07:23.622 2018.02.01 00:00:00 K 4: 63.076923 ``` And so on. But I want to have a reversed array, i.e. the `14th` array element must be the `0th` and the `0th` must be the `14th` element of the array. I tried to make the `CopyBuffer()` statement to reverse the buffer, but got error, see the example: ``` 2018.03.22 18:11:11.957 Total_back_lagANDvantage_required=3 2018.03.22 18:11:12.073 2018.02.01 00:00:00 K 0: 78.260870 2018.03.22 18:11:12.073 2018.02.01 00:00:00 D 0: 72.579331 2018.03.22 18:11:12.073 2018.02.01 00:00:00 array out of range in 'adxSTUDY.mq5' (173,33) 2018.03.22 18:11:12.073 OnTick critical error 2018.03.22 18:11:12.087 EURUSD,M1: 1 ticks, 1 bars generated. Environment synchronized in 0:00:00.312. Test passed in 0:00:00.594 (including ticks preprocessing 0:00:00.016). 2018.03.22 18:11:12.087 EURUSD,M1: total time from login to stop testing 0:00:00.906 (including 0:00:00.312 for history data synchronization) ``` Kindly, help me. I do not want to have another buffer to copy the array and reverse it, Is there a way through which I can reverse the array and use it?<issue_comment>username_1: > > I do not want to have another buffer to copy the array and reverse it. > > > Right, each ***`copy`*** is expensive in two dimensions - in `[TIME]`-domain and in `[SPACE]`-domain. There is for sure better way to avoid any copy to ever take place, for both of these reasons. --- There are two principal approaches: ----------------------------------- **A )** **the internal, native** MetaTrader Terminal / MQL5 modus operandi, which uses a sort of ***flag*** to indicate a reversed-time-stepping addressing on TimeSeries data, where **`[0]`** is being always the "***NOW***" - so changing the *flag* changes from native-addressing to "natural"-addressing, where `[0]` is a statically oldest ever cell, but the "NOW"'s address keeps creeping as time is moving forwards. This is the fastest method, yet requires designer to keep attention in which mode the access is set ( uses an On-Off-FSA ). **B )** a proxy-mode, where one can use an access function, which internally translates the access mode without having to pay attention to FSA-state. Using class-based proxy became even easier way to go in proxy-based operation, as more class-methods allow for designing iterators and other tools, re-using the concept of autonomous proxy-abstracted details and prevent user from "damaging" the state of proxy-abstracted operations and fall outside of proper addressing in either of the actual `array[]`'s native-states. B)-is not any slower than A), yet very handy to use, as one can stop remembering in what native-state the `array[]` has been left by the last operation, so a comfortable ( similarly if `array[]`-s get used for emulations of stack-based ops and other higher-level of abstraction data-structures in MQL4/5 domains ). Upvotes: 1 [selected_answer]<issue_comment>username_2: Use the ArraySetAsSeries function. In your case it will be ``` ArraySetAsSeries(KArray,false); ``` Upvotes: 2
2018/03/22
287
925
<issue_start>username_0: Let's say I would like to implement a route that accepts email and a reference id ``` email: <EMAIL> ref_id: abcd1234 website.com/ticket/email=<EMAIL>1&ref_id=abcd1234 ``` how do I design this url in laravel? should I just use a get route?<issue_comment>username_1: ``` Route::get('ticket/{email}/{ref_id}', 'YourController@YourMethod'); ``` Please visit [this link](https://laravel.com/docs/5.6/routing) for more details about routes. Upvotes: 3 [selected_answer]<issue_comment>username_2: you should try this: ``` Route::get('ticket/email={email}/ref_id={ref_id}', 'YourController@metodName'); ``` Upvotes: 1 <issue_comment>username_3: ``` Route::get('/ticket/{email}/{id}', function(){ // You controller code goes here } ``` Or if you are using seperate controller for each model ``` Route::get('/ticket/{email}/{id}', 'TicketController@method_name'); ``` Upvotes: 0
2018/03/22
965
3,317
<issue_start>username_0: For one of my exercises, I have to test my work with JUnit. The first test passed with no errors but the other two have no errors but have failures instead. What does this mean? ``` public class TestExercise2 { int [][] numArray = {{3, -1, 4, 0},{5, 9, -2, 6},{5, 3, 7, -8}}; @Test public void sumOfRows() { assertEquals(31, Exercise2.sum(numArray)); } @Test public void rowsSums() { int [] i = new int [] {6, 18, 7}; assertArrayEquals(i, Exercise2.rowsSums(numArray)); } @Test public void columnSums() { int [] i = new int [] {13,11,9,-2}; assertArrayEquals(i, Exercise2.columnSums(numArray)); } ```<issue_comment>username_1: This means that the method the methods being tested in other two test cases are not returning the result as per your expectation and `assertArrayEquals` method checks your expectation for you. Refer to the [documentation](http://junit.sourceforge.net/javadoc/org/junit/Assert.html) for more information. Upvotes: 2 <issue_comment>username_2: Your assertions are totally fine and legal, you just need to make sure you're comparing two comparable arrays. I believe the problem is in retrieving wrongly created arrays from `Exercise2`'s methods `rowsSums()` and `columnSums()`. So I attempted to create those and couple of helping methods such as `getRows()` and `getColumns()`. > > Now all tests will pass! > > > ``` public class Exercise2 { public static int getRows(int[][] numArray) { // if there are no rows, method will simply return 0 return numArray.length; } public static int getColumns(int[][] numArray) { // if there are no rows, // ArrayIndexOutOfBoundsException will be thrown // so need to check if (getRows(numArray) != 0) return numArray[0].length; return 0; } public static int[] rowsSums(int[][] numArray) { // getRows(numArray) will return 3 int[] rowsSums = new int[getRows(numArray)]; int sum = 0; // iterating over an array for (int i = 0; i < getRows(numArray); i++) { for (int j = 0; j < getColumns(numArray); j++) { sum += numArray[i][j]; } // when row is finished, // store sum as [i] element of an array rowsSums[i] = sum; // setting sum to zero before iterating over next row sum = 0; } return rowsSums; } public static int[] columnSums(int[][] numArray) { // getColumns(numArray) will return 4 int[] columnSums = new int[getColumns(numArray)]; int sum = 0; // now we iterate over columns first // so i < getColumns() for (int i = 0; i < getColumns(numArray); i++) { for (int j = 0; j < getRows(numArray); j++) { // swapped i and j sum += numArray[j][i]; } // same thing as before columnSums[i] = sum; sum = 0; } return columnSums; } } ``` --- You can also add a `sizesOfArray()` test to verify correctness of calculations. ``` @Test public void sizesOfArray() { assertEquals(3, Exercise2.getRows(numArray)); assertEquals(4, Exercise2.getColumns(numArray)); // ArrayIndexOutOfBoundsException will not be thrown assertEquals(0, Exercise2.getRows(new int[0][0])); assertEquals(0, Exercise2.getColumns(new int[0][0])); } ``` --- Upvotes: 1
2018/03/22
2,321
8,978
<issue_start>username_0: I have six `textfields`. Now if all my `textfield` are filled and tap on any `textfield` the it should always put focus on sixth `textfield` & show the keyboard. I have tried below code but it does not show `keyboard` and only put focus when I tap on sixth `textfield`. please tell me what is the issue with this ? ``` func textFieldDidBeginEditing(_ textField: UITextField) { textField.inputAccessoryView = emptyView if let textOneLength = textFieldOne.text?.length ,let textTwoLength = textFieldTwo.text?.length ,let textThreeLength = textFieldThree.text?.length , let textFourLength = textFieldFour.text?.length,let textFiveLength = textFieldFive.text?.length , let textSixLength = textFieldSix.text?.length { if (textOneLength > 0) && (textTwoLength > 0) && (textThreeLength > 0) && (textFourLength > 0) && (textFiveLength > 0) && (textSixLength > 0) { self.textFieldSix.becomeFirstResponder() } else if (textOneLength <= 0) && (textTwoLength <= 0) && (textThreeLength <= 0) && (textFourLength <= 0) && (textFiveLength <= 0) && (textSixLength <= 0){ self.textFieldOne.becomeFirstResponder() } } } ```<issue_comment>username_1: It should be work. Are you sure that the simulator has the property to show the keywoard enable? You can change that property with the keys: Command + Shift + k Upvotes: 0 <issue_comment>username_2: To check any textfield use this code ``` for view in self.view.subviews { if let textField = view as? UITextField { print(textField.text!) } } ``` \*\* you can also identify a textfiled by using this - ``` if let txtFieldINeed = self.view.viewWithTag(99) as? UITextField { print(txtFieldINeed.text!) } ``` \*\* then use -- txtFieldINeed.becomeFirstResponder() \*\* Make sure to turn on this options -- \* iOS Simulator -> Hardware -> Keyboard \* Uncheck "Connect Hardware Keyboard" Upvotes: -1 <issue_comment>username_3: I know it is strange for me as well but delaying the focus on text field worked for me. ``` DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { self.textFieldOne.becomeFirstResponder() } ``` I added above code in textFieldDidBeginEdting & it worked like magic. Upvotes: 0 <issue_comment>username_4: I think accepted answer is hack. Other thing that we can do is detect `touchDown` on `UITextField`, check if last textField should be in focus and do `becomeFirstResponder()` on it. Next thing, we should disallow focus other textFields if last should be in focus. We can do that in `textFieldShouldBeginEditing` method. Here example of `ViewController`. Just connect 3 textFields and all should work as expected (Swift 4): ``` class ViewController: UIViewController { @IBOutlet weak var firstTextField: UITextField! @IBOutlet weak var secondTextField: UITextField! @IBOutlet weak var thirdTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() firstTextField.delegate = self secondTextField.delegate = self thirdTextField.delegate = self firstTextField.addTarget(self, action: #selector(textFieldTouch(_:)), for: .touchDown) secondTextField.addTarget(self, action: #selector(textFieldTouch(_:)), for: .touchDown) thirdTextField.addTarget(self, action: #selector(textFieldTouch(_:)), for: .touchDown) } @IBAction private func textFieldTouch(_ sender: UITextField) { if shouldFocusOnLastTextField { thirdTextField.becomeFirstResponder() } } private var shouldFocusOnLastTextField: Bool { return firstTextField.text?.isEmpty == false && secondTextField.text?.isEmpty == false && thirdTextField.text?.isEmpty == false } } extension ViewController: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { guard shouldFocusOnLastTextField else { return true } return textField == thirdTextField } } ``` --- Other, more simple way to achieve that check the textField that is going to be focused: ``` extension ViewController: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { guard firstTextField.text?.isEmpty == false && secondTextField.text?.isEmpty == false && thirdTextField.text?.isEmpty == false && textField != thirdTextField else { return true } thirdTextField.becomeFirstResponder() return false } } ``` Upvotes: 2 <issue_comment>username_5: In this case, you'll want to reject attempted edits before they happened; when we wish to reject an attempted edit we will also need to set the sixth textfield as the new first responder. ``` extension MyViewController: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { if textFieldOne.text?.isEmpty == false && textFieldTwo.text?.isEmpty == false && textFieldThree.text?.isEmpty == false && textFieldFour.text?.isEmpty == false && textFieldFive.text?.isEmpty == false && textFieldSix.text?.isEmpty == false { if textField != textFieldSix { textFieldSix.becomeFirstResponder() return false } else { return true } } else { return true } } } ``` Upvotes: 0 <issue_comment>username_6: The problem with your implementation is that you are trying to assign the first responder when it was already assign to another textField. The following code should do the trick: ``` extension TestViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { textField.inputAccessoryView = UIView() } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { if let textOneLength = textFieldOne.text?.count ,let textTwoLength = textFieldTwo.text?.count ,let textThreeLength = textFieldThree.text?.count , let textFourLength = textFieldFour.text?.count,let textFiveLength = textFieldFive.text?.count , let textSixLength = textFieldSix.text?.count { if (textOneLength > 0) && (textTwoLength > 0) && (textThreeLength > 0) && (textFourLength > 0) && (textFiveLength > 0) && (textSixLength > 0) { ///Check if the sixth textField was selected to avoid infinite recursion if textFieldSix != textField { self.textFieldSix.becomeFirstResponder() return false } } else if (textOneLength <= 0) && (textTwoLength <= 0) && (textThreeLength <= 0) && (textFourLength <= 0) && (textFiveLength <= 0) && (textSixLength <= 0){ ///Check if the first textField was selected to avoid infinite recursion if textFieldOne != textField { self.textFieldOne.becomeFirstResponder() return false } } } return true } } ``` Upvotes: 1 <issue_comment>username_7: **1** Set UITextfielddelegate in viewcontroller **2** Set self delegate to every textfield **3** add tag value for every textfield **4** add textfield.becomeFirstResponder() **5** check if condition using tag for take specify textfield value Upvotes: 0 <issue_comment>username_8: Reference to this answer <https://stackoverflow.com/a/27098244/4990506> > > A responder object only becomes the first responder if the current > responder can resign first-responder status (canResignFirstResponder) > and the new responder can become first responder. > > > You may call this method to make a responder object such as a view the first responder. However, you should only call it on that view if > it is part of a view hierarchy. If the view’s window property holds a > UIWindow object, it has been installed in a view hierarchy; if it > returns nil, the view is detached from any hierarchy. > > > First set delegate to all field ``` self.textFieldOne.delegate = self self.textFieldTwo.delegate = self self.textFieldThree.delegate = self self.textFieldFour.delegate = self self.textFieldFive.delegate = self self.textFieldSix.delegate = self ``` And then delegate ``` extension ViewController : UITextFieldDelegate{ func textFieldDidBeginEditing(_ textField: UITextField) { if self.textFieldOne.hasText ,self.textFieldTwo.hasText ,self.textFieldThree.hasText ,self.textFieldFour.hasText ,self.textFieldFive.hasText ,self.textFieldSix.hasText { textFieldSix.perform( #selector(becomeFirstResponder), with: nil, afterDelay: 0.1 ) }else if !self.textFieldOne.hasText ,!self.textFieldTwo.hasText ,!self.textFieldThree.hasText ,!self.textFieldFour.hasText ,!self.textFieldFive.hasText ,!self.textFieldSix.hasText { textFieldOne.perform( #selector(becomeFirstResponder), with: nil, afterDelay: 0.1 ) } } } ``` Upvotes: 0
2018/03/22
2,355
8,916
<issue_start>username_0: I was doing the assignment when this came up and as I am just a beginner I have no idea what is going on or how to solve it. All the commented parts are just me trying out different ways to do it. ``` import sys # YOUR CODE HERE #small = input("Width, Height and Depth of small box: ") #big = input("Width, Height and Depth of big box: ") small_width = input("What is the width of the small box? ") small_height = input("What is the height of the small box? ") small_depth = input("What is the depth of the small box? ") #small = 0 small = int(small_width)*int(small_height)*int(small_depth) big_width = input("What is the width of the big box? ") big_height = input("What is the height of the big box? ") big_depth = input("What is the depth of the big box? ") #big = 0 big = int(big_width)*int(big_height)*int(big_depth) num = big%small num = int(num) print(num) #if int(num) > 0 #print("Number of " + small + " that will fit in " + big + " is: " + num) #else: #print("Number of " + small + " that will fit in " + big + " is: 0") ``` It keeps saying this part is wrong. ``` #if int(num) > 0 ^ ```<issue_comment>username_1: It should be work. Are you sure that the simulator has the property to show the keywoard enable? You can change that property with the keys: Command + Shift + k Upvotes: 0 <issue_comment>username_2: To check any textfield use this code ``` for view in self.view.subviews { if let textField = view as? UITextField { print(textField.text!) } } ``` \*\* you can also identify a textfiled by using this - ``` if let txtFieldINeed = self.view.viewWithTag(99) as? UITextField { print(txtFieldINeed.text!) } ``` \*\* then use -- txtFieldINeed.becomeFirstResponder() \*\* Make sure to turn on this options -- \* iOS Simulator -> Hardware -> Keyboard \* Uncheck "Connect Hardware Keyboard" Upvotes: -1 <issue_comment>username_3: I know it is strange for me as well but delaying the focus on text field worked for me. ``` DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { self.textFieldOne.becomeFirstResponder() } ``` I added above code in textFieldDidBeginEdting & it worked like magic. Upvotes: 0 <issue_comment>username_4: I think accepted answer is hack. Other thing that we can do is detect `touchDown` on `UITextField`, check if last textField should be in focus and do `becomeFirstResponder()` on it. Next thing, we should disallow focus other textFields if last should be in focus. We can do that in `textFieldShouldBeginEditing` method. Here example of `ViewController`. Just connect 3 textFields and all should work as expected (Swift 4): ``` class ViewController: UIViewController { @IBOutlet weak var firstTextField: UITextField! @IBOutlet weak var secondTextField: UITextField! @IBOutlet weak var thirdTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() firstTextField.delegate = self secondTextField.delegate = self thirdTextField.delegate = self firstTextField.addTarget(self, action: #selector(textFieldTouch(_:)), for: .touchDown) secondTextField.addTarget(self, action: #selector(textFieldTouch(_:)), for: .touchDown) thirdTextField.addTarget(self, action: #selector(textFieldTouch(_:)), for: .touchDown) } @IBAction private func textFieldTouch(_ sender: UITextField) { if shouldFocusOnLastTextField { thirdTextField.becomeFirstResponder() } } private var shouldFocusOnLastTextField: Bool { return firstTextField.text?.isEmpty == false && secondTextField.text?.isEmpty == false && thirdTextField.text?.isEmpty == false } } extension ViewController: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { guard shouldFocusOnLastTextField else { return true } return textField == thirdTextField } } ``` --- Other, more simple way to achieve that check the textField that is going to be focused: ``` extension ViewController: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { guard firstTextField.text?.isEmpty == false && secondTextField.text?.isEmpty == false && thirdTextField.text?.isEmpty == false && textField != thirdTextField else { return true } thirdTextField.becomeFirstResponder() return false } } ``` Upvotes: 2 <issue_comment>username_5: In this case, you'll want to reject attempted edits before they happened; when we wish to reject an attempted edit we will also need to set the sixth textfield as the new first responder. ``` extension MyViewController: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { if textFieldOne.text?.isEmpty == false && textFieldTwo.text?.isEmpty == false && textFieldThree.text?.isEmpty == false && textFieldFour.text?.isEmpty == false && textFieldFive.text?.isEmpty == false && textFieldSix.text?.isEmpty == false { if textField != textFieldSix { textFieldSix.becomeFirstResponder() return false } else { return true } } else { return true } } } ``` Upvotes: 0 <issue_comment>username_6: The problem with your implementation is that you are trying to assign the first responder when it was already assign to another textField. The following code should do the trick: ``` extension TestViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { textField.inputAccessoryView = UIView() } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { if let textOneLength = textFieldOne.text?.count ,let textTwoLength = textFieldTwo.text?.count ,let textThreeLength = textFieldThree.text?.count , let textFourLength = textFieldFour.text?.count,let textFiveLength = textFieldFive.text?.count , let textSixLength = textFieldSix.text?.count { if (textOneLength > 0) && (textTwoLength > 0) && (textThreeLength > 0) && (textFourLength > 0) && (textFiveLength > 0) && (textSixLength > 0) { ///Check if the sixth textField was selected to avoid infinite recursion if textFieldSix != textField { self.textFieldSix.becomeFirstResponder() return false } } else if (textOneLength <= 0) && (textTwoLength <= 0) && (textThreeLength <= 0) && (textFourLength <= 0) && (textFiveLength <= 0) && (textSixLength <= 0){ ///Check if the first textField was selected to avoid infinite recursion if textFieldOne != textField { self.textFieldOne.becomeFirstResponder() return false } } } return true } } ``` Upvotes: 1 <issue_comment>username_7: **1** Set UITextfielddelegate in viewcontroller **2** Set self delegate to every textfield **3** add tag value for every textfield **4** add textfield.becomeFirstResponder() **5** check if condition using tag for take specify textfield value Upvotes: 0 <issue_comment>username_8: Reference to this answer <https://stackoverflow.com/a/27098244/4990506> > > A responder object only becomes the first responder if the current > responder can resign first-responder status (canResignFirstResponder) > and the new responder can become first responder. > > > You may call this method to make a responder object such as a view the first responder. However, you should only call it on that view if > it is part of a view hierarchy. If the view’s window property holds a > UIWindow object, it has been installed in a view hierarchy; if it > returns nil, the view is detached from any hierarchy. > > > First set delegate to all field ``` self.textFieldOne.delegate = self self.textFieldTwo.delegate = self self.textFieldThree.delegate = self self.textFieldFour.delegate = self self.textFieldFive.delegate = self self.textFieldSix.delegate = self ``` And then delegate ``` extension ViewController : UITextFieldDelegate{ func textFieldDidBeginEditing(_ textField: UITextField) { if self.textFieldOne.hasText ,self.textFieldTwo.hasText ,self.textFieldThree.hasText ,self.textFieldFour.hasText ,self.textFieldFive.hasText ,self.textFieldSix.hasText { textFieldSix.perform( #selector(becomeFirstResponder), with: nil, afterDelay: 0.1 ) }else if !self.textFieldOne.hasText ,!self.textFieldTwo.hasText ,!self.textFieldThree.hasText ,!self.textFieldFour.hasText ,!self.textFieldFive.hasText ,!self.textFieldSix.hasText { textFieldOne.perform( #selector(becomeFirstResponder), with: nil, afterDelay: 0.1 ) } } } ``` Upvotes: 0
2018/03/22
415
1,686
<issue_start>username_0: I have a small C# console app that monitors some configured process(es)/app(s), these are also C# console apps, and keep them running so it starts them if they crashed. It works well if I run this monitor console app by executing exe file (in interactive mode). However if I install this app as a windows service using NSSM, the monitored process(es) are killed when the service is stopped which is not what I want. The minimum code to reproduce (this code starts the child process only once and does not monitor it at all): Monitoring app: ``` class Program { static void Main(string[] args) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "..\\..\\..\\TestApp\\bin\\debug\\TestApp.exe"; Process.Start(startInfo); Console.WriteLine("Process started"); Console.Read(); } } ``` Monitored app: ``` static void Main(string[] args) { while (true) { Console.WriteLine("running..."); Thread.Sleep(3000); } } ``` Is there a way how to keep these child process(es) running after windows service is stopped? Thanks<issue_comment>username_1: Try using `startInfo.UseShellExecute = true;` for the "child" processes. This will execute the process from the shell as a separate/independent process. Upvotes: 0 <issue_comment>username_2: NSSM has a configuration option which does not kill the entire process tree when stopping the service. You can configure this in the UI with `nssm.exe edit "my service name"` or directly with `nssm.exe set "my service name" AppKillProcessTree 0`. Upvotes: 3 [selected_answer]
2018/03/22
1,300
4,159
<issue_start>username_0: I build app that display webview. when I change the size of WebView my app is crashed. here my code: ``` final WebView videoWebView = (WebView) findViewById(R.id.videoWebView); videoWebView.getSettings().setJavaScriptEnabled(true); videoWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); videoWebView.getSettings().setPluginState(PluginState.ON); videoWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30); videoWebView.setLayoutParams(layoutParams); ``` (This webview hide in start of app, and when I display him the app is crash) Can you help me? Thank you very very much! My logout: ``` java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams at android.widget.FrameLayout.onMeasure(FrameLayout.java:186) at android.view.View.measure(View.java:19759) at android.widget.LinearLayout.measureVertical(LinearLayout.java:911) at android.widget.LinearLayout.onMeasure(LinearLayout.java:640) at android.view.View.measure(View.java:19759) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6122) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139) at android.view.View.measure(View.java:19759) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6122) at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:393) at android.view.View.measure(View.java:19759) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6122) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at android.view.View.measure(View.java:19759) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6122) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464) at android.widget.LinearLayout.measureVertical(LinearLayout.java:758) at android.widget.LinearLayout.onMeasure(LinearLayout.java:640) at android.view.View.measure(View.java:19759) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6122) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at com.android.internal.policy.DecorView.onMeasure(DecorView.java:690) at android.view.View.measure(View.java:19759) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2313) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1400) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1649) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1288) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6359) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:873) at android.view.Choreographer.doCallbacks(Choreographer.java:685) at android.view.Choreographer.doFrame(Choreographer.java:621) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:859) at android.os.Handler.handleCallback(Handler.java:754) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:163) at android.app.ActivityThread.main(ActivityThread.java:6326) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770) ```<issue_comment>username_1: Try this ``` ViewGroup.LayoutParams newParams=videoWebView.getLayoutParams(); newParams.height=30; newParams.width=30; videoWebView.setLayoutParams(newParams); ``` Or this ``` FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(30, 30); videoWebView.setLayoutParams(layoutParams); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Replace `LinearLayout.LayoutParams` with `FrameLayout.LayoutParams` in your code : ``` LinearLayout.LayoutParams layoutParams = LinearLayout.LayoutParams(30, 30); ``` with : ``` FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(30, 30); ``` Upvotes: 0
2018/03/22
893
3,031
<issue_start>username_0: In my code I need to keep track of two kinds of data items, namely the original data items and the transformed data items. Both original and transformed data items I store as `Array{Float64,1}`. However, I need to keep track if a data item is a transformed one or not as some functions in my code work with the original data items and some with the transformed ones. In order to ensure correctness and avoid ever passing a transformed data item to a function that is supposed to work with the original data item, I was thinking that I could create a type called `Transformed`. This type could be used in the function declarations thus enforcing correctness. Of course I looked in the documentation, but this did not help me enough. I guess what I need to do is something like: ``` primitive type Transformed :< Array{Float64,1} end ``` but of course this doesn't work (it is not even a primitive!) Do I have to go for a struct? any suggestions? Cheers.<issue_comment>username_1: Yes, you likely want a `struct` or a `mutable struct` containing an `Array{Float64, 1}`. You can learn more about these in the Julia manual section on composite types (i.e. structs): <https://docs.julialang.org/en/stable/manual/types/#Composite-Types-1> A simple example would be: ``` struct Transformed data::Array{Float64, 1} end ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: In case you don't want to access your arrays with the `.data` field you might consider using `StaticArrays`. There might be some other already existing data structures, but this was the first I could think of. You can declare these with `SVector` or [with some macros](https://github.com/JuliaArrays/StaticArrays.jl). The benefit of this is that then you can check whether an array is a StaticArray or a regular one quite easily, but you can just use them as regular arrays. ``` julia> using StaticArrays julia> original_array = SVector(1.5,2,3) 3-element StaticArrays.SArray{Tuple{3},Float64,1,3}: 1.5 2.0 3.0 julia> transformed_array = Array{Float64,1}(original_array + 1.3) 3-element Array{Float64,1}: 2.8 3.3 4.3 julia> # these will give you StaticArrays original_array + transformed_array 3-element StaticArrays.SArray{Tuple{3},Float64,1,3}: 4.3 5.3 7.3 julia> transformed_array + original_array 3-element StaticArrays.SArray{Tuple{3},Float64,1,3}: 4.3 5.3 7.3 julia> # matrix multiplication still works original_array' * transformed_array 23.699999999999996 julia> original_array * transformed_array' 3×3 Array{Float64,2}: 4.2 4.95 6.45 5.6 6.6 8.6 8.4 9.9 12.9 julia> # same for reductions sum(transformed_array) 10.399999999999999 ``` One obvious drawback is that you can't grow these StaticArrays. But I assumed if you want to keep your original values then this is not a problem anyways. Also, as shown above, be careful when operating on them as you might get StaticArrays back. Then you will need to explicitly convert the results into Arrays. Upvotes: 0
2018/03/22
556
1,954
<issue_start>username_0: ``` I have created docker container for ubuntu:16.04 and spark. ``` my docker image name `TestDocker` using spark application I have copied test.txt to container /opt/ml/ location. when i am executing below command it is showing like below: ``` docker images REPOSITORY TAG IMAGE ID CREATED SIZE xx.com/decision-trees-sample latest af30271f1528 19 minutes ago 959MB ``` then i try to execute below command ``` docker exec -it decision-trees-sample ls /opt/ml ``` it is showing error. now I want to check file is copied or not using docker command,is it possible to check? how can I list(LS) files contain in /opt/ml/ ?<issue_comment>username_1: you can launch a shell inside the container with the `docker exec` command, see the doc <https://docs.docker.com/engine/reference/commandline/exec/> For example, if the id of your container is 123abcdef, you may do either `docker exec -it 123abcdef ls /opt/ml` or open a shell inside your container `docker exec -it 123abcdef bash` and then launch `ls` or `find` or any other command Upvotes: 2 <issue_comment>username_2: Try below steps > > docker exec -it decision-trees-sample > > > then set the environmental variable as > > export TERM=xterm > > > then try with ``` docker exec -it 123abcdef ls /opt/ml ``` basically it tell your which kind of terminal you are trying to open.It mainly due to some package not installed regarding terminals, you can also add it to ~/.bashrc file and commit the image. Upvotes: 0 <issue_comment>username_3: I agree with above answers and `docker exec` is only for running containers but If you really want to explore container image content I would recommend using [container-diff](https://github.com/GoogleCloudPlatform/container-diff) ``` container-diff analyze --type=file ![]() | grep /opt/ml ``` Upvotes: 0
2018/03/22
4,677
8,343
<issue_start>username_0: After searching over an hour (this forum, Youtube, class notes, google) I've found no help for my question. I'm a complete newb who knows nothing about R or stats. I'm attempting to create a linear mixed effects model in R. I'm measuring leaf width across three different locations (Jacksonville FL, Augusta GA, & Atlanta GA), and within those three locations there is a high-nitrogen and low-nitrogen plot. I have 150 leaf measurements from 50 trees. My limited understanding tells me that the leaf width is the continuous response variable, and city and plot are the discrete explanatory variables. The random effect would be the individual trees, since the leaf width within a single tree is non-independent. I've used "nlme" to make a model: ``` leaf.width.model <- lme(width ~ city*plot, (1|tree.id), data=leaf) ``` I then ran an ANOVA test, and it suggested there's something going on with city and the interaction between city and plot. This is where I'm stuck. I want to make a plot that has lines for all three cities, but I haven't a clue how to do that. When I try to use the plot function, I just get a boxplot. I've literally tried for hours and am more lost and confused than before. 1) How can I make this graph? 2) What other tests should I do to analyze and/or visualize this data? I am forever grateful for any help at all. I really want to learn R and stats very badly, but I'm getting discouraged. Thank you, Rich P.S Here is the output of the `dput` function: ``` > dput(tree) structure(list(tree.id = structure(c(24L, 24L, 32L, 25L, 25L, 24L, 24L, 32L, 25L, 25L, 43L, 45L, 45L, 43L, 23L, 23L, 45L, 45L, 23L, 23L, 41L, 41L, 38L, 11L, 11L, 38L, 41L, 41L, 11L, 11L, 14L, 14L, 29L, 13L, 13L, 14L, 14L, 29L, 13L, 13L, 4L, 4L, 1L, 1L, 20L, 1L, 1L, 20L, 6L, 8L, 8L, 5L, 5L, 6L, 4L, 4L, 8L, 8L, 5L, 5L, 9L, 9L, 10L, 10L, 12L, 12L, 13L, 13L, 22L, 22L, 23L, 23L, 24L, 24L, 25L, 25L, 25L, 25L, 40L, 40L, 41L, 41L, 38L, 38L, 39L, 39L, 14L, 14L, 14L, 15L, 15L, 28L, 28L, 29L, 29L, 35L, 35L, 36L, 36L, 37L, 37L, 42L, 42L, 43L, 43L, 44L, 44L, 45L, 45L, 46L, 46L, 47L, 47L, 2L, 1L, 3L, 3L, 4L, 4L, 7L, 11L, 11L, 16L, 16L, 20L, 20L, 21L, 21L, 17L, 17L, 18L, 18L, 19L, 19L, 26L, 26L, 27L, 27L, 30L, 30L, 31L, 31L, 32L, 32L, 33L, 33L, 34L, 34L, 48L), .Label = c("Tree_112", "Tree_112 ", "Tree_115", "Tree_130", "Tree_137", "Tree_139", "Tree_140", "Tree_141", "Tree_153", "Tree_154", "Tree_156", "Tree_159", "Tree_166", "Tree_169", "Tree_171", "Tree_180", "Tree_182", "Tree_184", "Tree_185", "Tree_202", "Tree_213", "Tree_218", "Tree_222", "Tree_227", "Tree_239", "Tree_242", "Tree_246", "Tree_247", "Tree_252", "Tree_260", "Tree_267", "Tree_269", "Tree_271", "Tree_272", "Tree_291", "Tree_293", "Tree_298", "Tree_327", "Tree_329", "Tree_336", "Tree_350", "Tree_401", "Tree_403", "Tree_405", "Tree_407", "Tree_409", "Tree_420", "Tree_851"), class = "factor"), city = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Atlanta", "Augusta", "Jacksonville"), class = "factor"), plot = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("High-N", "Low-N"), class = "factor"), width = c(0.66, 0.716, 0.682, 0.645, 0.645, 0.696, 0.733, 0.707, 0.668, 0.686, 0.617, 0.733, 0.73, 0.615, 0.669, 0.746, 0.687, 0.682, 0.76, 0.713, 0.651, 0.664, 0.679, 0.729, 0.756, 0.669, 0.647, 0.713, 0.767, 0.685, 0.69, 0.731, 0.781, 0.729, 0.725, 0.739, 0.769, 0.791, 0.676, 0.688, 0.719, 0.753, 0.748, 0.791, 0.785, 0.78, 0.723, 0.756, 0.664, 0.645, 0.653, 0.615, 0.591, 0.642, 0.693, 0.716, 0.694, 0.676, 0.662, 0.629, 0.665, 0.748, 0.726, 0.693, 0.715, 0.714, 0.764, 0.732, 0.61, 0.721, 0.703, 0.713, 0.746, 0.752, 0.662, 0.733, 0.707, 0.674, 0.734, 0.79, 0.732, 0.794, 0.703, 0.712, 0.737, 0.731, 0.747, 0.746, 0.787, 0.709, 0.716, 0.764, 0.77, 0.764, 0.802, 0.663, 0.777, 0.642, 0.779, 0.81, 0.724, 0.645, 0.68, 0.637, 0.695, 0.768, 0.761, 0.7, 0.759, 0.726, 0.696, 0.794, 0.774, 0.799, 0.747, 0.606, 0.691, 0.733, 0.707, 0.698, 0.706, 0.72, 0.694, 0.697, 0.737, 0.716, 0.73, 0.706, 0.667, 0.734, 0.528, 0.695, 0.684, 0.763, 0.733, 0.809, 0.6, 0.676, 0.718, 0.759, 0.609, 0.665, 0.667, 0.647, 0.701, 0.663, 0.688, 0.693, 0.899)), .Names = c("tree.id", "city", "plot", "width"), class = "data.frame", row.names = c(NA, -149L)) ``` Thank you all so much for your comments, I sincerely appreciate everyone's help!<issue_comment>username_1: As suggested in comments, a line plot might not make sense for your data, as you are studying how width varies in discrete categories (in separate cities and separate plots). Boxplots would make sense as you can make them for each of the interactions of city and plot. To give you a sense of what you can do I generated some fake data and made an example of the sort of plot that might be helpful to you: ```r # fake data leaf <- data.frame(tree.id = rep(1:50, each = 3), city = rep(c("Jackson", "Augusta", "Atlanta"), each = 50), plot = rep(1:6, each = 25)) # I'll make the average of width different for each plot leaf$width <- rnorm(nrow(leaf), leaf$plot, 1) # plotting the data library(ggplot2) # this is a great library for plotting in R ggplot(leaf, aes(x = factor(plot), y = width, color = factor(plot))) + facet_grid(~city, scales = 'free_x') + # This creates a subplot for each city geom_boxplot() + geom_point(position = "jitter") + theme_bw() ``` ![](https://i.stack.imgur.com/qbG6c.png) In this plot I added the points (the leaf widths for each individual tree) but I 'jittered' them, meaning perturbing their position slightly so that they do not pile up on top of each other and are all visible. You could remove this if you liked. Exploratory data analysis should be fun! And I think visualization is a good place to start when beginning in statistics. Hopefully this will prove helpful to you. Upvotes: 2 [selected_answer]<issue_comment>username_2: ``` leaf.width.model <- lme(width ~ city*plot, (1|tree.id), data=leaf) ``` In this model if you want to plot something, you are probably trying to answer: How much is the average leaf width for all trees in each city for each type of plot. To show this information in a figure, you need to plot `width` on y axis plot `plot`(high and low nitrogen) on x axis and group the data by `city`. Then you will get the 3 lines you are taking about. However, you need to get the average width in each group as you only want to show city variation. To get this plot from raw data: (Using fake data provided by username_1) ``` set.seed(100) leaf <- data.frame(tree.id = rep(1:50, each = 3), city = rep(c("Jackson", "Augusta", "Atlanta"), each = 50), plot = rep(c(1, 0), each = 25)) # I'll make the average of width different for each plot leaf$width <- rnorm(nrow(leaf), leaf$plot, 1) library(plotly) library(tidyverse) leaf %>% group_by(city,plot) %>% summarise(avwidth = mean(width, na.rm=T), avsd = 1.96*sd(width, na.rm=T)/sqrt(25)) %>% plot_ly(x = ~plot, y = ~avwidth, color= ~city, type="scatter", mode="markers+lines", error_y = ~list(array=avsd) ) ``` ![](https://i.stack.imgur.com/82qwH.png) Upvotes: 0
2018/03/22
401
1,040
<issue_start>username_0: I have a list inside a table, I want to align this list to the right, it sounds easy, but some reason is not working. This is my code: ```css ul { list-style: none; } td{ vertical-align: top; width:300px } .ri{ background-color:#AAA; text-align:right; } ``` ```html | | | | --- | --- | | Equipo | * CA046 * CA047 * CA055 * CA056 | ``` On jsfiddle: <https://jsfiddle.net/aftc6vq8/7/> Why is not working? How to fix it?<issue_comment>username_1: You've forced your list to be 140px wide, so it only makes it halfway across the cell. Change this line to this Upvotes: -1 <issue_comment>username_2: `text-align` does not align block level elements like a `ul` Change it's display to `inline-block` ```css ul { list-style: none; display: inline-block; } td { vertical-align: top; width: 300px } .ri { background-color: #AAA; text-align: right; } ``` ```html | | | | --- | --- | | Equipo | * CA046 * CA047 * CA055 * CA056 | ``` Upvotes: 3 [selected_answer]
2018/03/22
366
1,196
<issue_start>username_0: I have a form in which a unique class is set for one option: ``` One Two ``` When I connect `selectmenu` ``` $('#mylist').selectmenu(); ``` Class in new `selectmenu` object disappears (does not appear) ``` - Two ``` How to fix it? I want ``` - Two ``` OR ``` - Two ```<issue_comment>username_1: In jquery-ui `.selectmenu()` we can specify additional classes to add to the widget's elements. You may find code example at their [documentation here.](http://api.jqueryui.com/selectmenu/#option-classes) Hope this helps. Upvotes: 0 <issue_comment>username_2: You can overwrite [\_renderMenu()](http://api.jqueryui.com/selectmenu/#method-_renderMenu): ```js $('#mylist').selectmenu().data("ui-selectmenu")._renderMenu = function(ul, items) { var that = this; items.forEach(function(ele, idx) { var li = that._renderItemData(ul, ele); if (ele.element.get(0).classList.length>0) { // preserve original classes... li.addClass(ele.element.get(0).classList.value); } }); }; ``` ```css .my_element { background-color: red; } ``` ```html One Two ``` Upvotes: 3 [selected_answer]
2018/03/22
656
2,313
<issue_start>username_0: I want my SAPUI5 ODataModel to send OData requests of the form ``` https:////?search='lalaland' ``` There are tons of examples how to add a filter with `model.filter(new Filter(...));` but this is *not* what I want. Filtering means I directly address a certain property with a certain comparator. Searching means I address the resource in general and let the OData service decide which properties to search, and how. The one thing that seems to be possible is: ``` model.bindRows(..., { "customData": {"search": "lalaland"}}); ``` But this is also not what I want because that sets the search term once when the model is created, but cannot update it later on when the user enters. Funnily, SAPUI5's own implementation of the SmartTable performs exactly the kind of query I want - but doesn't reveal a possibility how I could do that without a SmartTable.<issue_comment>username_1: Found one solution: ``` oList = this.byId("list"); // or oTable oBindingInfo = oList.getBindingInfo("items"); // or "rows" if (!oBindingInfo.parameters) { oBindingInfo.parameters = {}; } if (!oBindingInfo.parameters.custom) { oBindingInfo.parameters.custom = {}; } oBindingInfo.parameters.custom.search = sValue; oList.bindItems(oBindingInfo); ``` However, I don't specifically like the `bindItems` part. Looks a bit over-the-top to require this to re-bind the whole entity set again and again. So leaving this question open in case somebody has a better idea. Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use on bindItems or bindRows depending what control is, something like this: ``` oList = this.byId("list"); oList.bindItems({path: '/XXXX', parameters : {custom: {'search':'searchstring'}}}) ``` Upvotes: 0 <issue_comment>username_3: Why does it has to be $search and not $filter? The [OData V4 Tutorial](https://sapui5nightly.int.sap.hana.ondemand.com/#/topic/426ff318051a465191c861b51a74f00e) in SAPUI5's Demo Kit uses ``` onSearch : function () { var oView = this.getView(), sValue = oView.byId("searchField").getValue(), oFilter = new Filter("LastName", FilterOperator.Contains, sValue); oView.byId("peopleList").getBinding("items").filter(oFilter, FilterType.Application); }, ``` Upvotes: 0
2018/03/22
1,466
4,197
<issue_start>username_0: I have been searching everywhere for something equivalent of the following to PyTorch, but I cannot find anything. ``` L_1 = np.tril(np.random.normal(scale=1., size=(D, D)), k=0) L_1[np.diag_indices_from(L_1)] = np.exp(np.diagonal(L_1)) ``` I guess there is no way to replace the diagonal elements in such an elegant way using Pytorch.<issue_comment>username_1: I do not think that such a functionality is implemented as of now. But, you can implement the same functionality using `mask` as follows. ``` # Assuming v to be the vector and a be the tensor whose diagonal is to be replaced mask = torch.diag(torch.ones_like(v)) out = mask*torch.diag(v) + (1. - mask)*a ``` So, your implementation will be something like ``` L_1 = torch.tril(torch.randn((D, D))) v = torch.exp(torch.diag(L_1)) mask = torch.diag(torch.ones_like(v)) L_1 = mask*torch.diag(v) + (1. - mask)*L_1 ``` Not as elegant as numpy, but not too bad either. Upvotes: 3 [selected_answer]<issue_comment>username_2: **There is an easier way to do it** ``` dest_matrix[range(len(dest_matrix)), range(len(dest_matrix))] = source_vector ``` In fact we have to generate diagonal indices ourselves. **Usage example:** ``` dest_matrix = torch.randint(10, (3, 3)) source_vector = torch.randint(100, 200, (len(dest_matrix), )) print('dest_matrix:\n', dest_matrix) print('source_vector:\n', source_vector) dest_matrix[range(len(dest_matrix)), range(len(dest_matrix))] = source_vector print('result:\n', dest_matrix) # dest_matrix: # tensor([[3, 2, 5], # [0, 3, 5], # [3, 1, 1]]) # source_vector: # tensor([182, 169, 147]) # result: # tensor([[182, 2, 5], # [ 0, 169, 5], # [ 3, 1, 147]]) ``` in case `dest_matrix` is not square you have to take `min(dest_matrix.size())` instead of `len(dest_matrix)` in `range()` Not as elegant as `numpy` but this doesn't require to store a new matrix of indices. And yes, **this preserves gradients** Upvotes: 2 <issue_comment>username_3: You can extract the diagonal elements with `diagonal()`, and then assign the transformed values inplace with [`copy_()`](https://discuss.pytorch.org/t/replace-diagonal-elements-with-vector/15311/49?u=username_3): ```py new_diags = L_1.diagonal().exp() L_1.diagonal().copy_(new_diags) ``` Upvotes: 2 <issue_comment>username_4: For simplicity, let's say you have a matrix `L_1` and want to replace it's diagonal with zeros. You can do this in multiple ways. Using `fill_diagonal_()`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) L_1 = L_1.fill_diagonal_(0.) ``` Using advanced indexing: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) length = len(L_1) zero_vector = torch.zeros(length, dtype=torch.float32) L_1[range(length), range(length)] = zero_vector ``` Using `scatter_()`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) diag_idx = torch.arange(len(L_1)).unsqueeze(1) zero_matrix = torch.zeros(L_1.shape, dtype=torch.float32) L_1 = L_1.scatter_(1, diag_idx, zero_matrix) ``` Note that all of the above solutions are in-place operations and will affect the backward pass, because the original value might be needed to compute it. So if you want to keep the backward pass unaffected, meaning to "break the graph" by not recording the change (operation), meaning not computing the gradients in the backward pass corresponding to what you computed in the forward pass, then you can just add the `.data` when using advanced indexing or `scatter_()`. Using advanced indexing with `.data`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) length = len(L_1) zero_vector = torch.zeros(length, dtype=torch.float32) L_1[range(length), range(length)] = zero_vector.data ``` Using `scatter_()` with `.data`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) diag_idx = torch.arange(len(L_1)).unsqueeze(1) zero_matrix = torch.zeros(L_1.shape, dtype=torch.float32) L_1 = L_1.scatter_(1, diag_idx, zero_matrix.data) ``` For reference check out [this](https://discuss.pytorch.org/t/replace-diagonal-elements-with-vector/15311) discussion. Upvotes: 0
2018/03/22
1,675
5,077
<issue_start>username_0: I am working on an AR app for which I am placing one **3D model** in front of the device **without horizontal surface detection**. Based on this 3D model's **transform**, I creating **ARAnchor** object. [ARAnchor](https://developer.apple.com/documentation/arkit/aranchor) objects are useful to track real world objects and 3D objects in **ARKit**. Code to place **ARAnchor**: ``` ARAnchor* anchor = [[ARAnchor alloc] initWithTransform:3dModel.simdTransform]; // simd transform of the 3D model [self.sceneView.session addAnchor:anchor]; ``` **Issue**: Sometimes, I found that the 3D model starts moving in random direction without stopping. **Questions**: 1. Is my code to create ARAnchor is correct? If no, what is the correct way to create an anchor? 2. Are there any known problems with ARKit where objects starts moving? If yes, is there a way to fix it? I would appreciate any suggestions and thoughts on this topic. **EDIT:** I am placing the 3D object when the AR tracking state in **normal**. The 3D object is placed (without horizontal surface detection) when the user taps on the screen. As soon as the 3D model is placed, the model starts moving without stopping, even if the device is not moving.<issue_comment>username_1: I do not think that such a functionality is implemented as of now. But, you can implement the same functionality using `mask` as follows. ``` # Assuming v to be the vector and a be the tensor whose diagonal is to be replaced mask = torch.diag(torch.ones_like(v)) out = mask*torch.diag(v) + (1. - mask)*a ``` So, your implementation will be something like ``` L_1 = torch.tril(torch.randn((D, D))) v = torch.exp(torch.diag(L_1)) mask = torch.diag(torch.ones_like(v)) L_1 = mask*torch.diag(v) + (1. - mask)*L_1 ``` Not as elegant as numpy, but not too bad either. Upvotes: 3 [selected_answer]<issue_comment>username_2: **There is an easier way to do it** ``` dest_matrix[range(len(dest_matrix)), range(len(dest_matrix))] = source_vector ``` In fact we have to generate diagonal indices ourselves. **Usage example:** ``` dest_matrix = torch.randint(10, (3, 3)) source_vector = torch.randint(100, 200, (len(dest_matrix), )) print('dest_matrix:\n', dest_matrix) print('source_vector:\n', source_vector) dest_matrix[range(len(dest_matrix)), range(len(dest_matrix))] = source_vector print('result:\n', dest_matrix) # dest_matrix: # tensor([[3, 2, 5], # [0, 3, 5], # [3, 1, 1]]) # source_vector: # tensor([182, 169, 147]) # result: # tensor([[182, 2, 5], # [ 0, 169, 5], # [ 3, 1, 147]]) ``` in case `dest_matrix` is not square you have to take `min(dest_matrix.size())` instead of `len(dest_matrix)` in `range()` Not as elegant as `numpy` but this doesn't require to store a new matrix of indices. And yes, **this preserves gradients** Upvotes: 2 <issue_comment>username_3: You can extract the diagonal elements with `diagonal()`, and then assign the transformed values inplace with [`copy_()`](https://discuss.pytorch.org/t/replace-diagonal-elements-with-vector/15311/49?u=username_3): ```py new_diags = L_1.diagonal().exp() L_1.diagonal().copy_(new_diags) ``` Upvotes: 2 <issue_comment>username_4: For simplicity, let's say you have a matrix `L_1` and want to replace it's diagonal with zeros. You can do this in multiple ways. Using `fill_diagonal_()`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) L_1 = L_1.fill_diagonal_(0.) ``` Using advanced indexing: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) length = len(L_1) zero_vector = torch.zeros(length, dtype=torch.float32) L_1[range(length), range(length)] = zero_vector ``` Using `scatter_()`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) diag_idx = torch.arange(len(L_1)).unsqueeze(1) zero_matrix = torch.zeros(L_1.shape, dtype=torch.float32) L_1 = L_1.scatter_(1, diag_idx, zero_matrix) ``` Note that all of the above solutions are in-place operations and will affect the backward pass, because the original value might be needed to compute it. So if you want to keep the backward pass unaffected, meaning to "break the graph" by not recording the change (operation), meaning not computing the gradients in the backward pass corresponding to what you computed in the forward pass, then you can just add the `.data` when using advanced indexing or `scatter_()`. Using advanced indexing with `.data`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) length = len(L_1) zero_vector = torch.zeros(length, dtype=torch.float32) L_1[range(length), range(length)] = zero_vector.data ``` Using `scatter_()` with `.data`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) diag_idx = torch.arange(len(L_1)).unsqueeze(1) zero_matrix = torch.zeros(L_1.shape, dtype=torch.float32) L_1 = L_1.scatter_(1, diag_idx, zero_matrix.data) ``` For reference check out [this](https://discuss.pytorch.org/t/replace-diagonal-elements-with-vector/15311) discussion. Upvotes: 0
2018/03/22
1,438
4,165
<issue_start>username_0: I am looking to change the image header height on my WordPress site, I am using The Company theme, but I can't seem to figure out the CSSrequired [My site](http://www.thepowerwithin.org.uk/what-we-offer/) As you can see there is a clouds image in the header I would like this to go further down the page.<issue_comment>username_1: I do not think that such a functionality is implemented as of now. But, you can implement the same functionality using `mask` as follows. ``` # Assuming v to be the vector and a be the tensor whose diagonal is to be replaced mask = torch.diag(torch.ones_like(v)) out = mask*torch.diag(v) + (1. - mask)*a ``` So, your implementation will be something like ``` L_1 = torch.tril(torch.randn((D, D))) v = torch.exp(torch.diag(L_1)) mask = torch.diag(torch.ones_like(v)) L_1 = mask*torch.diag(v) + (1. - mask)*L_1 ``` Not as elegant as numpy, but not too bad either. Upvotes: 3 [selected_answer]<issue_comment>username_2: **There is an easier way to do it** ``` dest_matrix[range(len(dest_matrix)), range(len(dest_matrix))] = source_vector ``` In fact we have to generate diagonal indices ourselves. **Usage example:** ``` dest_matrix = torch.randint(10, (3, 3)) source_vector = torch.randint(100, 200, (len(dest_matrix), )) print('dest_matrix:\n', dest_matrix) print('source_vector:\n', source_vector) dest_matrix[range(len(dest_matrix)), range(len(dest_matrix))] = source_vector print('result:\n', dest_matrix) # dest_matrix: # tensor([[3, 2, 5], # [0, 3, 5], # [3, 1, 1]]) # source_vector: # tensor([182, 169, 147]) # result: # tensor([[182, 2, 5], # [ 0, 169, 5], # [ 3, 1, 147]]) ``` in case `dest_matrix` is not square you have to take `min(dest_matrix.size())` instead of `len(dest_matrix)` in `range()` Not as elegant as `numpy` but this doesn't require to store a new matrix of indices. And yes, **this preserves gradients** Upvotes: 2 <issue_comment>username_3: You can extract the diagonal elements with `diagonal()`, and then assign the transformed values inplace with [`copy_()`](https://discuss.pytorch.org/t/replace-diagonal-elements-with-vector/15311/49?u=username_3): ```py new_diags = L_1.diagonal().exp() L_1.diagonal().copy_(new_diags) ``` Upvotes: 2 <issue_comment>username_4: For simplicity, let's say you have a matrix `L_1` and want to replace it's diagonal with zeros. You can do this in multiple ways. Using `fill_diagonal_()`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) L_1 = L_1.fill_diagonal_(0.) ``` Using advanced indexing: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) length = len(L_1) zero_vector = torch.zeros(length, dtype=torch.float32) L_1[range(length), range(length)] = zero_vector ``` Using `scatter_()`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) diag_idx = torch.arange(len(L_1)).unsqueeze(1) zero_matrix = torch.zeros(L_1.shape, dtype=torch.float32) L_1 = L_1.scatter_(1, diag_idx, zero_matrix) ``` Note that all of the above solutions are in-place operations and will affect the backward pass, because the original value might be needed to compute it. So if you want to keep the backward pass unaffected, meaning to "break the graph" by not recording the change (operation), meaning not computing the gradients in the backward pass corresponding to what you computed in the forward pass, then you can just add the `.data` when using advanced indexing or `scatter_()`. Using advanced indexing with `.data`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) length = len(L_1) zero_vector = torch.zeros(length, dtype=torch.float32) L_1[range(length), range(length)] = zero_vector.data ``` Using `scatter_()` with `.data`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) diag_idx = torch.arange(len(L_1)).unsqueeze(1) zero_matrix = torch.zeros(L_1.shape, dtype=torch.float32) L_1 = L_1.scatter_(1, diag_idx, zero_matrix.data) ``` For reference check out [this](https://discuss.pytorch.org/t/replace-diagonal-elements-with-vector/15311) discussion. Upvotes: 0
2018/03/22
1,476
4,320
<issue_start>username_0: What does the constraint Required do in the form builder? If a field was not submitted (not empty value!), I don't receive a corresponding error message. This field is just ignored. ``` $builder ->add('firstname', TextType::class, [ 'constraints' => [new NotBlank()], 'required'=>true]) ->add('lastname', TextType::class, [ 'constraints' => [new NotBlank(),] ,'required'=>true]) ``` How can say, that the field always MUST be submitted? Thank you.<issue_comment>username_1: I do not think that such a functionality is implemented as of now. But, you can implement the same functionality using `mask` as follows. ``` # Assuming v to be the vector and a be the tensor whose diagonal is to be replaced mask = torch.diag(torch.ones_like(v)) out = mask*torch.diag(v) + (1. - mask)*a ``` So, your implementation will be something like ``` L_1 = torch.tril(torch.randn((D, D))) v = torch.exp(torch.diag(L_1)) mask = torch.diag(torch.ones_like(v)) L_1 = mask*torch.diag(v) + (1. - mask)*L_1 ``` Not as elegant as numpy, but not too bad either. Upvotes: 3 [selected_answer]<issue_comment>username_2: **There is an easier way to do it** ``` dest_matrix[range(len(dest_matrix)), range(len(dest_matrix))] = source_vector ``` In fact we have to generate diagonal indices ourselves. **Usage example:** ``` dest_matrix = torch.randint(10, (3, 3)) source_vector = torch.randint(100, 200, (len(dest_matrix), )) print('dest_matrix:\n', dest_matrix) print('source_vector:\n', source_vector) dest_matrix[range(len(dest_matrix)), range(len(dest_matrix))] = source_vector print('result:\n', dest_matrix) # dest_matrix: # tensor([[3, 2, 5], # [0, 3, 5], # [3, 1, 1]]) # source_vector: # tensor([182, 169, 147]) # result: # tensor([[182, 2, 5], # [ 0, 169, 5], # [ 3, 1, 147]]) ``` in case `dest_matrix` is not square you have to take `min(dest_matrix.size())` instead of `len(dest_matrix)` in `range()` Not as elegant as `numpy` but this doesn't require to store a new matrix of indices. And yes, **this preserves gradients** Upvotes: 2 <issue_comment>username_3: You can extract the diagonal elements with `diagonal()`, and then assign the transformed values inplace with [`copy_()`](https://discuss.pytorch.org/t/replace-diagonal-elements-with-vector/15311/49?u=username_3): ```py new_diags = L_1.diagonal().exp() L_1.diagonal().copy_(new_diags) ``` Upvotes: 2 <issue_comment>username_4: For simplicity, let's say you have a matrix `L_1` and want to replace it's diagonal with zeros. You can do this in multiple ways. Using `fill_diagonal_()`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) L_1 = L_1.fill_diagonal_(0.) ``` Using advanced indexing: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) length = len(L_1) zero_vector = torch.zeros(length, dtype=torch.float32) L_1[range(length), range(length)] = zero_vector ``` Using `scatter_()`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) diag_idx = torch.arange(len(L_1)).unsqueeze(1) zero_matrix = torch.zeros(L_1.shape, dtype=torch.float32) L_1 = L_1.scatter_(1, diag_idx, zero_matrix) ``` Note that all of the above solutions are in-place operations and will affect the backward pass, because the original value might be needed to compute it. So if you want to keep the backward pass unaffected, meaning to "break the graph" by not recording the change (operation), meaning not computing the gradients in the backward pass corresponding to what you computed in the forward pass, then you can just add the `.data` when using advanced indexing or `scatter_()`. Using advanced indexing with `.data`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) length = len(L_1) zero_vector = torch.zeros(length, dtype=torch.float32) L_1[range(length), range(length)] = zero_vector.data ``` Using `scatter_()` with `.data`: ``` L_1 = torch.tensor([[1,2,3],[4,5,6],[7,8,9]], dtype=torch.float32) diag_idx = torch.arange(len(L_1)).unsqueeze(1) zero_matrix = torch.zeros(L_1.shape, dtype=torch.float32) L_1 = L_1.scatter_(1, diag_idx, zero_matrix.data) ``` For reference check out [this](https://discuss.pytorch.org/t/replace-diagonal-elements-with-vector/15311) discussion. Upvotes: 0
2018/03/22
633
2,128
<issue_start>username_0: I have built a query with a few condition statements added on. They all work fine, but when I type to had a limit option, I only get errors. So I am using go 1.10 with Gorm and the Gin framework. This is my current working code, ``` qb := myDB.Table("table").Select("xx, xxx, xxx, xxx") rows, err := qb.Rows() if err != nil { fmt.Println(err) } defer myDB.Close() return rows ``` This is all working, but when I add a limit anywhere, e.g. before the table or after, I tried both but did not really think it made a difference? For example, ``` qb := myDB.Table("table").Limit(3).Select("xx, xxx, xxx, xxx") ``` Now I know MS SQL does not use limit but uses TOP within the select statement (forgive me if that is not the only use case, still not used MS SQL much). The error I get back is, ``` mssql: Invalid usage of the option NEXT in the FETCH statement. ``` Now I have found the following on Gorm's GitHub, <https://github.com/jinzhu/gorm/issues/1205> They have a work around but that will not work for me. The guy has also posted an updated function to correct the issue. However, I am not sure how I could update the code in a third party lib. Also this was posted in 2016, so not sure if that code has already been added to the Gorm code base.<issue_comment>username_1: You need an `Order By` to use OFFSET + FETCH in the generated SQL sent to SQL Server, which would be added by your ORM > > ...the following conditions must be met: > > > ... > > > The ORDER BY clause contains a column or combination of columns that > are guaranteed to be unique. > > > How GORM does it, I don't know Upvotes: 1 <issue_comment>username_2: I am posting this as an answer, i am guesting its more a work around and please let me know if this not recommend for any reason. My working solution, ``` qb := myDB.Table("table").Select("TOP(?) xx, xxx, xxx, xxx", 3) ``` Thanks Upvotes: 0 <issue_comment>username_3: I'm facing similar issue. Got it working by adding .Order like this: ``` qb := db.Table("tableName").Order("columnName").Limit(2).Select("col1, col2") ``` Upvotes: 0
2018/03/22
671
2,336
<issue_start>username_0: I am trying to start uiautomatorviewer from default sdk installed location using terminal (Ubuntu 16) : ``` >abc@abc:~/Android/Sdk/tools/bin$ ./uiautomatorviewer ``` and I am getting an error as below : **Error** ``` -Djava.ext.dirs=/home/mukesh/Android/Sdk/tools/lib/x86_64: /home/abc/Android/Sdk/tools/lib is not supported.Use -classpath instead. Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit. ``` Till yesterday things are working fine for me . So , far I tried looking into the post [unable to start uiautomatorviewer](https://stackoverflow.com/questions/18658322/unable-to-start-uiautomatorviewer) but what I am getting is a different error , Forgive me but I am a newbie to this and absolutely no idea of what went wrong in one day , Any help to resolve the error would be highly appreciated .<issue_comment>username_1: Finally I was able to find out a solution , so just posting the same for other's reference : Downgrading the Java version from 9 to 8 resolved the issue : Command Used : ``` sudo update-alternatives --config java ``` This is list out the version installed like this with \* on the selected version : ``` Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-9-openjdk-amd64/bin/java 1091 auto mode * 1 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1081 manual mode 2 /usr/lib/jvm/java-9-openjdk-amd64/bin/java 1091 manual mode Press to keep the current choice[\*], or type selection number: ``` Enter here the number 1 as we need version 8 . Thats's all done , rerun uiautomatorviewer . EDIT: If You see something like "you don't have any alternatives" try donwloading openjdk-8 from the link below (for linux) [Install open jdk-8](https://docs.datastax.com/en/jdk-install/doc/jdk-install/installOpenJdkDeb.html) Upvotes: 5 [selected_answer]<issue_comment>username_2: for the record, `uiautomatorviewer` requires java8 and if your system doesn have it, then you need to install it. for ubuntu, do the following as root, ``` apt-get install openjdk-8-jdk update-alternatives --config java #choose java8 ``` Upvotes: 2
2018/03/22
570
2,350
<issue_start>username_0: I would like to register my AuthenticationGuard, which checks for Authentication, globally on my application, so that by default all routes require authentication. ``` const authGuard = app .select(AuthModule) .get(AuthGuard); app.useGlobalGuards(authGuard); ``` What is the best/nest.js way to add route exceptions, so that anonymous routes can also be implemented?<issue_comment>username_1: There is no way to configure such behavior in a succinct way. If `useGlobalGuards` used, the only way to do this is to customize or extend `AuthGuard`. [See original issue](https://github.com/nestjs/nest/issues/964#issuecomment-413563009) Upvotes: 4 [selected_answer]<issue_comment>username_2: You can actually set metadata for the global `AuthGuard` so it can determine if it should allow an unauthorized request. e.g. Set Global Auth Guard ```js import { Module } from '@nestjs/common'; import { APP_GUARD } from '@nestjs/core'; import { AuthGuard } from './auth.guard'; @Module({ providers: [ { provide: APP_GUARD, useClass: AuthGuard, }, ], }) export class AppModule {} ``` Use `SetMetadata` to pass in data to the `AuthGuard` ```js import { SetMetadata } from '@nestjs/common'; // Convienience Function const AllowUnauthorizedRequest = () => SetMetadata('allowUnauthorizedRequest', true); @Controller() export class AppController { @Get('my-unauthorized-path') @AllowUnauthorizedRequest() myHandler () { return { unauthorized: true }; } } ``` Use data passed in from `SetMetadata` to determine if unauthorized request is allowed. ```js import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { validateRequest } from './validateRequest' // your custom implementation @Injectable() export class AuthGuard implements CanActivate { constructor(private reflector: Reflector) {} canActivate(context: ExecutionContext) { const request = context.switchToHttp().getRequest(); const allowUnauthorizedRequest = this.reflector.get('allowUnauthorizedRequest', context.getHandler()); return allowUnauthorizedRequest || validateRequest(request); } } ``` Upvotes: 5
2018/03/22
1,591
5,036
<issue_start>username_0: I am stumped on a problem. This problem requires involves a clue which has missing letters. There is an array of words that are to be matched against the clue, however, the word should only match if it does not already have a letter from the clue. I am using a regex and it is matching all instances of the match but I can't figure out how to exclude the ones that have a repeating letter in the word list. e.g., clue is `aba???` therefore, `abaton` should match, but `abatua` should not as there is an `a` in both words and the clue part that is masked by the `???` Here is my code: ``` import java.util.ArrayList; public class MatchTest { public ArrayList wordLookup(ArrayList wordList, String clue) { ArrayList arrayList = new ArrayList<>(); String regex = clue.replaceAll("\\?", "\\.?"); for (int i = 0; i < wordList.size(); i++) { if (wordList.get(i).matches(regex)) { arrayList.add(wordList.get(i)); } } return arrayList; } } class MatchTestMain { public static void main(String[] args) { MatchTest mt = new MatchTest(); ArrayList wordList = new ArrayList(); wordList.add("abandon"); wordList.add("wanton"); wordList.add("abaton"); wordList.add("abator"); wordList.add("abatua"); System.out.println(mt.wordLookup(wordList, "aba???")); } } ``` I am getting this output ``` [abaton, abator, abatua] ``` But the correct output would be ``` [abaton, abator] ``` Any ideas? Edit for completeness: I found an edge case where the clue is all ?, e.g., clue is ??????, it would cause an Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character [^] I extended the solution proposed by @<NAME> to account for the edge case. Here is the final version: ``` import java.util.ArrayList; public class MatchTest { public ArrayList wordLookup(ArrayList wordList, String clue) { ArrayList arrayList = new ArrayList<>(); String givenLetters = clue.replaceAll("\\?", ""); String regex = clue.replaceAll("\\?", "\\[^" + givenLetters + "]"); String regex2 = clue.replaceAll("\\?", "\\.?"); if (givenLetters.length() == 0) { for (int i = 0; i < wordList.size(); i++) { if (wordList.get(i).matches(regex2) && wordList.get(i).length() == clue.length()) { arrayList.add(wordList.get(i)); } } } if (givenLetters.length() > 0) { for (int i = 0; i < wordList.size(); i++) { if (wordList.get(i).matches(regex)) { arrayList.add(wordList.get(i)); } } } return arrayList; } } class MatchTestMain { public static void main(String[] args) { MatchTest mt = new MatchTest(); ArrayList wordList = new ArrayList<>(); wordList.add("abandon"); wordList.add("wanton"); wordList.add("abaton"); wordList.add("abator"); wordList.add("abatua"); System.out.println(mt.wordLookup(wordList, "ab??o?")); System.out.println(mt.wordLookup(wordList, "?b????")); System.out.println(mt.wordLookup(wordList, "abatua")); System.out.println(mt.wordLookup(wordList, "a?a???")); System.out.println(mt.wordLookup(wordList, "?ridge")); System.out.println(mt.wordLookup(wordList, "aba???")); System.out.println(mt.wordLookup(wordList, "??????")); } } ``` output: ``` [] [abaton, abator, abatua] [abatua] [abaton, abator] [] [abaton, abator] [wanton, abaton, abator, abatua] ```<issue_comment>username_1: You can first extract a list of letters that are given in the clue: ``` String givenLetters = clue.replaceAll("\\?", ""); // givenLetters = "aba" ``` If you use that list in your regex, you can tell the masked char **not** to be one of those given letters: ``` String regex = clue.replaceAll("\\?", "\\[^" + givenLetters + "]"); // regex = "aba[^aba][^aba][^aba]"; ``` This replaces your `.?` by `[^aba]` in your example, meaning "anything not `a` or `b`" (or `a`, which is irrelevant in this case). It should also work for clues that do not just have `?` at the end, like `??a?b?`, which would result in `pattern = [^ab][^ab]a[^ab]b[^ab]`. Upvotes: 3 [selected_answer]<issue_comment>username_2: did some changes in your program..it is giving required output package testProgram; ``` import java.util.ArrayList; class MatchTest { public ArrayList wordLookup(ArrayList wordList, String clue) { ArrayList arrayList = new ArrayList<>(); // String regex = clue.replaceAll("\\?", "\\.?"); for (int i = 0; i < wordList.size(); i++) { if (wordList.get(i).matches(clue)) { arrayList.add(wordList.get(i)); } } return arrayList; } } public class MatchTestMain { public static void main(String[] args) { MatchTest mt = new MatchTest(); ArrayList wordList = new ArrayList(); wordList.add("abandon"); wordList.add("wanton"); wordList.add("abaton"); wordList.add("abator"); wordList.add("abatua"); System.out.println(mt.wordLookup(wordList, "(aba)[^aba]{0,3}")); } } ``` (aba)[^aba]{0,3} means first 3 chars will remain constant (aba) rest 0-3 chars will not contains any character from these 3 i.e. (aba). {0,3} means at least 0 and at most 3 char. Upvotes: -1
2018/03/22
880
3,173
<issue_start>username_0: I was following several different Web Sites explaining how to use RetryAnalyzer (they all say basically the same thing, but I checked several to see whether there was any difference). I implemented as they did in the samples, and deliberately caused a failure the first run (which ended up being the only run). Even though it failed, the test was not repeated. I even put a breakpoint inside the analyzer at the first line (res = false). which never got hit. I tell it to try 3 times but it did not retry at all. Am I missing something? My sample is below: Is it something to do with setting counter = 0? But the "res = false" at least should get hit? ``` public class RetryAnalyzer implements IRetryAnalyzer { int counter = 0; @Override public boolean retry(ITestResult result) { boolean res = false; if (!result.isSuccess() && counter < 3) { counter++; res = true; } return res; } } ``` and ``` @Test(dataProvider = "dp", retryAnalyzer = RetryAnalyzer.class) public void testA(TestContext tContext) throws IOException { genericTest("A", "83701"); } ``` The test usually passes. I deliberately caused it to fail but it did not do a retry. Am I missing something? =============================================== Default suite Total tests run: 1, Failures: 1, Skips: 0 =========================================<issue_comment>username_1: You can first extract a list of letters that are given in the clue: ``` String givenLetters = clue.replaceAll("\\?", ""); // givenLetters = "aba" ``` If you use that list in your regex, you can tell the masked char **not** to be one of those given letters: ``` String regex = clue.replaceAll("\\?", "\\[^" + givenLetters + "]"); // regex = "aba[^aba][^aba][^aba]"; ``` This replaces your `.?` by `[^aba]` in your example, meaning "anything not `a` or `b`" (or `a`, which is irrelevant in this case). It should also work for clues that do not just have `?` at the end, like `??a?b?`, which would result in `pattern = [^ab][^ab]a[^ab]b[^ab]`. Upvotes: 3 [selected_answer]<issue_comment>username_2: did some changes in your program..it is giving required output package testProgram; ``` import java.util.ArrayList; class MatchTest { public ArrayList wordLookup(ArrayList wordList, String clue) { ArrayList arrayList = new ArrayList<>(); // String regex = clue.replaceAll("\\?", "\\.?"); for (int i = 0; i < wordList.size(); i++) { if (wordList.get(i).matches(clue)) { arrayList.add(wordList.get(i)); } } return arrayList; } } public class MatchTestMain { public static void main(String[] args) { MatchTest mt = new MatchTest(); ArrayList wordList = new ArrayList(); wordList.add("abandon"); wordList.add("wanton"); wordList.add("abaton"); wordList.add("abator"); wordList.add("abatua"); System.out.println(mt.wordLookup(wordList, "(aba)[^aba]{0,3}")); } } ``` (aba)[^aba]{0,3} means first 3 chars will remain constant (aba) rest 0-3 chars will not contains any character from these 3 i.e. (aba). {0,3} means at least 0 and at most 3 char. Upvotes: -1
2018/03/22
319
1,204
<issue_start>username_0: Are there any existing services which could help built a simple server for a Unity game? All I want is to make an app to request and receive an image and some text from the web and show it to users. So when I change the image and the text on the server side, all my apps will display new pic and text. Thank you<issue_comment>username_1: For what you are asking for is just a http server, you can connect to you server using the [WWW Class](https://docs.unity3d.com/ScriptReference/WWW.html) Upvotes: 1 <issue_comment>username_2: You can simply place your image and the text you want on a standard webserver, then you can use Unity's WWW class to access it. For example, "<http://example.com/unitygametext.txt>" and "<http://example.com/image.png>". Unity's documentation has [some examples on how to get textures and text](https://docs.unity3d.com/ScriptReference/WWW-texture.html): ``` IEnumerator Start() { using (WWW www = new WWW("http://example.com/image.png")) { yield return www; Renderer renderer = GetComponent(); renderer.material.mainTexture = www.texture; } } ``` For text you just have to replace `WWW.texture` with `WWW.text`. Upvotes: 2
2018/03/22
361
1,726
<issue_start>username_0: I am using Firebase to send remote push notification for an iOS app. Now I need to show only badge in app icon without alert when app is not running. Is it possible to implement something like that? Thank you<issue_comment>username_1: Request `UIUserNotificationTypeBadge` permission only when you set permissions in `didFinishLaunchingWithOptions` Remove `.alert` ``` func requestNotificationAuthorization(application: UIApplication) { if #available(iOS 10.0, *) { UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.badge] UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in }) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.badge], categories: nil) application.registerUserNotificationSettings(settings) } } ``` Upvotes: 1 <issue_comment>username_2: You should set the notification setting options to `.badge` only when you request notifications authorization from user: ``` let notificationCenter = UNUserNotificationCenter.current() notificationCenter.requestAuthorization(options: [.badge], completionHandler: { [weak self] success, error in guard success else { guard error == nil else { print("Error occured while requesting push notification permission. In \(#function)") print("Error: \(error!.localizedDescription)") return } print("User has denied permission to send push notifications") return } print("User has granted permission to send push notifications") } ``` Upvotes: 0
2018/03/22
806
2,566
<issue_start>username_0: I have a string that is comma separated, so it could be `test1, test2, test3` or `test1,test2,test3` or `test1, test2, test3`. I split this in Go currently with `strings.Split(s, ",")`, but now I have a `[]string` that can contain elements with an arbitrary numbers of whitespaces. How can I easily trim them off? What is best practice here? This is my current code ``` var property= os.Getenv(env.templateDirectories) if property != "" { var dirs = strings.Split(property, ",") for index,ele := range dirs { dirs[index] = strings.TrimSpace(ele) } return dirs } ``` I come from Java and assumed that there is a map/reduce etc functionality in Go also, therefore the question.<issue_comment>username_1: You can use `strings.TrimSpace` in a loop. If you want to preserve order too, the indexes can be used rather than values as the loop parameters: [Go Playground Example](https://play.golang.org/p/PUolmtfK1ox) **EDIT:** To see the code without the click: ```golang package main import ( "fmt" "strings" ) func main() { input := "test1, test2, test3" slc := strings.Split(input , ",") for i := range slc { slc[i] = strings.TrimSpace(slc[i]) } fmt.Println(slc) } ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: Easy way without looping ``` test := "2 , 123, 1" result := strings.Split(strings.ReplaceAll(test," ","") , ",") ``` Upvotes: 3 <issue_comment>username_3: The `encoding/csv` package can handle this: ``` package main import ( "encoding/csv" "fmt" "strings" ) func main() { for _, each := range []string{ "test1, test2, test3", "test1, test2, test3", "test1,test2,test3", } { r := csv.NewReader(strings.NewReader(each)) r.TrimLeadingSpace = true s, e := r.Read() if e != nil { panic(e) } fmt.Printf("%q\n", s) } } ``` <https://golang.org/pkg/encoding/csv#Reader.TrimLeadingSpace> Upvotes: 1 <issue_comment>username_4: If you already use `regexp` may be you can split using regular expressions: ```golang regexp.MustCompile(`\s*,\s*`).Split(test, -1) ``` This solution is probably slower than the standard Split + TrimSpaces, but is more flexible. For example if you want to skip empty fields you can : ```golang regexp.MustCompile(`(\s*,\s*)+`).Split(test, -1) ``` or to use multiple separators ```golang regexp.MustCompile(`\s*[,;]\s*`).Split(test, -1) ``` You can test it in [the go playground](https://play.golang.org/p/EKjVwXcAcFn). Upvotes: 0
2018/03/22
654
2,126
<issue_start>username_0: I’m trying to learn react and was wondering where in the react documentation is using a callback function with setstate described? Specifically the part that explains what the arguments to the callback are? The first argument being state and the second being props?<issue_comment>username_1: You can use `strings.TrimSpace` in a loop. If you want to preserve order too, the indexes can be used rather than values as the loop parameters: [Go Playground Example](https://play.golang.org/p/PUolmtfK1ox) **EDIT:** To see the code without the click: ```golang package main import ( "fmt" "strings" ) func main() { input := "test1, test2, test3" slc := strings.Split(input , ",") for i := range slc { slc[i] = strings.TrimSpace(slc[i]) } fmt.Println(slc) } ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: Easy way without looping ``` test := "2 , 123, 1" result := strings.Split(strings.ReplaceAll(test," ","") , ",") ``` Upvotes: 3 <issue_comment>username_3: The `encoding/csv` package can handle this: ``` package main import ( "encoding/csv" "fmt" "strings" ) func main() { for _, each := range []string{ "test1, test2, test3", "test1, test2, test3", "test1,test2,test3", } { r := csv.NewReader(strings.NewReader(each)) r.TrimLeadingSpace = true s, e := r.Read() if e != nil { panic(e) } fmt.Printf("%q\n", s) } } ``` <https://golang.org/pkg/encoding/csv#Reader.TrimLeadingSpace> Upvotes: 1 <issue_comment>username_4: If you already use `regexp` may be you can split using regular expressions: ```golang regexp.MustCompile(`\s*,\s*`).Split(test, -1) ``` This solution is probably slower than the standard Split + TrimSpaces, but is more flexible. For example if you want to skip empty fields you can : ```golang regexp.MustCompile(`(\s*,\s*)+`).Split(test, -1) ``` or to use multiple separators ```golang regexp.MustCompile(`\s*[,;]\s*`).Split(test, -1) ``` You can test it in [the go playground](https://play.golang.org/p/EKjVwXcAcFn). Upvotes: 0
2018/03/22
454
1,517
<issue_start>username_0: I recently started working with Imagemagick and I had a problem that needs to be solved. I have such a thumbnail. ![thumbnail](https://i.stack.imgur.com/KlQZ6.png) And there is such a mask. ![cloud-mask](https://i.stack.imgur.com/7k9a9.png) I need to get this image on the output. ![complete](https://i.stack.imgur.com/RpMbO.png) I looked through this link <http://www.imagemagick.org/Usage/thumbnails/> I tried everything there, but I did not get success (( I hope you will help me.<issue_comment>username_1: In Imagemagick, you should extract the alpha channel of your mask and put that into the alpha channel of your other image. So try (unix syntax) ``` convert KlQZ6.png \( 7k9a9.png -alpha extract \) -alpha off -compose copy_opacity -composite result.png ``` (windows syntax) ``` convert KlQZ6.png ( 7k9a9.png -alpha extract ) -alpha off -compose copy_opacity -composite result.png ``` [![enter image description here](https://i.stack.imgur.com/N6OVN.png)](https://i.stack.imgur.com/N6OVN.png) Upvotes: 0 <issue_comment>username_2: This should give you a result very much like your example... ``` convert mask.png image.png -gravity north -composite \ mask.png -compose copyopacity -composite result.png ``` You can adjust the positioning of the overlay by including something like "-geometry -10+0" before the first composite. To use this command in Windows you'll need to change that continued line backslash "\" to a caret "^". Upvotes: 3 [selected_answer]
2018/03/22
900
2,372
<issue_start>username_0: I want to add the current news article title to my breadcrumb navigation. Following is my output: [![Breadcrumb output](https://i.stack.imgur.com/uSiQo.png)](https://i.stack.imgur.com/uSiQo.png) URL: **Default (German)** index.phpid=19& L=0& tx\_news\_pi1%5Bnews%5D=1& tx\_news\_pi1%5Bcontroller%5D=News& tx\_news\_pi1%5Baction%5D=detail& cHash=b182adf919054989c8d640e1da19f0a2 **English** index.php?id=19& tx\_news\_pi1%5Bnews%5D=1& tx\_news\_pi1%5Bcontroller%5D=News& tx\_news\_pi1%5Baction%5D=detail& L=1& cHash=b182adf919054989c8d640e1da19f0a2 **French** index.phpid=19& L=2& tx\_news\_pi1%5Bnews%5D=1& tx\_news\_pi1%5Bcontroller%5D=News& tx\_news\_pi1%5Baction%5D=detail& cHash=b182adf919054989c8d640e1da19f0a2 As you can see the last part in my breadcrumb navigation won't get translated. Following my TypoScript for the news title output. ``` [globalVar = GP:tx_news_pi1|news > 0] lib.nav_breadcrumb.20 = RECORDS lib.nav_breadcrumb.20 { tables = tx_news_domain_model_news dontCheckPid = 1 source { data = GP:tx_news_pi1|news intval = 1 } conf.tx_news_domain_model_news = TEXT conf.tx_news_domain_model_news.field = title conf.tx_news_domain_model_news.htmlSpecialChars = 1 wrap = - | } [global] ``` This now fetches the title from the news records. But only from the main language. How can I fetch the other languages? My System: * TYPO3 Version **8.7.11** * Webserver **Apache** * PHP Version **7.0.27-0+deb9u1** * Database (Default) **MySQL 5.5.5** * Application Context **Production** * Composer mode **Enabled** * Operating System **Linux 4.9.0-5-amd64** * News Extension **6.3.0**<issue_comment>username_1: Instead of `RECORDS` you should use `CONTENT` where you have more [options](https://docs.typo3.org/typo3cms/TyposcriptReference/8.7/ContentObjects/Content/) to select the records you want. With `CONTENT` you can change the query to select the record which has that `sys_language_uid` you want to show, of course you need to select `l10n_parent` instead of `uid` for languages other than default: use a TS condition or `stdwrap.if` to build two kinds of selections. Upvotes: 1 <issue_comment>username_2: I had to activate sys\_language\_overlay. And now everything works ``` config.sys_language_overlay = 1 ``` Upvotes: 1 [selected_answer]
2018/03/22
1,281
4,316
<issue_start>username_0: I have created svg from fabric js. While creating card i have applied text-align to object using below code: ``` activeObj.set({ textAlign : 'center', }); canvas.renderAll(); ``` So my svg is look like below: <https://codepen.io/dhavalsisodiya/pen/BrRbRG> Now when i changed my {company\_address} address variable with original value, that text should be align center but it is not. <https://codepen.io/dhavalsisodiya/pen/VXbRzy> Then i have modified SVG manually, I have added `text-anchor="middle"` in tspan tag of SVG (that is the placing of my varaible) <https://codepen.io/dhavalsisodiya/pen/ZxKPab> After adding that my text is appearing center in SVG. So is there a way to do that using fabric js, so it contain `text-anchor="middle"` when i apply text alignment? Update ====== I have applied the textAnchor also, but it is not converting to svg. Codepen ======= <https://codepen.io/dhavalsisodiya/pen/gvQooL><issue_comment>username_1: There is no text-anchor support in fabric.js for svgs. You can make it quite easily maybe... Take the text class from fabric.js, take the `_getSVGLeftTopOffsets` method for svg export. This methods return `-this.width/2` always. I suppose it could return 0 if textAnchor is middle, and `this.width/2` if textAnchor is end, becoming: ``` /** * @private */ _getSVGLeftTopOffsets: function() { return { textLeft: this.textAnchor === 'middle' ? 0 : this.textAnchor === 'start' -this.width / 2 : this.width / 2, textTop: -this.height / 2, lineTop: this.getHeightOfLine(0) }; }, ``` Now take the `_wrapSVGTextAndBg` method and add the text-anchor property to the svg code: ``` /** * @private */ _wrapSVGTextAndBg: function(markup, textAndBg) { var noShadow = true, filter = this.getSvgFilter(), style = filter === '' ? '' : ' style="' + filter + '"', textDecoration = this.getSvgTextDecoration(this); markup.push( '\t\n', textAndBg.textBgRects.join(''), '\t\t', textAndBg.textSpans.join(''), '\n', '\t\n' ); }, ``` at this point add to the text class the default for textAnchor value that should be start Upvotes: 1 <issue_comment>username_2: Thanks to @username_1, i was able to resolve it using below method: I have modified fabric js file with below: Added `'text-anchor="' + this.textAnchor + '" ',` in `_wrapSVGTextAndBg: function(markup, textAndBg) {` as @username_1 suggested. ``` /** * @private */ _wrapSVGTextAndBg: function(markup, textAndBg) { var noShadow = true, filter = this.getSvgFilter(), style = filter === '' ? '' : ' style="' + filter + '"', textDecoration = this.getSvgTextDecoration(this); markup.push( '\t\n', textAndBg.textBgRects.join(''), '\t\t', textAndBg.textSpans.join(''), '\n', '\t\n' ); }, ``` Then i have modified below: ``` _createTextCharSpan: function(_char, styleDecl, left, top) { var styleProps = this.getSvgSpanStyles(styleDecl, _char !== _char.trim()), fillStyles = styleProps ? 'style="' + styleProps + '"' : ''; //Addded to support text-anhor middle if(this.textAnchor==='middle') { return [ '\t\t\t', fabric.util.string.escapeXml(\_char), '\n' ].join(''); } else { return [ '\t\t\t', fabric.util.string.escapeXml(\_char), '\n' ].join(''); } }, ``` Extend the toObjectTo to add textAnchor in json, see here: [extend toObject](http://fabricjs.com/fabric-intro-part-3) : ``` $('.text_alignment').click(function(){ var cur_value = $(this).attr('data-action'); var activeObj = canvas.getActiveObject(); if (cur_value != '' && activeObj) { activeObj.set({ textAlign : cur_value, textAnchor : 'middle' }); //To modify Object activeObj.toObject = (function(toObject) { return function() { return fabric.util.object.extend(toObject.call(this), { textAnchor: 'middle' }); }; })(activeObj.toObject); //activeObj.textAnchor = cur_value; canvas.renderAll(); } else { alert('Please select text'); return false; } }); ``` By making above changes, now my variable stays middle even if i modified text. Upvotes: 1 [selected_answer]
2018/03/22
847
3,642
<issue_start>username_0: I have the following requirement. I have An Angular service with an BehaviorSubject. A http request is done and when this is done the BehaviorSubject.next method is invoked with the value. This value can change during the lifecycle of the single page. Different subscribers are registered to it and get invoked whenever this changes. The problem is that while the http request is pending the BehaviorSubject already contains a default value and subscribers are already immediately getting this value. What I would want is that subscribers have to wait till the http request is done (deferred) and get the value when the http request is done and sets the value. So what I need is some kind of deferred Behavior subject mechanism. How would i implement this using rxjs? Another requirement is that if I subscribe to the behaviorsubject in a method we want the subcriber to get the first non default value and that the subscription ends. We don't want local subscriptions in functions to be re-executed.<issue_comment>username_1: Use a filter on your behavior subject so your subscribers won't get the first default emitted value: ``` mySubject$: BehaviorSubject = new BehaviorSubject(null); httpResponse$: Observable = this.mySubject$.pipe( filter(response => response) map(response => { const modifyResponse = response; // modify response return modifyResponse; }), take(1) ); this.httpResponse$.subscribe(response => console.log(response)); this.myHttpCall().subscribe(response => this.mySubject$.next(response)); ``` You can of course wrap the httpResponse$ observable in a method if you need to. Upvotes: 2 [selected_answer]<issue_comment>username_2: I think the fact that you want to defer the emitted default value, straight away brings into question why you want to use a BehaviorSubject. Let's remember: the primary reason to use a BehaviorSubject (instead of a Subject, or a plain Observable), is to emit a value **immediately** to any subscriber. If you need an Observable type where you need control of the producer (via .next([value])) and/or you want multicasting of subscription out of the box, then *Subject* is appropriate. **If** an additional requirement on top of this is that subscribers need a value immediately then you need to consider *BehaviorSubject*. If you didn't say you need to update the value from other non-http events/sources, then I would've suggested using a shareReplay(1) pattern. Nevertheless... ``` private cookieData$: Subject = new Subject(null); // Function for triggering http request to update // internal Subject. // Consumers of the Subject can potentially invoke this // themselves if they receive 'null' or no value on subscribe to subject public loadCookieData(): Observable { this.http.get('http://someurl.com/api/endpoint') .map(mapDataToRelevantDataType()); } // Function for dealing with updating the service's // internal cookieData$ Subject from external // consumer which need to update this value // via non-http events public setCookieData(data: any): void { const newCookieValue = this.mapToRelevantDataType(data); // <-- If necessary this.cookieData$.next(newCookieValue); // <-- updates val for all subscribers } get cookieData(): Observable { return this.cookieData$.asObservable(); } ``` The solution is based on OPs comments etc. - deals with subscribing to subject type. - deals with external subscribers not being able to 'next' a new value directly - deals with external producers being able to set a new value on the Subject type - deals with not giving a default value whilst http request is pending Upvotes: 0
2018/03/22
839
3,409
<issue_start>username_0: I have this little crazy method that removes decimal places from string value. ``` private double getDoubleFromString(final String value) throws ParseException { NumberFormat format = NumberFormat.getInstance(Locale.getDefault()); Number number = format.parse(value); return number.doubleValue(); } ``` It produces values with out comma ( **,** ) if local language is 'en' it working fine, in other languages that contains **,** in that strings it's returns value without comma. Ex : ``` xx,x result is xxx. 74,5 --> 745 (problem facing in this format) 74.5 --> 74.5 (working fine it string has dot) ``` I do need the separator to be a dot or a point and a comma along with value string. Does anybody have a clue of how to accomplish this little feat?<issue_comment>username_1: Use a filter on your behavior subject so your subscribers won't get the first default emitted value: ``` mySubject$: BehaviorSubject = new BehaviorSubject(null); httpResponse$: Observable = this.mySubject$.pipe( filter(response => response) map(response => { const modifyResponse = response; // modify response return modifyResponse; }), take(1) ); this.httpResponse$.subscribe(response => console.log(response)); this.myHttpCall().subscribe(response => this.mySubject$.next(response)); ``` You can of course wrap the httpResponse$ observable in a method if you need to. Upvotes: 2 [selected_answer]<issue_comment>username_2: I think the fact that you want to defer the emitted default value, straight away brings into question why you want to use a BehaviorSubject. Let's remember: the primary reason to use a BehaviorSubject (instead of a Subject, or a plain Observable), is to emit a value **immediately** to any subscriber. If you need an Observable type where you need control of the producer (via .next([value])) and/or you want multicasting of subscription out of the box, then *Subject* is appropriate. **If** an additional requirement on top of this is that subscribers need a value immediately then you need to consider *BehaviorSubject*. If you didn't say you need to update the value from other non-http events/sources, then I would've suggested using a shareReplay(1) pattern. Nevertheless... ``` private cookieData$: Subject = new Subject(null); // Function for triggering http request to update // internal Subject. // Consumers of the Subject can potentially invoke this // themselves if they receive 'null' or no value on subscribe to subject public loadCookieData(): Observable { this.http.get('http://someurl.com/api/endpoint') .map(mapDataToRelevantDataType()); } // Function for dealing with updating the service's // internal cookieData$ Subject from external // consumer which need to update this value // via non-http events public setCookieData(data: any): void { const newCookieValue = this.mapToRelevantDataType(data); // <-- If necessary this.cookieData$.next(newCookieValue); // <-- updates val for all subscribers } get cookieData(): Observable { return this.cookieData$.asObservable(); } ``` The solution is based on OPs comments etc. - deals with subscribing to subject type. - deals with external subscribers not being able to 'next' a new value directly - deals with external producers being able to set a new value on the Subject type - deals with not giving a default value whilst http request is pending Upvotes: 0