date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/21
1,264
3,313
<issue_start>username_0: I have a dataframe: ``` Name y1 y2 y3 1 Ben 01 02 03 2 Jane 04 05 06 3 Sarah 07 07 06 ``` I am trying to add in a row in my dataframe which provides a total of the rows in each column. My code is: ``` import pandas as pd df = pd.DataFrame(np.insert(df.values, 0, values=[df.sum(axis=0)], axis=0)) df.set_value(0, 0,'total') df.head() ``` This is successful, but also removes my column names like this: ``` 0 1 2 3 0 Total 12 14 15 1 Ben 01 02 03 2 Jane 04 05 06 3 Sarah 07 07 06 ``` rather than returning this as desired: ``` Name y1 y2 y3 0 Total 12 14 15 1 Ben 01 02 03 2 Jane 04 05 06 3 Sarah 07 07 06 ``` I have tried inserting ``` Index(['Name'], name=df.index.name) ``` to ``` df = pd.DataFrame(np.insert(df.values, 0, values=[df.sum(axis=0)], Index(['Name'], name=df.index.name) axis=0)) ``` but this just returns the error > > TypeError: unhashable type: 'Index' > > > Where am I going wrong?<issue_comment>username_1: You can use `pandas.concat` to stack two dataframes: ``` import pandas as pd df = ... df_total = pd.DataFrame(df.iloc[:, 1:].sum(), columns=["Total"]).T.reset_index() df_total.columns = df.columns df = pd.concat([df_total, df]) # Name y1 y2 y3 # 0 Total 12 14 15 # 1 Ben 1 2 3 # 2 Jane 4 5 6 # 3 Sarah 7 7 6 ``` Upvotes: 1 <issue_comment>username_2: One way to avoid this is to add a new row via `.loc`, then move it to the top: ``` df.loc[len(df)+1] = ['Total'] + df.iloc[:, 1:].sum(axis=0).tolist() df = df.loc[[df.index[-1]] + df.index[:-1].tolist(), :] # Name y1 y2 y3 # 4 Total 12 14 15 # 1 Ben 1 2 3 # 2 Jane 4 5 6 # 3 Sarah 7 7 6 ``` You can use `df.reset_index` afterwards if this is important to you. Upvotes: 2 <issue_comment>username_3: IIUC, you can do it this way, using `select_types`, `assign`, and `pd.concat`: ``` pd.concat([df.select_dtypes(include=np.number) .sum() .to_frame() .T .assign(Name='Total'),df]) ``` Output: ``` Name y1 y2 y3 0 Total 12 14 15 1 Ben 1 2 3 2 Jane 4 5 6 3 Sarah 7 7 6 ``` Upvotes: 2 <issue_comment>username_4: You can try ``` s=df.sum() s.loc['Name']='Total' df.loc[0]=s df.sort_index() Out[457]: Name y1 y2 y3 0 Total 12 14 15 1 Ben 1 2 3 2 Jane 4 5 6 3 Sarah 7 7 6 ``` Upvotes: 1 <issue_comment>username_5: Solution with `np.insert` should be very fast, but is necessary create `index` with non numeric columns first: ``` #create index from `Name` column df = df.set_index('Name') #add first value to index idx = np.insert(df.index, 0, 'Total') #add columns and index parameters to DataFrame contructor and last reset index df = pd.DataFrame(np.insert(df.values, 0, df.sum(), axis=0), columns=df.columns, index=idx).reset_index() print (df) Name y1 y2 y3 0 Total 12 14 15 1 Ben 1 2 3 2 Jane 4 5 6 3 Sarah 7 7 6 ``` Upvotes: 2 [selected_answer]
2018/03/21
1,187
3,074
<issue_start>username_0: I have a field-name called "customer" contains the following values, 1. Brooks Sports 2. AM-Records 3. 1elememt 4. ALTAVISTA 5. Adidas 6. 3gdata 7. Apple 8. BMW 9. 7eleven 10. bic corporation customer field in solr schema.xml ``` ``` I need to perform case-insensitive sort on above customer values. so i can get the data as follow, 1. 1elememt 2. 3gdata 3. 7eleven 4. Adidas 5. ALTAVISTA 6. AM-Records 7. Apple 8. bic corporation 9. BMW 10. Brooks Sports for this i create a new copyField named "customer\_sort" field in scheme.xml ``` ``` fieldType in scheme.xml ``` ``` copyfield in scheme.xml ``` ``` currently the sort result is 1. 1elememt 2. 3gdata 3. 7eleven 4. ALTAVISTA 5. AM-Records 6. Adidas 7. Apple 8. BMW 9. Brooks Sports 10. bic corporation sort happening based on ascii value. i.e.(A then a, B then b,...). Same happen when i tried alphaOnlySort. Can anybody please tell me what i'm missing? Thanks<issue_comment>username_1: You can use `pandas.concat` to stack two dataframes: ``` import pandas as pd df = ... df_total = pd.DataFrame(df.iloc[:, 1:].sum(), columns=["Total"]).T.reset_index() df_total.columns = df.columns df = pd.concat([df_total, df]) # Name y1 y2 y3 # 0 Total 12 14 15 # 1 Ben 1 2 3 # 2 Jane 4 5 6 # 3 Sarah 7 7 6 ``` Upvotes: 1 <issue_comment>username_2: One way to avoid this is to add a new row via `.loc`, then move it to the top: ``` df.loc[len(df)+1] = ['Total'] + df.iloc[:, 1:].sum(axis=0).tolist() df = df.loc[[df.index[-1]] + df.index[:-1].tolist(), :] # Name y1 y2 y3 # 4 Total 12 14 15 # 1 Ben 1 2 3 # 2 Jane 4 5 6 # 3 Sarah 7 7 6 ``` You can use `df.reset_index` afterwards if this is important to you. Upvotes: 2 <issue_comment>username_3: IIUC, you can do it this way, using `select_types`, `assign`, and `pd.concat`: ``` pd.concat([df.select_dtypes(include=np.number) .sum() .to_frame() .T .assign(Name='Total'),df]) ``` Output: ``` Name y1 y2 y3 0 Total 12 14 15 1 Ben 1 2 3 2 Jane 4 5 6 3 Sarah 7 7 6 ``` Upvotes: 2 <issue_comment>username_4: You can try ``` s=df.sum() s.loc['Name']='Total' df.loc[0]=s df.sort_index() Out[457]: Name y1 y2 y3 0 Total 12 14 15 1 Ben 1 2 3 2 Jane 4 5 6 3 Sarah 7 7 6 ``` Upvotes: 1 <issue_comment>username_5: Solution with `np.insert` should be very fast, but is necessary create `index` with non numeric columns first: ``` #create index from `Name` column df = df.set_index('Name') #add first value to index idx = np.insert(df.index, 0, 'Total') #add columns and index parameters to DataFrame contructor and last reset index df = pd.DataFrame(np.insert(df.values, 0, df.sum(), axis=0), columns=df.columns, index=idx).reset_index() print (df) Name y1 y2 y3 0 Total 12 14 15 1 Ben 1 2 3 2 Jane 4 5 6 3 Sarah 7 7 6 ``` Upvotes: 2 [selected_answer]
2018/03/21
503
1,922
<issue_start>username_0: I have the below string which I have bound to a DOM element's 'innerHTML'. I have sanitized it so the browser does not remove it. The routerLink is not working. If I change it to href then it does work. How can I get Angular to bind this link? **HTML string being bound** ``` Something ```<issue_comment>username_1: Here is the link to the [Angular documentation](https://angular.io/api/router/RouterLink), as well as an example: ```html Your Route ``` Upvotes: 0 <issue_comment>username_2: `routerLink='/somelink'` is a way of telling Angular how to behvae when you click on the link. It isn't a native Javascript behavior. If you use `innerHTML` to add this to your component, this will **never** work. Using `routerLink='/somelink'` works only **when your code isn't compiled**. To visualize this, let's take `(click)` as an example, since it is the same case. Look at the snippet below : ```html (click) onclick ``` Click on both buttons and see which one works. This is because **Angular compiles your code according to its syntax**. And `routerLink` is part of its syntax, not part of native Javascript. Upvotes: 2 <issue_comment>username_3: I found this code to dynamically compile the routerLink at run-time. I have tried it and it works. [Plunker example](https://plnkr.co/edit/mcvILwmOLvrS2PxIrXX8?p=preview) ``` function createComponentFactory(compiler: Compiler, metadata: Component): Promise> { const cmpClass = class DynamicComponent {}; const decoratedCmp = Component(metadata)(cmpClass); @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] }) class DynamicHtmlModule { } return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule) .then((moduleWithComponentFactory: ModuleWithComponentFactories) => { return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp); }); ``` } Upvotes: 1
2018/03/21
670
2,458
<issue_start>username_0: I'm writing an application that uses MSMQ and I'm encountering a problem specifically to do with encoding attribute for the XML declaration tag. I'm constructing the message as below: ``` string xmlmsg = reqText.Text; XmlDocument xdoc = new XmlDocument(); xdoc.Load(new StringReader(xmlmsg)); xdoc.InsertBefore(xdoc.CreateXmlDeclaration("1.0", "UTF-8", "yes"), xdoc.DocumentElement); Message _msg = new Message(); _msg.BodyStream = new MemoryStream(Encoding.ASCII.GetBytes(xdoc.OuterXml)); reqQueue.Send(_msg, "XML Request"); ``` The console output of ***xdoc.OuterXml*** reveals that the encoding is included: ``` xml version="1.0" encoding="UTF-8" standalone="yes"? ``` But when I send the message over MSMQ, the encoding attribute gets removed. ``` xml version="1.0" standalone="yes"? ``` What am I missing here?<issue_comment>username_1: Here is the link to the [Angular documentation](https://angular.io/api/router/RouterLink), as well as an example: ```html Your Route ``` Upvotes: 0 <issue_comment>username_2: `routerLink='/somelink'` is a way of telling Angular how to behvae when you click on the link. It isn't a native Javascript behavior. If you use `innerHTML` to add this to your component, this will **never** work. Using `routerLink='/somelink'` works only **when your code isn't compiled**. To visualize this, let's take `(click)` as an example, since it is the same case. Look at the snippet below : ```html (click) onclick ``` Click on both buttons and see which one works. This is because **Angular compiles your code according to its syntax**. And `routerLink` is part of its syntax, not part of native Javascript. Upvotes: 2 <issue_comment>username_3: I found this code to dynamically compile the routerLink at run-time. I have tried it and it works. [Plunker example](https://plnkr.co/edit/mcvILwmOLvrS2PxIrXX8?p=preview) ``` function createComponentFactory(compiler: Compiler, metadata: Component): Promise> { const cmpClass = class DynamicComponent {}; const decoratedCmp = Component(metadata)(cmpClass); @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] }) class DynamicHtmlModule { } return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule) .then((moduleWithComponentFactory: ModuleWithComponentFactories) => { return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp); }); ``` } Upvotes: 1
2018/03/21
651
2,315
<issue_start>username_0: I was advised to use the following piece of code: ``` query = 'Select "logtext" from log where jobid = %s;' cursorErrorData.execute(query, str(row[0])) ``` Instead of using this: ``` query = 'Select "logtext" from log where jobid = %s;' % str(row[0]) cursorErrorData.execute(query) ``` I have used the first example and it works fine, but in this example it crashes. The data that str(row[0]) retrieve is the following: ``` 3090 ``` And this is the exception: > > > > > > not all arguments converted during string formatting > > > > > > > > > ****Could someone explain to me the difference between both methods and why in this particular case, I can't use it?****<issue_comment>username_1: Here is the link to the [Angular documentation](https://angular.io/api/router/RouterLink), as well as an example: ```html Your Route ``` Upvotes: 0 <issue_comment>username_2: `routerLink='/somelink'` is a way of telling Angular how to behvae when you click on the link. It isn't a native Javascript behavior. If you use `innerHTML` to add this to your component, this will **never** work. Using `routerLink='/somelink'` works only **when your code isn't compiled**. To visualize this, let's take `(click)` as an example, since it is the same case. Look at the snippet below : ```html (click) onclick ``` Click on both buttons and see which one works. This is because **Angular compiles your code according to its syntax**. And `routerLink` is part of its syntax, not part of native Javascript. Upvotes: 2 <issue_comment>username_3: I found this code to dynamically compile the routerLink at run-time. I have tried it and it works. [Plunker example](https://plnkr.co/edit/mcvILwmOLvrS2PxIrXX8?p=preview) ``` function createComponentFactory(compiler: Compiler, metadata: Component): Promise> { const cmpClass = class DynamicComponent {}; const decoratedCmp = Component(metadata)(cmpClass); @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] }) class DynamicHtmlModule { } return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule) .then((moduleWithComponentFactory: ModuleWithComponentFactories) => { return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp); }); ``` } Upvotes: 1
2018/03/21
600
2,099
<issue_start>username_0: Does anyone know if it's possible to use a function in a v-for loop? I would like to do something like: ``` {{ foo }} [...] props: { Configuration: { required: true } }, computed: { data(){ return this.Configuration.something .filter(stbc => { return stbc.val !== "no" }); } }, methods: { bar(arg1, arg2){ this.$http.get(`server_url/baz?arg1=${arg1}&arg2=${arg2}`) .then(res => { return res.split('\n') }); } } ``` I tried but without success :( Thank you !<issue_comment>username_1: `v-for` can iterate over a the result of any valid expression (though personally I would consider adding a `computed` property instead). However, if you're calling the server as you indicate in your comment, you are introducing asynchronous code, and `bar(arg1, arg2)` is probably returning a promise, rather than an array of strings. I guess what you want to do is: ``` props: { Configuration: { required: true } }, data() { return { serverData: [] }; }, mounted() { this.fetchData(); }, methods: { fetchData() { // obtain `arg1` and `arg2` from `this.Configuration` // (or use a computed property if you prefer) if (arg1 && arg2) { this.$http.get(`server_url/baz?arg1=${arg1}&arg2=${arg2}`) .then(res => { this.serverData = res.split('\n') }); } } } ``` Then just refer to `serverData` in your template. The array will be empty until the promise returned by the AJAX call resolves. If the `Configuration` prop changes during the lifetime of the component, you may want to also add a watcher, to call `fetchData` again with the new values. Upvotes: 3 [selected_answer]<issue_comment>username_2: yes, you could use the `computed` to achieve that instead of `methods`, see bellow ``` {{ foo }} [...] computed: { bar(arg1, arg2){ //get data from server return serverData; //this is a string array } } ``` See this fiddle: <https://jsfiddle.net/49gptnad/2449/> I hope this will help you. Upvotes: 2
2018/03/21
1,290
3,813
<issue_start>username_0: This one however is a bit different, as I have absolutely no clue about XSL, and need to get this template working for our shipping software. I've got this doing what I want for the most part, learning as I go as I did with most other languages. But I can't seem to get the recursive loop going that I need. Basically I need it to use the numeric value of `$order/Item/Quantity` to determine how many times to loop each of the "Name" variables in the for-each. It will currently print the line items as it is supposed to, but only one of them. I've played with various different recursive templates that have been posted here, but due to my lack of knowledge in XSL I've been unable to get it working, so have reverted back to the original (before I started working on the quantity part). Here is the entire template, ``` Can label - gallon - Paints/Primers body, table { <xsl:value-of select="$pageFont" /> } | | | --- | | Eggshell Matte | ``` EDIT: Here is the input that ShipWorks provides. The output should be a page with either "Matte" or "Eggshell" in the center ``` xml version="1.0" encoding="utf-8"? 2018-03-21T16:09:39.905698Z 1521648579 Order XML Source System\Utility 7 9.5 true `GENERIC` Generic - Module 2018-03-21T16:05:50.933Z Not Checked Unknown Unknown Unknown Unknown 80.4000 1 Not Checked Unknown Unknown Unknown Unknown Not Checked Unknown Unknown Unknown Unknown 71704 2018-01-19T00:10:28Z Complete Complete C 11886 false UPS Ground (Signature Required) 80.4000 Fixed Yes No No No Fixed Yes No No No Gloss Varnish 29.7500 29.7500 0 0 1 29.7500 29.7500 0 0 false Size 1 Quart 0 Wood Stain 20.3500 20.3500 0 0 1 20.3500 20.3500 0 0 false Ordered this color before ? No 0 Size 1 Gallon 0 Matte Interior Wall & Ceiling Paint 20.3500 20.3500 0 0 1 20.3500 20.3500 0 0 false Size 1 Quart 0 SHIPPING Shipping 9.9500 UPS Processed true 2018-01-19T16:46:14.09Z false false 2018-01-19T12:00:00Z UPS Ground false 16.3300 9 Fixed Yes No No No Not Checked Unknown Unknown Unknown Unknown None NotApplied Actual weight 9 Carrier 100.0000 13 13 7.25 9 Thermal - ZPL ```<issue_comment>username_1: `v-for` can iterate over a the result of any valid expression (though personally I would consider adding a `computed` property instead). However, if you're calling the server as you indicate in your comment, you are introducing asynchronous code, and `bar(arg1, arg2)` is probably returning a promise, rather than an array of strings. I guess what you want to do is: ``` props: { Configuration: { required: true } }, data() { return { serverData: [] }; }, mounted() { this.fetchData(); }, methods: { fetchData() { // obtain `arg1` and `arg2` from `this.Configuration` // (or use a computed property if you prefer) if (arg1 && arg2) { this.$http.get(`server_url/baz?arg1=${arg1}&arg2=${arg2}`) .then(res => { this.serverData = res.split('\n') }); } } } ``` Then just refer to `serverData` in your template. The array will be empty until the promise returned by the AJAX call resolves. If the `Configuration` prop changes during the lifetime of the component, you may want to also add a watcher, to call `fetchData` again with the new values. Upvotes: 3 [selected_answer]<issue_comment>username_2: yes, you could use the `computed` to achieve that instead of `methods`, see bellow ``` {{ foo }} [...] computed: { bar(arg1, arg2){ //get data from server return serverData; //this is a string array } } ``` See this fiddle: <https://jsfiddle.net/49gptnad/2449/> I hope this will help you. Upvotes: 2
2018/03/21
918
3,027
<issue_start>username_0: I was using `shared_preferences` plugin in my Flutter application. From one moment (probably after Flutter upgrade), it started to throw an exception: ``` E/flutter (27778): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception: E/flutter (27778): type '_InternalLinkedHashMap' is not a subtype of type 'Map' where E/flutter (27778): \_InternalLinkedHashMap is from dart:collection E/flutter (27778): Map is from dart:core E/flutter (27778): String is from dart:core E/flutter (27778): Object is from dart:core E/flutter (27778): E/flutter (27778): #0 SharedPreferences.getInstance (package:shared\_preferences/shared\_preferences.dart) E/flutter (27778): E/flutter (27778): #1 loadFirstUse (\*\*path\*\*/lib/main.dart:29:53) E/flutter (27778): E/flutter (27778): #2 main (\*\*path\*\*/lib/main.dart:17:9) E/flutter (27778): E/flutter (27778): #3 \_startIsolate. (dart:isolate/runtime/libisolate\_patch.dart:279:19) E/flutter (27778): #4 \_RawReceivePortImpl.\_handleMessage (dart:isolate/runtime/libisolate\_patch.dart:165:12) ``` It happens when I simple try to create instance of SharedPreferences: ``` SharedPreferences prefs = await SharedPreferences.getInstance(); ``` I was trying to find root of the problem, but was unable to find it. Thank you for any help. EDIT: I am using `shared_preferences: "^0.4.0"`<issue_comment>username_1: I've tried `shared_preferences: "0.2.4"` and other versions suggested above without any success. Finally got it to work after changing flutter channel from dev to beta: ``` flutter channel beta ``` At least this fixes this problem for now and just wait for a fix for the shared\_preferences plugin on the dev channel. Upvotes: 3 [selected_answer]<issue_comment>username_2: I fixed it by changing to `shared_preferences: "0.3.3"`. There is a good chance this breaks again. Upvotes: 2 <issue_comment>username_3: you need to use Future like this ``` Future \_sprefs = SharedPreferences.getInstance(); ``` Upvotes: 0 <issue_comment>username_4: I solved this using the following workaround: ``` Future prefs = SharedPreferences.getInstance(); prefs.then( (pref) { //call functions like pref.getInt(), etc. here } ); ``` Upvotes: 3 <issue_comment>username_5: To debug this, use the following: ``` Future \_sprefs = SharedPreferences.getInstance(); \_sprefs.then((prefs) { // ... }, onError: (error) { print("SharedPreferences ERROR = $error"); }); ``` In my case the error was that I wanted to call `await SharedPreferences.getInstance()` before I called `runApp()`, so that solution the error message gave me was to order my code as follows: First: ``` WidgetsFlutterBinding.ensureInitialized(); ``` Afterwards: ``` SharedPreferences prefs = await SharedPreferences.getInstance(); ``` Finally: ``` runApp(...); ``` Upvotes: 3 <issue_comment>username_6: I remove packages one by one, and found that it was caused by `flutter_barcode_scanner`. I upgraded it to version 2.0.0 and it solved my problem. Upvotes: 0
2018/03/21
612
2,401
<issue_start>username_0: I have the below "working" code in component.ts file (I have included the html code as well) Please look at the commented lines in 3 places in the code. When I use FormControl variable directly then the valueChanges property works fine but when I access the FormControl variable from a FormGroup then I get `"ERROR Error: Cannot find control with unspecified name attribute"` What am I doing wrong here? Code in app.component.ts: ``` import { Component } from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms'; import 'rxjs/add/operator/debounceTime'; @Component({ selector: "app-root", template: ` Observable events from formcontrol ---------------------------------- ` }) export class AppComponent { //searchFormGroup = new FormGroup({searchInput: new FormControl('')}); searchInput: FormControl = new FormControl(''); constructor(){ //this.searchFormGroup.get('searchInput').valueChanges this.searchInput.valueChanges .debounceTime(500) .subscribe(input => console.log(input)); } } ``` Thanks<issue_comment>username_1: Because you don't build a form group like that. Here is how you build it. ```js constructor(private fb: FormBuilder) { this.searchFormGroup = fb.group({ searchInput: [''] }); } ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: Started working fine after I used formControlName in the html code: ``` import { Component } from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms'; import 'rxjs/add/operator/debounceTime'; @Component({ selector: "app-root", template: ` Observable events from formcontrol ---------------------------------- ` }) export class AppComponent { searchFormGroup = new FormGroup({'searchInput': new FormControl('')}); //searchInput: FormControl = new FormControl(''); constructor(){ this.searchFormGroup.get('searchInput').valueChanges //this.searchInput.valueChanges .debounceTime(500) .subscribe(input => console.log(input)); } } ``` Upvotes: 0 <issue_comment>username_3: it cannot work in RXjs 6.0, here is how you can write it with `Formcontrol` ```js // it works const searchInput = this.eleRef.nativeElement.querySelector('#search'); fromEvent(searchInput, 'input').pipe( debounceTime(500) ) .subscribe(input => { console.log(input); }); ``` Upvotes: 1
2018/03/21
350
1,595
<issue_start>username_0: In the fragment,I want to scroll the TextView inside the RecyclerView so i put Scrollbar inside RecyclerView but its not working in mobile but works well in emulator and also tried nested scrollview but have the same problem. What could i do if i want to scroll the particular textview inside the Recyclerview ex.There are multiple attributes inside the recyclerview ex. imageview for user photo textview for user name and textview for user details as the user details field is lengthy i want to scroll this field seperatly ``` ```<issue_comment>username_1: Recyclerview view has defualt scrollable behaviour so remove scrollbar from inside of recyaclerview Upvotes: 0 <issue_comment>username_2: In your Layout.xml file u can use below code : ``` ``` Below code is used in you **`ViewHolder`** file : ``` public ViewHolder(View itemView) { super(itemView); scrollText = (TextView) itemView.findViewById(R.id.scrollText); scrollView = (ScrollView) itemView.findViewById(R.id.scrollView); scrollText.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { // Disallow the touch request for parent scroll on touch of child view v.getParent().requestDisallowInterceptTouchEvent(true); return false; } }); //Enabling scrolling on TextView. scrollText.setMovementMethod(new ScrollingMovementMethod()); } ``` Upvotes: 3 [selected_answer]
2018/03/21
1,311
5,157
<issue_start>username_0: In my app login using mobile number or phone number in single edittext. if we give digits it check valid phone number else if we give character(alphabet) check it is valid email address. Note : check both email and phone number in single edit text. Here java code, ``` if (username.getText().toString().length() == 0) { erroredit(username, getResources().getString(R.string.login_label_alert_username)); } else if (!isValidEmail(username.getText().toString().replace(" ","").trim())) { erroredit(username, getResources().getString(R.string.login_label_alert_email_invalid)); } else if (!isValidmobilenumber(username.getText().toString().replace(" ","").trim())) { erroredit(username, getResources().getString(R.string.register_label_alert_phoneNo)); } else if (password.getText().toString().length() == 0) { erroredit(password, getResources().getString(R.string.login_label_alert_password)); } ``` Attached screenshot here, [![enter image description here](https://i.stack.imgur.com/5Fb8B.png)](https://i.stack.imgur.com/5Fb8B.png)<issue_comment>username_1: assume your `EditText` variable is `editText`: ``` String username = editText.getText().toString(); if(android.util.Patterns.EMAIL_ADDRESS.matcher(username).matches() || android.util.Patterns.PHONE.matcher(username).matches()){ //do stuff } else{ //do stuff } ``` Upvotes: 1 <issue_comment>username_2: you can combine codes to achieve that, first add the following methods: ``` private boolean isValidMobile(String phone) { boolean check=false; if(!Pattern.matches("[a-zA-Z]+", phone)) { if(phone.length() < 6 || phone.length() > 13) { // if(phone.length() != 10) { check = false; txtPhone.setError("Not Valid Number"); } else { check = true; } } else { check=false; } return check; } ``` and for email validatio add this one: ``` private boolean isValidMail(String email) { boolean check; Pattern p; Matcher m; String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; p = Pattern.compile(EMAIL_STRING); m = p.matcher(email); check = m.matches(); if(!check) { txtEmail.setError("Not Valid Email"); } return check; } ``` also this is needed to check if the string numeric or not ``` public static boolean isNumeric(String str) { return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal. } ``` in your code you call those function like ``` if(isValidMobile(login) || isValidMail(login){ // success if(isNumeric(login)){ //it mean the user typed a phone number //show phone invalid image } else{ //show email invalid image } } else { // failure } ``` Upvotes: 2 <issue_comment>username_3: [I very often use this dependency when it comes to manipulating phone numbers. It's very useful.](https://github.com/hbb20/CountryCodePickerProject) For email it's not complicated just check the character "@" and "." Upvotes: 0 <issue_comment>username_4: Try this ``` button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String data = editemail.getText().toString().trim(); String pass = edtPass.getText().toString().trim(); boolean flag = false; if (TextUtils.isEmpty(pass)) { edtPass.setError("Enter password"); //edtPass.requestFocus(); }else { } if (TextUtils.isEmpty(data)) { editemail.setError("Enter Data"); } else { if (data.matches("[0-9]+")) { if (data.length() < 10 && data.length() > 10) { editemail.setError("Please Enter valid phone number"); editemail.requestFocus(); } else { flag = true; } } else { if (!android.util.Patterns.EMAIL_ADDRESS.matcher(data).matches()) { editemail.setError("Please Enter valid email"); editemail.requestFocus(); }else { flag = true; } } } if(!TextUtils.isEmpty(pass)&&flag){ Toast.makeText(MainActivity.this, "pass", Toast.LENGTH_SHORT).show(); } } }); ``` Upvotes: 3 [selected_answer]<issue_comment>username_5: If you want real time checking while user is writing then you can have a TextWatcher [How to use the TextWatcher class in Android?](https://stackoverflow.com/questions/8543449/how-to-use-the-textwatcher-class-in-android) Do your checks in the afterTextChanged override method with `android.util.Patterns.PHONE` or an equivalent like the user Godot explained above. Upvotes: 0
2018/03/21
1,051
3,921
<issue_start>username_0: I have the following structure in C++ ``` struct A { int a; double b; float c; } ``` Is there a difference in memory layout between this struct and one with a function added to it? ``` struct B { int a; double b; float c; void foo(); } B::foo() { //do stuff } ```<issue_comment>username_1: It formally depends on your compiler, but a compiler where declaring a non-virtual member function changes the layout of the class would be borderline sabotage. You need this kind of stability to enforce the compatibility on which shared objects rely on every platform. Upvotes: 2 <issue_comment>username_2: The C++ standard guarantees that memory layouts of a C struct and a C++ class (or struct -- same thing) will be identical, provided that the C++ class/struct fits the criteria of being POD ("Plain Old Data"). So what does POD mean? A class or struct is POD if: All data members are public and themselves POD or fundamental types (but not reference or pointer-to-member types), or arrays of such * It has no user-defined constructors, assignment operators or destructors * It has no virtual functions * It has no base classes So yes in your case, the memory layout is the same. Source: [Structure of a C++ Object in Memory Vs a Struct](https://stackoverflow.com/questions/422830/structure-of-a-c-object-in-memory-vs-a-struct) Upvotes: 4 [selected_answer]<issue_comment>username_3: Yes and no... In your specific case, no. The struct is nothing more than a data container, and the function resides elsewhere. When the function is called, a pointer to the struct is passed as an additional, implicit first parameter that appears as `this` pointer within the function. Matter changes, though, if you add a *virtual* function. Although the C++ standard does not mandate it, vtables are the *defacto* standard, and the class will receive a pointer to a vtable as very first, but invisible member. You can try this out by printing out the size of an object before and after adding the virtual function. On the other hand, if the class *is* virtual already because of inheriting from another class that already has virtual functions, memory layout won't change any more again as there is already a pointer to the vtable included (although it will point to a different location for instances of the sub-class). Upvotes: 1 <issue_comment>username_4: > > Is there a difference in memory layout between this struct and one with a function added to it? > > > ### It might. Since `A` and `B` are standard layout1, and their common initial sequence consists of every non-static data member2, they are *layout-compatible*. The Standard only describe the semantics of an abstract machine, so there is no *guarantee* an object of type `A` will be represented in memory as an object of type `B`, but *layout-compatible* types tend to be. --- 1) [`[class]/7`](http://eel.is/c++draft/class#7) > > A standard-layout class is a class that: > > > * has no non-static data members of type non-standard-layout class (or array of such types) or reference, > * has no virtual functions (10.3) and no virtual base classes (10.1), > * has the same access control (Clause 11) for all non-static data members, > * has no non-standard-layout base classes, > either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and > * has no base classes of the same type as the first non-static data member. > > > 2) [`[class.mem]/21`](http://eel.is/c++draft/class#mem-21) & [`[class.mem]/22`](http://eel.is/c++draft/class#mem-22) > > Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout compatible types (3.9). > > > Upvotes: 3
2018/03/21
389
1,439
<issue_start>username_0: My input tensor is torch.DoubleTensor type. But I got the RuntimeError below: ``` RuntimeError: Expected object of type torch.DoubleTensor but found type torch.FloatTensor for argument #2 'weight' ``` I didn't specify the type of the weight explicitly(i.e. I did not init my weight by myself. The weight is created by pytorch). What will influence the type of weight in the forward process? Thanks a lot!!<issue_comment>username_1: The default type for `weights` and `biases` are `torch.FloatTensor`. So, you'll need to cast either your model to `torch.DoubleTensor` or cast your inputs to `torch.FloatTensor`. For casting your inputs you can do ``` X = X.float() ``` or cast your complete model to `DoubleTensor` as ``` model = model.double() ``` You can also set the default type for all tensors using ``` pytorch.set_default_tensor_type('torch.DoubleTensor') ``` It is better to convert your inputs to `float` rather than converting your model to `double`, because mathematical computations on `double` datatype is considerably slower on GPU. Upvotes: 6 [selected_answer]<issue_comment>username_2: I was also receiving exact same error. The root cause turned out to be this statement in my data loading code: ``` t = t.astype(np.float) ``` Here np.float translates to 64-bit float which maps to DoubleTensor. So changing this to, ``` t = t.astype(np.float32) ``` solved the issue. Upvotes: 2
2018/03/21
593
1,791
<issue_start>username_0: How can I get form data that is setup like an array? My form for a questionlist has many inputs and they all have as name `name='p_Id[UUId of something]'` When i get the `$_POST['p_Id']` in php i get a perfect array. which looks like this. ``` array (size=2) '0d2af2c0ce9d2872c3d153a5021543d1' => array (size=1) 0 => string '4ec83937bb4146ed6b6c0fc44311be83' (length=32) '99de3d39e446040fee8d7033f4ebf459' => array (size=1) 0 => string '3e7373d3fb5145373e4b51ce915de337' (length=32) ``` So it is an array of all the questions with the uuid of the question at top. Inside this question there is an array with the uuid of the selected answer(s). How can i get the values of 'p\_Id' in Javascript and have an array much like this one?<issue_comment>username_1: The default type for `weights` and `biases` are `torch.FloatTensor`. So, you'll need to cast either your model to `torch.DoubleTensor` or cast your inputs to `torch.FloatTensor`. For casting your inputs you can do ``` X = X.float() ``` or cast your complete model to `DoubleTensor` as ``` model = model.double() ``` You can also set the default type for all tensors using ``` pytorch.set_default_tensor_type('torch.DoubleTensor') ``` It is better to convert your inputs to `float` rather than converting your model to `double`, because mathematical computations on `double` datatype is considerably slower on GPU. Upvotes: 6 [selected_answer]<issue_comment>username_2: I was also receiving exact same error. The root cause turned out to be this statement in my data loading code: ``` t = t.astype(np.float) ``` Here np.float translates to 64-bit float which maps to DoubleTensor. So changing this to, ``` t = t.astype(np.float32) ``` solved the issue. Upvotes: 2
2018/03/21
2,777
5,886
<issue_start>username_0: I'm trying to calculate the difference in days of my rows to create interval. My data set called `temp` looks like this, ``` ID Event 31933 11/12/2016 31933 11/14/2016 31750 09/04/2016 31750 09/10/2016 31750 09/30/2016 31750 10/01/2016 30995 09/04/2016 30995 09/09/2016 30995 09/10/2016 30995 9/24/2016 ``` So my question is how can I calculate the difference between dates in day by ID? So for ID 31933 it is 2 days and for 31750 6, 20 and 1 days. I've tried several options which were given in other examples here, such as ``` library(zoo) setDT(temp) Interval<- function(x) difftime(x[3], x[1],units = "days") temp[, INTERVAL := rollapply(Event, 3, diff, align = "left", fill = NA), by= ID] ``` The error here was `"Type of RHS ('double') must match LHS ('logical')`. To check and coerce would impact performance too much for the fastest cases. Either change the type of the target column, or coerce the `RHS` of := yourself (e.g. by using 1L instead of 1)" Also tried a few data.table functions but they did not work. I'm quite new to R, so I suppose there is a simple solution.<issue_comment>username_1: The date class is stored in a format that measures dates by days, so you can perform simple arthimetic with them, [as per this SO thread.](https://stackoverflow.com/questions/2254986/how-to-subtract-add-days-from-to-a-date) It uses a YYYY/MM/DD format. For example ``` abs(as.Date("2016/11/12") - as.Date("2016/11/14")) Time difference of 2 days ``` If you reformat your dates to YYYY/MM/DD, you should be able to use, for example, `abs(temp[1, 2] - temp[2, 2])` to determine the difference between the dates in the first two rows. Upvotes: 0 <issue_comment>username_2: With `data.table` and `lubridate`: ``` library(lubridate) library(data.table) setDT(df)[, Days := c(NA, diff(mdy(Event))), by=ID] ``` or: ``` setDT(df)[, Days := mdy(Event)-lag(mdy(Event)), by=ID] ``` **Result:** ``` ID Event Days 1: 31933 11/12/2016 NA days 2: 31933 11/14/2016 2 days 3: 31750 09/04/2016 NA days 4: 31750 09/10/2016 6 days 5: 31750 09/30/2016 20 days 6: 31750 10/01/2016 1 days 7: 30995 09/04/2016 NA days 8: 30995 09/09/2016 5 days 9: 30995 09/10/2016 1 days 10: 30995 9/24/2016 14 days ``` You can also try the following with `dplyr` and `lubridate`: ``` library(lubridate) library(dplyr) df %>% group_by(ID) %>% mutate(Event = mdy(Event), Days = Event - lag(Event)) ``` **Result:** ``` # A tibble: 10 x 3 # Groups: ID [3] ID Event Days 1 31933 2016-11-12 NA days 2 31933 2016-11-14 2 days 3 31750 2016-09-04 NA days 4 31750 2016-09-10 6 days 5 31750 2016-09-30 20 days 6 31750 2016-10-01 1 days 7 30995 2016-09-04 NA days 8 30995 2016-09-09 5 days 9 30995 2016-09-10 1 days 10 30995 2016-09-24 14 days ``` Or if you prefer to remove the NA rows: ``` df %>% group_by(ID) %>% mutate(Event = mdy(Event), Days = Event - lag(Event)) %>% filter(Days > 0) ``` **Result:** ``` # A tibble: 7 x 3 # Groups: ID [3] ID Event Days 1 31933 2016-11-14 2 days 2 31750 2016-09-10 6 days 3 31750 2016-09-30 20 days 4 31750 2016-10-01 1 days 5 30995 2016-09-09 5 days 6 30995 2016-09-10 1 days 7 30995 2016-09-24 14 days ``` **Data:** ``` df = structure(list(ID = c(31933L, 31933L, 31750L, 31750L, 31750L, 31750L, 30995L, 30995L, 30995L, 30995L), Event = structure(c(6L, 7L, 1L, 3L, 4L, 5L, 1L, 2L, 3L, 8L), .Label = c("09/04/2016", "09/09/2016", "09/10/2016", "09/30/2016", "10/01/2016", "11/12/2016", "11/14/2016", "9/24/2016"), class = "factor")), .Names = c("ID", "Event"), class = "data.frame", row.names = c(NA, -10L)) ``` Upvotes: 2 <issue_comment>username_3: There are several problems: * the dates should be of `"Date"` class, not `"character"` class * in R, `NA` is logical. An `NA` of type double is written `NA_real_` Often it does not matter but in this case it matters due to the way data.table works. * if you indent your code 4 spaces then SO will format it for you * the desired output is not shown in the question but from the code it is asking for the difference between every other row. We show both the solution for every other row but if you wanted successive rows just replace 2 with 1 in each solution. Using the above we write it like this: ``` library(data.table) library(zoo) setDT(temp) temp$Event <- as.Date(temp$Event, "%m/%d/%Y") roll <- function(x, k) rollapply(x, k+1, diff, lag = k, align = "left", fill = NA_real_) temp[, INTERVAL := roll(as.numeric(Event), 2), by = ID] ``` giving for the every other row case: ``` > temp ID Event INTERVAL 1: 31933 2016-11-12 NA 2: 31933 2016-11-14 NA 3: 31750 2016-09-04 26 4: 31750 2016-09-10 21 5: 31750 2016-09-30 NA 6: 31750 2016-10-01 NA 7: 30995 2016-09-04 6 8: 30995 2016-09-09 15 9: 30995 2016-09-10 NA 10: 30995 2016-09-24 NA ``` This alternative using data.table's `shift` could also be used and only requires data.table: ``` temp[, INTERVAL := as.numeric(shift(Event, 2, type = "lead") - Event), by = ID] ``` If you had intended successive rows rather than every other row replace 2 in either of the above solutions with 1. Note ---- The input in reproducible form is: ``` Lines <- "ID Event 31933 11/12/2016 31933 11/14/2016 31750 09/04/2016 31750 09/10/2016 31750 09/30/2016 31750 10/01/2016 30995 09/04/2016 30995 09/09/2016 30995 09/10/2016 30995 09/24/2016" temp <- read.table(text = Lines, header = TRUE) ``` Upvotes: 1 <issue_comment>username_4: Great thanks for all your suggestions. I figured it out. ``` temp<- data.table(ID,Event, key = c("ID", "Event")) temp[,INTER := c(0,'units<-'(diff(Event), "days")),by= ID] ``` and then merged it with my dataset. Suppose its not very elegant but it worked. Upvotes: 0
2018/03/21
2,665
5,894
<issue_start>username_0: So, far I have the program working, but I dont know how to close it out using the enter key or returning a value thats not a name like (y,n). I havent seen a solution that would write well into my code without giving me bugs so I feel like there might be a formatting error due to my inexperience. ``` namespace Likes { class Program { static void Main(string[] args) { var rollcall = new List(); while (true) { string names = Console.ReadLine(); rollcall.Add(names); var number = rollcall.Count; if (number == 1) { Console.WriteLine(" {0} likes your post.", rollcall[0]); continue; } else if (number == 2) { Console.WriteLine("{0} and {1} likes your post\n Press Enter to Exit", rollcall[0], rollcall[1]); continue; } else if (number == 3) { Console.WriteLine("{0}, {1}, and {2} other likes your post.\n Press Enter to Exit", rollcall[0], rollcall[1], number - 2); continue; } else if (number >= 4) { Console.WriteLine("{0}, {1}, and {2} others like your post.\n Press Enter to Exit", rollcall[0], rollcall[1], number - 2); continue; } } } } } ```<issue_comment>username_1: The date class is stored in a format that measures dates by days, so you can perform simple arthimetic with them, [as per this SO thread.](https://stackoverflow.com/questions/2254986/how-to-subtract-add-days-from-to-a-date) It uses a YYYY/MM/DD format. For example ``` abs(as.Date("2016/11/12") - as.Date("2016/11/14")) Time difference of 2 days ``` If you reformat your dates to YYYY/MM/DD, you should be able to use, for example, `abs(temp[1, 2] - temp[2, 2])` to determine the difference between the dates in the first two rows. Upvotes: 0 <issue_comment>username_2: With `data.table` and `lubridate`: ``` library(lubridate) library(data.table) setDT(df)[, Days := c(NA, diff(mdy(Event))), by=ID] ``` or: ``` setDT(df)[, Days := mdy(Event)-lag(mdy(Event)), by=ID] ``` **Result:** ``` ID Event Days 1: 31933 11/12/2016 NA days 2: 31933 11/14/2016 2 days 3: 31750 09/04/2016 NA days 4: 31750 09/10/2016 6 days 5: 31750 09/30/2016 20 days 6: 31750 10/01/2016 1 days 7: 30995 09/04/2016 NA days 8: 30995 09/09/2016 5 days 9: 30995 09/10/2016 1 days 10: 30995 9/24/2016 14 days ``` You can also try the following with `dplyr` and `lubridate`: ``` library(lubridate) library(dplyr) df %>% group_by(ID) %>% mutate(Event = mdy(Event), Days = Event - lag(Event)) ``` **Result:** ``` # A tibble: 10 x 3 # Groups: ID [3] ID Event Days 1 31933 2016-11-12 NA days 2 31933 2016-11-14 2 days 3 31750 2016-09-04 NA days 4 31750 2016-09-10 6 days 5 31750 2016-09-30 20 days 6 31750 2016-10-01 1 days 7 30995 2016-09-04 NA days 8 30995 2016-09-09 5 days 9 30995 2016-09-10 1 days 10 30995 2016-09-24 14 days ``` Or if you prefer to remove the NA rows: ``` df %>% group_by(ID) %>% mutate(Event = mdy(Event), Days = Event - lag(Event)) %>% filter(Days > 0) ``` **Result:** ``` # A tibble: 7 x 3 # Groups: ID [3] ID Event Days 1 31933 2016-11-14 2 days 2 31750 2016-09-10 6 days 3 31750 2016-09-30 20 days 4 31750 2016-10-01 1 days 5 30995 2016-09-09 5 days 6 30995 2016-09-10 1 days 7 30995 2016-09-24 14 days ``` **Data:** ``` df = structure(list(ID = c(31933L, 31933L, 31750L, 31750L, 31750L, 31750L, 30995L, 30995L, 30995L, 30995L), Event = structure(c(6L, 7L, 1L, 3L, 4L, 5L, 1L, 2L, 3L, 8L), .Label = c("09/04/2016", "09/09/2016", "09/10/2016", "09/30/2016", "10/01/2016", "11/12/2016", "11/14/2016", "9/24/2016"), class = "factor")), .Names = c("ID", "Event"), class = "data.frame", row.names = c(NA, -10L)) ``` Upvotes: 2 <issue_comment>username_3: There are several problems: * the dates should be of `"Date"` class, not `"character"` class * in R, `NA` is logical. An `NA` of type double is written `NA_real_` Often it does not matter but in this case it matters due to the way data.table works. * if you indent your code 4 spaces then SO will format it for you * the desired output is not shown in the question but from the code it is asking for the difference between every other row. We show both the solution for every other row but if you wanted successive rows just replace 2 with 1 in each solution. Using the above we write it like this: ``` library(data.table) library(zoo) setDT(temp) temp$Event <- as.Date(temp$Event, "%m/%d/%Y") roll <- function(x, k) rollapply(x, k+1, diff, lag = k, align = "left", fill = NA_real_) temp[, INTERVAL := roll(as.numeric(Event), 2), by = ID] ``` giving for the every other row case: ``` > temp ID Event INTERVAL 1: 31933 2016-11-12 NA 2: 31933 2016-11-14 NA 3: 31750 2016-09-04 26 4: 31750 2016-09-10 21 5: 31750 2016-09-30 NA 6: 31750 2016-10-01 NA 7: 30995 2016-09-04 6 8: 30995 2016-09-09 15 9: 30995 2016-09-10 NA 10: 30995 2016-09-24 NA ``` This alternative using data.table's `shift` could also be used and only requires data.table: ``` temp[, INTERVAL := as.numeric(shift(Event, 2, type = "lead") - Event), by = ID] ``` If you had intended successive rows rather than every other row replace 2 in either of the above solutions with 1. Note ---- The input in reproducible form is: ``` Lines <- "ID Event 31933 11/12/2016 31933 11/14/2016 31750 09/04/2016 31750 09/10/2016 31750 09/30/2016 31750 10/01/2016 30995 09/04/2016 30995 09/09/2016 30995 09/10/2016 30995 09/24/2016" temp <- read.table(text = Lines, header = TRUE) ``` Upvotes: 1 <issue_comment>username_4: Great thanks for all your suggestions. I figured it out. ``` temp<- data.table(ID,Event, key = c("ID", "Event")) temp[,INTER := c(0,'units<-'(diff(Event), "days")),by= ID] ``` and then merged it with my dataset. Suppose its not very elegant but it worked. Upvotes: 0
2018/03/21
779
2,448
<issue_start>username_0: How can i remove from **data** to end of the string in a single function? I need to pass the string and get the desired output. How can i trim the string which is not needed ? How can i achieve this? ``` var firsturl = "www.google.com/sample/data/merge.html" var secondurl = "www.google.com/sample/data/change.html" ``` expected output ``` var firsturl = "www.google.com/sample/" var secondurl = "www.google.com/sample/" ``` I have tried this much, but to the end, the word changes. ``` let url = window.location.href url.replace('data', '') ```<issue_comment>username_1: You can use `split()` on the string by `data` then take the string from first index: ```js var firsturl = "www.google.com/sample/data/merge.html" var secondurl = "www.google.com/sample/data/change.html" firsturl = firsturl.split('data')[0]; secondurl = secondurl.split('data')[0]; console.log(firsturl); console.log(secondurl); ``` **Using Function:** ```js function getSubString(str){ return str.split('data')[0]; } var firsturl = "www.google.com/sample/data/merge.html"; var secondurl = "www.google.com/sample/data/change.html"; console.log(getSubString(firsturl)); console.log(getSubString(secondurl)); ``` Upvotes: 2 <issue_comment>username_2: Use `String#replace` with a regular expression: ```js var firsturl = "www.google.com/sample/data/merge.html" var secondurl = "www.google.com/sample/data/change.html" function trimData(str) { return str.replace(/data.*$/, ''); } console.log(trimData(firsturl)); console.log(trimData(secondurl)); ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: You can split by '/' and get the firts and second part by destructuring: ```js var firstUrl = "www.google.com/sample/data/merge.html"; var [part1, part2] = firstUrl.split('/'); var res = [part1, part2].join('/'); console.log(res); ``` Upvotes: 0 <issue_comment>username_4: Your problem can be simply solved by using regex and str.replace() method provided by javascript itself ``` var firsturl = "www.google.com/sample/data/merge.html" var secondurl = "www.google.com/sample/data/change.html" function trimmer(regex,str){ return str.replace(new RegExp(regex,'i'),''); } changedFirstUrl = trimmer('data.*',firstUrl); changedSecondUrl = trimmer('data.*',secondUrl); ``` With this the result you get is `www.google.com/sample/` I hope this helps you Happy coding Upvotes: 0
2018/03/21
794
3,282
<issue_start>username_0: ``` public abstract class Entity { public abstract IList Values { get; set; } } public class GenericEntity : Entity { private IList \_Values; public override IList Values { get { return \_Values; } set { ValidateValues(value); \_Values = value; } } protected virtual void ValidateValues(IList values) { // many validation conditions here, if values validation fails, throws... } } public class AEntity : GenericEntity { protected override void ValidateValues(IList values) { base.ValidateValues(values); // there is an extra validation condition if(values.Count < 1) throw InvalidOperationException("values count!"); } } public class BEntity : GenericEntity { protected override void ValidateValues(IList values) { base.ValidateValues(values); if(values.Count < 2) throw InvalidOperationException("values count!"); } } ``` Is this a violation of the LSP for `GenericEntity` users when its inheritors have an extra validation conditions (checking the count of `Values` items)? I think so since preconditions have become strengthened. Does it mean should I remove `GenericEntity` class and let both `AEntity` and `BEntity` be direct inheritors of `Entity`? But it will lead to repeated code in the two classes. Also I consider another option: when `Entity` gets a referenece to some abstract class `Validation` instance. Is it the most elegant solution of the issue?<issue_comment>username_1: Currently not "violating LSP" totally because you do not alter the class base validations. Unfortunately, Other developpers can override `ValidateValues` without calling base method... A solution to avoid this is to create a two methods : ``` public void ValidateValues(IList values) { // many validation conditions here, if values validation fails, throws... ValidateValuesEx(); } protected virtual void ValidateValuesEx() { // for extension } ``` Upvotes: 1 <issue_comment>username_2: With your code design, a sub-class could completely bypass your validation by not calling `base.ValidateValues`. I don't know if this is a LSP-violation, but it is something you should consider. If you make a small change, you can ensure that the validation that happens in `GenericEntity.ValidateValues` gets called every time. ``` public class GenericEntity : Entity { private IList \_Values; public override IList Values { get { return \_Values; } set { ValidateValues(value); \_Values = value; } } private void ValidateValues(IList values) { // many validation conditions here, if values validation fails, throws... this.OnValidateValues(values); } protected virtual void OnValidateValues(IList values) { //do nothing. Let sub-classes override. } } } public class AEntity : GenericEntity { protected override void OnValidateValues(IList values) { if(values.Count < 1) throw InvalidOperationException("values count!"); } } ``` In this code, the GenericEntity controls the call to the sub-classes' validation code. Not the other way around. The parent class validation is guaranteed to always run, and it always happens before any sub-class validation. Note that the code works exactly the same whether or not the sub-class calls `base.OnValidateValues`. Upvotes: 0
2018/03/21
606
1,562
<issue_start>username_0: I have 2 columns in a table :[CatId], [ItemId] CatId is 4 digits and ItemId is 1 or 2. What I want to achieve is to replace the ItemId with the concatenation [CatId]+[ItemId] , but if ItemId is 1 digit then add a 0. For example: `CatId: 1555, ItemId: 12 -> ItemId: 155512` `CatId: 1555, ItemId: 2 -> ItemId: 155502`<issue_comment>username_1: I would do this as ``` select cast(catId as int) * 100 + cast(itemid as int) ``` If you want this as a string: ``` select cast(cast(catId as int) * 100 + cast(itemid as int) as varchar(255)) ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: If you want to *update* your table then try this option: ``` UPDATE yourTable SET ItemId = CatId + RIGHT('00' + ItemId, 2); ``` This assumes that the `CatId` and `ItemId` columns are text and not numbers. If they be numeric, then see Gordon's answer. Upvotes: 1 <issue_comment>username_3: ``` CREATE TABLE [dbo].[Test]( [CatId] [char](4) NULL, [ItemId] [char](2) NULL ) ON [PRIMARY] Insert Data USE [ABC] GO INSERT INTO [dbo].[Test]([CatId] ,[ItemId]) VALUES ('1231','1') INSERT INTO [dbo].[Test]([CatId] ,[ItemId]) VALUES ('1232','2') INSERT INTO [dbo].[Test]([CatId] ,[ItemId]) VALUES ('1233','10') INSERT INTO [dbo].[Test]([CatId] ,[ItemId]) VALUES ('1234','23') INSERT INTO [dbo].[Test]([CatId] ,[ItemId]) VALUES ('1237','6') Select [CatId]+ (Case WHEN len(ItemId) =1 THEN '0'+[ItemId] ELSE [ItemId] END ) as DATA from [dbo].[Test] **Result** DATA 123101 123202 123310 123423 123706 ``` Upvotes: 0
2018/03/21
427
1,402
<issue_start>username_0: I'm currently trying to figure out how to access the child of one of the elements in the following collection: `var items = document.querySelectorAll(".timeline li");` At one point I loop through the `items` and I'd like to be able access one of the child elements of the `li` that I collected. If I use `items[i]` I will get list item, but from there I'm not sure how to access the span inside of it. Any ideas?<issue_comment>username_1: > > If I use items[i] I will get list item, but from there I'm not sure > how to access the span inside of it. > > > Use `querySelector` on `items[i]` ``` var spanEl = items[i].querySelector( "span" ); ``` If there are multiple `span`s, use `querySelectorAll` ``` var spanEls = items[i].querySelectorAll( "span" ); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use the function `querySelector` on `items[i]`. ``` items[i].querySelector(...) ``` **Why not just to get the `span` directly:** ``` var items = document.querySelectorAll(".timeline li > span"); ``` ```js var items = document.querySelectorAll(".timeline li > span"); items.forEach(function(span) { console.log("Parent: ", span.closest('li').getAttribute("id")); console.log(span.textContent); }); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` ```html * span#1 * span#2 * span#3 ``` Upvotes: 1
2018/03/21
362
1,151
<issue_start>username_0: Hi Can anyone please help in getting linked defects for test runs in using rest API. I have tried giving ../defects//defect-links but i am getting bad request error.<issue_comment>username_1: > > If I use items[i] I will get list item, but from there I'm not sure > how to access the span inside of it. > > > Use `querySelector` on `items[i]` ``` var spanEl = items[i].querySelector( "span" ); ``` If there are multiple `span`s, use `querySelectorAll` ``` var spanEls = items[i].querySelectorAll( "span" ); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use the function `querySelector` on `items[i]`. ``` items[i].querySelector(...) ``` **Why not just to get the `span` directly:** ``` var items = document.querySelectorAll(".timeline li > span"); ``` ```js var items = document.querySelectorAll(".timeline li > span"); items.forEach(function(span) { console.log("Parent: ", span.closest('li').getAttribute("id")); console.log(span.textContent); }); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` ```html * span#1 * span#2 * span#3 ``` Upvotes: 1
2018/03/21
577
1,913
<issue_start>username_0: I want a callback to be called when a specific DOM node enters the viewport. Additionally I have the following situation: * [`aFarkas/lazysizes`](https://github.com/aFarkas/lazysizes) is used on the page. * [`Intersection Observer API`](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Browser_compatibility) is not implemented in some of the Browsers that need to be supported. I don't want to add a [`Intersection Observer Polyfill`](https://github.com/w3c/IntersectionObserver/tree/master/polyfill) as `aFarkas/lazysizes` comes bundled with the same functionality. Hence my question: Is it possible to use `aFarkas/lazysizes` to detect when a DOM node enters the viewport?<issue_comment>username_1: No I don't think its possible. Looks like aFarkas/lazysizes only uses the intersection observer if available: <https://github.com/aFarkas/lazysizes/blob/master/src/lazysizes-intersection.js#L11> Otherwise they throttle an internal function called `checkElements` that is triggered on every scroll. <https://github.com/aFarkas/lazysizes/blob/master/src/lazysizes-core.js#L332> Does not look like they expose this function: <https://github.com/aFarkas/lazysizes/blob/master/src/lazysizes-core.js#L676> They don't fully polyfill it, they just implement the *make sure something is visible part* themselves. So could you depending on what you are doing. `` Upvotes: 1 <issue_comment>username_2: You can use the `data-expand` attribute to tell `aFarkas/lazysizes` when to trigger the `lazybeforeunveil` event as follows: ```html This will trigger a lazybeforeunveil event when entering the viewport. ``` ```js window.addEventListener( 'lazybeforeunveil', callback, false ); ``` See the documentation for the `data-expand` attribute: [aFarkas/lazysizes#data-expand-attribute](https://github.com/aFarkas/lazysizes#data-expand-attribute) Upvotes: 2
2018/03/21
1,362
3,646
<issue_start>username_0: I'm trying to get all Youtube video IDs from string like this: ``` https://www.youtube.com/watch?v=OovKTBO4aQs https://www.youtube.com/watch?v=DOQsYk8cbnE https://www.youtube.com/watch?v=97aiSGxmizg ``` Following to [this answers](https://stackoverflow.com/questions/6323417/how-do-i-retrieve-all-matches-for-a-regular-expression-in-javascript) I wrote code: ``` var re = /(?:https?:\/\/)?(?:youtu\.be\/|(?:www\.)?youtube\.com\/watch(?:\.php)?\?.*v=)([a-zA-Z0-9\-_]+)/g, str = 'https://www.youtube.com/watch?v=OovKTBO4aQs https://www.youtube.com/watch?v=DOQsYk8cbnE https://www.youtube.com/watch?v=97aiSGxmizg', match; while (match = re.exec(str)) { if (match.index === re.lastIndex) { re.lastIndex++; } console.log(match[1]); } ``` But `console.log` shows only last ID `97aiSGxmizg`. What am I doing wrong?<issue_comment>username_1: You regex is not correct. The correct regex would be like this: ```js var re = /(?:https?:\/\/)?(?:youtu\.be\/|(?:www\.)?youtube\.com\/watch(?:\.php)?\?[^ ]*v=)([a-zA-Z0-9\-_]+)/g; var str = 'https://www.youtube.com/watch?v=OovKTBO4aQs jiberish https://www.youtube.com/watch?v=DOQsYk8cbnE jiberish a https://www.youtube.com/watch?v=97aiSGxmizg' console.log(str.match(re)) ``` Upvotes: -1 [selected_answer]<issue_comment>username_2: The capture group will only match the last match in that string. Split the strings into an array and log them there: ```js var re = /(?:https?:\/\/)?(?:youtu\.be\/|(?:www\.)?youtube\.com\/watch(?:\.php)?\?.*v=)([a-zA-Z0-9\-_]+)/g, str = 'https://www.youtube.com/watch?v=OovKTBO4aQs https://www.youtube.com/watch?v=DOQsYk8cbnE https://www.youtube.com/watch?v=97aiSGxmizg', strs = str.split(' '); strs.forEach((str) => { var match; while (match = re.exec(str)) { if (match.index === re.lastIndex) { re.lastIndex++; } console.log(match[1]); } }) ``` Upvotes: 0 <issue_comment>username_3: Assuming v=something, try this (regex from [Extract parameter value from url using regular expressions](https://stackoverflow.com/questions/1280557/extract-parameter-value-from-url-using-regular-expressions)) ```js var regex = /\?v=([a-z0-9\-]+)\&?/gi, matches = [], index=1; urls = "https://www.youtube.com/watch?v=OovKTBO4aQs https://www.youtube.com/watch?v=DOQsYk8cbnE https://www.youtube.com/watch?v=97aiSGxmizg"; while (match = regex.exec(urls)) matches.push(match[index]) console.log(matches) ``` Upvotes: 1 <issue_comment>username_4: Based on the posted string's format, `v=id`, one can do something as simple as split the string at space and the again, combined with `reduce()`, at `v=`, to get the successfully split'ed id's. *I also used an anonymous function `(function(){...})();` to only have to run the split once.* Stack snippet ```js var str = 'https://www.youtube.com/watch?v=OovKTBO4aQs https://www.youtube.com/watch?v=DOQsYk8cbnE https://www.youtube.com/watch?v=97aiSGxmizg'; var list = str.split(' ').reduce(function(r, e) { (function(i){ if (i.length > 1) r.push(i[1]); })(e.split('v=')); return r; }, []); console.log(list); ``` --- As mentioned, if there are other formats, one can easily use a regex, e.g. Stack snippet ```js var str = 'https://www.youtube.com/watch?v=OovKTBO4aQs https://www.youtube.com/watch?v=DOQsYk8cbnE https://www.youtube.com/watch?v=97aiSGxmizg http://www.youtube.com/v/-wtIMTCHWuI http://youtu.be/-DOQsYk8cbnE'; var list = str.split(' ').reduce(function(r, e) { (function(i){ if (i.length > 1) r.push(i[1]); })(e.split(/v=|v\/-|be\/-/)); return r; }, []); console.log(list); ``` Upvotes: 1
2018/03/21
1,704
6,610
<issue_start>username_0: What I have: A `RecyclerView` with pictures of places like bars, coffee stores, etc. What I want: That when you click on one of these images I show you the info of the selected place My question: How can i set the `OnCLickListener` for the third picture for example Please, if you can explain with code it would be great, I am not good programming yet, so I would really appreciate My adapter ``` public class AdapterDatos extends RecyclerView.Adapter implements View.OnClickListener { ArrayList listalugares; private View.OnClickListener listener; public AdapterDatos(ArrayList listaLugares) { listalugares = listaLugares; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {//esto es lo que hacereferencia al xml donde vamos a meter la info View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item\_list,null,false);//aqui le asignamos el valor del view al viewHolder view.setOnClickListener(this); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) {// este metodo es el que se encarga de establecer la conexion entre el adaptador y la clase Viewholder ( a la cual le asignamos el xml) holder.etiLugares.setText(listalugares.get(position).getLugares());// asi se asignan los textos holder.Foto.setImageResource(listalugares.get(position).getFoto());//asi se asignan las fotos } @Override public int getItemCount() {//este metodo va a decir el tamaño del viewHolder, en este caso de tamaño del array listalugares return listalugares.size();//se hace asi } public void setOnClickListener(View.OnClickListener listener){ this.listener = listener; } @Override public void onClick(View view) { if(listener!= null){ listener.onClick(view); } } public class ViewHolder extends RecyclerView.ViewHolder{ TextView etiLugares; ImageView Foto; Context context; public ViewHolder(View itemView) { super(itemView); etiLugares = (TextView) itemView.findViewById(R.id.idNombre);//esto hace referencia a los elementos donde queremos meter la info Foto = (ImageView) itemView.findViewById(R.id.idImagen); } } } ``` My java class ``` public class foodAndGo extends Activity { ArrayList listalugares; RecyclerView recyclerLugares; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity\_food\_and\_go); listalugares = new ArrayList<>(); recyclerLugares = (RecyclerView) findViewById(R.id.RecyclerID); recyclerLugares.setLayoutManager(new LinearLayoutManager(this)); llenarNombres(); AdapterDatos adapter = new AdapterDatos(listalugares); adapter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(),"Seleccion"+listalugares.get(recyclerLugares.getChildAdapterPosition(v)).getLugares(),Toast.LENGTH\_SHORT).show(); Intent myIntent = new Intent(foodAndGo.this, MapsActivity.class); startActivity(myIntent); } }); recyclerLugares.setAdapter(adapter); } private void llenarNombres() { listalugares.add(new ClaseNueva("Restaurantes", R.drawable.carnemejor)); listalugares.add(new ClaseNueva("Bares", R.drawable.beers)); listalugares.add(new ClaseNueva("Cafeterías",R.drawable.desayunosmejor)); listalugares.add(new ClaseNueva("Pizzerias",R.drawable.pizzaamejor)); listalugares.add(new ClaseNueva("Favoritos",R.drawable.favoritosmejo)); } } ```<issue_comment>username_1: If you need to set onClick only for the third position from the List Remove your `view.setOnClickListener(this);` from `onCreateViewHolder` ``` @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {//esto es lo que hacereferencia al xml donde vamos a meter la info View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,null,false);//aqui le asignamos el valor del view al viewHolder return new ViewHolder(view); } ``` set OnClick inside the `OnBindViewHolder` only for the Third position using if Statement ``` @Override public void onBindViewHolder(ViewHolder holder, int position) {// este metodo es el que se encarga de establecer la conexion entre el adaptador y la clase Viewholder ( a la cual le asignamos el xml) holder.etiLugares.setText(listalugares.get(position).getLugares());// asi se asignan los textos holder.Foto.setImageResource(listalugares.get(position).getFoto());//asi se asignan las fotos if(holder.getAdapterPosition() == 3) holder.itemView.setOnClickListener(this); // Parent ID } ``` Upvotes: 0 <issue_comment>username_2: > > Attach a click listener on view > > > ``` holder.imgView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Do Something } ``` Upvotes: 1 <issue_comment>username_3: In your adapter's **onBindViewHolder** try this code: ``` holder.Foto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(position==0){ Intent intent = new Intent(context,MapsActivity.class) // You can get context from onCreateViewHolder, initialize one from parent.getContext() or pass one in constructor of adapter startActivity(intent) }else if(position==1){ // open Second Activity }else{ // open Third Activity } }); ``` Upvotes: 1 [selected_answer]<issue_comment>username_4: ``` @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {//esto es lo que hacereferencia al xml donde vamos a meter la info View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,null,false);//aqui le asignamos el valor del view al viewHolder return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) {// este metodo es el que se encarga de establecer la conexion entre el adaptador y la clase Viewholder ( a la cual le asignamos el xml) holder.etiLugares.setText(listalugares.get(position).getLugares());// asi se asignan los textos holder.Foto.setImageResource(listalugares.get(position).getFoto());//asi se asignan las fotos if(position%3==0) holder.Foto.setOnClickListener(this); } ``` Upvotes: 0
2018/03/21
1,004
3,544
<issue_start>username_0: **My Objective:** To update array attribute and other sub json attribute programatically. **Environment:** Visual Studio C#, NewtonSoft Library I have a json file sample as below ``` { "model": "xx.yyy", "make": "philips", "alias": [ "abc", "bcd", "aee", "sample" ], "variables": { "temperature": { "dataType": "number", "unit": { "value": "°C", "enum": [ "°C", "°F" ] }, "min": -50, "max": 300, "description": "The skin temperature measured outside of the motor." } } } ``` I am loading the json file content as below ``` var jsonContent = File.ReadAllText(@"\path\example.json"); ``` I want to update **alias** attribute as below First I parse the data as below to convert into an object ``` var dataObj = JObject.Parse(jsonContent); ``` From here I could able to update the root level properties as below. ``` dataObj.Root["make"].Replace("siemens"); ``` I am not sure how to update the ***alias*** attribute and ***datatype*** attribute under *variable*. I want it as below ``` "alias": [ "abc", "bcd", "aee", "discard" ] "datatype": "string" ``` As a crude way I tried replacing the values as below after serializing it. ``` var serializedData = JsonConvert.SerializeObject(dataObj); serializedData.Replace("sample", "discard"); ``` That too did not work. Any help. > > Note: I wish to see the solution without associating to class object > > ><issue_comment>username_1: This code works for me. I used this json and deserialized it into a class object. Once you have a class object, you can play with it and update whataver you want to. JSON : ``` { "model": "xx.yyy", "make": "philips", "alias": [ "abc", "bcd", "aee", "sample" ], "variables": { "temperature": { "dataType": "number", "unit": { "value": "°C", "enum": [ "°C", "°F" ] }, "min": -50, "max": 300, "description": "The skin temperature measured outside of the motor." } } } ``` C# classes : ``` public class Unit { public string value { get; set; } public List @enum { get; set; } } public class Temperature { public string dataType { get; set; } public Unit unit { get; set; } public int min { get; set; } public int max { get; set; } public string description { get; set; } } public class Variables { public Temperature temperature { get; set; } } public class RootObject { public string model { get; set; } public string make { get; set; } public List alias { get; set; } public Variables variables { get; set; } } ``` C# Code: ``` var jsonContent = File.ReadAllText(@"C:\Users\kanaka\Desktop\sample.json"); var serializedData = JsonConvert.DeserializeObject(jsonContent); var q = serializedData.variables.temperature.unit.@enum; // update whatever you want to, serialize again ``` Now you can update the class object values to whatever you want to. Once updated, serialize it again. It will be more maintainable and easy if you deserialize it to a class object Upvotes: 0 <issue_comment>username_2: For string array attribute **alias** I have achieved as below ``` var aliasNew = new string[] { "abc", "bcd", "aee", "discard"}; var aliasSer = JsonConvert.SerializeObject(aliasNew); dataObj.Root["alias"].Replace[aliasSer] ``` For variable attribute part I have achieved as below ``` dataObj.Root["variables"]["temperature"]["dataType"].Replace("string"); ``` Upvotes: 2 [selected_answer]
2018/03/21
882
3,155
<issue_start>username_0: I'm building a .NET c# app that's connecting to my SQL Anywhere 12 Database to get data using the ODBC driver but i have a weird problem that whenever i use a filter in the query i get nothing in the reader but if i do the same query in Sybase Center i get the expected results .. this is an example of my code ``` connection = new OdbcConnection(conStrMonitor); connection.Open(); var cmd = new OdbcCommand("Select art_artnr, art_ben from monitor.ARTIKEL WHERE art_artnr='VSV203798'", connection); var sdr = cmd.ExecuteReader(); while (sdr.Read()) { SearchArticleNr article = new SearchArticleNr(); article.Article = sdr["art_artnr"].ToString(); article.Ben = sdr["art_ben"].ToString(); SarticleList.Add(article); } ``` reader loop does not trigger and when i look at sdr.hasrows it's set as false [Using the same query in Sybase Central](https://i.stack.imgur.com/M8E0z.png) i tried other filters for example LIKE and the same problem occurs then, i'm at a loss as to why this is happening. reference used for my app is System.Data.Odbc<issue_comment>username_1: This code works for me. I used this json and deserialized it into a class object. Once you have a class object, you can play with it and update whataver you want to. JSON : ``` { "model": "xx.yyy", "make": "philips", "alias": [ "abc", "bcd", "aee", "sample" ], "variables": { "temperature": { "dataType": "number", "unit": { "value": "°C", "enum": [ "°C", "°F" ] }, "min": -50, "max": 300, "description": "The skin temperature measured outside of the motor." } } } ``` C# classes : ``` public class Unit { public string value { get; set; } public List @enum { get; set; } } public class Temperature { public string dataType { get; set; } public Unit unit { get; set; } public int min { get; set; } public int max { get; set; } public string description { get; set; } } public class Variables { public Temperature temperature { get; set; } } public class RootObject { public string model { get; set; } public string make { get; set; } public List alias { get; set; } public Variables variables { get; set; } } ``` C# Code: ``` var jsonContent = File.ReadAllText(@"C:\Users\kanaka\Desktop\sample.json"); var serializedData = JsonConvert.DeserializeObject(jsonContent); var q = serializedData.variables.temperature.unit.@enum; // update whatever you want to, serialize again ``` Now you can update the class object values to whatever you want to. Once updated, serialize it again. It will be more maintainable and easy if you deserialize it to a class object Upvotes: 0 <issue_comment>username_2: For string array attribute **alias** I have achieved as below ``` var aliasNew = new string[] { "abc", "bcd", "aee", "discard"}; var aliasSer = JsonConvert.SerializeObject(aliasNew); dataObj.Root["alias"].Replace[aliasSer] ``` For variable attribute part I have achieved as below ``` dataObj.Root["variables"]["temperature"]["dataType"].Replace("string"); ``` Upvotes: 2 [selected_answer]
2018/03/21
633
2,477
<issue_start>username_0: I want to update the values of the DataGrid only when we come out of the control. So to achieve this i used LostFocus event of the datagrid. But this event triggering every action of the datagrid. For example when i clik on the cell to edit it is triggering. Control ctrl = FocusManager.GetFocusedElement(this) as Control; gives always null. :( ``` DataGrid simpleTable = new DataGrid(); DataGridTextColumn textColumn = new DataGridTextColumn(); textColumn.Width = new DataGridLength(DefaultSize.Width/2, DataGridLengthUnitType.Pixel); simpleTable.Style = tableStyle; textColumn.Binding = new Binding("Value"); textColumn.ElementStyle = elementStyle; // textColumn.Width = DataGridLength.SizeToCells; simpleTable.Columns.Add(textColumn); simpleTable.ItemsPanel = template; simpleTable.LostFocus += _dataGridLostFocus; private void _dataGridLostFocus(object sender, RoutedEventArgs e) { Control ctrl = FocusManager.GetFocusedElement(this) as Control; if (ctrl.Parent != null && ctrl.Parent.GetType() != typeof(DataGridCell)) MessageBox.Show("outside!");} ```<issue_comment>username_1: If I remember correctly, the DataGrid looses the Focus because the inner control does receive it. Please try [IsKeyboardFocusWithin](https://msdn.microsoft.com/en-us/library/system.windows.uielement.iskeyboardfocuswithinchanged(v=vs.110).aspx) either by using the property or with this event. Upvotes: 2 [selected_answer]<issue_comment>username_2: When `DataGridCell` loses focus, it triggers the `DataGrid`Lost Focus event. You need to handle the cells event. Throw this style in your `DataGrid` ``` <EventSetter Event="LostFocus" Handler="DataGridCell\_LostFocus"/> ``` Then in your code behind ``` private void DataGridCell_LostFocus(object sender, RoutedEventArgs e) { e.Handled = true; } ``` EDIT: Since you are creating your DataGrid dynamically, here is how you would style the DataGrid's cells to subscribe to the lost focus event above. Create a delagate ``` private delegate void Lost_Focus_Delegate(object sender, RoutedEventArgs e); ``` Then in your DataGrid generation. ``` Style style = new Style { TargetType = typeof(DataGridCell) }; style.Setters.Add(new EventSetter(LostFocusEvent, new RoutedEventHandler(new Lost_Focus_Delegate(this.DataGridCell_LostFocus)))); dataGrid.CellStyle = style; ``` Upvotes: 0
2018/03/21
563
2,140
<issue_start>username_0: Not even sure the best way to describe it, but basically I have a function in an Express Controller, available at /api/lookupJobName which takes query param Q, which is a number, and then does some background work (connects to Salesforce, looks up the job number, gets it's actual name) and returns a json object like this: ``` oppName = { name: "whateverCameBack" } res.json(oppName) ``` Pretty straightforward, and I created it that way because it gets called from some client-side JS when they enter a number in a form. Now I'm further along in the project and I need to quickly grab a job name from a job number again, but it's all server-side. I don't think it makes sense to re-write what is essentially the same code, or to use Axios to call the function against my own API (it's extra traffic, and get's a bit messy needing a proxy), but I can't just call the module directly because it throws an error because I'm using res.json to send back the data. Can I re-use the code from the API or do I need to write a copy of it for my specific purpose?<issue_comment>username_1: What you could do is to write a module that exports the core functionality as a simple function. This module in turn could be called by 1. your express api 2. a cli tool of your making (for example) So your api and the cli are just thin layers around the actual functionality, which shouldn't know anything about cli or express. Upvotes: 1 <issue_comment>username_2: If I am understanding correctly then you can use a module! This is assuming your secondary use is on the same server. If it isn't then you would need to do something else. ```js // fn.js module.exports = function doStuff(jobId) { const whateverCameBack = doSomething(jobId); return { name: whateverCameBack } } // app.js var doStuff = require('./fn'); app.get('api/jobs/:id', function (req, res, next) { doStuff(req.params.id) .then(x => res.json(x)) // assuming it's async .then(next); }); // somewhere else in server var doStuff = require('./fn'); doStuff(jobId).then(oppName => // whatever); ``` Upvotes: 1 [selected_answer]
2018/03/21
394
1,335
<issue_start>username_0: I have the following string: ``` text = "i eat salad" ``` I would like to change `eat` to `ate` to get: ``` text = "i ate salad" ``` Do i have to use join or split? ``` text.split()[1] = 'ate' print(text) ``` I've tried this before unsuccessfully.<issue_comment>username_1: What you could do is to write a module that exports the core functionality as a simple function. This module in turn could be called by 1. your express api 2. a cli tool of your making (for example) So your api and the cli are just thin layers around the actual functionality, which shouldn't know anything about cli or express. Upvotes: 1 <issue_comment>username_2: If I am understanding correctly then you can use a module! This is assuming your secondary use is on the same server. If it isn't then you would need to do something else. ```js // fn.js module.exports = function doStuff(jobId) { const whateverCameBack = doSomething(jobId); return { name: whateverCameBack } } // app.js var doStuff = require('./fn'); app.get('api/jobs/:id', function (req, res, next) { doStuff(req.params.id) .then(x => res.json(x)) // assuming it's async .then(next); }); // somewhere else in server var doStuff = require('./fn'); doStuff(jobId).then(oppName => // whatever); ``` Upvotes: 1 [selected_answer]
2018/03/21
1,359
5,786
<issue_start>username_0: In Java, I have a TreeViewer and I am trying to detect a click on a specific cell (not any cell). For example, if I click on a the first cell in a row, I want to detect that the click was made on the first cell in particular. The following code will fire an event as soon as I double click on a row and it will return all the information about that row. How can I ensure that it will only fire the double click event when I only double click on a particular cell (i.e. a particular row and column). ``` viewer = new TreeViewer(parent, SWT.BORDER | SWT.FULL_SELECTION); viewer.addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { IStructuredSelection thisSelection = (IStructuredSelection) event.getSelection(); Object selectedNode = thisSelection.getFirstElement(); System.out.println(selectedNode.toString()); } }); ``` **EDIT** greg-449 is right. The getFirstElement method doesn't have row or col attributes. Here is the answer to greg-449's question why I don't use the cell editing support. In fact, I am using the cell edition support already for one of the columns. Please have a look at the following tree structure: ``` October |__(Report 1)(Forecast revenue)(Actual revenue <-- editable) |__(Report 2)(Forecast revenue)(Actual revenue <-- editable) November |__(Report 1)(Forecast revenue)(Actual revenue <-- editable) |__(Report 2)(Forecast revenue)(Actual revenue <-- editable) December |__(Report 1)(Forecast revenue)(Actual revenue <-- editable) |__(Report 2)(Forecast revenue)(Actual revenue <-- editable) |__(Report 3)(Forecast revenue)(Actual revenue <-- editable) ``` In the above TreeView, I have 3 main columns: Report, Forecast revenue and Actual revenue. The actual revenue is an editable column which allows the user to enter a value, and that is the column I use the cell editing support. Now when the user double click on the cell of "Report 3" in December, I want to open the corresponding pdf file related to the report 3 in December on a tab. Basically, I want to treat the column 1 (Report) as a double click button to do something corresponding to that particular cell. When the user clicks or double clicks on column 2 "Forecast revenue", it shouldn't do anything. When the user clicks on column 3 Actual revenue", he can enter the actual value. Using the viewer.addDoubleClickListener(new IDoubleClickListener() {...} as mentioned in my 1st thread, when the user double clicks on column 2 or column 3, it opens the pdf file, which is not what I want! In addition, I have tried to use the cell editing support for column one "Report". If I set the canEdit to true, the column one becomes editable. If I set the canEdit to false, nothing happens. I don't want to edit column 1. I just want to detect the double click event! I hope I've made myself clear this time. Thanks in advance...<issue_comment>username_1: The event will always fire, you should look trough the attributes of selectedNode object, and check if it has any col and row attributes. Then you just do something like: ``` if(selectedNode.row == theRowYouWant && selectedNode.col == theColYouWant) { // do something. } ``` Upvotes: -1 <issue_comment>username_2: To detect a double-click on a particular cell in a TreeView, here is a possible solution which is based on the idea of showing cell tips in a TreeView found on the Internet. The mistake I've made was using viewer.addDoubleClickListener(new IDoubleClickListener() {..}. ``` Listener treeListener = new Listener () { @Override public void handleEvent (Event event) { switch (event.type) { case SWT.MouseDoubleClick: { Point coords = new Point(event.x, event.y); TreeItem item = viewer.getTree().getItem(coords); if (item != null) { int columns = viewer.getTree().getColumnCount(); for (int i = 0; i < columns; i++) { if (item.getBounds(i).contains(coords)) { System.out.println("Double Clicked on: " + item.getData() + " : " + i); } } } } } } }; viewer.getTree().addListener (SWT.MouseDoubleClick, treeListener); ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: Wow, this was great help, I had the same issue! The viewer.getTree() part however didn't work for me, but I managed to get the result with some small adjustments. Also, I added a little code to show content of the double-clicked Cell. ``` Listener doubleClickListener = new Listener () { @Override public void handleEvent (Event event) { if (event.type == SWT.MouseDoubleClick) { Point coords = new Point(event.x, event.y); TableItem item = tableViewer.getTable().getItem(coords); if (item != null) { int columns = tableViewer.getTable().getColumnCount(); for (int i = 0; i < columns; i++) { if (item.getBounds(i).contains(coords)) { if (item.getData() != null) { @SuppressWarnings("unchecked") ArrayList row = (ArrayList)item.getData(); if (row.get(i) != null) System.out.println("Cell contain: " + row.get(i)); } } } } } } }; tableViewer.getTable().addListener (SWT.MouseDoubleClick, doubleClickListener); ``` Upvotes: 1
2018/03/21
892
3,956
<issue_start>username_0: I'm having trouble reading the values from a textfield. Every time I type in this line `let username = UsernameTextField.text` I get an error saying "Cannot use instance member 'UsernameTextField' within property initializer; property initializers run before 'self' is available". Here is the full code: ``` import UIKit class SignInViewController: UIViewController,UITextFieldDelegate { @IBOutlet var UsernameTextField: UITextField! @IBOutlet var PasswordTextField: UITextField! @IBOutlet var LogInButton: UIButton! override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.isTranslucent = true navigationController?.view.backgroundColor = UIColor.clear // Remove Autocorrection Type UsernameTextField.autocorrectionType = .no PasswordTextField.autocorrectionType = .no PasswordTextField.textContentType = UITextContentType("") //Next button takes user to the next textfield UsernameTextField.delegate = self PasswordTextField.delegate = self } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == UsernameTextField{ PasswordTextField.becomeFirstResponder() } else if textField == PasswordTextField { self.view.endEditing(true) } return true } let username = UsernameTextField.text } ```<issue_comment>username_1: Any chance that you have a subclass of `UITextField` called `UsernameTextField`? If so, it might be referencing the class instead of the instance. I would recommend keeping variables' names camelCased. Makes it easier to differentiate between variables and classes. If this is the convention you use, you might also try using `let name = self.UsernameTextField.text` EDIT: It seems that this line is outside the function scope. Should move it before the closing `}`. Upvotes: 1 <issue_comment>username_2: The line ``` let username = UsernameTextField.text ``` is in the scope of your class definition, not inside the scope of a method. Therefore this constitutes a property initialization which is run upon construction of an instance of the class. You're trying to initialize the member variable username using ANOTHER member variable (UsernameTextField). This, of course, cannot work, since the object has to be fully initialized before any members can be read. Did you mean to put the line inside the scope of the method textFieldShouldReturn? Upvotes: 0 <issue_comment>username_3: That is what you have, the call to set the text is NOT in a function. ``` func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == UsernameTextField{ PasswordTextField.becomeFirstResponder() } else if textField == PasswordTextField { self.view.endEditing(true) } return true } let username = UsernameTextField.text // THIS IS NOT IN A FUNCTION ``` Move it here: ``` func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == UsernameTextField{ PasswordTextField.becomeFirstResponder() } else if textField == PasswordTextField { self.view.endEditing(true) } let username = UsernameTextField.text // THIS IS NOW IN A FUNCTION return true } ``` Upvotes: 2 [selected_answer]<issue_comment>username_4: As the error suggests "UsernameTextField" is an instance member which means it does not get instantiated until the class is instantiated (as opposed to static members) which means that by the time your line is compiled which is before the class is instantiated, that member does not exist yet. Upvotes: 0 <issue_comment>username_5: You have to move you constants and place them right under "return true" Upvotes: 0
2018/03/21
595
2,181
<issue_start>username_0: I want to insert a blank line in csv using java. I have written following code: ``` CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n").withEscape('\\'); FileWriter fileWriter = new FileWriter(csvFile); CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter,csvFileFormat); csvFilePrinter.printRecord("data1"); csvFilePrinter.printRecord("\n"); csvFilePrinter.printRecord("data2"); ``` When I open this generated CSV in notepad++, I am getting 2 blank lines: ``` data1 " " data2 ``` How can I get a single blank line?<issue_comment>username_1: I guess replacing `csvFilePrinter.printRecord("\n");` with `csvFilePrinter.println();` does the job. [`println()`](https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVPrinter.html#println--) will output lines separator, so you will get completely empty line without quotes. Hope it helps! Upvotes: 1 <issue_comment>username_2: Try ~~`csvFilePrinter.printRecord("");`~~ `csvFilePrinter.println();` `printRecord` will escape the line automatically. You do not need an additional escape character. Upvotes: 3 [selected_answer]<issue_comment>username_3: [`printRecord`](https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVPrinter.html#printRecord-java.lang.Iterable-) prints a record separator after the data, in this case a newline. Then you print a newline which is printed as a string containing another newline, which gives you those two double quotes on separate lines. Just remove the one that prints a newline or, if you really want that empty line, use [`csvFilePrinter.println()`](https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVPrinter.html#println--) which will output the record separator (in your case, `"\n"`). Upvotes: 2 <issue_comment>username_4: You define the CSVFilePrinter with ``` CSVFormat.DEFAULT.withRecordSeparator("\n") ``` so for each record an additional `\n` will be appended. You then print three records: "data1", "\n", "data2" This will results in "data1\n\n\ndata2\n", which is exactly the result you get. Just replace the second record with "". Upvotes: 0
2018/03/21
530
1,987
<issue_start>username_0: i have probably a small trouble. Here is a function that returns a Promise. ``` export default ()=>{ const socket = io(config.crypt_compare_api_url); let subscription = config.subscription; socket.emit('SubAdd', { subs: subscription }); return new Promise(resolve => { socket.on("m",resolve); }); } ``` And a here i use it. It's imported as get\_crypto ``` get_crypto().then((parsedData)=>{ let el=this.state.currencies.find(element=> element.name===parsedData.name); if(el) { el.price=parsedData.price; } else this.state.currencies.push(parsedData); this.setState( { currencies: this.state.currencies }); }); ``` \*\* **'then'** function always have to repeat after socket gets a message. But it works only one time,\*\*<issue_comment>username_1: You cannot recall then callback multiple times. You should use observable or just call a callback on 'm' event: ```js export const getCrypto = (cb) => { const socket = io(config.crypt_compare_api_url); let subscription = config.subscription; socket.emit('SubAdd', { subs: subscription }); socket.on("m", cb); } import { getCrypto } from 'get-crypto.js'; getCrypto(parsedData => { console.log(parsedData); // Do something with parsed data }) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You'll have to call `get_crypto()` again to get a new promise, so you could do something like this: ``` const datahandler = function(parsedData){ let el=this.state.currencies.find(element=> element.name===parsedData.name); if(el) { el.price=parsedData.price; } else this.state.currencies.push(parsedData); this.setState( { currencies: this.state.currencies }); } const loop = function(){ get_crypto().then(datahandler).then(loop); } loop(); ``` Upvotes: 0
2018/03/21
454
1,832
<issue_start>username_0: I am semi-new to Dialogflow, so sorry if this is really simple, but I can't seem to find an answer anywhere. Here's my problem: I am trying to make a chatbot where if the user says something like "speak to a human", the chatbot just stops talking all together. I know the easiest way to do this is through a server but as I don't have access to one, I am trying to use a workaround where it uses a follow-up intent to catch anything the user says afterward (using @sys.any) and have no response. This works fine if it doesn't understand what I say next, but if I say something that has a specific intent after that (like "hello"), it uses the hello intent instead of the follow-up. I am looking for a way to prioritize the follow-up intent so that it will catch anything the user says instead of looking for other intents that also match, until the user says something like "speak to the bot". Is this possible without a server? Please help!<issue_comment>username_1: No, there isn't a way to achieve this. As you mention, the correct way to implement the behavior you're looking for is by intercepting user requests through your own server. The server can be very simple; you can see the official [Agent Human Handoff sample](https://github.com/dialogflow/agent-human-handoff-nodejs) for a possible implementation. Upvotes: 0 <issue_comment>username_2: Answering in case someone stumbles upon it. This would work well with simple bots, but when you have hundreds of intent you might not want to do this. 1. Add an outgoing context to the welcome intent with a lifespan of 100. Eg. `convo_started`. 2. Add the `convo_started` intent as incoming context to all the intents. 3. When your agent intent is hit, reset the context to lifespan 0, so now only your followup intent an be triggered. Upvotes: 1
2018/03/21
2,455
8,215
<issue_start>username_0: I am trying to get a formatted output from 2 arrays one with the countries and the otyher with the populations which should provide an output as follows: ``` Egypt | 92592000 France | 66991000 Japan | 126860000 Switzerland | 8401120 ``` The only hint I received was that I should calculate the max width required for each column and then use that to align the values. This is what I have come up with so far but stuck on getting anything to output while formatting. ``` public static void main (String[] args) throws java.lang.Exception { String [] countries = {"Egypt", "France", "Japan", "Switzerland"}; int[] populations = {92592000, 66991000, 126860000, 8401120}; printTable(countries, populations); } public static void printTable(String[] countries, int[] populations){ int longestInput = 0; for(int i = 0; i < countries.length; i++){ int countLength = countries[i].length(); int popLength = String.valueOf(populations[i]).length(); if(countLength + popLength > longestInput) longestInput = countLength + popLength; } for(int i = 0; i < countries.length; i++) System.out.format("%-10",countries[i] + " | " + populations[i]); } ```<issue_comment>username_1: The pattern you are probably looking for is: ``` "%-" + maxCountryLength + "s | %" + maxPopulationLength + "d\n" ``` * `%-Xs` means "`X` characters in width, a left-justified `String`" * `%Xd` means "`X` characters in width, a right-justified number" * `\n` means it occupies a line The method might look like: ``` public static void printTable(String[] countries, int[] populations) { int defaultLength = 10; int maxCountryLength = stream(countries).mapToInt(String::length).max().orElse(defaultLength); int maxPopulationLength = stream(populations).mapToObj(Integer::toString).mapToInt(String::length).max().orElse(defaultLength); for (int i = 0; i < countries.length; i++) { System.out.format("%-" + maxCountryLength + "s | %" + maxPopulationLength + "d\n", countries[i], populations[i]); } } ``` The result: ``` Egypt | 92592000 France | 66991000 Japan | 126860000 Switzerland | 8401120 ``` Upvotes: 1 <issue_comment>username_2: Using Java 8 ============ ``` public static void main (String[] args) throws java.lang.Exception { String [] countries = {"Egypt", "France", "Japan", "Switzerland"}; int[] populations = {92592000, 66991000, 126860000, 8401120}; printTable(countries, populations); } public static void printTable(String[] countries, int[] populations) { if (countries.length == 0 || populations.length == 0 || countries.length != populations.length) { return; } int longestCountry = Arrays.stream(countries) .map(String::toString) .mapToInt(String::length) .max() .getAsInt(); int longestPop = Arrays.stream(populations) .mapToObj(Integer::toString) .mapToInt(String::length) .max() .getAsInt(); for (int i = 0; i < countries.length; i++) { System.out.printf("%-" + longestCountry + "s | %" + longestPop + "d%n", countries[i], populations[i]); } } ``` The trick is using streams to get the lengths and using a negative format string to pad the right of the string. Upvotes: 2 <issue_comment>username_3: This is a little example how you can do it: ``` public static void main (String[] args) throws java.lang.Exception { String [] countries = {"Egypt", "France", "Japan", "Switzerland"}; int[] populations = {92592000, 66991000, 126860000, 8401120}; printTable(countries, populations); } public static void printTable(String[] countries, int[] populations){ int countryLength = 0; long populationLength = 0; for(String country: countries){ //get longest country if (country.length() > countryLength) countryLength = country.length(); } for(int i : populations) { //get longest number if(String.valueOf(i).length() > populationLength) populationLength = String.valueOf(i).length(); } for(int i = 0; i < countries.length; i++) // print it out System.out.format("%-"+ (countryLength+1) +"s|%" + (populationLength+1) +"d\n",countries[i], populations[i]); } ``` First get the longest country: ``` for(String country: countries){ //get longest country if (country.length() > countryLength) countryLength = country.length(); } ``` Secondly get the longest population with `String.valueOf(i).length()`: ``` for(int i : populations) { //get longest number if(String.valueOf(i).length() > populationLength) populationLength = String.valueOf(i).length(); } ``` Finally print it out with `System.out.format`: ``` System.out.format("%-"+ (countryLength+1) +"s|%" + (populationLength+1) +"d\n",countries[i], populations[i]); ``` Upvotes: 3 [selected_answer]<issue_comment>username_4: ```java public static void main (String[] args) throws java.lang.Exception { String [] countries = {"Egypt", "France", "Japan", "Switzerland"}; Integer[] populations = {92592000, 66991000, 126860000, 8401120}; printTable(countries, populations); } public static void printTable(String[] countries, Integer[] populations){ int longestInput = 0; for(int i = 0; i < countries.length; i++){ int countLength = countries[i].length(); int popLength = String.valueOf(populations[i]).length(); if(countLength + popLength > longestInput) longestInput = countLength + popLength; } String longestString = getLongestString( countries ); System.out.format("longest string: '%s'\n", longestString); Integer longestNumber = getLongestNumber( populations ); System.out.format("longest Number: '%s'\n", longestNumber); for(int i = 0; i < countries.length; i++) System.out.format("%-" + longestString.length() + "s | %" + String.valueOf(longestNumber).length() + "d\n", countries[i], populations[i]); } ``` To find the longest String in an array of Strings ```java public static String getLongestString(String[] array) { int maxLength = 0; String longestString = null; for (String s : array) { if (s.length() > maxLength) { maxLength = s.length(); longestString = s; } } return longestString; } ``` To find the longest Number in an array of Integers ```java public static Integer getLongestNumber(Integer[] array) { int maxLength = 0; Integer longestNumber = null; for (Integer i : array) { if (String.valueOf(i).length() > maxLength) { maxLength = String.valueOf(i).length(); longestNumber = i; } } return longestNumber; } ``` output « ```java longest string: 'Switzerland' longest Number: '126860000' Egypt | 92592000 France | 66991000 Japan | 126860000 Switzerland | 8401120 ``` Upvotes: 0 <issue_comment>username_5: I rewrote the printTable method and it works perfectly: ``` public static void printTable(String[] countries, int[] populations) { if(countries.length != 0) { int longestNameInput = countries[0].length(); int longestPopInput = String.valueOf(populations[0]).length(); for(int i = 0; i < countries.length; i++) { int countLength = countries[i].length(); int popLength = String.valueOf(populations[i]).length(); if(countLength > longestNameInput) longestNameInput = countLength; if(popLength > longestPopInput) longestPopInput = popLength; } for(int i = 0; i < countries.length; i++) { System.out.print(countries[i]); for(int j = 0; j < (longestNameInput - countries[i].length()); j++) System.out.print(" "); System.out.print(" | "); for(int k = 0; k < (longestPopInput - String.valueOf(populations[i]).length()); k++) System.out.print(" "); System.out.println(populations[i]); } } } ``` Upvotes: 1
2018/03/21
552
1,607
<issue_start>username_0: there is a table "Likes" with fields "ID1" and "ID2" where there is mutually exclusive pairs , i want to find them i tried it by concatenation and it didn't work , i can't figure out why [enter image description here](https://i.stack.imgur.com/h04Qf.png)<issue_comment>username_1: If I've correctly interpreted your question, you can do like that: ``` SELECT name FROM highschooler GROUP BY name HAVING count(*) > 1 ``` It returns all names who occours are more than once in the `highschooler` table Upvotes: 0 <issue_comment>username_2: Normally you would use `GROUP BY [column]` in combination with `HAVING COUNT([column|*]) >= [number]` to find duplicates within a column ``` SELECT name FROM Highschooler GROUP BY name HAVING COUNT(*) >= 2 ORDER BY name ASC ``` If you need more information about the highschooler you need to JOIN again. ``` SELECT Highschooler.* FROM ( SELECT name FROM Highschooler GROUP BY name HAVING COUNT(*) >= 2 ORDER BY name ASC ) AS name_duplicated INNER JOIN Highschooler ON name_duplicated.name = Highschooler.name ``` Upvotes: 1 <issue_comment>username_3: If you're trying to find duplicate pairs but in any order, there are possibly many ways to do it. Here's one: ``` create table likes(id1,id2); insert into likes values (1689,1709), (1709,1689), (1782,1709), (1911,1247), (1247,1468), (1641,1468), (1316,1304), (1501,1934), (1934,1501), (1025,1101); select min(id1,id2)||'-'||max(id1,id2) as pairs from likes group by pairs having count(*) > 1; ``` Upvotes: 0
2018/03/21
706
2,259
<issue_start>username_0: I create a window and immediately after launch hide it and show another window. There's a button in that another window, clicking that should show the main window but the program crushes. Here I send signal to show the main window: ``` class Launcher(QWidget): signal = pyqtSignal() def __init__(self, signal, parent=None): super(Launcher, self).__init__(parent) self.signal = signal ... # Here's a button def click(self): # slot for the button self.signal.emit() ``` Here I set slot to get the signal and show the window: ``` class MainWindow(QWidget): signal = pyqtSignal() def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.hide() self.window = Launcher(self.signal, self) self.window.show() self.signal.connect(self.showWindow) def showWindow(self): self.show() ```<issue_comment>username_1: If I've correctly interpreted your question, you can do like that: ``` SELECT name FROM highschooler GROUP BY name HAVING count(*) > 1 ``` It returns all names who occours are more than once in the `highschooler` table Upvotes: 0 <issue_comment>username_2: Normally you would use `GROUP BY [column]` in combination with `HAVING COUNT([column|*]) >= [number]` to find duplicates within a column ``` SELECT name FROM Highschooler GROUP BY name HAVING COUNT(*) >= 2 ORDER BY name ASC ``` If you need more information about the highschooler you need to JOIN again. ``` SELECT Highschooler.* FROM ( SELECT name FROM Highschooler GROUP BY name HAVING COUNT(*) >= 2 ORDER BY name ASC ) AS name_duplicated INNER JOIN Highschooler ON name_duplicated.name = Highschooler.name ``` Upvotes: 1 <issue_comment>username_3: If you're trying to find duplicate pairs but in any order, there are possibly many ways to do it. Here's one: ``` create table likes(id1,id2); insert into likes values (1689,1709), (1709,1689), (1782,1709), (1911,1247), (1247,1468), (1641,1468), (1316,1304), (1501,1934), (1934,1501), (1025,1101); select min(id1,id2)||'-'||max(id1,id2) as pairs from likes group by pairs having count(*) > 1; ``` Upvotes: 0
2018/03/21
2,739
12,004
<issue_start>username_0: Background ---------- I have a layout that has some views at the top, which should be scrollable together with an EditText below them. The EditText takes the rest of the space, as much space as it needs. Here's a sample POC layout that demonstrate it (used just 2 EditTexts here) : ``` ``` I've set a background frame to have a visual indication of how large the EditText is. The problem ----------- I've found so many solutions to what I wrote, but none of them actually handles the scrolling well. What I'm always seeing, is at least one of those issues: 1. Unable to scroll entire page (only EditText might be scrollable, which I'm trying to avoid), so can't get to the views at the top anymore. 2. When I enter text, the caret might go outside of the visible area 3. As I type more and more lines, it doesn't scroll the entire page. Only in the EditText itself. What I've tried --------------- I've tried those solutions: 1. All from [here](https://stackoverflow.com/q/23319438/878126), [here](https://stackoverflow.com/q/16605486/878126), [here](https://stackoverflow.com/q/9770252/878126) , [here](https://stackoverflow.com/q/22552656/878126). Maybe more, but I didn't keep enough track... 2. I tried various `windowSoftInputMode` values in the manifest, and tried to set `isNestedScrollingEnabled` in the NestedScrollView. 3. Tried various configurations in the XML, to let the EditText take as much space as it needs, to prevent it from being scrollable within it. The question ------------ How can I make the bottom EditText to take as much space as it needs, and still be able to scroll entire NestedScrollView, without an issue in editing ? --- EDIT: since the original app is a bit more complex, having some views at the bottom (inside what is like a toolbar) that auto-hide when you are not in focus on the bottom EditText , this made the answer I've found not to work. Also, I've accidentally granted the bounty to the wrong answer, so here's a new bounty, on the more complex POC. The question stays the same. The NestedScrollView should remain on the same place, without scrolling when focusing on the bottom EditText. ``` class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) container.setOnClickListener { contentEditText.requestFocus() contentEditText.setSelection(contentEditText.length()) } contentEditText.setOnFocusChangeListener { view, hasFocus -> autoHideLayout.visibility = if (hasFocus) View.VISIBLE else View.GONE if (hasFocus) nestedScrollView.scrollTo(0, 0) } } } ```<issue_comment>username_1: I realize that `NestedScrollView` would not scroll until it's content goes out of the screen. I make a hack and put some empty rows after the entered text to ensure that the content will go outside the current screen. After the EditText losses focus I remove the empty rows. ``` public class MainActivity extends AppCompatActivity { String EMPTY_SPACES = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; EditText mEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mEditText = findViewById(R.id.contentEditText); mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean hasFocus) { if (!hasFocus) { // code to execute when EditText loses focus mEditText.setText(mEditText.getText().toString().trim()); } } }); mEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { int charsThatGuaranteesTextIsOutOfScreen = 400; if (mEditText.hasFocus() && charSequence.length() < charsThatGuaranteesTextIsOutOfScreen) { mEditText.setText(String.format(Locale.getDefault(), "%1$s%2$s", charSequence, EMPTY_SPACES)); mEditText.setSelection(i2); } } @Override public void afterTextChanged(Editable editable) { } }); } @Override public void onBackPressed() { if (mEditText.hasFocus()) { mEditText.clearFocus(); } else { super.onBackPressed(); } } } ``` Upvotes: 1 <issue_comment>username_2: You should be able to achieve what you want by calculating the `minLines` based on the height of the screen. See the example activity and layout below. You'll need to type quite a bit of text to use up the minimum lines and grow beyond the height of the screen to start the scrolling behavior, but you can circumvent this by adding a few constant lines to the `minLines` calculation ``` public class ScrollingActivity extends AppCompatActivity { EditText editText2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scrolling); editText2 = findViewById(R.id.editText2); int minHeight = getResources().getDisplayMetrics().heightPixels - editText2.getTop(); float lineHeight = editText2.getPaint().getFontMetrics().bottom - editText2.getPaint().getFontMetrics().top; int minLines = (int)(minHeight/lineHeight); editText2.setMinLines(minLines); } } ``` Here is the layout ``` xml version="1.0" encoding="utf-8"? ``` **EDIT** I recreated your solution and you can correct the focus issue by setting this listener to your EditText. It works by overriding the scroll action when the Edit Text gets the focus, to only scroll enough to make the cursor visible. ``` contentEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean hasFocus) { if(hasFocus){ nestedScrollView.scrollTo(0, 0); } } }); ``` **EDIT 2** I've updated my answer to reflect the changes with the new bounty, this should be pretty close to what you need, if I've understood the question properly. ``` public class ScrollingActivity extends AppCompatActivity { ConstraintLayout parentLayout; EditText contentEditText; NestedScrollView nestedScrollView; LinearLayout autoHideLayout; boolean preventScroll = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scrolling); contentEditText = findViewById(R.id.contentEditText); nestedScrollView = findViewById(R.id.nestedScrollView); autoHideLayout = findViewById(R.id.autoHideLayout); parentLayout = findViewById(R.id.parentLayout); nestedScrollView.setOverScrollMode(View.OVER_SCROLL_NEVER); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); parentLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int minHeight = autoHideLayout.getTop() - contentEditText.getTop(); float lineHeight = contentEditText.getPaint().getFontMetrics().bottom - contentEditText.getPaint().getFontMetrics().top; int minLines = (int)(minHeight/lineHeight); if(minLines != contentEditText.getMinLines()){ contentEditText.setMinLines(minLines); } } }); contentEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean hasFocus) { ViewGroup.LayoutParams layoutParams = autoHideLayout.getLayoutParams(); if(hasFocus){ nestedScrollView.scrollTo(0,0); layoutParams.height = ConstraintLayout.LayoutParams.WRAP_CONTENT; } else{ layoutParams.height = 0; } autoHideLayout.setLayoutParams(layoutParams); } }); } } ``` Here is the new layout ``` ``` Upvotes: 4 <issue_comment>username_3: I got some workaround for this, by wrapping the bottom EditText with a layout that will grant it focus. Doesn't require much code at all **activity\_main.xml** ``` ``` **MainActivity.kt** ``` class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) container.setOnClickListener { contentEditText.requestFocus() contentEditText.setSelection(contentEditText.length()) } contentEditText.setOnFocusChangeListener { view, hasFocus -> if (hasFocus) { nestedScrollView.scrollTo(0, 0) } } } } ``` **manifest** ``` ``` Upvotes: 4 <issue_comment>username_4: Your expected result can be achieved by changing the layout.xml and MainActivity. Change `layout_height` and adding `layout_weight` for `ConstraintLayout` as follows: ``` xml version="1.0" encoding="utf-8"? ``` Manifest.xml is: ``` ``` Record the current value of scrollX & scroll Y for `NestedScrollView` and adjust `NestedScrollView` as follows: **MainActivity.java** ``` public class MainActivity extends AppCompatActivity { private int scrollX; private int scrollY; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText editText = findViewById(R.id.contentEditText); final LinearLayout autoHideLayout = findViewById(R.id.autoHideLayout); ConstraintLayout container = findViewById(R.id.container); container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { autoHideLayout.setVisibility(View.VISIBLE); editText.requestFocus(); editText.setSelection(editText.length()); } }); final NestedScrollView nestedScrollView = findViewById(R.id.nestedScrollView); editText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { scrollX = nestedScrollView.getScrollX(); scrollY = nestedScrollView.getScrollY(); autoHideLayout.setVisibility(View.VISIBLE); return false; } }); editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) nestedScrollView.scrollTo(scrollX, scrollY); if (!hasFocus) { autoHideLayout.setVisibility(View.GONE); } } }); } } ``` It didn't scroll when it was not necessary. See the screenshot: [![screen shot](https://i.stack.imgur.com/ExmW4.png)](https://i.stack.imgur.com/ExmW4.png) Upvotes: 3 [selected_answer]
2018/03/21
1,628
4,005
<issue_start>username_0: I tried some code to flatten but it flattens the whole json. My requirement is just to flatten only position property. I have following json array: ``` [{ amount:"1 teine med 110 mtr iletau" comment:"" created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)" locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden)." position:{lat: 59.441388, lng: 10.579491} time:"15-05-2016" type:"Teine" userId:"" }, { amount:"1 teine med 110 mtr iletau" comment:"" created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)" locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden)." position:{lat: 59.441388, lng: 10.579491} time:"15-05-2016" type:"Teine" userId:"" }] ``` I want output like: ``` [{ amount:"1 teine med 110 mtr iletau" comment:"" created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)" locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden)." position.lat:59.441388, position.lng: 10.579491, time:"15-05-2016" type:"Teine" userId:"" }, { amount:"1 teine med 110 mtr iletau" comment:"" created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)" locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden)." position.lat: 59.441388, position.lng: 10.579491, time:"15-05-2016" type:"Teine" userId:"" }] ``` Can someone suggests me how to achieve the above output in javascript ?<issue_comment>username_1: You could iterate the array and build new properties and delete `position.` ```js var array = [{ amount: "1 teine med 110 mtr iletau", comment: "", created: "Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription: "På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position: { lat: 59.441388, lng: 10.579491 }, time: "15-05-2016", type: "Teine", userId: "" }, { amount: "1 teine med 110 mtr iletau", comment: "", created: "Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription: "På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position: { lat: 59.441388, lng: 10.579491 }, time: "15-05-2016", type: "Teine", userId: "" }]; array.forEach(o => { Object.assign(o, { 'position.lat': o.position.lat, 'position.lng': o.position.lng }); delete o.position; }); console.log(array); ``` Upvotes: 2 <issue_comment>username_2: or using Array.map() ```js const arr = [ { amount:"1 teine med 110 mtr iletau", comment:"", created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position:{lat: 59.441388, lng: 10.579491}, time:"15-05-2016", type:"Teine", userId:"" }, { amount:"1 teine med 110 mtr iletau", comment:"", created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription:"På vestsiden av Jeløya, utenfor Moss.(Oslofjorden).", position:{lat: 59.441388, lng: 10.579491}, time:"15-05-2016", type:"Teine", userId:"" } ]; const flattenPositions = o => { o["position.lng"] = o.position.lng; o["position.lat"] = o.position.lat; delete o.position; return o; }; arr = arr.map(el=>flattenPositions(el)); console.log(arr); ``` Upvotes: 0 <issue_comment>username_3: For a flexible solution, you can use [recursion](https://en.wikipedia.org/wiki/Recursion_(computer_science)). Notice that the function calls itself to traverse the object: ``` $ cat test.js && echo "\n-------\n" && node test.js const subject = {a:1, b:2, c:{d:3, e:{f:4, g:5}}}; function flatten (obj){ const result = {}; Object.keys(obj).forEach(key => { const value = obj[key]; if (typeof value === 'object') { const flattened = flatten(value); Object.keys(flattened).forEach( subKey => { result[`${key}.${subKey}`] = flattened[subKey] }) } else { result[key] = value } }); return result; } console.log(JSON.stringify(flatten(subject), null, 2)); ------- { "a": 1, "b": 2, "c.d": 3, "c.e.f": 4, "c.e.g": 5 } ``` Upvotes: 1
2018/03/21
1,237
3,379
<issue_start>username_0: I have a `StackPanel` that was made with a `ItemsControl` and `DataTemplate` using an `ItemSource` of objects. I know how to get the list of objects from the `ItemsControl` in the `StackPanel`: `itemsControl.Items` But, now I'd like to get the `UIElement`s associated with these `Items`. If we have a `StackPanel` like this: ``` ``` I tried this method but it's giving me a `null` value. I can visually see all my buttons generated at runtime: `var brandButton = (Button)itemsControl.ContainerFromItem(itemIndex);` Any ideas? Or is there a better way? Thanks EDIT: This states that a FindChildren method exists for UWP. But I'm not seeing it... <https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.media.visualtreehelper><issue_comment>username_1: You could iterate the array and build new properties and delete `position.` ```js var array = [{ amount: "1 teine med 110 mtr iletau", comment: "", created: "Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription: "På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position: { lat: 59.441388, lng: 10.579491 }, time: "15-05-2016", type: "Teine", userId: "" }, { amount: "1 teine med 110 mtr iletau", comment: "", created: "Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription: "På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position: { lat: 59.441388, lng: 10.579491 }, time: "15-05-2016", type: "Teine", userId: "" }]; array.forEach(o => { Object.assign(o, { 'position.lat': o.position.lat, 'position.lng': o.position.lng }); delete o.position; }); console.log(array); ``` Upvotes: 2 <issue_comment>username_2: or using Array.map() ```js const arr = [ { amount:"1 teine med 110 mtr iletau", comment:"", created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position:{lat: 59.441388, lng: 10.579491}, time:"15-05-2016", type:"Teine", userId:"" }, { amount:"1 teine med 110 mtr iletau", comment:"", created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription:"På vestsiden av Jeløya, utenfor Moss.(Oslofjorden).", position:{lat: 59.441388, lng: 10.579491}, time:"15-05-2016", type:"Teine", userId:"" } ]; const flattenPositions = o => { o["position.lng"] = o.position.lng; o["position.lat"] = o.position.lat; delete o.position; return o; }; arr = arr.map(el=>flattenPositions(el)); console.log(arr); ``` Upvotes: 0 <issue_comment>username_3: For a flexible solution, you can use [recursion](https://en.wikipedia.org/wiki/Recursion_(computer_science)). Notice that the function calls itself to traverse the object: ``` $ cat test.js && echo "\n-------\n" && node test.js const subject = {a:1, b:2, c:{d:3, e:{f:4, g:5}}}; function flatten (obj){ const result = {}; Object.keys(obj).forEach(key => { const value = obj[key]; if (typeof value === 'object') { const flattened = flatten(value); Object.keys(flattened).forEach( subKey => { result[`${key}.${subKey}`] = flattened[subKey] }) } else { result[key] = value } }); return result; } console.log(JSON.stringify(flatten(subject), null, 2)); ------- { "a": 1, "b": 2, "c.d": 3, "c.e.f": 4, "c.e.g": 5 } ``` Upvotes: 1
2018/03/21
1,151
3,130
<issue_start>username_0: I have the following questions: 1. Is there a way to make a histogram with frequency vector except using plt.bar? I have a frequency vector of size one million and bar plot seems to be very slow on that. 2. I tried a bar plot with smaller size data but seems even after setting a width size, I am still getting a different wide size for each bar as following, any way to fix it? [![enter image description here](https://i.stack.imgur.com/pjM8T.png)](https://i.stack.imgur.com/pjM8T.png)<issue_comment>username_1: You could iterate the array and build new properties and delete `position.` ```js var array = [{ amount: "1 teine med 110 mtr iletau", comment: "", created: "Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription: "På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position: { lat: 59.441388, lng: 10.579491 }, time: "15-05-2016", type: "Teine", userId: "" }, { amount: "1 teine med 110 mtr iletau", comment: "", created: "Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription: "På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position: { lat: 59.441388, lng: 10.579491 }, time: "15-05-2016", type: "Teine", userId: "" }]; array.forEach(o => { Object.assign(o, { 'position.lat': o.position.lat, 'position.lng': o.position.lng }); delete o.position; }); console.log(array); ``` Upvotes: 2 <issue_comment>username_2: or using Array.map() ```js const arr = [ { amount:"1 teine med 110 mtr iletau", comment:"", created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position:{lat: 59.441388, lng: 10.579491}, time:"15-05-2016", type:"Teine", userId:"" }, { amount:"1 teine med 110 mtr iletau", comment:"", created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription:"På vestsiden av Jeløya, utenfor Moss.(Oslofjorden).", position:{lat: 59.441388, lng: 10.579491}, time:"15-05-2016", type:"Teine", userId:"" } ]; const flattenPositions = o => { o["position.lng"] = o.position.lng; o["position.lat"] = o.position.lat; delete o.position; return o; }; arr = arr.map(el=>flattenPositions(el)); console.log(arr); ``` Upvotes: 0 <issue_comment>username_3: For a flexible solution, you can use [recursion](https://en.wikipedia.org/wiki/Recursion_(computer_science)). Notice that the function calls itself to traverse the object: ``` $ cat test.js && echo "\n-------\n" && node test.js const subject = {a:1, b:2, c:{d:3, e:{f:4, g:5}}}; function flatten (obj){ const result = {}; Object.keys(obj).forEach(key => { const value = obj[key]; if (typeof value === 'object') { const flattened = flatten(value); Object.keys(flattened).forEach( subKey => { result[`${key}.${subKey}`] = flattened[subKey] }) } else { result[key] = value } }); return result; } console.log(JSON.stringify(flatten(subject), null, 2)); ------- { "a": 1, "b": 2, "c.d": 3, "c.e.f": 4, "c.e.g": 5 } ``` Upvotes: 1
2018/03/21
1,073
2,866
<issue_start>username_0: I found option to get visible cell height as shown in below but how to get all the cell height ``` let cells = self.tableView.visibleCells for cell in cells { heightOfTableView += cell.frame.height } ```<issue_comment>username_1: You could iterate the array and build new properties and delete `position.` ```js var array = [{ amount: "1 teine med 110 mtr iletau", comment: "", created: "Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription: "På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position: { lat: 59.441388, lng: 10.579491 }, time: "15-05-2016", type: "Teine", userId: "" }, { amount: "1 teine med 110 mtr iletau", comment: "", created: "Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription: "På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position: { lat: 59.441388, lng: 10.579491 }, time: "15-05-2016", type: "Teine", userId: "" }]; array.forEach(o => { Object.assign(o, { 'position.lat': o.position.lat, 'position.lng': o.position.lng }); delete o.position; }); console.log(array); ``` Upvotes: 2 <issue_comment>username_2: or using Array.map() ```js const arr = [ { amount:"1 teine med 110 mtr iletau", comment:"", created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position:{lat: 59.441388, lng: 10.579491}, time:"15-05-2016", type:"Teine", userId:"" }, { amount:"1 teine med 110 mtr iletau", comment:"", created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription:"På vestsiden av Jeløya, utenfor Moss.(Oslofjorden).", position:{lat: 59.441388, lng: 10.579491}, time:"15-05-2016", type:"Teine", userId:"" } ]; const flattenPositions = o => { o["position.lng"] = o.position.lng; o["position.lat"] = o.position.lat; delete o.position; return o; }; arr = arr.map(el=>flattenPositions(el)); console.log(arr); ``` Upvotes: 0 <issue_comment>username_3: For a flexible solution, you can use [recursion](https://en.wikipedia.org/wiki/Recursion_(computer_science)). Notice that the function calls itself to traverse the object: ``` $ cat test.js && echo "\n-------\n" && node test.js const subject = {a:1, b:2, c:{d:3, e:{f:4, g:5}}}; function flatten (obj){ const result = {}; Object.keys(obj).forEach(key => { const value = obj[key]; if (typeof value === 'object') { const flattened = flatten(value); Object.keys(flattened).forEach( subKey => { result[`${key}.${subKey}`] = flattened[subKey] }) } else { result[key] = value } }); return result; } console.log(JSON.stringify(flatten(subject), null, 2)); ------- { "a": 1, "b": 2, "c.d": 3, "c.e.f": 4, "c.e.g": 5 } ``` Upvotes: 1
2018/03/21
420
1,448
<issue_start>username_0: I have this circular array, and I need to permute it somehow such that every element has both its neighbors altered. Example: ``` 1 2 3 4 5 ``` becomes ``` 3 1 4 2 5 ``` The restriction is that the array needs to be at least 5 elements otherwise it's impossible. Been trying to solve it for a long time, I'm sure it has a name but I had no luck finding the answer online.<issue_comment>username_1: I assume you are aware of choose-permute-unchoose paradigm to solve such problems. Having said that, during choose what you need to do is when you are choosing make sure that you are not choosing a neighbor so for example your current permutation is 1 2 3 4 5 i.e. your current string is 1, rest is 2 3 4 5. Now you have to choose from 2 3 4 5, but your current string has 1, so you shouldn't choose 2. you should choose 3 instead. and so on. Upvotes: 0 <issue_comment>username_2: This is actually very easy to solve, you just need to find some strategy that works for odd and even number of elements in the array: *First choose all numbers at even positions, then the first number at an odd position, followed by the last number at an odd position and finally the rest of the numbers at odd positions.* 12345 becomes 13524, so it works for an odd amount of elements. 123456 becomes 135264, so it works for an even amount of elements. 0123456789 becomes 0246819357, another example. Upvotes: 2 [selected_answer]
2018/03/21
1,156
3,081
<issue_start>username_0: In my environment (g++ 5.4.0), a code ``` complex cmp; cin >> cmp; //input 3 or (3) (not (3,0)) cout << "cmp = " << cmp << "\n"; ``` gives me the result: ``` cmp = (3,0) //imaginary part is automatically set to 0 ``` Does anyone have a written evidence which guarantee this behavior? N4140 (§ 26.4.6-12; p.921) says ``` Effects: Extracts a complex number x of the form: u, (u), or (u,v), where u is the real part and v is the imaginary part (172.16.31.10). ``` but this doesn't imply that the input of the form `u` or `(u)` makes the object's imaginary part `0`. You can see this behavior in a reliable MSDN's example (<https://msdn.microsoft.com/ja-jp/library/mt771459.aspx#operator_gt__gt_>) but even this doesn't make an explicit explaination. The draft says "`u` is the real part", and I input only the real part. I think there is an ambiguity in deciding what kind of value is set to imaginary part. Of course, `u`'s imaginary part is `0`, but this guarantees nothing, I think.<issue_comment>username_1: If you take a look at the implementation (<https://gcc.gnu.org/onlinedocs/gcc-4.6.3/libstdc++/api/a00812_source.html>) ``` 00486 template 00487 basic\_istream<\_CharT, \_Traits>& 00488 operator>>(basic\_istream<\_CharT, \_Traits>& \_\_is, complex<\_Tp>& \_\_x) 00489 { 00490 \_Tp \_\_re\_x, \_\_im\_x; 00491 \_CharT \_\_ch; 00492 \_\_is >> \_\_ch; 00493 if (\_\_ch == '(') 00494 { 00495 \_\_is >> \_\_re\_x >> \_\_ch; 00496 if (\_\_ch == ',') 00497 { 00498 \_\_is >> \_\_im\_x >> \_\_ch; 00499 if (\_\_ch == ')') 00500 \_\_x = complex<\_Tp>(\_\_re\_x, \_\_im\_x); 00501 else 00502 \_\_is.setstate(ios\_base::failbit); 00503 } 00504 else if (\_\_ch == ')') 00505 \_\_x = \_\_re\_x; 00506 else 00507 \_\_is.setstate(ios\_base::failbit); 00508 } 00509 else 00510 { 00511 \_\_is.putback(\_\_ch); 00512 \_\_is >> \_\_re\_x; 00513 \_\_x = \_\_re\_x; 00514 } 00515 return \_\_is; 00516 } ``` you can see that in the case where `s` or `(s)` is the format that you type on the keyboard `__x` which is your complex gets assigned to `__re_x` (either lines 505 or 513) which we can think of it as a `double` for simplicity. A rapid look at the `operator=` tells you that the imaginary part is default constructed. ``` 00230 complex<_Tp>::operator=(const _Tp& __t) 00231 { 00232 _M_real = __t; 00233 _M_imag = _Tp(); 00234 return *this; 00235 } ``` This means that your only guarantee is that the imaginary part will be default constructed (on GCC). For most types this translates to `0` initialized. Upvotes: 1 <issue_comment>username_2: The intention of the standard is likely that it should work, even if the text when scrutinized doesn't explicitly say so. And in practice the code will work with the known implementations. There is an existing defect report requesting the committee to clarify that its intention *is* what is already implemented: [#2714 complex stream extraction underspecified](http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#2714) Upvotes: 3 [selected_answer]
2018/03/21
2,005
5,999
<issue_start>username_0: I'm trying to send a message to IBM MQ (Version: 9.0.0.0), code bellow. \* I have tried with\without the userid and password. When I try the same code with IBM MQ installed on my machine (localhost) it works smoothly. ``` private static void foo() throws JMSException { Request request = new Request(); request.setRequestKey("11-12347"); request.setQueryString("This is a query string!"); MQQueueConnectionFactory cf = new MQQueueConnectionFactory(); cf.setHostName("192.168.1.107"); cf.setPort(1414); cf.setAppName("WMQ Tester"); // cf.createConnection(sccsid, sccsid) cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT); cf.setQueueManager("SanctionManager"); cf.setChannel("system.def.sanction"); MQQueueConnection connection = (MQQueueConnection) cf.createQueueConnection("hanash", "hanash1"); MQQueueSession session = (MQQueueSession) connection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE); MQQueue queue = (MQQueue) session.createQueue("queue:///SanctionQueue"); MQQueueSender sender = (MQQueueSender) session.createSender(queue); ObjectMessage objectMessage = session.createObjectMessage(request); connection.start(); sender.send(objectMessage); session.commit(); } ``` This gives the following exception: ``` Exception in thread "main" com.ibm.msg.client.jms.DetailedJMSException: JMSWMQ0018: Failed to connect to queue manager 'SanctionManager' with connection mode 'Client' and host name '192.168.1.107(1414)'. Check the queue manager is started and if running in client mode, check there is a listener running. Please see the linked exception for more information. at com.ibm.msg.client.wmq.common.internal.Reason.reasonToException(Reason.java:595) at com.ibm.msg.client.wmq.common.internal.Reason.createException(Reason.java:215) at com.ibm.msg.client.wmq.internal.WMQConnection.(WMQConnection.java:422) at com.ibm.msg.client.wmq.factories.WMQConnectionFactory.createV7ProviderConnection(WMQConnectionFactory.java:8475) at com.ibm.msg.client.wmq.factories.WMQConnectionFactory.createProviderConnection(WMQConnectionFactory.java:7814) at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl.\_createConnection(JmsConnectionFactoryImpl.java:299) at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl.createConnection(JmsConnectionFactoryImpl.java:236) at com.ibm.mq.jms.MQConnectionFactory.createCommonConnection(MQConnectionFactory.java:6024) at com.ibm.mq.jms.MQQueueConnectionFactory.createQueueConnection(MQQueueConnectionFactory.java:136) at com.dgbi.cre.MQSample.foo(MQSample.java:135) at com.dgbi.cre.MQSample.main(MQSample.java:63) Caused by: com.ibm.mq.MQException: JMSCMQ0001: IBM MQ call failed with compcode '2' ('MQCC\_FAILED') reason '2195' ('MQRC\_UNEXPECTED\_ERROR'). at com.ibm.msg.client.wmq.common.internal.Reason.createException(Reason.java:203) ... 9 more Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2195;AMQ9204: Connection to host '192.168.1.107(1414)' rejected. [1=com.ibm.mq.jmqi.JmqiException[CC=2;RC=2195;AMQ6047: Conversion not supported. [1=720,5=???]],3=192.168.1.107(1414),5=RemoteConnection.initSess] at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:2280) at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:1285) at com.ibm.mq.ese.jmqi.InterceptedJmqiImpl.jmqiConnect(InterceptedJmqiImpl.java:376) at com.ibm.mq.ese.jmqi.ESEJMQI.jmqiConnect(ESEJMQI.java:563) at com.ibm.msg.client.wmq.internal.WMQConnection.(WMQConnection.java:355) ... 8 more Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2195;AMQ6047: Conversion not supported. [1=720,5=???] at com.ibm.mq.jmqi.remote.impl.RemoteConnection.initSess(RemoteConnection.java:1282) at com.ibm.mq.jmqi.remote.impl.RemoteConnection.connect(RemoteConnection.java:863) at com.ibm.mq.jmqi.remote.impl.RemoteConnectionSpecification.getSessionFromNewConnection(RemoteConnectionSpecification.java:409) at com.ibm.mq.jmqi.remote.impl.RemoteConnectionSpecification.getSession(RemoteConnectionSpecification.java:305) at com.ibm.mq.jmqi.remote.impl.RemoteConnectionPool.getSession(RemoteConnectionPool.java:146) at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:1721) ... 12 more Caused by: java.io.UnsupportedEncodingException: 720 at com.ibm.mq.jmqi.remote.impl.RemoteConnection.initSess(RemoteConnection.java:1268) ... 17 more ``` What does this exception mean? and how can I solve it?<issue_comment>username_1: The key errors in the exception is: ``` Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2195;AMQ6047: Conversion not supported. [1=720,5=???] Caused by: java.io.UnsupportedEncodingException: 720 ``` It appears this is a known issue in IBM MQ v9.0.0.0 documented in the following APAR: [IT17154: Java client fails to connect to z/OS with exception 'AMQ6047: conversion not supported' in a non-IBM Java runtime](http://www-01.ibm.com/support/docview.wss?uid=swg1IT17154) This APAR was fixed in 9.0.0.1. I would suggest you go with 9.0.0.3 which is the current LTS (Long Term Support) version. If you review the APAR and compare to your issue the difference is that you are connecting to a remote queue manager that is set with CCSID 720 (MSDOS ARABIC). The problem is that the Java JRE you are using does not support this CCSID and due to a defect the client does not attempt to renegotiate the CCSID to one supported by the JRE and the connection fails with the 2195 error. Upvotes: 3 [selected_answer]<issue_comment>username_2: From JoshMC answer, after reading: [IT17154: Java client fails to connect to z/OS with exception 'AMQ6047: conversion not supported' in a non-IBM Java runtime](http://www-01.ibm.com/support/docview.wss?uid=swg1IT17154) One way to solve the issue is to use IBM Java version to build the application. (which I actually did.) Upvotes: 0
2018/03/21
986
3,691
<issue_start>username_0: What I am trying to do **is showing** a div when clicking a related checkbox, **without** using any jQuery. **I also want to hide the div when the checkbox is unchecked.** It's pretty simple with only one checkbox, as I managed to do it. For some reason, I can't manage to make it work on multiple checkboxes (and their related divs). I tried many approaches but none of them work, so my understanding of the problem must be wrong. Here is a simplified version of my code. HTML : ``` Some content Some content Some content Some content Some content Some content Some content ``` and my JS : ``` function addDay() { let tabDays = []; let checked = document.querySelectorAll("input[type='checkbox']:checked"); for (let i = 0; i < checked.length; i++) { tabDays.push(document.querySelector("#" + checked[i].value)); tabDays.forEach(function (day) { if (tabDays.includes(document.querySelector("#" + checked[i].value))) { day.style.display = jour.style.display === "none" ? "block" : "none"; } }) } } ``` Many thanks<issue_comment>username_1: You can just pass the element into your function and because it has the `value` which corresponds to the `id` of the element you want to hide/show you don't need to search for anything. ```js function addDay(e) { document.getElementById(e.value).style.display = e.checked ? "initial" : "none"; } ``` ```html Some content Some content Some content Some content Some content Some content Some content ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: If you want to make it more clean and remove multiple loops then remove the onClick from checkboxes and just listen to its click event and based on that show hide Elements ``` (function() { let checkBoxes = document.querySelectorAll("input[type='checkbox']"); for (let i = 0; i < checkBoxes.length; i++) { checkBoxes[i].addEventListener('click', function(e) { if (e.target.checked) { document.getElementById(e.target.value).style.display = 'block'; } else { document.getElementById(e.target.value).style.display = 'none'; } }); } })(); ``` Upvotes: 0 <issue_comment>username_3: This should also do the job hopefully you can learn the principle of it. ```js function addDay(element) { if(element.checked){ document.getElementById(element.value).style.display = "block"; } else { document.getElementById(element.value).style.display = "none"; } } ``` ```html Some content Some content Some content Some content Some content Some content Some content ``` We can pass the element in the html by using: ``` onclick="addDay(this)" ``` Now we have access to the `DOM` element in our javascript code and can use the properties of it. ``` element.checked // returns true or false based on if the element is checked element.value // returns the value which is determined by the value attribute ``` Upvotes: 0 <issue_comment>username_4: You're doing a lot of extra work by not passing a context into your `addDay` function. Just add `this` (which references the DOM element the `onclick` handler is registered to) to the checkbox element arguments. Then use the built in DOM methods to update style. **HTML** ``` Some content Some content Some content Some content Some content Some content Some content ``` **CSS** ``` .row { display: none; } ``` **JS** ``` function addDay(checkbox) { var row = document.querySelector('#' + checkbox.value); if (!row) return; row.style.display = checkbox.checked ? 'block' : 'none'; } ``` Upvotes: 0
2018/03/21
1,200
4,059
<issue_start>username_0: I downloaded SonarQube 7.0, and setup the Maven project to use Sonar scanner. The pom.xml looks like the following: ``` 4.0.0 com.github.jitpack maven-simple 0.2-SNAPSHOT jar Simple Maven example https://jitpack.io/#jitpack/maven-simple/0.1 1.8 1.8 2.20 UTF-8 src/main/java pom.xml,src/main/java 2.20 org.testng testng 6.8 test sonarLocal false http://localhost:9000 ${src.dir} ${project.basedir} true maven-compiler-plugin 3.3 ${maven.compiler.source} ${maven.compiler.source} ${project.build.sourceEncoding} org.apache.maven.plugins maven-resources-plugin 3.0.2 ${project.build.sourceEncoding} org.apache.maven.plugins maven-checkstyle-plugin 3.0.0 validate validate true google\_checks.xml ${project.build.sourceEncoding} true true true warning check org.apache.maven.plugins maven-surefire-plugin ${mavenSurefireVersion} org.sonarsource.scanner.maven sonar-maven-plugin 3.4.0.905 ``` My structure of the project looks like below: src/main/java --> Contains app code. src/test/java --> Contains all test code. I use the command, "mvn clean install sonar:sonar -PsonarLocal" to execute Sonar. Now I observed that Sonar never analyzes all .java files in the src/test/java folder. To prove this, I added an unused variable in one of the test classes, and Sonar didn't catch it. If I do the same thing in any file in the src/main/java folder, Sonar catches it. Is there something I'm missing?<issue_comment>username_1: You're expecting "normal" rules to be applied to tests. Today that's not the case. Instead, only a subset of test-specific rules are applied. Try instead marking a test `@Ignore`d. You should see an issue then. A way to double-check without another analysis is to look at the project's Code page. You should see the test files listed there and if you drill in to one should be able to access file-specific metrics from the "hamburger menu" icon at the top-right of the file viewer. Currently, to run normal rules on source files, you would need to do a second, separate analysis (be sure to feed in a different project key with `-Dsonar.projectKey` or you'll overlay your normal analysis) and specify your tests directory as the sources (`sonar.sources=relative/path/to/tests`). Upvotes: 2 <issue_comment>username_2: Using the following commands, you can analyze code in both `src/main/java` *and* `src/test/java` in the same Sonar project: 1. First build your application and store its code coverage using JaCoCo: `mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install -Dmaven.test.failure.ignore=false` 2. Then upload the results to Sonar: `mvn sonar:sonar -Dsonar.host.url=http://localhost:9000 -Dsonar.login=-Dsonar.sources=src -Dsonar.test.inclusions=src/test/java/\*` Note that the `-Dsonar.login=` property should only be necessary if <http://localhost:9000> (or whichever host url) requires authentication. Replace with a valid token. **However**, I recommend scanning your `src/test/java` code in a *separate* Sonar project, because metrics like code coverage get thrown off when scanning test code alongside application code (as Sonar will report 0% coverage on all the test classes themselves). To scan separately: For application code (`src/main/java`), run: `mvn sonar:sonar -Dsonar.host.url=http://localhost:9000 -Dsonar.login=` For test code (`src/test/java`), run: `mvn sonar:sonar -Dsonar.projectKey=-tests -Dsonar.host.url=http://localhost:9000 -Dsonar.login=-Dsonar.sources=src/test -Dsonar.test.inclusions=src/test/java/\*` Update `-Dsonar.projectKey=-tests` with the name of your project, so that you have a unique project key for the test scan. For this approach, no additions specific to Sonar/JaCoCo need to be made to `pom.xml`. Note that `mvn clean` with JaCoCo (step 1. above) must be executed before `mvn sonar:sonar...` whenever you make updates to your code in order for those updates to be reflected in Sonar. I tested this using SonarQube 6.6 and Sonar Scanner 3.0.3.778. Upvotes: 2
2018/03/21
1,433
5,251
<issue_start>username_0: I know there are a lot of question about automapper. My problem is that the related object did not mapped by Automapper, but the foreignId did. ``` public class Location { public int Id { get; set; } public string Name{ get; set; } [ForeignKey("Company")] public int? CompanyId { get; set; } public Company Company { get; set; } } ``` Dto object: ``` public class LocationDto { public int Id{ get; set; } public string Name{ get; set; } public int? CompanyId { get; set; } // this is 1 - which the Company.Id public CompanyDto Company { get; set; } // this is NULL } ``` Here the mapping configuration: ``` var configurator= new MapperConfigurationExpression(); configurator.CreateMap() .ForMember(d => d.Company, opt => opt.MapFrom(s => s.Company)); configurator.CreateMap(); configurator.CreateMap(); Mapper.Initialize(configurator); ``` *If I know well, I did it in the right way, because I see this solution in a lot of post and tutorial.* Here the called mapping command: ``` Task.FromResult(Mapper.Map(DataLayer.Get(id))); ``` I have no idea, why the `LocationDto.Company` always NULL (however the `LocationDto.CompanyId` prop always have value). **Do you know why that is null?** I have tried without ForMember too, or with Member.Sourclist ``` configurator.CreateMap(); configurator.CreateMap(Member.SourceList); ``` But nothing helped. Update: Companies ``` public class CompanyDto { public int Id{ get; set; } public string Title{ get; set; } public string Description { get; set; } public int? CountryId { get; set; } //public CountryDto Country { get; set; } public int? CountyId{ get; set; } //public County County{ get; set; } public bool Active { get; set; } } ``` Here the Server part: ``` public class Company { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id{ get; set; } public string Title{ get; set; } public string Description { get; set; } [ForeignKey("Country")] public int? CountryId { get; set; } public Country Country { get; set; } [ForeignKey("County")] public int? CountyId{ get; set; } public County County{ get; set; } public bool Active { get; set; } public virtual ICollection Haders { get; set; } public virtual ICollection Parts{ get; set; } public Company() { this.Active = true; } public Company(string title, string description) { this.Title = title; this.Description = description; } } ```<issue_comment>username_1: You're expecting "normal" rules to be applied to tests. Today that's not the case. Instead, only a subset of test-specific rules are applied. Try instead marking a test `@Ignore`d. You should see an issue then. A way to double-check without another analysis is to look at the project's Code page. You should see the test files listed there and if you drill in to one should be able to access file-specific metrics from the "hamburger menu" icon at the top-right of the file viewer. Currently, to run normal rules on source files, you would need to do a second, separate analysis (be sure to feed in a different project key with `-Dsonar.projectKey` or you'll overlay your normal analysis) and specify your tests directory as the sources (`sonar.sources=relative/path/to/tests`). Upvotes: 2 <issue_comment>username_2: Using the following commands, you can analyze code in both `src/main/java` *and* `src/test/java` in the same Sonar project: 1. First build your application and store its code coverage using JaCoCo: `mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install -Dmaven.test.failure.ignore=false` 2. Then upload the results to Sonar: `mvn sonar:sonar -Dsonar.host.url=http://localhost:9000 -Dsonar.login=-Dsonar.sources=src -Dsonar.test.inclusions=src/test/java/\*` Note that the `-Dsonar.login=` property should only be necessary if <http://localhost:9000> (or whichever host url) requires authentication. Replace with a valid token. **However**, I recommend scanning your `src/test/java` code in a *separate* Sonar project, because metrics like code coverage get thrown off when scanning test code alongside application code (as Sonar will report 0% coverage on all the test classes themselves). To scan separately: For application code (`src/main/java`), run: `mvn sonar:sonar -Dsonar.host.url=http://localhost:9000 -Dsonar.login=` For test code (`src/test/java`), run: `mvn sonar:sonar -Dsonar.projectKey=-tests -Dsonar.host.url=http://localhost:9000 -Dsonar.login=-Dsonar.sources=src/test -Dsonar.test.inclusions=src/test/java/\*` Update `-Dsonar.projectKey=-tests` with the name of your project, so that you have a unique project key for the test scan. For this approach, no additions specific to Sonar/JaCoCo need to be made to `pom.xml`. Note that `mvn clean` with JaCoCo (step 1. above) must be executed before `mvn sonar:sonar...` whenever you make updates to your code in order for those updates to be reflected in Sonar. I tested this using SonarQube 6.6 and Sonar Scanner 3.0.3.778. Upvotes: 2
2018/03/21
1,007
3,598
<issue_start>username_0: Is it possible to remove from a TAR archive some file using `tarfile`? For example: If an `x.tar` file includes the files `a.txt`, `b.txt` and `c.txt`, is it possible to remove `a.txt`? In other words: does any python solution exist to achieve something like this: `tar -vf x.tar --delete a.txt`?<issue_comment>username_1: Not with `tarfile` directly, although there may be some other library out there. A quick hack you can do is to extract the files, then recreate the `tar` minus the files you want to delete. Upvotes: 2 <issue_comment>username_2: I had a similar problem and ended up using the 7z Command Line ([7za.exe](https://www.7-zip.org/download.html)), since it supports more functions than Python's *tarfile*, including deleting files from archive. The downside of this solution is that you need to carry the 7za.exe file around with the program. In your case, you could use something like ``` os.system("7za d x.tar a.txt") ``` Do however keep in mind that `os.system` is deprecated and you should use `subprocess`. Never used it, so I can't really help more. Upvotes: 1 <issue_comment>username_3: In fact, it is possible... but with huge restrictions. You can only delete the end/tail of the archive, not files at the beginning or in the middle of it. I just had a similar need for extracting files from a huge tar (450G) without enough space for both the tar and the extracted files. I had to extract files one at a time and remove them from the `.tar` as soon as they were extracted. The command `tar -vf x.tar --delete a.txt` does not solve that because it does not delete the `a.txt` from the `x.tar` (the `x.tar` remains the same size), it just removes it from the list of contained files (`a.txt` will not be extracted when untaring `x.tar` later). The only thing you can do with `.tar` files, because they are sequential, is to truncate them. So the only solution is to extract files from the end. First you get the list of all the members of the tar file: ``` with tarfile.open(name=tar_file_path, mode="r") as tar_file: tar_members = tar_file.getmembers() ``` Then you can extract the files you want from the end: ``` with tarfile.open(name=tar_file_path, mode="r") as tar_file: tar_file.extractall(path = extracting_dir, members = tar_members[first_of_files_to_extract:]) ``` You compute where to truncate the file (in bytes): ``` truncate_size = tar_members[first_of_files_to_extract].offset ``` Then you add "end of file" marker, i.e. two consecutive blocks of Nulls. Each block is 512 bytes long in `.tar`, so you need to have 1024 Null bytes at the end. Here, just for the record, you can add 512 bytes (one block) because the previous tar\_member already finish by a 512 bytes Null block (marker of end of tar\_member). ``` new_file_size = truncate_size + 1024 # 2 blocs of 512 Null bytes ``` And you finally do the truncations, first for removing last members, second for adding null bytes (here we do not open the `.tar` with `tarfile.open()` anymore, truncation is just regular file operation): ``` with open(tar_file_path) as tar_file: tar_file.truncate(truncate_size) tar_file.truncate(new_file_size) ``` Here you have extracted files from the end of the `.tar`, and you've got a new valid `.tar` file, smaller than the previous one by the size of the extracted files plus some blocks bytes, and you have limitated extra memory usage to the size of the files extracted: I personally did that file by file (extract last file, truncate, extract last file truncate etc). Upvotes: 1
2018/03/21
766
2,930
<issue_start>username_0: I am currently working on a project in `React` and I use `Typescript` as language. In my project I have `Webpack` installed. Everything works fine but now, since we are going to production, I would like to have an easy way to store/retrieve `config settings` such as server URL (which is usually different between development, testing and production phases) and I got stuck. I tried to use the `webpack.config.js` file by adding the `"externals"` key: ``` externals: { 'config': JSON.stringify(process.env.ENV === 'production' ? { serviceUrl: "https://prod.myserver.com" } : { serviceUrl: "http://localhost:8000" }) } ``` and then try to reference the file from my `tsx` component files as such (take into account that the `webpack.config.js` is in the root folder and my components in `/ClientApp/components`): ``` import config from '../../webpack.config.js'; ``` or ``` import {externals} from '../../webpack.config.js'; ``` but I get the following error message: > > 'webpack.config.js' was resolved to '[PROJECT\_DIR]/webpack.config.js', > but '--allowJs' is not set. > > > Any solution/alternative to solve this issue? Thanks<issue_comment>username_1: My favorite way of solving the problem you're describing is to use Webpack's [DefinePlugin](https://webpack.js.org/plugins/define-plugin/): > > The `DefinePlugin` allows you to create global constants which can be configured at **compile** time. This can be useful for allowing different behavior between development builds and release builds. > > > In your `webpack.config.js`, you can create a global constant that you can access in your application code like this: ``` new webpack.DefinePlugin({ ENVIRONMENT: 'prod' }) ``` Then, in your TypeScript code, you can access this constant like this: ``` declare const ENVIRONMENT: 'prod' | 'test' | 'dev' | 'etc...'; if (ENVIRONMENT === 'prod') { serverUrl = 'https://example.com'; } else { .... } ``` Note that this method requires that you build your application separately for each environment. If instead you build your application once, and then deploy the output to multiple environments, you might consider putting this kind of configuration in a JSON file that you can swap out on a per-environment basis. Upvotes: 3 [selected_answer]<issue_comment>username_2: `import config from '../../webpack.config.js'` shouldn't be used in the application itself, it will cause ill effects (it is supposed to be used by Webpack) and won't provide necessary export. `externals: { 'config': ... }` means that non-existing `config` module export is mapped to specified value. It is supposed to be used like: ``` import * as config from 'config'; ``` A more conventional approach is to [provide environment constant as a global](https://webpack.js.org/guides/production/#specify-the-environment) and use it in real `config.ts` module. Upvotes: 1
2018/03/21
979
3,464
<issue_start>username_0: I am using the [ngx-monaco-editor](https://github.com/atularen/ngx-monaco-editor) component together with Angular 5. The monaco-editor is loading fine on localhost, but not on my dev-server. > > Loading failed for the script with source > “<https://se-dnexec.cic.muc/assets/monaco/vs/loader.js>”. > > > This is my webpack.common configuration (under plugins): ``` new WriteFilePlugin(), new CopyWebpackPlugin([ { from: 'src/assets', to: 'assets' }, { from: 'src/meta' }, { from: 'node_modules/ngx-monaco-editor/assets/monaco', to: 'assets/monaco/', } ], isProd ? { ignore: ['mock-data/**/*'] } : undefined ), ``` In webpack.dev I am using the configuration from webpack.common. When I run the application from localhost under assets I can see this. [![localhost_monaco](https://i.stack.imgur.com/qDlNA.png)](https://i.stack.imgur.com/qDlNA.png) But when running from dev-server I see that the monaco folder is missing: [![devserver_monaco](https://i.stack.imgur.com/PwtYV.png)](https://i.stack.imgur.com/PwtYV.png) I am using: * copy-webpack-plugin: "^4.5.1", * write-file-webpack-plugin: "^4.2.0" * webpack: "^3.11.0", * webpack-dev-server: "~2.7.1", I would expect that when I run the dev-server that under assets folder the monaco folder is also copied, but for some reason that is not the case. Maybe someone experienced the same problem and can help me. (If further info is needed I can provide it). I tried the following solution: [Does not copy files to actual output folder when webpack-dev-server is used](https://github.com/webpack-contrib/copy-webpack-plugin/issues/29#issuecomment-348031891)<issue_comment>username_1: My favorite way of solving the problem you're describing is to use Webpack's [DefinePlugin](https://webpack.js.org/plugins/define-plugin/): > > The `DefinePlugin` allows you to create global constants which can be configured at **compile** time. This can be useful for allowing different behavior between development builds and release builds. > > > In your `webpack.config.js`, you can create a global constant that you can access in your application code like this: ``` new webpack.DefinePlugin({ ENVIRONMENT: 'prod' }) ``` Then, in your TypeScript code, you can access this constant like this: ``` declare const ENVIRONMENT: 'prod' | 'test' | 'dev' | 'etc...'; if (ENVIRONMENT === 'prod') { serverUrl = 'https://example.com'; } else { .... } ``` Note that this method requires that you build your application separately for each environment. If instead you build your application once, and then deploy the output to multiple environments, you might consider putting this kind of configuration in a JSON file that you can swap out on a per-environment basis. Upvotes: 3 [selected_answer]<issue_comment>username_2: `import config from '../../webpack.config.js'` shouldn't be used in the application itself, it will cause ill effects (it is supposed to be used by Webpack) and won't provide necessary export. `externals: { 'config': ... }` means that non-existing `config` module export is mapped to specified value. It is supposed to be used like: ``` import * as config from 'config'; ``` A more conventional approach is to [provide environment constant as a global](https://webpack.js.org/guides/production/#specify-the-environment) and use it in real `config.ts` module. Upvotes: 1
2018/03/21
1,556
5,907
<issue_start>username_0: I have been working on this for a long time now. I have read articles from [Get currently typed word in UITextView](https://stackoverflow.com/questions/38969833/get-currently-typed-word-in-uitextview?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) and [Get currently typed word in a UITextView](https://stackoverflow.com/questions/27379765/get-currently-typed-word-in-a-uitextview/27380612#27380612) and I think I am very close. My problem is that after I am able to successfully detect the '@' symbol, for some reason the word that should be returned is not getting returned. For example: ``` func textViewDidChange(_ textView: UITextView) { commentString = commentTextView.text commentTextView.setTextTyping(text: commentTextView.text, withHashtagColor: .blue, andMentionColor: .red, andCallBack: callBack, normalFont: UIFont(name: "HelveticaNeue", size: 14)!, hashTagFont: UIFont(name: "HelveticaNeue-Medium", size: 14)!, mentionFont: UIFont(name: "HelveticaNeue-Medium", size: 14)!) if let word = textView.currentWord { if word.hasPrefix("@") { print(word) print(users) print("Observing") } } } ``` I am able to detect the "@" however, after the boolean test of .hasPrefix, the word that should follow is not being printed to the console. If I print 'word' prior to the boolean test then the correct word is printed to the console. This is the extension I am using to detect the "@" symbol. ``` extension UITextView { var currentWord : String? { let beginning = beginningOfDocument if let start = position(from: beginning, offset: selectedRange.location), let end = position(from: start, offset: selectedRange.length) { let textRange = tokenizer.rangeEnclosingPosition(end, with: .word, inDirection: 1) if let textRange = textRange { return text(in: textRange) } } return nil } } ``` Any help is appreciated in advance, Thanks!<issue_comment>username_1: You could achieve it by [*separating*](https://developer.apple.com/documentation/foundation/nsstring/1413214-components) the whole textview's text by the "@": ``` let text = "My Text goes here @ the next text" let separated = text.components(separatedBy: "@") ``` Thus get the last string from the result array (`separated`): ``` if let textAfterAt = separated.last { print(textAfterAt) // " the next text" } ``` Note that in case the text contains more than one "@", the result would be the string after the last "@", so for instance: ``` let text = "My Text goes here @ the next text @ the last text after the at" let separated = text.components(separatedBy: "@") if let textAfterAt = separated.last { print(textAfterAt) // " the last text after the at" } ``` Upvotes: 0 <issue_comment>username_2: My preference in this case would be to use a regular expression but it seems much more complicated than I remember. See the code below (playground code) ``` #1 let testString1: NSString = "This is a test of a @single prepended word" let testString2: NSString = "This is a test of a @two @prepended words" let regEx = try? NSRegularExpression(pattern: "\\@\\w+") let results = regEx?.matches(in: String(testString2), options: [], range: NSMakeRange(0, testString2.length)) for result in results! { let word = testString2.substring(with: result.range) // #2 print(word) } ``` > > **Output** > > > @two > > > @prepended > > > **#1** I could only achieve this using NSStrings because of the recent Swift 4 changes to String (String is a collection of characters again). **#2** you now have each word and the range of the word in the String, so you can now do some work/calculations and replace each word with whatever you want. Upvotes: 0 <issue_comment>username_3: Use the delegate to get updates as characters are typed. Use a regex to find all words beginning with @ and then apply the desired attributes to each match and assign the attributed string back to the textfield. ``` class ViewController: UIViewController { let regex = try! NSRegularExpression(pattern: "\\@(\\w+)") let highlightAttributes = [NSForegroundColorAttributeName : UIColor.blue] } extension ViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let originalText = textField.text as? NSString else { return false } let proposedText = originalText.replacingCharacters(in: range, with: string) let matches = regex.matches(in: proposedText, options: [], range: NSRange(location: 0, length: proposedText.count)) let attributedText = NSMutableAttributedString(string: proposedText) matches.forEach {attributedText.addAttributes(self.highlightAttributes, range: $0.range)} textField.attributedText = attributedText return false } } ``` Upvotes: 0 <issue_comment>username_4: So you aren't currently getting the whole word in `currentWord`. It looks like you're only getting the `@` character. `currentWord` is a variable and it doesn't look like you're properly iterating through all of the characters in the textField. This is how I would handle that: ``` if let splitText = textField.text?.split(separator: " ") { for word in splitText { if word.hasPrefix("@") { print(word) // call whatever function you need here } else { print("NOPE") } } } else { print("No Text!!") } ``` This will only fire when it finds an `@` and the `word` contains the `@` and every character after the `@` until a `" "` (space) Upvotes: 2 [selected_answer]
2018/03/21
1,193
4,799
<issue_start>username_0: So... i was working at this Wave System for a little game and i wanted the system to wait a specific amount of time before spawning another enemy, so i did this thing: ``` void ExecuteWaveAction(WaveAction action) { int numberOfSpawns = spawnLocations.Length; int currentSpawnToInstantiate = 0; float timeLeftToSpawnEnemy = 0f; for (int i = 0; i < action.quantityOfEnemysToSpawn; i++) { if (timeLeftToSpawnEnemy < action.spawnRate) { timeLeftToSpawnEnemy += Time.deltaTime; i--; } else { GameObject.Instantiate (action.enemyToSpawn, spawnLocations [currentSpawnToInstantiate].position, Quaternion.identity); currentSpawnToInstantiate++; timeLeftToSpawnEnemy = 0f; if (currentSpawnToInstantiate >= numberOfSpawns) currentSpawnToInstantiate = 0; } } } ``` if you are asking yourself what a WaveAction is : ``` public struct WaveAction { public int quantityOfEnemysToSpawn; public float spawnRate; public GameObject enemyToSpawn; } ``` i don't know what is wrong with the code, when i am debugging everything seems to be fine, the script actually waits before spawning, but when i am playing the script spawn all creatures at once. if someone could help me i would be very grateful, and last of all, if i made any spelling or english mistakes i am sorry, i am not a native english speaker<issue_comment>username_1: First let's take a look at `Time.deltaTime`: > > The time in seconds it took to complete the last frame (Read Only). > > > Use this function to make your game frame rate independent. > > > In Unity whenever you need to formulate a time related scenario you have to use co-routines or else it's all up to your code logic to measure delta time. In a simple coroutine we have the logic wrapped in a loop and we have a yield statement which value indicates the amount of time (frames) the coroutine should wait after each pass. `Update` and `FixedUpdate` methods are Unity built-in coroutines which are being executed every `Time.deltaTime` and `Time.fixedDeltaTime` seconds respectively. The logic of your spawning must have a coroutine in order to work since `ExecuteWaveAction` must use delta time. ``` int numberOfSpawns = spawnLocations.Length; int currentSpawnToInstantiate = 0; float timeLeftToSpawnEnemy = 0f; WaveAction action = set this in advance; void Start() { action = ... ExecuteWaveAction(); } void ExecuteWaveAction() { numberOfSpawns = spawnLocations.Length; currentSpawnToInstantiate = 0; timeLeftToSpawnEnemy = 0f; i = 0; } ``` Now look how the looped logic is being separated from the original method and being put in a coroutine: ``` int i = 0; void Update() { //if spawning is active then continue... if (i < action.quantityOfEnemysToSpawn) { if (timeLeftToSpawnEnemy < action.spawnRate) { timeLeftToSpawnEnemy += Time.deltaTime; } else { i++; GameObject.Instantiate (action.enemyToSpawn, spawnLocations [currentSpawnToInstantiate].position, Quaternion.identity); currentSpawnToInstantiate++; timeLeftToSpawnEnemy = 0f; if (currentSpawnToInstantiate >= numberOfSpawns) currentSpawnToInstantiate = 0; } } } ``` Note: You may wonder why can't we use Time.deltaTime in a loop? Answer is: because Time.deltaTime represents the time length of one frame (which is basically equal to the delay between each two consecutive executions of the same `Update` method) but a simple loop runs all at once in one frame and thus Time.deltaTime only tells us some other delay which our loop isn't working upon it. In other words Unity does not wait inside a loop for a frame to end, but it waits after the execution of each coroutine (waiting time = frame length (i.e. Time.deltaTime or Time.fixedDeltaTime or manual coroutine waiting time). Upvotes: 2 [selected_answer]<issue_comment>username_2: I suggest to use a coroutine for that: ``` IEnumerator ExecuteWaveAction(WaveAction action) { int currentSpawnToInstantiate = 0; for (int i = 0; i < action.quantityOfEnemysToSpawn; i++) { // spawn object GameObject.Instantiate (action.enemyToSpawn, spawnLocations [currentSpawnToInstantiate].position, Quaternion.identity); currentSpawnToInstantiate++; if (currentSpawnToInstantiate >= numberOfSpawns) currentSpawnToInstantiate = 0; // waits for 1 sec before continue. you can change the time value yield return new WaitForSeconds(1); } } ``` Upvotes: 2
2018/03/21
923
3,611
<issue_start>username_0: I'm having difficulties to write SQL query that returns me IDs for which there is no typeA records for example ``` ID | type 1 | typeA 1 | typeB 1 | typeC 2 | typeB 2 | typeC 3 | typeB ``` this query should return IDs 2 and 3 thanks in advance for any suggestions Jan<issue_comment>username_1: First let's take a look at `Time.deltaTime`: > > The time in seconds it took to complete the last frame (Read Only). > > > Use this function to make your game frame rate independent. > > > In Unity whenever you need to formulate a time related scenario you have to use co-routines or else it's all up to your code logic to measure delta time. In a simple coroutine we have the logic wrapped in a loop and we have a yield statement which value indicates the amount of time (frames) the coroutine should wait after each pass. `Update` and `FixedUpdate` methods are Unity built-in coroutines which are being executed every `Time.deltaTime` and `Time.fixedDeltaTime` seconds respectively. The logic of your spawning must have a coroutine in order to work since `ExecuteWaveAction` must use delta time. ``` int numberOfSpawns = spawnLocations.Length; int currentSpawnToInstantiate = 0; float timeLeftToSpawnEnemy = 0f; WaveAction action = set this in advance; void Start() { action = ... ExecuteWaveAction(); } void ExecuteWaveAction() { numberOfSpawns = spawnLocations.Length; currentSpawnToInstantiate = 0; timeLeftToSpawnEnemy = 0f; i = 0; } ``` Now look how the looped logic is being separated from the original method and being put in a coroutine: ``` int i = 0; void Update() { //if spawning is active then continue... if (i < action.quantityOfEnemysToSpawn) { if (timeLeftToSpawnEnemy < action.spawnRate) { timeLeftToSpawnEnemy += Time.deltaTime; } else { i++; GameObject.Instantiate (action.enemyToSpawn, spawnLocations [currentSpawnToInstantiate].position, Quaternion.identity); currentSpawnToInstantiate++; timeLeftToSpawnEnemy = 0f; if (currentSpawnToInstantiate >= numberOfSpawns) currentSpawnToInstantiate = 0; } } } ``` Note: You may wonder why can't we use Time.deltaTime in a loop? Answer is: because Time.deltaTime represents the time length of one frame (which is basically equal to the delay between each two consecutive executions of the same `Update` method) but a simple loop runs all at once in one frame and thus Time.deltaTime only tells us some other delay which our loop isn't working upon it. In other words Unity does not wait inside a loop for a frame to end, but it waits after the execution of each coroutine (waiting time = frame length (i.e. Time.deltaTime or Time.fixedDeltaTime or manual coroutine waiting time). Upvotes: 2 [selected_answer]<issue_comment>username_2: I suggest to use a coroutine for that: ``` IEnumerator ExecuteWaveAction(WaveAction action) { int currentSpawnToInstantiate = 0; for (int i = 0; i < action.quantityOfEnemysToSpawn; i++) { // spawn object GameObject.Instantiate (action.enemyToSpawn, spawnLocations [currentSpawnToInstantiate].position, Quaternion.identity); currentSpawnToInstantiate++; if (currentSpawnToInstantiate >= numberOfSpawns) currentSpawnToInstantiate = 0; // waits for 1 sec before continue. you can change the time value yield return new WaitForSeconds(1); } } ``` Upvotes: 2
2018/03/21
989
3,493
<issue_start>username_0: I am using command line inputs to do some simple tasks in my .py script. My inputs are .py (GPIO) (SERIAL) (Log) (Debug)(Can Include an integer) (Pin)(Can include an Integer) (Verbose) (Help) Of course it is all user input so it is case sensitive. I am using: ``` if "gpio" in [x.lower() for x in sys.argv]: ``` which works fine and ``` if str(['Debug','10'])[1:-1] in str([sys.argv]): if str(['Pin','10'])[1:-1] in str([sys.argv]): ``` Which works fine for Case Sensitive and exact integer value but fails for Case Sensitivity and different integer values. So I need to make this accept any case str.lower() and any integer value int() But everything I try fails. str.lower wont accept lists and I'm not sure what to do with integer. I'd like to do this without importing a module if possible.<issue_comment>username_1: Yes, as username_3 says, the correct way to do this is use argparse. You can roll your own, but there's a reason argparse exists -- parsing gets complicated and the work has already been done. Despite that here's a simple argument parser that will do what you want, assuming I understood your question: ``` import sys cmd = None commands = {} for arg in sys.argv[1:]: # set the cmd for all the args that have a value if arg.lower() == 'debug' or arg.lower() == 'pin': cmd = arg # next check for boolean args elif arg.lower() == 'gpio': commands[arg.lower()] = True # take everything else to be a value associated with cmd else: commands[cmd] = int(arg) cmd = None print(commands) ``` Upvotes: 0 <issue_comment>username_2: What I ended up doing with username_1's help "arg.lower() was: ``` if len(sys.argv) > 1: for i in range(1,len(sys.argv)): if str.isdigit(sys.argv[i]): arg = sys.argv[i-1] newval[arg.lower()] = int(sys.argv[i]) ``` Creating a "Dictionary" and then calling: ``` if "debug" in newval: if "pin" in newval: ``` Worked out for me. Upvotes: 0 <issue_comment>username_3: An example for `argparse`. It isn't case insensitive but I see no point in allowing `--gpio`, `--Gpio`, `--gPiO`, … ``` from argparse import ArgumentParser def main(): parser = ArgumentParser() parser.add_argument( '--gpio', action='store_true', default=False, help='Use GPIO.' ) parser.add_argument( '--serial', action='store_true', default=False, help='Make a serial connection.' ) parser.add_argument( '--log', action='store_true', default=False, help='Log actions.' ) parser.add_argument( '--debug', metavar='LEVEL', type=int, default=0, help='Debug level.' ) parser.add_argument('--pin', type=int, help='Pin number.') parser.add_argument( '--verbose', action='count', default=0, help='Increase level of verbosity.' ) options = parser.parse_args() if options.gpio: pass if options.debug > 0: pass if options.pin is not None: pass if __name__ == '__main__': main() ``` You get a `--help` for free: ``` usage: test.py [-h] [--gpio] [--serial] [--log] [--debug LEVEL] [--pin PIN] [--verbose] optional arguments: -h, --help show this help message and exit --gpio Use GPIO. --serial Make a serial connection. --log Log actions. --debug LEVEL Debug level. --pin PIN Pin number. --verbose Increase level of verbosity. ``` Upvotes: 1
2018/03/21
486
1,795
<issue_start>username_0: When using ajax, we use certain 'words' as the protocol checks in JavaScript. But if I am right then every function is an object in JS. Hence when created a new function instance, e.g., > > var xhr = new XMLHttpRequest(); > > > that means we created a new function instance. Now, when doing checks, we write > > xhr.onreadystatechange > > > and > > xhr.readyState > > > and also > > xhr.status > > > etc. We use dot '.' operator with xhr to reflect them as the properties of readyStateChange() function object. So, ... does it mean that these terms are the implicit properties of the JS function objects? Thanks<issue_comment>username_1: These are properties inherited from the **prototype** of `XMLHttpRequest`, not general properties of `Function` objects. Also, `new XMLHttpRequest()` returns a non-function `Object`. ```js let func = new Function() let xhr = new XMLHttpRequest() console.log(func.__proto__) console.log(xhr.__proto__) console.log(func instanceof Function) console.log(xhr instanceof Function) ``` Upvotes: 1 <issue_comment>username_2: > > **onreadystatechange**,**readyState,responseText,responseXML,status,statusText** are the 6 XMLHttpRequest Object Properties > > > When we create a prototype of XMLHttpRequest these properties are also inherited with it **Hence when created a new function instance, e.g., var xhr = new XMLHttpRequest(); ???** No, here we created an object of type XMLHttpRequest Upvotes: 0 <issue_comment>username_3: This is commonly achieved through `prototypal inheritance` in javascript. You can find a lot of info about this on the net, start reading [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) for example. Upvotes: 0
2018/03/21
418
1,656
<issue_start>username_0: I am accessing certain route eg: <http://xyz.domain.com/profile/1>. Now when i manipulate the same url with parameter 2 i.e <http://xyz.domain.com/profile/2>, the component associated with this route is not getting activated that is OnInit is not getting called. Does any one have idea why is that behavior ? Can anyone help on this<issue_comment>username_1: It doesn't work because your component isn't destroyed. If you stay on the same route, then you neither destroy your component, nor recreate it. If you want to see an example of this behavior, [feel free to look at this stackblitz](https://stackblitz.com/edit/angular-2nkzsc?file=app%2Frouted%2Frouted.component.ts). If you want to make something on same URL navigation, you will have to listen to routing events, and do something when it ends. Something like this. ```js this.router.events.subscribe(event => { if (!(event instanceof NavigationEnd)) { return; } this.ngOnInit(); }); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Hope this helps anyone as per @trichetriche comment ``` // ... your class variables here navigationSubscription; this.navigationSubscription = this.router.events.subscribe(event => { if (!(event instanceof NavigationEnd)) { return; } this.ngOnInit(); }); ``` Now on ngDestroy we need to unsubscribe it else on following router events will make the ngOnInit() called for every route instance even in case of normal navigation. ``` ngOnDestroy() { // method on every navigationEnd event. if (this.navigationSubscription) { this.navigationSubscription.unsubscribe(); } } ``` Upvotes: -1
2018/03/21
628
2,622
<issue_start>username_0: I'm trying to get the hash key in kotlin for facebook-app before that i use this java method to get hask key for my apps: **Java code:** ``` // Add code to print out the key hash try { PackageInfo info = getPackageManager().getPackageInfo( "your.package", PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT)); } } catch (NameNotFoundException e) { } catch (NoSuchAlgorithmException e) { } ``` Now i tried this code snippet by converting it into kotlin code: **Kotlin Code:** ``` try { val info = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES) for (signature in info.signatures) { val md = MessageDigest.getInstance("SHA") md.update(signature.toByteArray()) Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT)) } } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } catch (e: NoSuchAlgorithmException) { e.printStackTrace() } ``` but getting error on this line of code i have tried some solutions but didn't get anything useful: ``` Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT)) ``` `encodeToString` is unresolved and same for `Base64.DEFAULT`. Thanks in advance for your time.<issue_comment>username_1: Use below code for getting keyhash ``` try { val info = packageManager.getPackageInfo( "your package", PackageManager.GET_SIGNATURES) for (signature in info.signatures) { val md = MessageDigest.getInstance("SHA") md.update(signature.toByteArray()) Log.e("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT)) } } catch (e: PackageManager.NameNotFoundException) { } catch (e: NoSuchAlgorithmException) { } ``` Make sure that. You import correct packages ``` import android.content.pm.PackageManager import android.util.Base64 import android.util.Log import java.security.MessageDigest import java.security.NoSuchAlgorithmException ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Nothing wrong in your code only one change needed Please add **import android.util.Base64** instead of import java.util.\* Upvotes: 1
2018/03/21
1,319
4,340
<issue_start>username_0: I have a database used for simple reverse geocoding. The database rely on a table containing latitude, longitude and place name. Everytime a couple latitude,longitude is not present or, better, everytime the searched latitude,longitude differs too much from an existing latitude, longitude, I add a new row using GoogleMaps reverse geocoding service. Below the code to generate the address table: ``` CREATE TABLE `data_addresses` ( `ID` int(11) NOT NULL COMMENT 'Primary Key', `LAT` int(11) NOT NULL COMMENT 'Latitude x 10000', `LNG` int(11) NOT NULL COMMENT 'Longitude x 10000', `ADDRESS` varchar(128) NOT NULL COMMENT 'Reverse Geocoded Street Address' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `data_addresses` ADD PRIMARY KEY (`ID`), ADD UNIQUE KEY `IDX_ADDRESS_UNIQUE_LATLNG` (`LAT`,`LNG`), ADD KEY `IDX_ADDRESS_LAT` (`LAT`), ADD KEY `IDX_ADDRESS_LNG` (`LNG`); ALTER TABLE `data_addresses` MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key'; ``` As you can see the trick is to use place two indexes on Latitude and Longitude. As normally latitude and longitude are float we use their value multiplied by 10000, so each couple latitude/longitude is unique. This implies a resolution of about 50m that is satisfying for my needs. Now the problem: everytime I need to know if a given latitude/longitude (MyLat,MyLon) is already present or not I execute the following query: ``` SELECT `id`, ROUND(SQRT(POW(ABS(`LAT`-ROUND(MyLat*10000)),2)+POW(ABS(`LNG`-ROUND(MyLon*10000)),2))) AS R FROM splc_smarttrk.`data_addresses` ORDER BY R ASC LIMIT 1 ``` This query will return to me the closest point and will give me also R (the rating): smaller R means closest approximation, so let say that everytime I find an R that is above 10 I need to add a new row to address table. Address table at present contains about 615k rows. The problem is that despite indexes that I have placed this query is too slow (takes about 2 seconds on a 2x Xeon server). Below the results of Explain: [![enter image description here](https://i.stack.imgur.com/n2fEp.png)](https://i.stack.imgur.com/n2fEp.png)<issue_comment>username_1: Can't you optimize this by retriving a fixed dataset of nearby latitude(s) and longitude(s) and calculate the Rating (R) and pick the smallest Rating on this fixed dataset. p.s not tested might contain errors in the sorting. but it might help you on your way. ``` SELECT id , ROUND(SQRT(POW(ABS(`LAT`-ROUND([LAT]*10000)),2)+POW(ABS(`LNG`- ROUND([LNG]*10000)),2))) AS R FROM ( SELECT LAT FROM data_addresses WHERE LAT <= [LAT] ORDER BY LAT DESC LIMIT 100 UNION ALL SELECT LAT FROM data_addresses WHERE LAT >= [LAT] ORDER BY LAT ASC LIMIT 100 SELECT LNG FROM data_addresses WHERE LNG <= [LNG] ORDER BY LNG DESC LIMIT 100 UNION ALL SELECT LNG FROM data_addresses WHERE LNG >= [LNG] ORDER BY LNG ASC LIMIT 100 ) AS data_addresses_range ORDER BY R ASC LIMIT 1 ``` Upvotes: 2 <issue_comment>username_2: Following the suggestion of username_1 I modified the query as follows: ``` SELECT `id` AS ID, ROUND(SQRT(POW(ABS(`LAT`-ROUND(NLat*10000)), 2) + POW(ABS(`LNG`-ROUND(NLon*10000)), 2)) ) AS RT INTO ADDR_ID, RATING FROM splc_smarttrk.`data_addresses` WHERE (`LAT` BETWEEN (ROUND(NLat*10000)-R) AND (ROUND(NLat*10000)+R)) AND (`LNG` BETWEEN (ROUND(NLon*10000)-R) AND (ROUND(NLon*10000)+R)) ORDER BY RT ASC LIMIT 1; ``` this trick reduces the dataset to 10 records in the worst case scenario, hence the speed is fair good despite the ORDER BY clause. In fact I don't really need to know the Distance from existing point, I just need to know if that distance is above a givel limit (here if is within a 10x10 rectangle that means R=5). Upvotes: 0 <issue_comment>username_3: Instead of computing the distance (or in addition to), provide a "bounding box". This will be much faster. Still faster would be the complex code here: mysql.rjweb.org/doc.php/latlng Once you have `UNIQUE KEY IDX_ADDRESS_UNIQUE_LATLNG (LAT, LNG)`, there is no need for `KEY IDX_ADDRESS_LAT (LAT)` \*10000 can fit in `MEDIUMINT`. And it is good to about 16 meters or 52 feet. Upvotes: 1
2018/03/21
1,166
4,753
<issue_start>username_0: This question is about using function pointers, which are not precisely compatible, but which I hope I can use nevertheless as long as my code relies only on the compatible parts. Let's start with some code to get the idea: ``` typedef void (*funcp)(int* val); static void myFuncA(int* val) { *val *= 2; return; } static int myFuncB(int* val) { *val *= 2; return *val; } int main(void) { funcp f = NULL; int v = 2; f = myFuncA; f(&v); // now v is 4 // explicit cast so the compiler will not complain f = (funcp)myFuncB; f(&v); // now v is 8 return 0; } ``` While the arguments of `myFuncA` and `myFuncB` are identical and fully compatible, the return values are not and are thus just ignored by the calling code. I [tried the above code](http://coliru.stacked-crooked.com/a/816cf130ea0d6a81) and it works correctly using GCC. What I learned so far from [here](https://stackoverflow.com/questions/559581/casting-a-function-pointer-to-another-type) and [here](https://stackoverflow.com/questions/31942838/casting-function-pointers) is that the functions are incompatible by definition of the standard and **may** cause undefined behavior. My intuition, however, tells me that my code example will still work correctly, since it does not rely in any way on the incompatible parts (the return value). However, in the answers to [this question](https://stackoverflow.com/questions/22782166/function-pointers-with-different-return-types) a possible corruption of the stack has been mentioned. So my question is: Is my example above valid C code so it will **always** work as intended (without any side effects), or does it depend on the compiler? --- EDIT: I want to do this in order to use a "more powerful" function with a "les powerful" interface. In my example `funcp` is the interface but I would like to provide additional functionality like `myFuncB` for optional use.<issue_comment>username_1: Yes, this is an undefined behaviour and you should never rely on undefined behaviour if want to write portable code. Function with different return values can have different calling conventions. Your example will probably work for small return types, but when returning large structs (e.g. larger than 32 bits) some compilers will generate code where struct is returned in a temporary memory area which should be cleaned up the the caller. Upvotes: 2 <issue_comment>username_2: Agreed it is undefined behaviour, don't do that! Yes the code functions, i.e. it doesn't fall over, but the value you assign after returning void is undefined. In a very old version of "C" the return type was unspecified and int and void functions could be 'safely' intermixed. The integer value being returned in the designated accumulator register. I remember writing code using this 'feature'! For almost anything else you might return the results are likely to be fatal. Going forward a few years, floating-point return values are often returned using the fp coprocessor (we are still in the 80s) register, so you can't mix int and float return types, because the state of the coprocessor would be confused if the caller does not strip off the value, or strips off a value that was never placed there and causes an fp exception. Worse, if you build with fp emulation, then the fp value may be returned on the stack as described next. Also on 32-bit builds it is possible to pass 64bit objects (on 16 bit builds you can have 32 bit objects) which would be returned either using multiple registers or on the stack. If they are on the stack and allocated the wrong size, then some local stomping will occur, Now, c supports struct return types and return value copy optimisations. All bets are off if you don't match the types correctly. Also some function models have the caller allocate stack space for the parameters for the call, but the function itself releases the stack. Disagreement between caller and implementation on on the number or types of parameters and return values would be fatal. By default C function names are exported and linked undecorated - just the function name defines the symbol, so different modules of your program could have different views about function signatures, which conflict when you link, and potentially generate very interesting runtime errors. In c++ the function names are highly decorated primarily to allow overloading, but also it helps to avoid signature mismatches. This helps with keeping arguments in step, but actually, ( as noted by @Jens ) the return type is not encoded into the decorated name, primarily because the return type isn't used (wasn't, but I think occasionally can now influence) for overload resolution. Upvotes: 4 [selected_answer]
2018/03/21
558
1,995
<issue_start>username_0: I need to run a job that sends email to the user when a contest's field named `published_at` will be set. So I have a `Contest` model and a method that runs a job: ``` class Contest < ApplicationRecord after_create :send_contest private def send_contest SendContestJob.set(wait: 30.minutes).perform_later(self) end end ``` But the job will run even if `published_at` field is blank. Validating the field to be present is not an option because `published_at` can be set later. So are there any solutions how can I run the job after setting the field? Thanks ahead.<issue_comment>username_1: [ActiveModel::Dirty](http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-changes) might be useful here. With it, you can inspect what fields are about to change/have been changed: ``` person.name # => "bob" person.name = 'robert' person.save person.previous_changes # => {"name" => ["bob", "robert"]} ``` So, say, if `published_at_changed?` returns true, you schedule the job. Upvotes: 4 [selected_answer]<issue_comment>username_2: Instead of using `after_create` you can use `before_save` which is fired both for new and existing records. The `if:` and `unless:` options allow you to specify conditions that need to be met for a callback to be called, you can pass a Proc, Lambda or the name of a method to be called. ``` class Contest < ApplicationRecord before_save :send_contest, if: -> { published_at.present? && published_at_changed? } # or before_save :send_contest, if: :publishable? private def send_contest SendContestJob.set(wait: 30.minutes).perform_later(self) end def publishable? published_at.present? && published_at_changed? end end ``` As recommended by username_1 you can use [ActiveRecord::Dirty](http://api.rubyonrails.org/classes/ActiveModel/Dirty.html) to check for changes to the value of the column. Be sure to read the docs carefully though as there are plenty of gotchas. Upvotes: 2
2018/03/21
696
2,188
<issue_start>username_0: I'm still a beginner so please bear with me. So I'm trying to get a list of factorial numbers from 1 to 5. ``` factorial=[] for i in range(1,5): for x in range(1,5): while(i>x): factorial.append(i*x) ``` When I switch out the factorial.append for print it just continously spits out 2s, does anyone know why, and if so what to do to fix this and what other viable method is there to get a list of factorial numbers?<issue_comment>username_1: I this case, I recommend you to use a recursive function: ``` def factorial(x): if x == 1: return 1 else: return x*factorial(x-1) ``` Ex: ``` >>>factorial(5) 120 >>>factorial(10) 3628800 ``` Upvotes: 1 <issue_comment>username_2: you can do something like : ``` >>> f=[1] # initialized your list >>> for i in range(5): # take each value in the list [0,1,2,3,4] ... f.append(f[i]*(i+1)) #to create a next point multiply with the last value ... >>> f=f[1:] #don't keep the first (repeated) point >>> f #you have your list ! [1, 2, 6, 24, 120] ``` Upvotes: 1 <issue_comment>username_3: You're getting stuck in your `while` loop. If you go step by step through your code, you'll see what is going on: In the first loop, `i` value will be 1, and `x` values from 1 to 5, so `i` will never be > than `x`, thus you won't enter the while loop. At the start of the second loop, `i` value will be 2 and `x` value will be 1, so you will enter the `while` loop. You will stay in stay in the `while` loop until `i` becomes lower or equal to `x`, but this will never happen because to continue with the `for` loop you'll need to exit the `while` loop first. Despite the error, i do not understand the reasoning that brought you there. The common way to handle factorials is with recursion, as @username_1's answer shows, but it may simplier to understand the following: ``` # in each for loop, you multiply your n variable for the i value # and you store the result of the moltiplication in your n variable n=1 for i in range(1,6): # if you want the numbers from 1 to 5, you have to increase by one your maximum value n = n*i print n ``` Upvotes: 0
2018/03/21
864
3,130
<issue_start>username_0: I have caught up in a situation, where in i need to verify the response of the Previous Sampler for one of the value and if the Value for that is [], then i need to trigger the below request or else then switch to another Sampler. ``` Flow: Check Response of Sampler for One of the attribute IF(attribute value==[]) Execute the Sampler under IF Conditions. ELSE New Sampler ``` Sample Response: {"id":8,"merchant\_id":"39","title":"Shirts-XtraLarge","subtitle":null,"price":110,"description":null,"images":"image\_thumbs":[[]],"options":[],"options\_available":[],"custom\_options":[]} I need to check if the attribute custom\_options is empty or not! If Empty do some actions and if not empty do some other action ! Need if condition to simulate this! Help is useful!<issue_comment>username_1: A nice to have feature in JMeter would be Else statement, but until then you will have to use 2 [If Controllers](http://jmeter.apache.org/usermanual/component_reference.html#If_Controller) > > If Controller allows the user to control whether the test elements below it (its children) are run or not. > > > Assuming you hold your attribute value using regex/json/css/other post processor extractor add two condition, first is positive and under it the Sampler: ``` ${__groovy("${attributeValue}" == "[]")} ``` Second is negative and under it add the New Sampler ``` ${__groovy("${attributeValue}" != "[]")} ``` [\_\_groovy](http://jmeter.apache.org/usermanual/functions.html#__groovy) is encourage to use over default Javascript > > Checking this and using \_\_jexl3 or \_\_groovy function in Condition is advised for performances > > > Upvotes: 2 <issue_comment>username_2: Go for [Switch Controller](https://jmeter.apache.org/usermanual/component_reference.html#Switch_Controller) 1. Add [JSR223 PostProcessor](http://jmeter.apache.org/usermanual/component_reference.html#JSR223_PostProcessor) as a child of the request which returns your JSON 2. Put the following code into "Script" area: ``` def size = com.jayway.jsonpath.JsonPath.read(prev.getResponseDataAsString(), '$..custom_options')[0].size() if (size == 0) { vars.put('size', 'empty') } else { vars.put('size', 'notempty') } ``` 3. Add [Switch Controller](https://jmeter.apache.org/usermanual/component_reference.html#Switch_Controller) to your Test Plan and use `${size}` as "Switch Value" 4. Add [Simple Controller](https://jmeter.apache.org/usermanual/component_reference.html#Simple_Controller) as a child of the Switch Controller and give `empty` name to it. Put request(s) related to empty "custom\_options" under that `empty` Simple Controller 5. Add another Simple Controller as a child of the Switch Controller and give `notempty` name to it. Put request(s) related to not empty "custom\_options" under that `notempty` Simple Controller. [![JMeter Switch Controller](https://i.stack.imgur.com/y2D1X.png)](https://i.stack.imgur.com/y2D1X.png) More information: [Selection Statements in JMeter Made Easy](https://www.blazemeter.com/blog/selection-statements-in-jmeter-made-easy) Upvotes: 2 [selected_answer]
2018/03/21
1,815
6,467
<issue_start>username_0: I am currently exploring neural networks and machine learning and I implemented a basic neural network in c#. Now I wanted to test my back propagation training algorithm with the MNIST database. Although I am having serious trouble reading the files correctly. Spoiler the code is currently very badly optimised for performance. My aim currently is to grasp the subject and get a structured view how things work before I start throwing out my data structures for faster ones. To train the network I want to feed it a custom TrainingSet data structure: ``` [Serializable] public class TrainingSet { public Dictionary, List> data = new Dictionary, List>(); } ``` Keys will be my input data (784 pixels per entry(image) which will represent the greyscale values in range from 0 to 1). Values will be my output data (10 entries representing the digits from 0-9 with all entries on 0 except the exspected one at 1) Now I want to read the MNIST database according to this contract. I am currentl on my 2nd try which is inspired by this blogpost: <https://jamesmccaffrey.wordpress.com/2013/11/23/reading-the-mnist-data-set-with-c/> . Sadly it is still producing the same nonsense as my first try scattering the pixels in a strange pattern: [![Pattern screenshot](https://i.stack.imgur.com/r8awl.png)](https://i.stack.imgur.com/r8awl.png) My current reading algorithm: ``` public static TrainingSet GenerateTrainingSet(FileInfo imagesFile, FileInfo labelsFile) { MnistImageView imageView = new MnistImageView(); imageView.Show(); TrainingSet trainingSet = new TrainingSet(); List> labels = new List>(); List> images = new List>(); using (BinaryReader brLabels = new BinaryReader(new FileStream(labelsFile.FullName, FileMode.Open))) { using (BinaryReader brImages = new BinaryReader(new FileStream(imagesFile.FullName, FileMode.Open))) { int magic1 = brImages.ReadBigInt32(); //Reading as BigEndian int numImages = brImages.ReadBigInt32(); int numRows = brImages.ReadBigInt32(); int numCols = brImages.ReadBigInt32(); int magic2 = brLabels.ReadBigInt32(); int numLabels = brLabels.ReadBigInt32(); byte[] pixels = new byte[numRows \* numCols]; // each image for (int imageCounter = 0; imageCounter < numImages; imageCounter++) { List imageInput = new List(); List exspectedOutput = new List(); for (int i = 0; i < 10; i++) //generate empty exspected output exspectedOutput.Add(0); //read image for (int p = 0; p < pixels.Length; p++) { byte b = brImages.ReadByte(); pixels[p] = b; imageInput.Add(b / 255.0f); //scale in 0 to 1 range } //read label byte lbl = brLabels.ReadByte(); exspectedOutput[lbl] = 1; //modify exspected output labels.Add(exspectedOutput); images.Add(imageInput); //Debug view showing parsed image....................... Bitmap image = new Bitmap(numCols, numRows); for (int y = 0; y < numRows; y++) { for (int x = 0; x < numCols; x++) { image.SetPixel(x, y, Color.FromArgb(255 - pixels[x \* y], 255 - pixels[x \* y], 255 - pixels[x \* y])); //invert colors to have 0,0,0 be white as specified by mnist } } imageView.SetImage(image); imageView.Refresh(); //....................................................... } brImages.Close(); brLabels.Close(); } } for (int i = 0; i < images.Count; i++) { trainingSet.data.Add(images[i], labels[i]); } return trainingSet; } ``` All images produce a pattern as shown above. It's never the exact same pattern but always seems to have the pixels "pulled" down to the right corner.<issue_comment>username_1: That is how I did it: ``` public static class MnistReader { private const string TrainImages = "mnist/train-images.idx3-ubyte"; private const string TrainLabels = "mnist/train-labels.idx1-ubyte"; private const string TestImages = "mnist/t10k-images.idx3-ubyte"; private const string TestLabels = "mnist/t10k-labels.idx1-ubyte"; public static IEnumerable ReadTrainingData() { foreach (var item in Read(TrainImages, TrainLabels)) { yield return item; } } public static IEnumerable ReadTestData() { foreach (var item in Read(TestImages, TestLabels)) { yield return item; } } private static IEnumerable Read(string imagesPath, string labelsPath) { BinaryReader labels = new BinaryReader(new FileStream(labelsPath, FileMode.Open)); BinaryReader images = new BinaryReader(new FileStream(imagesPath, FileMode.Open)); int magicNumber = images.ReadBigInt32(); int numberOfImages = images.ReadBigInt32(); int width = images.ReadBigInt32(); int height = images.ReadBigInt32(); int magicLabel = labels.ReadBigInt32(); int numberOfLabels = labels.ReadBigInt32(); for (int i = 0; i < numberOfImages; i++) { var bytes = images.ReadBytes(width * height); var arr = new byte[height, width]; arr.ForEach((j,k) => arr[j, k] = bytes[j * height + k]); yield return new Image() { Data = arr, Label = labels.ReadByte() }; } } } ``` `Image` class: ``` public class Image { public byte Label { get; set; } public byte[,] Data { get; set; } } ``` Some extension methods: ``` public static class Extensions { public static int ReadBigInt32(this BinaryReader br) { var bytes = br.ReadBytes(sizeof(Int32)); if (BitConverter.IsLittleEndian) Array.Reverse(bytes); return BitConverter.ToInt32(bytes, 0); } public static void ForEach(this T[,] source, Action action) { for (int w = 0; w < source.GetLength(0); w++) { for (int h = 0; h < source.GetLength(1); h++) { action(w, h); } } } } ``` Usage: ``` foreach (var image in MnistReader.ReadTrainingData()) { //use image here } ``` or ``` foreach (var image in MnistReader.ReadTestData()) { //use image here } ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: Why not use a nuget package: * [MNIST.IO](https://www.nuget.org/packages/MNIST.IO/) Just a datareader (disclaimer: my package) * [Accord.DataSets](https://www.nuget.org/packages/Accord.DataSets/3.8.2-alpha) Contains classes to download and parse machine learning datasets such as MNIST, News20, Iris. This package is part of the Accord.NET Framework. Upvotes: 2
2018/03/21
420
1,193
<issue_start>username_0: I want to pull in all contacts whose postal code begins with L5h, K2S or L3S. My sql is: ``` SELECT * FROM [customer_list_DE] WHERE Postal_Code IN ('L5H%','K2S%','L3S%') ``` I have checked my data and many records exist with postal code that start with those characters, but my query is resulting in 0 records (however it is not erroring out). I am using Salesforce Marketing Cloud.<issue_comment>username_1: You need `OR`. `IN` doesn't do wildcards: ``` SELECT * FROM [customer_list_DE] WHERE Postal_Code = 'L5H%' OR Postal_Code = 'K2S%' OR Postal_Code = 'L3S%'; ``` You could also do this with string manipulation: ``` SELECT * FROM [customer_list_DE] WHERE LEFT(Postal_Code, 3) IN ('L5H', 'K2S', 'L3S') ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: `IN` list does not support wildcards. Use `OR` instead: ``` SELECT * FROM [customer_list_DE] WHERE Postal_Code LIKE 'L5H%' OR Postal_Code LIKE 'K2S%' OR Postal_Code LIKE 'L3S%' ``` Upvotes: 1 <issue_comment>username_3: Try this instead: ``` SELECT * FROM [customer_list_DE] WHERE Postal_Code LIKE 'L5H%' OR Postal_Code LIKE 'K2S%' OR Postal_Code LIKE 'L3S%'; ``` Upvotes: 0
2018/03/21
406
1,119
<issue_start>username_0: I have two modules in the same directory: `PDSC2.py` and `db_layer.py` I want to import a class named `DBLayer` from `db_layer.py` so I write: ``` from db_layer.py import DBLayer ``` But I get an error: ``` ModuleNotFoundError: No module named 'db_layer' ``` Does somebdy have an idea what i'm doing wrong?<issue_comment>username_1: You need `OR`. `IN` doesn't do wildcards: ``` SELECT * FROM [customer_list_DE] WHERE Postal_Code = 'L5H%' OR Postal_Code = 'K2S%' OR Postal_Code = 'L3S%'; ``` You could also do this with string manipulation: ``` SELECT * FROM [customer_list_DE] WHERE LEFT(Postal_Code, 3) IN ('L5H', 'K2S', 'L3S') ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: `IN` list does not support wildcards. Use `OR` instead: ``` SELECT * FROM [customer_list_DE] WHERE Postal_Code LIKE 'L5H%' OR Postal_Code LIKE 'K2S%' OR Postal_Code LIKE 'L3S%' ``` Upvotes: 1 <issue_comment>username_3: Try this instead: ``` SELECT * FROM [customer_list_DE] WHERE Postal_Code LIKE 'L5H%' OR Postal_Code LIKE 'K2S%' OR Postal_Code LIKE 'L3S%'; ``` Upvotes: 0
2018/03/21
512
1,836
<issue_start>username_0: I would like to know how I could take an object from a function and place it and all it's attributes into another object. ``` class Something: def create(self): print('Creating') class Foo(Something): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def do_something(self): print('Do somthing') def bar(): # Can not change this function return Something() s = bar() s.create() # 'Creating' -- I want to do this -- f = Foo(s) f.create() f.do_something() ``` Limitations: I cant alter `bar()`. I need to be able to access all of `Something`'s methods and attributes from `Foo`. I would like to stay away form composition so that I can call `Foo.create()` directly (not like `Foo.something.create()`).<issue_comment>username_1: I came up with this solution, which Im not very happy with as it requires me to call the function twice. ``` class Something: def create(self): print('Creating') class Foo: def __init__(self, something): self.sometthing = something def __getattr__(self, attr): return getattr(self.obj, attr) @some_special_decorator def create(self): return self.something.create() def do_something(self): print('Do somthing') def bar(): # Can not change this function return Something() s = bar() s.create() # 'Creating' f = Foo(s) f.create() f.do_something() ``` Upvotes: -1 <issue_comment>username_2: Change `__init__(self, *args, **kwargs)` to `__init__(self, _, *args, **kwargs):` ``` >>> Foo(Something()).create() Creating >>> Foo(Something()).do_something() Do somthing ``` I honestly don't see the problem here. Or why you want to supply an instance of `Something` when creating an instance of `Foo`, but there you go. Upvotes: 0
2018/03/21
1,915
7,528
<issue_start>username_0: I have using spydroid from <https://github.com/fyhertz/spydroid-ipcamera>. Based on the requirement streaming should be send and receive in the device. from local network we should able to shown the rtsp stream. Ex. VLC Media Player. The issue I am facing is, When I am change the resolution Ex. 640\*480. It should give black screen with streaming live. In Default demo, It should support 320\*240, which is working fine. I have also change the bitrate and framerate according to 640\*480 resolution. But couldn't get the result. Any help would be appreciate.<issue_comment>username_1: You might be using old library which the demo **SpyDroid** is using. I had same issue with the code i tried following way :- Steps:- 1.)include library [LibStreaming](https://github.com/fyhertz/libstreaming) . * As it is the latest library and supporting above Lollipop version. 2.)Find [H263Stream](https://github.com/fyhertz/libstreaming/blob/master/src/net/majorkernelpanic/streaming/video/H264Stream.java) **class** Change following method :- **From** ``` @SuppressLint("NewApi") private MP4Config testMediaCodecAPI() throws RuntimeException, IOException { createCamera(); updateCamera(); try { if (mQuality.resX>=640) { // Using the MediaCodec API with the buffer method for high resolutions is too slow mMode = MODE_MEDIARECORDER_API; } EncoderDebugger debugger = EncoderDebugger.debug(mSettings, mQuality.resX, mQuality.resY); return new MP4Config(debugger.getB64SPS(), debugger.getB64PPS()); } catch (Exception e) { // Fallback on the old streaming method using the MediaRecorder API Log.e(TAG,"Resolution not supported with the MediaCodec API, we fallback on the old streamign method."); mMode = MODE_MEDIARECORDER_API; return testH264(); } ``` } **To** ``` @SuppressLint("NewApi") private MP4Config testMediaCodecAPI() throws RuntimeException, IOException { createCamera(); updateCamera(); try { if (mQuality.resX>=1080) { // Using the MediaCodec API with the buffer method for high resolutions is too slow mMode = MODE_MEDIARECORDER_API; } EncoderDebugger debugger = EncoderDebugger.debug(mSettings, mQuality.resX, mQuality.resY); return new MP4Config(debugger.getB64SPS(), debugger.getB64PPS()); } catch (Exception e) { // Fallback on the old streaming method using the MediaRecorder API Log.e(TAG,"Resolution not supported with the MediaCodec API, we fallback on the old streamign method."); mMode = MODE_MEDIARECORDER_API; return testH264(); } } ``` -You can find the difference change resolution from "**640**" into "**1080**" -Don't know what exact reason is but above solution worked for me. -Revert me back if there is any loop fall. Upvotes: 1 <issue_comment>username_2: In my case the problem was in MediaRecorder: file: VideoStream.java method: encodeWithMediaRecorder MediaRecorder doesn't support ParcelFileDescriptor correctly. I created local file to save stream form MediaRecorder: ``` mMediaRecorder.setOutputFile(this.tmpFileToStream); //mMediaRecorder.setOutputFile(fd); //disable.. ``` and then I run new thread to copy bytes from tmpFileToStream to mParcelWrite ``` public void run() { FileDescriptor fd = mParcelWrite.getFileDescriptor(); try { InputStream isS = new FileInputStream(tmpFileToStream); //read from local file.. FileOutputStream outputStream = new FileOutputStream(fd); while (!Thread.interrupted()) { int content; while ((content = isS.read()) != -1) { outputStream.write(content); } Thread.sleep(10); } } catch (Exception e) { Log.e(TAG, "E.. " + e.getMessage()); } } /** * Video encoding is done by a MediaRecorder. */ protected void encodeWithMediaRecorder() throws IOException, ConfNotSupportedException { Log.d(TAG,"Video encoded using the MediaRecorder API"); Log.d(TAG,"Roz" + mRequestedQuality.resX + " x " + mRequestedQuality.resY + " frame " + mRequestedQuality.framerate ); // We need a local socket to forward data output by the camera to the packetizer createSockets(); // Reopens the camera if needed destroyCamera(); createCamera(); // The camera must be unlocked before the MediaRecorder can use it unlockCamera(); this.tmpFileToStream = this.getOutputMediaFile(MEDIA_TYPE_VIDEO); Log.d(TAG,"Video record to " + this.tmpFileToStream.getAbsolutePath() ); try { mMediaRecorder = new MediaRecorder(); mMediaRecorder.setCamera(mCamera); mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); // mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mMediaRecorder.setVideoEncoder(mVideoEncoder); mMediaRecorder.setPreviewDisplay(mSurfaceView.getHolder().getSurface()); mMediaRecorder.setVideoSize(mRequestedQuality.resX,mRequestedQuality.resY); mMediaRecorder.setVideoFrameRate(mRequestedQuality.framerate); // The bandwidth actually consumed is often above what was requested mMediaRecorder.setVideoEncodingBitRate((int)(mRequestedQuality.bitrate*0.8)); // We write the output of the camera in a local socket instead of a file ! // This one little trick makes streaming feasible quiet simply: data from the camera // can then be manipulated at the other end of the socket FileDescriptor fd = null; if (sPipeApi == PIPE_API_PFD) { fd = mParcelWrite.getFileDescriptor(); } else { fd = mSender.getFileDescriptor(); } mMediaRecorder.setOutputFile(this.tmpFileToStream); //save to local.. afeter read and stream that.. // mMediaRecorder.setOutputFile(fd); //disable.. // copy bytes from local file to mParcelWrite.. :) if(tInput == null) { this.tInput = new Thread(this); this.tInput.start(); } mMediaRecorder.prepare(); mMediaRecorder.start(); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.d(TAG, "Error stack " + sw.toString()); throw new ConfNotSupportedException(e.getMessage()); } InputStream is = null; if (sPipeApi == PIPE_API_PFD) { is = new ParcelFileDescriptor.AutoCloseInputStream(mParcelRead); } else { is = mReceiver.getInputStream(); } // This will skip the MPEG4 header if this step fails we can't stream anything :( try { byte buffer[] = new byte[4]; // Skip all atoms preceding mdat atom while (!Thread.interrupted()) { while (is.read() != 'm'); is.read(buffer,0,3); if (buffer[0] == 'd' && buffer[1] == 'a' && buffer[2] == 't') break; } } catch (IOException e) { Log.e(TAG,"Couldn't skip mp4 header :/"); stop(); throw e; } // The packetizer encapsulates the bit stream in an RTP stream and send it over the network mPacketizer.setInputStream(is); mPacketizer.start(); mStreaming = true; } ``` That's unusual solution but it works for another resolution Upvotes: 0
2018/03/21
722
2,813
<issue_start>username_0: I am trying to understand how wordpress nonces work in terms of security. `nonce` is for a number used once, but according to wordpress, it can be valid up to 24 hours, which makes no sense, it could be used 9999 times during this period (from same client). I thought that a wordpress nonce is really a number used once and that a nonce is valid only for one-time usage, but that's not the case. I guess for a better security, a one-time usage number would be better, e.g. you have a commenting system and someone clicks on "reply" two times. Instead of inserting the comment two times, it is being inserted one time, because of the one-time valid nonce (same one) given in the two requests. Am I getting something wrong? What is the purpose of those wordpress nonces?<issue_comment>username_1: You are getting it kind of wrong. Although it is true that nonce is valid up to 24 hours, after which it will expire and a new one will be generated, a nonce can be only used once. Hence the name *nonce* - **n**umber only used **once**. Here is a website which will be able to help you more about understading the whole thing behind nonces - <https://codex.wordpress.org/WordPress_Nonces> Upvotes: 0 <issue_comment>username_2: You are right WordPress nonce is not an actual nonce. It can be used multiple times during a period of time while nonce is valid (12-24 hours) [check nonce tick function](https://core.trac.wordpress.org/browser/tags/5.2/src/wp-includes/pluggable.php#L2023). The main reason why you need to use nonce is to prevent [CSRF](https://de.wikipedia.org/wiki/Cross-Site-Request-Forgery) (Cross Site Request Forgery) and malicious scripts. But in all other security cases, you shouldn't rely on WP nonce. Use `current_user_can()` to actually check what current user can and cannot do on your website. [Check docs](https://codex.wordpress.org/Function_Reference/current_user_can) Upvotes: 1 <issue_comment>username_3: Nonce can protect several types of attacks including CSRF, but do not provide protection against replay attacks because they are not checked for one time use. That is why for authentication, authorization or any access control purpose we should not rely on nonce. We can minimize nonce lifetime to any lower hour by adding filter to [nonce\_life](https://developer.wordpress.org/reference/hooks/nonce_life/) hook ``` add_filter( 'nonce_life', function () { return 4 * HOUR_IN_SECONDS; } ); ``` The example above will give you nonces that are valid for 2-4 hours. As Wordpress nonce are not providing one time use, for better protection we can add role permission checking after the nonce verification ``` if( current_user_can( 'edit_posts' ) ){ // Write you action code here after verifying the actual user permission } ``` Upvotes: 0
2018/03/21
2,498
8,192
<issue_start>username_0: I have a class that looks like this: Foo is my class; FooBar is a bunch of different types of classes from a library that each have independent names. **Foo.h** ``` class Foo { public: Foo() = default; // There many types, and many of these types have multiple constructors // All of the appropriate overloads are available here. template FooBar& getFooBarByFullName( ... ) { // construct & return FooBar(...); } // Then I have a hand full of overloaded function template declarations // with a generic name to call the appropriate functions from above. // Each FooBar has different parameters, and FooBar is a class template. template class FooBar> FooBar& getFooBar(...); }; // Outside of any class I have a generic function template template class FooBar, class... FP> Type doSomething( some param A, some param B, some param C, FP... params ) { // Code here to work with Other using A, B & C FooBar fooBar = getFooBar( params... ); // do something to fooBar return value generated from fooBar; } ``` **Foo.cpp** ``` #include **Foo.h** template class FooBar> FooBar& getFooBar(...) { return {}; } template<> FooBar& Foo::getFooBar( ... ) { return getFooBarByFullName( ... ); } template<> FooBar& Foo::getFooBar( ... ) { return getFooBarByFullName( ... ); } // etc... ``` --- One of the implementations that I'm working on has for one of its template parameter is a `class unary_op`. I do not want to define any such class. I need to be able to pass either a function object, function pointer, lambda, or std::function to these functions as the `unary_op` class. The problem I'm running into is if my declaration(s) in my header looks like this: ``` template FooBar& getFooBarByFullName( std::size\_t count, double xmin, double xmax, UnaryOp fw ) { // Constructors last parameter is defined as a class UnaryOp; // but can be any of a function object, function pointer, lambda, std::function<...> etc. FooBar fooBar( count, xmin, xmax, fw ); } // Then I can declare the appropriate generic declaration overload here template class FooBar, class FuncOp> FooBar& getFooBar( std::size\_t count, double xmin, double xmax, FuncOp fw ); // Declaration only ``` However when I go to the cpp file to write the definitions explicit specialization using the provided appropriate overloaded declaration while trying to avoid ambiguity is where I get into trouble. ``` template<> FooBar& Foo::getFooBar( std::size\_t count, double xmin, double xmax, ? ) { return getFooBarByFullName( count, xmin, xmax, ? ); } template<> FooBar& Foo:getFooBar( std::size\_t count, double xmin, double xmax, ? ) { return getFooBarByFullName( count, xmin, xmax, ? ); } ``` As you can see I don't know how to define the last parameter of type `class UnaryOp`. I would also like to be able to support that the caller can pass any of the types I mentioned above: `function object`, `function pointer`, `lambda`, `std::function<>` as the last parameter for the `UnaryOp`. I don't know where to go from here... **Edit** - I forgot to mention that in my actual code; the two classes above have deleted default constructors; and all the class methods are static.<issue_comment>username_1: It's unclear what you're actually asking, but it appears that your problem is to create an instantiatable yet generic function in your .cpp file. I think there are two options to solve this problem: 1. Abandon your plan: make these methods templates living only the .hpp file and taking `UnaryOp` as (deducible) template parameter. ``` .hpp: template Type Qoo(Type const&x, UnaryOp&&func) { // some simple/short code calling func() } ``` 2. Implement a function overload for `UnaryOp` = `std::function` in your .cpp file and implement the general `UnaryOp` (lambda, functor, function pointer etc) as template in your .hpp file, calling the former using a `std::function` object created from whatever `UnaryOp` is. ``` .hpp: template Type Qoo(Type const&, std::function&&); template Type Qoo(Type const&x, UnaryOp&&func) { return Qoo(x, std::function{func}); } .cpp template Type Qoo(Type const&t, std::function&&func); { // some lengthy code calling func() } // explicit instantiations template int Qoo(int const&, std::function&&); template short Qoo(short const&, std::function&&); ... ``` The second version allows pre-compilation, but generates overheads in case `UnaryOp`≠`std::function<>`. The first solution avoids such overheads but exposes the full implementation to the .hpp file and does not offer the benefit of pre-compilation. In similar situations, I tend to use the second version if the code implemented is substantial, such that the overhead of the `std::function` object can be tolerated, and the first version only for small code, which generally should be `inline` anyway. Finally, note that in the .cpp file you don't need to define all the specialisations, but give the template and specify the explicit instantiations. Upvotes: 1 <issue_comment>username_2: Okay scrap that whole idea above: I went and entirely rewritten my classes into a single class. The class itself is now a class template. And it looks like this: ``` #ifndef GENERATOR_H #define GENERATOR_H #include #include #include #include enum SeedType { USE\_CHRONO\_CLOCK, USE\_RANDOM\_DEVICE, USE\_SEED\_VALUE, USE\_SEED\_SEQ }; template class Distribution> class Generator { public: using Clock = std::conditional\_t; private: Engine \_engine; Distribution \_distribution; Type \_value; public: template explicit Generator( Engine engine, Params... params ) : \_engine( engine ) { \_distribution = Distribution( params... ); } void seed( SeedType type = USE\_RANDOM\_DEVICE, std::size\_t seedValue = 0, std::initializer\_list list = {} ) { switch( type ) { case USE\_CHRONO\_CLOCK: { \_engine.seed( getTimeNow() ); break; } case USE\_RANDOM\_DEVICE: { std::random\_device device{}; \_engine.seed( device() ); break; } case USE\_SEED\_VALUE: { \_engine.seed( seedValue ); break; } case USE\_SEED\_SEQ: { std::seed\_seq seq( list ); \_engine.seed( seq ); break; } } } void generate() { \_value = \_distribution( \_engine ); } Type getGeneratedValue() const { return \_value; } Distribution getDistribution() const { return \_distribution; } std::size\_t getTimeNow() { std::size\_t now = static\_cast(Clock::now().time\_since\_epoch().count()); return now; } }; #endif // !GENERATOR\_H ``` And to use it is as simple as: ``` #include #include #include #include "generator.h" int main() { // Engine, Seeding Type, & Distribution Combo 1 std::mt19937 engine1; Generator g1( engine1, 1, 100 ); g1.seed( USE\_RANDOM\_DEVICE ); std::vector vals1; for( unsigned int i = 0; i < 200; i++ ) { g1.generate(); auto v = g1.getGeneratedValue(); vals1.push\_back( v ); } int i = 0; for( auto& v : vals1 ) { if( (i % 10) != 0 ) { std::cout << std::setw( 3 ) << v << " "; } else { std::cout << '\n' << std::setw( 3 ) << v << " "; } i++; } std::cout << "\n\n"; // Engine, Seeding Type, & Distribution Combo 2 std::ranlux48 engine2; std::initializer\_list list2{ 3, 7, 13, 17, 27, 31, 43 }; Generator g2( engine2, 50, 0.75 ); g2.seed( USE\_SEED\_SEQ, std::size\_t(7), list2 ); std::vector vals2; for( int i = 0; i < 200; i++ ) { g2.generate(); auto v = g2.getGeneratedValue(); vals2.push\_back( v ); } for( auto& v : vals2 ) { if( (i % 10) != 0 ) { std::cout << std::setw( 3 ) << v << " "; } else { std::cout << '\n' << std::setw( 3 ) << v << " "; } i++; } std::cout << "\n\n"; // Engine, Seeding Type, & Distribution Combo 3 std::minstd\_rand engine3; Generator g3( engine3, 0.22222f, 0.7959753f ); g3.seed( USE\_CHRONO\_CLOCK ); std::vector vals3; for( int i = 0; i < 200; i++ ) { g3.generate(); auto v = g3.getGeneratedValue(); vals3.push\_back( v ); } for( auto& v : vals3 ) { if( (i % 5 ) != 0 ) { std::cout << std::setw( 12 ) << v << " "; } else { std::cout << '\n' << std::setw( 12 ) << v << " "; } i++; } std::cout << "\n\n"; std::cout << "\nPress any key and enter to quit.\n"; std::cin.get(); return 0; } ``` Upvotes: 0
2018/03/21
2,053
6,320
<issue_start>username_0: Let's say that I have a php file. In it, I have some variables and some functions. For example: ``` $results = getResults($analytics, $profile); printResults($results); function getResults($analytics, $profileId) { return $analytics->data_ga->get( 'ga:' . $profileId, '3daysAgo', '2daysAgo', 'ga:sessions'); } ``` and ``` function printResults($results) { if (count($results->getRows()) > 0) { $profileName = $result->getProfileInfo()->getProfileName(); $rows = $results->getRows(); $sessions = $rows[0][0]; // Print the results. print $sessions; } else { print "No results found.\n"; } } ``` Now, how could I loop through these, changing both variable and function names dynamically? So (pseudocode, hope it is clear what it is trying to do) ``` for($i=2; $i<30; $i++){ $results = $results$i = getResults$i($analytics, $profile); printResults$i($results$i); function getResults$i($analytics, $profileId){ return $analytics->data_ga->get( 'ga:' . $profileId, $i'daysAgo', ($i+1)'daysAgo, 'ga:sessions'); } } ``` meaning that `$results` becomes `$results2`, `$results3`, etc and `getResults()` becomes `getResults2()`, `getResults3()`, etc and '`3daysAgo`' becomes `4daysAgo`, `5daysAgo`, etc. Can it be done?<issue_comment>username_1: It's unclear what you're actually asking, but it appears that your problem is to create an instantiatable yet generic function in your .cpp file. I think there are two options to solve this problem: 1. Abandon your plan: make these methods templates living only the .hpp file and taking `UnaryOp` as (deducible) template parameter. ``` .hpp: template Type Qoo(Type const&x, UnaryOp&&func) { // some simple/short code calling func() } ``` 2. Implement a function overload for `UnaryOp` = `std::function` in your .cpp file and implement the general `UnaryOp` (lambda, functor, function pointer etc) as template in your .hpp file, calling the former using a `std::function` object created from whatever `UnaryOp` is. ``` .hpp: template Type Qoo(Type const&, std::function&&); template Type Qoo(Type const&x, UnaryOp&&func) { return Qoo(x, std::function{func}); } .cpp template Type Qoo(Type const&t, std::function&&func); { // some lengthy code calling func() } // explicit instantiations template int Qoo(int const&, std::function&&); template short Qoo(short const&, std::function&&); ... ``` The second version allows pre-compilation, but generates overheads in case `UnaryOp`≠`std::function<>`. The first solution avoids such overheads but exposes the full implementation to the .hpp file and does not offer the benefit of pre-compilation. In similar situations, I tend to use the second version if the code implemented is substantial, such that the overhead of the `std::function` object can be tolerated, and the first version only for small code, which generally should be `inline` anyway. Finally, note that in the .cpp file you don't need to define all the specialisations, but give the template and specify the explicit instantiations. Upvotes: 1 <issue_comment>username_2: Okay scrap that whole idea above: I went and entirely rewritten my classes into a single class. The class itself is now a class template. And it looks like this: ``` #ifndef GENERATOR_H #define GENERATOR_H #include #include #include #include enum SeedType { USE\_CHRONO\_CLOCK, USE\_RANDOM\_DEVICE, USE\_SEED\_VALUE, USE\_SEED\_SEQ }; template class Distribution> class Generator { public: using Clock = std::conditional\_t; private: Engine \_engine; Distribution \_distribution; Type \_value; public: template explicit Generator( Engine engine, Params... params ) : \_engine( engine ) { \_distribution = Distribution( params... ); } void seed( SeedType type = USE\_RANDOM\_DEVICE, std::size\_t seedValue = 0, std::initializer\_list list = {} ) { switch( type ) { case USE\_CHRONO\_CLOCK: { \_engine.seed( getTimeNow() ); break; } case USE\_RANDOM\_DEVICE: { std::random\_device device{}; \_engine.seed( device() ); break; } case USE\_SEED\_VALUE: { \_engine.seed( seedValue ); break; } case USE\_SEED\_SEQ: { std::seed\_seq seq( list ); \_engine.seed( seq ); break; } } } void generate() { \_value = \_distribution( \_engine ); } Type getGeneratedValue() const { return \_value; } Distribution getDistribution() const { return \_distribution; } std::size\_t getTimeNow() { std::size\_t now = static\_cast(Clock::now().time\_since\_epoch().count()); return now; } }; #endif // !GENERATOR\_H ``` And to use it is as simple as: ``` #include #include #include #include "generator.h" int main() { // Engine, Seeding Type, & Distribution Combo 1 std::mt19937 engine1; Generator g1( engine1, 1, 100 ); g1.seed( USE\_RANDOM\_DEVICE ); std::vector vals1; for( unsigned int i = 0; i < 200; i++ ) { g1.generate(); auto v = g1.getGeneratedValue(); vals1.push\_back( v ); } int i = 0; for( auto& v : vals1 ) { if( (i % 10) != 0 ) { std::cout << std::setw( 3 ) << v << " "; } else { std::cout << '\n' << std::setw( 3 ) << v << " "; } i++; } std::cout << "\n\n"; // Engine, Seeding Type, & Distribution Combo 2 std::ranlux48 engine2; std::initializer\_list list2{ 3, 7, 13, 17, 27, 31, 43 }; Generator g2( engine2, 50, 0.75 ); g2.seed( USE\_SEED\_SEQ, std::size\_t(7), list2 ); std::vector vals2; for( int i = 0; i < 200; i++ ) { g2.generate(); auto v = g2.getGeneratedValue(); vals2.push\_back( v ); } for( auto& v : vals2 ) { if( (i % 10) != 0 ) { std::cout << std::setw( 3 ) << v << " "; } else { std::cout << '\n' << std::setw( 3 ) << v << " "; } i++; } std::cout << "\n\n"; // Engine, Seeding Type, & Distribution Combo 3 std::minstd\_rand engine3; Generator g3( engine3, 0.22222f, 0.7959753f ); g3.seed( USE\_CHRONO\_CLOCK ); std::vector vals3; for( int i = 0; i < 200; i++ ) { g3.generate(); auto v = g3.getGeneratedValue(); vals3.push\_back( v ); } for( auto& v : vals3 ) { if( (i % 5 ) != 0 ) { std::cout << std::setw( 12 ) << v << " "; } else { std::cout << '\n' << std::setw( 12 ) << v << " "; } i++; } std::cout << "\n\n"; std::cout << "\nPress any key and enter to quit.\n"; std::cin.get(); return 0; } ``` Upvotes: 0
2018/03/21
845
1,967
<issue_start>username_0: I want to rename files names by substituting all the characters starting from "\_ " followed by eight capital letter and keep only the extension. ``` 4585_10_148_H2A119Ub_GTCTGTCA_S51_mcdf_mdup_ngsFlt.fm 4585_10_148_H3K27me3_TCTTCACA_S51_mcdf_mdup_ngsFlt.fm 4585_27_128_Bap1_Bethyl_ACAGATTC_S61_mcdf_mdup_ngsFlt.fw 4585_32_148_1_INPUT_previous_AGAGTCAA_S72_mcdf_mdup_ngsFlt.bw ``` expected output ``` 4585_10_148_H2A119Ub.fm 4585_10_148_H3K27me3.fm 4585_27_128_Bap1_Bethyl.fm 4585_32_148_1_INPUT_previous.fm ```<issue_comment>username_1: You may try this. ``` for i in *.fm; do mv $i $(echo $i | sed 's/_GTCTGTCA_S51_mcdf_mdup_ngsFlt//g'); done; for i in *.fm; do mv $i $(echo $i | sed 's/_TCTTCACA_S51_mcdf_mdup_ngsFlt//g'); done; ``` Upvotes: 0 <issue_comment>username_2: Try this: ``` for f in *; do target=$(echo "${f}" | sed -E 's/_[[:upper:]]{8}.*\././') mv "${f}" "${target}" done ``` The key thing is the `-E` argument to `sed`, since it enables expanded regular expressions. Upvotes: 3 [selected_answer]<issue_comment>username_3: You can also use `rename` (a.k.a. `prename` or `Perl rename`) like this: ``` rename --dry-run 's|_[[:upper:]]{8}.*\.|.|' * ``` **Sample Output** ``` '4585_10_148_H2A119Ub_GTCTGTCA_S51_mcdf_mdup_ngsFlt.fm' would be renamed to '4585_10_148_H2A119Ub.fm' '4585_32_148_1_INPUT_previous_AGAGTCAA_S72_mcdf_mdup_ngsFlt.bw' would be renamed to '4585_32_148_1_INPUT_previous.bw' ``` Remove the `--dry-run` and run again for real, if the output looks good. This has several added benefits: * that it will warn and avoid any conflicts if two files rename to the same thing, * that it can rename across directories, creating any necessary intermediate directories on the way, * that you can do a dry run first to test it, * that you can use arbitrarily complex Perl code to specify the new name. --- On a Mac, install it with **homebrew** using: ``` brew install rename ``` Upvotes: 1
2018/03/21
261
1,027
<issue_start>username_0: We have two identical servers A and B in our office. These two servers are synced together in all aspect. That's if some changes take place in one server then it will take effect in another server. This has been done to minimize the downtime. Now server A has a public IP address (X.X.X.X) form one ISP. Server B has a public IP address(XX.XX.XX.XX) from a different ISP. Now for some reason IP address X.X.X.X goes down. **Now How can we automatically forward traffic to another IP address so website will not go down?**<issue_comment>username_1: You're basically asking about high availability, you'd have a third server (called load balancer) in front which would sent traffic to either server based on their status. Have a look at a simple setup [in here.](https://www.digitalocean.com/community/tutorials/what-is-high-availability) Upvotes: 1 <issue_comment>username_2: can you use DNS-level fail over using <https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html> Upvotes: 0
2018/03/21
724
2,118
<issue_start>username_0: I have a 1 column dataframe ``` df = pd.read_csv(txt_file, header=None) ``` I am trying to search for a string in the column and then return the row after ``` key_word_df = df[df[0].str.contains("KeyWord")] ``` I dont know how you can then every each time the keyword is found, isolate the row below it and assign to a new df.<issue_comment>username_1: You can use the shift function. Here's an example ``` import pandas as pd df = pd.DataFrame({'word': ['hello', 'ice', 'kitten', 'hello', 'foo', 'bar', 'hello'], 'val': [1,2,3,4,5,6,7]}) val word 0 1 hello 1 2 ice 2 3 kitten 3 4 hello 4 5 foo 5 6 bar 6 7 hello keyword = 'hello' df[(df['word']==keyword).shift(1).fillna(False)] val word 1 2 ice 4 5 foo ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Here is one way. Get the index of the rows that match your condition. Then use `.loc` to get the matching index + 1. Consider the following example: ``` df = pd.DataFrame({0: ['KeyWord', 'foo', 'bar', 'KeyWord', 'blah']}) print(df) # 0 #0 KeyWord #1 foo #2 bar #3 KeyWord #4 blah ``` Apply the mask, and get the rows of the index + 1: ``` key_word_df = df.loc[df[df[0].str.contains("KeyWord")].index + 1, :] print(key_word_df) # 0 #1 foo #4 blah ``` Upvotes: 0 <issue_comment>username_3: You could use the `.shift` method on an indexer. I've split this into multiple lines to demonstrate what's happening, but you could do the operation in a one-liner for brevity in practice. ``` import pandas as pd # 1. Dummy DataFrame with strings In [1]: df = pd.DataFrame(["one", "two", "one", "two", "three"], columns=["text",]) # 2. Create the indexer, use `shift` to move the values down one and `fillna` to remove NaN values In [2]: idx = df["text"].str.contains("one").shift(1).fillna(False) In [3]: idx Out [3]: 0 False 1 True 2 False 3 True 4 False Name: text, dtype: bool # 3. Use the indexer to show the next row from the matched values: In: [4] df[idx] Out: [4] text 1 two 3 two ``` Upvotes: 2
2018/03/21
846
2,829
<issue_start>username_0: im working on a school project using laravel, i have a directory of images,those images will change with time, i'm trying to just display the name of those images as links without extensions but i don't know how to hide extensions, and when i click on link it dosen't work. ``` php $dir_nom = '../images'; // dossier listé (pour lister le répertoir courant : $dir_nom = '.' -- ('point') $dir = opendir($dir_nom) or die('Erreur de listage : le répertoire nexiste pas'); // on ouvre le contenu du dossier courant $fichier= array(); // on déclare le tableau contenant le nom des fichiers $dossier= array(); // on déclare le tableau contenant le nom des dossiers while($element = readdir($dir)) { if($element != '.' && $element != '..') { if (!is_dir($dir_nom.'/'.$element)) {$fichier[] = $element;} else {$dossier[] = $element;} } } if(!empty($fichier)){ echo "images : \n\n "; echo "\t\t\n"; foreach($fichier as $lien) { echo "\t\t\t[$lien](\"../images$lien) \n"; } echo "\t\t "; } closedir($dir); ?> ?> ```<issue_comment>username_1: You have to use `base_path` function to be sure that you have the correct path for open this directory. In many case, it due to wrong path so just verify the path. Or you can put the image directory in the public diectory and then you can easily have access to it. and for the path it will not be `..\images`or `../images` but just `ìmages` even if you are in linux distro. Upvotes: 0 <issue_comment>username_2: it worked with this : ``` php $dirname = 'images'; $dir = opendir($dirname); while($file = readdir($dir)) { if($file != '.' && $file != '..' && !is_dir($dirname.$file)) { echo '<a href="'.$dirname.'/'.$file.'"'.$file.''; } } closedir($dir); ?> ``` Upvotes: 0 <issue_comment>username_3: Create a controller and a route to get your images. The route parameter will be the image name so you can get it from the controller. ``` Route::get('img/{img}', 'ImageController@getImage')->name('image'); ``` And your controller `getImage()` method will look like this: ``` use Intervention\Image\Facades\Image; //... public function getImage($img) { return Image::make(asset('img/'.$img.'.jpg'))->response(); } ``` The [`asset()`](https://laravel.com/docs/5.6/helpers#method-asset) helpers creates an absolute path to the given resource located in the `public` folder. So now, thanks to the route, the extension is not displayed anymore. If you want your image to be only accessed via this route, use the [storage](https://laravel.com/docs/5.6/filesystem) instead. Finally, you can get the URL to your route using the [`route()`](https://laravel.com/docs/5.6/helpers#method-route) helper in your view. ``` [Link]({{ route('image', 'imageNameWithoutExtension') }}) ``` Upvotes: 1
2018/03/21
505
1,861
<issue_start>username_0: I'm a beginner to Kotlin and am loving it so far. I'm curious if Kotlin has a quick and simple solution to checking user input/strings for emptiness. I'd like the funtionality of the following: ``` "If readLine() is null or empty assign default value, else parse readLine()" ``` And so far, what I've come up with is this: ``` var inp = readLine() val double = if(inp.isNullOrEmpty()) 0.0 else inp.toDouble() ``` Is this the best it can be? I'd prefer to not store the original user input string if possible. Thanks for the help!<issue_comment>username_1: Using the elvis operator and null-safe calls ============================================ ``` fun main(args: Array) { val parsed = readLine()?.toDouble() ?: 0.0 } ``` * Using `?.` calls the method only if the value is not null, otherwise it just passes null along. * Using `?:` means that the value on the left is returned if it is not null, otherwise the value on the right is returned Upvotes: 2 <issue_comment>username_2: You can use [`toDoubleOrNull`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-double-or-null.html) here: ``` val double: Double = readLine()?.toDoubleOrNull() ?: 0 ``` If `readLine()` returns `null`, then the `readLine()?.toDoubleOrNull()` expression will also return `null`, and you'll fall back on the default value. If `readLine()` returns a non-null value, `toDoubleOrNull` will attempt to parse it, and if it fails (for example, for an empty string), it will return `null`, making you fall back to the default once again. Upvotes: 4 [selected_answer]<issue_comment>username_3: How about this solution: ``` System.console().readLine()?.ifBlank { null } ?: "default string value" ``` and for password (this doesn't work inside IntelliJ): ``` String(System.console().readPassword()).ifBlank { "password" } ``` Upvotes: 2
2018/03/21
740
2,813
<issue_start>username_0: I'm not sure if this was asked before, but I couldn't find it. Suppose I have a procedure with a local variable inside it. Normally, that variable is destroyed after the function finishes running. But in some cases, I'd like for it to persist, like in this example: ``` Function myFunction() Dim runCount As Integer runCount = runCount +1 debug.print "This function is now running for the " & runCount & " time." End Function ``` In this example, the code wouldn't work, because the runCount would be reset each time. Of course, the simplest solution would be to declare a global variable instead, but in some cases, I want to avoid that for the sake of simplicity, encapsulation or other reasons. So, is there any way to have the local variable persist after the procedure has finished running?<issue_comment>username_1: Use the `Static` keyword to declare your local variable, instead of `Dim`, and the variable's content will outlive a call to the procedure it's declared in. e.g. this will work as intended: ``` Function myFunction() Static runCount As Integer runCount = runCount + 1 debug.print "This function is now running for the " & runCount & " time." End Function ``` Using `Static` locals is arguably preferable to declaring module-scope variables, when the variable only makes sense in a local scope or is only used in one procedure. --- Note that module-scope does not equate global scope. This variable is accessible anywhere in the module it's declared in, but not outside of it: ``` Option Explicit Private foo As Long ``` Use the `Private` (or `Dim`, but I prefer to keep `Dim` for declaring locals) or `Public` keyword to declare module-scope variables. The `Global` keyword is deprecated, and does exactly the same thing as `Public`. --- As [<NAME>. correctly points out](https://stackoverflow.com/questions/49407926/having-a-local-variable-that-persists-after-the-procedure-is-ended/49408376?noredirect=1#comment85823388_49408376), VBA also supports `Static` members. See this signature: ``` Function myFunction() ``` Is implicitly a `Public` member. This would be explicit: ``` Public Function myFunction() ``` VBA supports adding the `Static` modifier at the procedure level, so you can do this: ``` Public Static Function myFunction() ``` And now you have a `Public` function where every local variable is implicitly `Static`. This is too much implicit, easily bug-prone stuff going on for my own personal taste, so I would avoid it. But it's probably good to know it's there *if you need it*. Upvotes: 3 <issue_comment>username_2: Do not use `Static` (*imo*). Use **`Private`** on module level instead of is more preferable. But much more preferable will be to pass counter to function `ByRef`. Upvotes: -1
2018/03/21
468
1,628
<issue_start>username_0: I want to create like bellow image. [![enter image description here](https://i.stack.imgur.com/3PB70.png)](https://i.stack.imgur.com/3PB70.png) For creating like this I write the bellow code. ``` ``` It working. But the problem is, **It don't show app toolbar**. **Note :** The tools of toolbar working. Now how I can show toolbar or toolbar tools?<issue_comment>username_1: You need to use `CollapsingToolbarLayout` with `AppBarLayout` over there. For your reference I have posted one xml file. refer this.. ``` ``` hope you have listed below necessary gradles! ``` compile 'com.android.support:appcompat-v7:25.2.0' compile 'com.android.support:recyclerview-v7:25.2.0' compile 'com.android.support:cardview-v7:25.2.0' compile 'com.android.support:design:25.2.0' ``` Upvotes: 0 <issue_comment>username_2: Add new scroll activity then in activity layout file put imageview in collapsing toolbar layout ``` ``` Upvotes: 0 <issue_comment>username_3: Wrap the layout in `toolbar` as follows ``` xml version="1.0" encoding="utf-8"? ``` Upvotes: 0 <issue_comment>username_4: This is happening because your LinearLayout is displaying over your toolbar(Views inside a RelativeLayout display over one other, and you haven't mentioned any view to display above or below the other one). Assign an id to your toolbar, and instruct your LinearLayout to be below it, something like this: ``` ``` You might also need to increase your parent RelativeLayout's height from 220dp to something like 250dp to accommodate both the children without clipping the bottom one. Upvotes: 2 [selected_answer]
2018/03/21
3,441
10,614
<issue_start>username_0: I have a text file containing the following strings (which are **versions** of a software): ``` 1_10_2_0_154 3_10_5_2_10 2_10_4_1 3_10_5_1_37 ``` I'm trying to find the most recent version, in this case **3\_10\_5\_2\_10** is the version that I'm trying to display using java. For the moment, here is my code: ``` BufferedReader br; String version; ArrayList> array = new ArrayList>(); List liste = new ArrayList(); try{ br = new BufferedReader(new FileReader(new File(FILEPATH))); while((version= br.readLine()) != null) { liste = Arrays.asList(version.split("\_")).stream(). map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList()); array.add(liste); } for(int i = 0; i < array.size(); i++) { for (List l: array) { Object z = l.get(i); List listes = new ArrayList(); listes.add(z); System.out.println(listes); } } br.close(); System.out.println(array); }catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } ``` I made a loop to save strings to ArrayList> like: ``` [[1,10,2,0,154] , [3,10,5,2,10], [2,10,4,1], [3,10,5,1,37]] ``` I want to get the elements of each list and compare them to find the most biggest one (most recent one) but I don't know to do that..<issue_comment>username_1: A simple object oriented approach would be to create object, representing version number, let's call it VersionNumber, which would have a constructor of a factory method that does the parsing of the string. This VersionNumber class should implement interface Comparable and implement method compareTo. Here is a hint for using Comparable [Why should a Java class implement comparable?](https://stackoverflow.com/questions/3718383/why-should-a-java-class-implement-comparable?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) Then you can easily write an algorithm to find the max version or google some library that would do it for you. Upvotes: 0 <issue_comment>username_2: I sugguest you a object approach, define a class named **Version** with **compareTo** method, then using method **sort** on **Collections** class you can simply sort your versions. **Advantages** * Clean and Clear code * Data validation **Main:** ``` public class Main { public static void main(String[] args){ List versions = Arrays.asList( Version.create("1\_10\_2\_0\_154"), Version.create("3\_10\_5\_2\_10"), Version.create("2\_10\_4\_1\_49"), Version.create("3\_10\_5\_1\_37")); versions.sort(Version::compareTo); System.out.println(versions.get(0).toString()); } } ``` **Version:** ``` public class Version implements Comparable { private final int major; private final int minor; private final int bug; private final int release; private final int build; public Version(int major, int minor, int bug, int release, int build) { this.major = major; this.minor = minor; this.bug = bug; this.release = release; this.build = build; } public int getMajor() { return major; } public int getMinor() { return minor; } public int getBug() { return bug; } public int getRelease() { return release; } public int getBuild() { return build; } @Override public String toString() { return "Version{" + "major=" + major + ", minor=" + minor + ", bug=" + bug + ", release=" + release + ", build=" + build + '}'; } public static Version create(String value){ String[] splitRes = value.split("\_"); List intValues = new ArrayList<>(); for(String v : splitRes){ intValues.add(Integer.parseInt(v)); } return create(intValues); } public static Version create(List values){ if(Objects.requireNonNull(values).size() < 5) throw new IllegalArgumentException(); return new Version( values.get(0), values.get(1), values.get(2), values.get(3), values.get(4) ); } @Override public int compareTo(Version that) { if (this.major > that.major) { return -1; } else if (this.major < that.major) { return 1; } if (this.minor > that.minor) { return -1; } else if (this.minor < that.minor) { return 1; } if (this.bug > that.bug) { return -1; } else if (this.bug < that.bug) { return 1; } if (this.release > that.release) { return -1; } else if (this.release < that.release) { return 1; } if (this.build > that.build) { return -1; } else if (this.build < that.build) { return 1; } return 0; } } ``` --- **UPDATE 1** As suggested by @Henrik i updated the list sorting with a Java 8 approach. **UPDATE 2** I reversed the **compareTo** method so now you can simply do plain sort calling **sort** method on list and passing method reference **Version::compareTo** **UPDATE 3** A more dynamic solution for **Version** class: ``` public class Version implements Comparable { private final List values; public Version(List values) { this.values = values; } public List getValues() { return values; } @Override public String toString() { return String.join("\_", values .stream() .map(Object::toString) .collect(Collectors.toList())); } @Override public int compareTo(Version that) { List thatValues = that.getValues(); for(int index = 0; index < values.size(); index++){ Integer value = values.get(index); Integer thatValue = thatValues.get(index); if (value > thatValue) { return -1; } else if (value < thatValue) { return 1; } } return 0; } public static Version create(String value){ String[] splitRes = value.split("\_"); List intValues = new ArrayList<>(); for(String v : splitRes){ intValues.add(Integer.parseInt(v)); } return new Version(intValues); } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: slap your arrays together into a number then just do number comparison. ``` class Scratch { public static void main(String[] args) { List> arr = new ArrayList<>(); arr.add(fromArray(new Integer[]{1,10,2,0,154})); arr.add(fromArray(new Integer[]{3,10,5,2,10})); arr.add(fromArray(new Integer[]{2,10,4,1,49})); arr.add(fromArray(new Integer[]{3,10,5,1,37})); Integer[] maxLengths = {0,0,0,0,0}; for (List v : arr) { for(int idx = 0; idx < v.size(); idx++) { Integer n = v.get(idx); int curMaxLen = maxLengths[idx]; maxLengths[idx] = Math.max(n.toString().length(), curMaxLen); } } Long largest = arr.stream().map(v -> { StringBuilder result = new StringBuilder(); for(int idx = 0; idx < v.size(); idx++) { Integer n = v.get(idx); int maxLen = maxLengths[idx]; result.append(String.format("%-" + maxLen + 's', n).replace(' ', '0')); } return result.toString(); }).map(Long::valueOf).max(Comparator.naturalOrder()).get(); System.out.println(largest); } public static List fromArray(Integer[] array) { List list = new ArrayList<>(); Collections.addAll(list, array); return list; } } ``` Upvotes: -1 <issue_comment>username_4: You can write a `Comparator` to compare two Lists ``` Comparator> comparator = (list1, list2) -> { Iterator iteratorA = list1.iterator(); Iterator iteratorB = list2.iterator(); //It iterates through each list looking for an int that is not equal to determine which one precedes the other while (iteratorA.hasNext() && iteratorB.hasNext()) { int elementA = iteratorA.next(); int elementB = iteratorB.next(); if (elementA > elementB) { return 1; } else if (elementA < elementB) { return -1; } } //All elements seen so far are equal. Use the list size to decide return iteratorA.hasNext() ? 1 : iteratorB.hasNext() ? -1 : 0; }; ``` You can sort it as ``` Collections.sort(list, comparator); ``` **EDIT:** You can refer to [username_2's answer](https://stackoverflow.com/a/49408484/4405757) to convert the version string as a POJO and move the comparator logic inside that. But that is highly tied/coupled to the input string format. My solution works for any `List>`. Upvotes: 1 <issue_comment>username_5: It is not optimized but should work. You can use both of comparators. ``` static List versions = Arrays.asList( "1\_10\_2\_0\_154", "3\_10\_5\_2\_10", "2\_10\_4\_1\_49", "3\_10\_5\_1\_37"); static Comparator> c = (o1,o2) -> { int length = o1.size()>o2.size()?o2.size():o1.size(); for (int i = 0; i < length; i++) { int i1 = o1.get(i); int i2 = o2.get(i); if (i1 != i2) return i1 - i2; } return 0; }; static Comparator> c2 = (o1,o2) -> { Iterator i1=o1.iterator(); Iterator i2=o2.iterator(); while (i1.hasNext() && i2.hasNext()){ int i = i1.next()-i2.next(); if (i!=0) return i; } return 0; }; static Optional> getTheMostRecentVersion(List versions) { return versions.stream(). map(s -> Arrays.stream(s.split("\_")). map(Integer::parseInt). collect(Collectors.toList())).max(c2); } ``` Upvotes: 0 <issue_comment>username_6: I think that this text file could be very big and it is better to compare each line on the fly (instead of store all line into collection to sort it after): ``` public static String getMostRecentVersion(BufferedReader in) throws IOException { final Comparator version = (s1, s2) -> { int res = 0; for (int i = 0; i < 5 && res == 0; i++) res = Integer.compare(Integer.parseInt(s1[i]), Integer.parseInt(s2[i])); return res; }; String str; String resStr = null; String[] resPparts = null; while ((str = in.readLine()) != null) { String[] parts = str.split("\_"); if (resStr == null || version.compare(parts, resPparts) > 0) { resStr = str; resPparts = parts; } } return resStr; } ``` Upvotes: 0 <issue_comment>username_7: A general `ListComparator` should help. ``` static class ListComparator> implements Comparator> { @Override public int compare(List o1, List o2) { for (int i = 0; i < Math.max(o1.size(), o2.size()); i++) { int diff = // Off the end of both - same. i >= o1.size() && i >= o2.size() ? 0 // Off the end of 1 - the other is greater. : i >= o1.size() ? -1 : i >= o2.size() ? 1 // Normal diff. : o1.get(i).compareTo(o2.get(i)); if (diff != 0) { return diff; } } return 0; } } private static final Comparator> BY\_VERSION = new ListComparator().reversed(); public void test(String[] args) { String[] tests = { "1\_10\_2\_0\_154", "3\_10\_5\_2\_10", "2\_10\_4\_1\_49", "3\_10\_5\_1\_37", "3\_10\_5\_1\_37\_0" }; System.out.println("Before: " + Arrays.toString(tests)); System.out.println("After: " + Arrays.stream(tests) // Split into parts. .map(s -> s.split("\_")) // Map String[] to List .map(a -> Arrays.stream(a).map(s -> Integer.valueOf(s)).collect(Collectors.toList())) // Sort it. .sorted(BY\_VERSION) // Back to a new list. .collect(Collectors.toList())); } ``` Upvotes: 0
2018/03/21
317
1,222
<issue_start>username_0: I am trying to use the MessageAttributes parameter in AWS SNS POST request. This is to customize the Sender ID (by AWS.SNS.SMS.SenderID). I am trying for Germany phone number and hence is allowed to customize the Sender ID. Can any one help me with the correct syntax? Thanks, Subhajit<issue_comment>username_1: I was able to solve it using the following: ``` MessageAttributes.entry.N.Name (key) MessageAttributes.entry.N.Value (value) ``` Upvotes: -1 <issue_comment>username_2: You need to send 3 key/value pairs for each attribute: ``` MessageAttributes.entry.${index}.Name=${attributeName}& MessageAttributes.entry.${index}.Value.DataType=String& MessageAttributes.entry.${index}.Value.StringValue=${attributeValue} ``` `${index}` is the numerical index of each attribute, starting with 1 On the second line you need to specify [the type of the value](https://docs.aws.amazon.com/sns/latest/dg/SNSMessageAttributes.html#SNSMessageAttributes.DataTypes). Most common cases are `String`. The third line is the actual value. You can see more information in the link above, I have only used strings and `StringValue`. All the values need to be url-encoded for obvious reasons. Upvotes: 3
2018/03/21
1,314
5,075
<issue_start>username_0: I am using the query function from the boto3 library in Python and receiving the following error: ``` name 'Key' is not defined: NameError Traceback (most recent call last): File "/var/task/lambda_function.py", line 51, in lambda_handler if not getAssetExistance(slack_userID): File "/var/task/lambda_function.py", line 23, in getAssetExistance response = dynamoTable.query(KeyConditionExpression=Key('userID').eq(asset)) NameError: name 'Key' is not defined ``` I have been reading through a bunch of tutorials on accessing DynamoDB through Lambda, and this they all use this KeyConditionExpression line when trying to if a key exists. Here is the relevant code (line 23 is the query line): ``` def getAssetExistance(asset): dynamoTable = dynamo.Table('Assets') response = dynamoTable.query(KeyConditionExpression=Key('userID').eq(asset)) return bool(response) ``` I basically want to check the primary partition key in my DynamoDB table (which is a slack user ID) and see if exist. Here is the rest of the code if it is relevant: ``` ################################ # Slack Lambda handler. ################################ import boto3 import logging import os import urllib # Grab data from the environment. BOT_TOKEN = os.environ["BOT_TOKEN"] ASSET_TABLE = os.environ["ASSET_TABLE"] REGION_NAME = os.getenv('REGION_NAME', 'us-east-1') dynamo = boto3.resource('dynamodb', region_name=REGION_NAME, endpoint_url="https://dynamodb.us-east-1.amazonaws.com") # Define the URL of the targeted Slack API resource. SLACK_URL = "https://slack.com/api/chat.postMessage" def getAssetExistance(asset): dynamoTable = dynamo.Table('Assets') response = dynamoTable.query(KeyConditionExpression=Key('userID').eq(asset)) return bool(response) def lambda_handler(data, context): # Slack challenge answer. if "challenge" in data: return data["challenge"] # Grab the Slack channel data. slack_event = data['event'] slack_userID = slack_event["user"] slack_text = slack_event["text"] channel_id = slack_event["channel"] slack_reply = "" # Ignore bot messages. if "bot_id" in slack_event: slack_reply = "" else: # Start data sift. if slack_text.startswith("!networth"): slack_reply = "Your networth is: " elif slack_text.startswith("!price"): command,asset = text.split() slack_reply = "The price of a(n) %s is: " % (asset) elif slack_text.startswith("!addme"): if not getAssetExistance(slack_userID): slack_reply = "Adding user: %s" % (slack_userID) dynamo.update_item(TableName=ASSET_TABLE, Key={'userID':{'S':'slack_userID'}}, AttributeUpdates= { 'resources':{ 'Action': 'ADD', 'Value': {'N': '1000'} } } ) else: slack_reply = "User %s already exists" % (slack_userID) # We need to send back three pieces of information: data = urllib.parse.urlencode( ( ("token", BOT_TOKEN), ("channel", channel_id), ("text", slack_reply) ) ) data = data.encode("ascii") # Construct the HTTP request that will be sent to the Slack API. request = urllib.request.Request( SLACK_URL, data=data, method="POST" ) # Add a header mentioning that the text is URL-encoded. request.add_header( "Content-Type", "application/x-www-form-urlencoded" ) # Fire off the request! urllib.request.urlopen(request).read() # Everything went fine. return "200 OK" ``` My DynamoDB table is named 'Assets' and has a primary partition key named 'userID' (string). I am definitely still new to all this, so don't be afraid of calling me a dummy. Any and all help is appreciated. The goal of this code is to check if a user exists as a key in DynamoDB and if not, add them to the table.<issue_comment>username_1: You need to import the `Key` function, like so: ``` from boto3.dynamodb.conditions import Key ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: Without importing it second time, u can address it like: **boto3.dynamodb.conditions.Key** ``` def getAssetExistance(asset): dynamoTable = dynamo.Table('Assets') response = dynamoTable.query(KeyConditionExpression= boto3.dynamodb.conditions.Key('userID').eq(asset)) return bool(response) ``` Upvotes: 2 <issue_comment>username_3: Wrote the below code for getting data from dynamo db and got the error 'NameError: name 'Key' is not defined'. I had to fix it by importing 'from boto3.dynamodb.conditions import Key' ``` response = dynamo_table.query(KeyConditionExpression=Key(val).eq(str(key_dictionary[val]))) ``` Upvotes: 0
2018/03/21
344
1,185
<issue_start>username_0: According to ORACLE's doc [Quick Start for Platform Developers](https://docs.oracle.com/javase/8/embedded/develop-apps-platforms/plat-dev-quick-start.htm) I used Jrecreate and got JRE . I copied JRE to my Arm Linux, `cd ./bin` and inputted `java -version`. But terminal displayed:`-sh:java:not found` Do I miss any Share Library?<issue_comment>username_1: You need to import the `Key` function, like so: ``` from boto3.dynamodb.conditions import Key ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: Without importing it second time, u can address it like: **boto3.dynamodb.conditions.Key** ``` def getAssetExistance(asset): dynamoTable = dynamo.Table('Assets') response = dynamoTable.query(KeyConditionExpression= boto3.dynamodb.conditions.Key('userID').eq(asset)) return bool(response) ``` Upvotes: 2 <issue_comment>username_3: Wrote the below code for getting data from dynamo db and got the error 'NameError: name 'Key' is not defined'. I had to fix it by importing 'from boto3.dynamodb.conditions import Key' ``` response = dynamo_table.query(KeyConditionExpression=Key(val).eq(str(key_dictionary[val]))) ``` Upvotes: 0
2018/03/21
478
1,649
<issue_start>username_0: I am doing something similar to [Weighted choice short and simple](https://stackoverflow.com/questions/10803135/weighted-choice-short-and-simple/15907274) however, i am additionally in need of adjusting weights depending on scenarios. I tried doing some simple arithmetics, i.e `weight *= 2` but the cumulative sum has to equal 1 (obviously) and i don't see how I can adjust one weight, and have the other weights adjust too.. There must be some simplistic solution that i am overseeing. Scenario ``` mylist = ['a', 'b', 'c', 'd'] myweights = [0.25, 0.25, 0.25, 0.25] ``` After selecting an item from `mylist` and running it through a function, i would like to adjust the weight associated with that item, either up or down, before selecting another item based on adjusted weights and so on.<issue_comment>username_1: You need to import the `Key` function, like so: ``` from boto3.dynamodb.conditions import Key ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: Without importing it second time, u can address it like: **boto3.dynamodb.conditions.Key** ``` def getAssetExistance(asset): dynamoTable = dynamo.Table('Assets') response = dynamoTable.query(KeyConditionExpression= boto3.dynamodb.conditions.Key('userID').eq(asset)) return bool(response) ``` Upvotes: 2 <issue_comment>username_3: Wrote the below code for getting data from dynamo db and got the error 'NameError: name 'Key' is not defined'. I had to fix it by importing 'from boto3.dynamodb.conditions import Key' ``` response = dynamo_table.query(KeyConditionExpression=Key(val).eq(str(key_dictionary[val]))) ``` Upvotes: 0
2018/03/21
708
2,702
<issue_start>username_0: I have a program that creates excel objects, writes to an excel sheet, prints, saves as, and finally quits. Of course however, there is an excel zombie I can see in the task manager that only goes away once the program is completely closed, (but is not there until the writing to excel begins.) It's driving me insane and I've read dozens of examples of how to use garbage collection to solve this issue however none seem to work. I'd prefer not to use kill process either, as that is clearly not the correct way to go about it. I also swear I had it working at one point, maybe when the program didn't, "save as" a new excel sheet. I believe the error could be, I am closing only one excel sheet while the new save as version is staying open. (Using win 10 and Excel 2016) ``` Dim objExcel As New Microsoft.Office.Interop.Excel.Application() Dim objWorkbook As Excel.Workbook 'Represents a workbook object Dim objWorksheet As Excel.Worksheet 'Represents a worksheet object Dim OrderTemplate As String = "insert file path here" objWorkbook = objExcel.Workbooks.Open(OrderTemplate) objExcel.DisplayAlerts = False objExcel.ActiveWorkbook.Close(SaveChanges:=True) objExcel.DisplayAlerts = True objExcel.Quit() objExcel = Nothing GC.GetTotalMemory(False) GC.Collect() GC.WaitForPendingFinalizers() GC.Collect() GC.WaitForPendingFinalizers() GC.GetTotalMemory(False) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objWorksheet) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objWorkbook) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objExcel) Private Sub releaseObject(ByVal obj As Object) Try System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing Finally GC.Collect() End Try End Sub ```<issue_comment>username_1: You need to import the `Key` function, like so: ``` from boto3.dynamodb.conditions import Key ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: Without importing it second time, u can address it like: **boto3.dynamodb.conditions.Key** ``` def getAssetExistance(asset): dynamoTable = dynamo.Table('Assets') response = dynamoTable.query(KeyConditionExpression= boto3.dynamodb.conditions.Key('userID').eq(asset)) return bool(response) ``` Upvotes: 2 <issue_comment>username_3: Wrote the below code for getting data from dynamo db and got the error 'NameError: name 'Key' is not defined'. I had to fix it by importing 'from boto3.dynamodb.conditions import Key' ``` response = dynamo_table.query(KeyConditionExpression=Key(val).eq(str(key_dictionary[val]))) ``` Upvotes: 0
2018/03/21
306
1,000
<issue_start>username_0: I can't convert a video file. Example: ``` exec(ffmpeg -i 01.시대조감.wmv 0001.mp4 -hide_banner, $output, $exit_code); ``` Just returns exit code -1<issue_comment>username_1: You need to import the `Key` function, like so: ``` from boto3.dynamodb.conditions import Key ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: Without importing it second time, u can address it like: **boto3.dynamodb.conditions.Key** ``` def getAssetExistance(asset): dynamoTable = dynamo.Table('Assets') response = dynamoTable.query(KeyConditionExpression= boto3.dynamodb.conditions.Key('userID').eq(asset)) return bool(response) ``` Upvotes: 2 <issue_comment>username_3: Wrote the below code for getting data from dynamo db and got the error 'NameError: name 'Key' is not defined'. I had to fix it by importing 'from boto3.dynamodb.conditions import Key' ``` response = dynamo_table.query(KeyConditionExpression=Key(val).eq(str(key_dictionary[val]))) ``` Upvotes: 0
2018/03/21
424
1,298
<issue_start>username_0: Having a timestamp, for example `1519357500`, is it possible to send it in this form to html and convert it into date format inside interpolation? I've tried to do it like this but it doesn't work: ``` {{moment($ctrl.myTimestamp).format('MMMM Do YYYY, h:mm:ss a')}} ```<issue_comment>username_1: Yes, very easily. ``` {{$ctrl.myTimestamp | date:'MMMM d y, h:mm:ss a'}} ``` (this assumes $ctrl.myTimestamp contains the epoch milliseconds) If you have the seconds till epoch do this: ``` {{$ctrl.myTimestamp * 1000 | date:'MMMM d y, h:mm:ss a'}} ``` More information [here.](https://docs.angularjs.org/api/ng/filter/date) Upvotes: 3 [selected_answer]<issue_comment>username_2: This is how I would have done it. ps. I am just doing it using no dependency (`moment`). coz I've never used it. So this is how you can achieve this. ```js var app = angular.module('test-app', []); app.controller('testCtrl', function($scope){ $scope.timestamp = "1519357500"; var date = new Date($scope.timestamp * 1000); var datevalues = ('0' + date.getDate()).slice(-2) + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + date.getFullYear() + ' ' + date.getHours() + ':' + date.getMinutes(); $scope.timestamp = datevalues; }) ``` ```html {{timestamp}} ``` Upvotes: 0
2018/03/21
2,074
7,832
<issue_start>username_0: I have found that WebSockets in Chrome and Firefox disconnect after exactly one minute of inactivity. Based on stuff I've seen online, I was all set to blame proxies or some server settings or something, but this does not happen in IE or Edge. It seems like if sockets are disconnected by the server after one minute of inactivity that would apply to IE and Edge just as much as Chrome and Firefox. Does anyone know why this is? Is it documented anywhere? I know a possible way to stop it by pinging, but I'm more interested in why it's happening. The reason code given on disconnect is 1006, indicating that the browser closed the connection. No errors are thrown and the onerror event for the socket is not triggered. This project was built at <https://glitch.com/edit/#!/noiseless-helmet> where you can see and run everything. The client page is served here: <https://noiseless-helmet.glitch.me/> Here is my client page: ``` let socket = new WebSocket("wss://noiseless-helmet.glitch.me/"); socket.onmessage = function(event) { div.innerHTML += "<br>message " + new Date().toLocaleString() + " " + event.data; }; socket.onopen = function (event) { div.innerHTML += "<br>opened " + new Date().toLocaleString(); socket.send("Hey socket! " + new Date().toLocaleString()); }; socket.onclose = function(event) { div.innerHTML += "<br>socket closed " + new Date().toLocaleString(); div.innerHTML += "<br>code: " + event.code; div.innerHTML += "<br>reason: " + event.reason; div.innerHTML += "<br>clean: " + event.wasClean; }; socket.onerror = function(event) { div.innerHTML += "<br>error: " + event.error; }; ``` And here is my Node.js server code: ``` var express = require('express'); var app = express(); app.use(express.static('public')); let server = require('http').createServer(), WebSocketServer = require('ws').Server, wss = new WebSocketServer({ server: server }); app.get("/", function (request, response) { response.sendFile(__dirname + '/views/index.html'); }); let webSockets = []; wss.on('connection', function connection(socket) { webSockets.push(socket); webSockets.forEach((w) => { w.send("A new socket connected"); }); socket.on('close', (code, reason) => { console.log('closing socket'); console.log(code); console.log(reason); let i = webSockets.indexOf(socket); webSockets.splice(i, 1); }); }); server.on('request', app); server.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + server.address().port); }); ```<issue_comment>username_1: As much as i understood from researching this, this is caused by websocket timing out over a period of time when no data is sent. This is probably per browser. You could use pings to resolve this or just reconnect when you need to use the socket again. It makes sense to not keep sockets open when they are not used from server side as from browser side. For example, Chrome has a limit how many connections can be open, if the limit would be 64 connections and you have open 64 tabs (which is very likely for me as i always have loads of tabs open) and each tab is connected to a server, no more connections could be done (Actually similar thing happened to me once, when i ran out of available sockets in Chrome, funny). > > There is proxy\_read\_timeout (<http://nginx.org/r/proxy_read_timeout>) > which as well applies to WebSocket connections. You have to bump > it if your backend do not send anything for a long time. > Alternatively, you may configure your backend to send websocket > ping frames periodically to reset the timeout (and check if the > connection is still alive). > > > <https://forum.nginx.org/read.php?2,236382,236383#msg-236383> > > **Web Sockets have an idle timeout of 60 seconds**: if you do not use a heartbeat or similar via ping and pong frames then the socket assumes that the user has closed the page and closes the socket to save resources. > > > <https://www.codeproject.com/Questions/1205863/Websocket-is-closed-after-min> <https://github.com/tornadoweb/tornado/issues/1070> Upvotes: 4 <issue_comment>username_2: > > It seems like if sockets are disconnected by the server after one minute of inactivity that would apply to IE and Edge just as much as Chrome and Firefox. > > > Hmmm, no, it doesn't. IE and Edge *might* be implementing a `ping` packet as part of the WebSocket protocol. [The WebSocket protocol includes support for a protocol level `ping`](https://www.rfc-editor.org/rfc/rfc6455#page-37) that the JavaScript API doesn't expose. It's a bit lower-level than the user level pinging that is often implemented. This `ping`-`pong` traffic resets the timers in any network intermediaries (proxies, load balancers, etc') - and they all time connections to mark stale connections for closure (for example, the [Heroku setup times connections at 55 seconds](https://devcenter.heroku.com/articles/limits#router)). Most browsers trust the server to implement the `ping`, which is polite (since servers need to manage their load and their timeout for pinging... ...however it's also slightly frustrating, since browsers have no idea if a connection was abnormally lost and JavaScript doesn't emit an event for the WebSocket protocol `ping`. This is why many JavaScript clients implement a user level ping (i.e., a JSON `{event: "ping", data: {...}}` or another "empty" event message). Anyway, I just wanted to point out that your assumption was incorrect, this is still a timeout occurring and the difference in browser behavior is probably related to the browsers themselves. For a few specifics regarding nginx default timeouts (when proxying WebSocket connections) you can read @username_1's answer. Upvotes: 6 [selected_answer]<issue_comment>username_3: The WebSocket protocol specification defines Ping and Pong frames that can be used for keep-alive, heart-beats, network status probing. **Ping** means client/server is sending an iq to tell the other side server/client that to keep the connection alive and also the other side will send an acknowledgement with **pong** having same payload data. You can also define a timeout when the browser stops respond or be considered dead. read more: <http://vunse.blogspot.in/2014/04/websocket-ping-pong.html> Upvotes: 2 <issue_comment>username_4: Maybe not a clean solution but this is how I implemented websocket in JS to automatically reconnect when disconnected ``` var socket_main const mainSocketMessageListener = (event) => { //retreive the data here console.log(event.data) } const mainSocketOpenListener = (event) => { console.log("Websocket opened") //Example of sending message to websocket here socket_main.send(JSON.stringify({ event: "subscribe", data: ["all"] })) } const mainSocketCloseListener = (event) => { if (socket_main) { console.error('Websocket disconnected.') } socket_main = new WebSocket('wss://ws.example.com') socket_main.addEventListener('open', mainSocketOpenListener) socket_main.addEventListener('message', mainSocketMessageListener) socket_main.addEventListener('close', mainSocketCloseListener) } //connect the first time mainSocketCloseListener() ``` Upvotes: 0 <issue_comment>username_5: I think the issue is related to policy changes on chrome and other browsers. Please see discussions at * "Chrome terminates WebSocket connection": <https://github.com/SignalR/SignalR/issues/4536> * "How to detect when browser throttles timers and websockets disconnection": [How to detect when browser throttles timers and websockets disconnection after a user leaves a tab or turns off the screen? (javascript)](https://stackoverflow.com/questions/60758141/how-to-detect-when-browser-throttles-timers-and-websockets-disconnection-after-a) Upvotes: 0
2018/03/21
652
2,676
<issue_start>username_0: Using .net Core, MVC, C# I have created a single model that contains 2 separate models. Code as below: ``` public abstract class ViewModelBase { public string Environment { get; set; } } public class CombinedViewModel : ViewModelBase { public FirstViewModel FirstViewModel { get;set;} public SecondViewModel SecondViewModel { get; set; } } public class FirstViewModel : ViewModelBase { public string FirstName{ get;set;} public string LastName{ get; set; } } public class SecondViewModel : ViewModelBase { public string Mode { get;set;} } ``` Here is my MVC Controller: ``` public IActionResult Index(string environment, string mode) { var model = new CombinedViewModel (); model.Environment = environment; model.SecondViewModel.Mode = mode; return View(model); } ``` What I have searched it that this is way to initialize multiple model. Not sure what I am doing wrong here but I get the below error: > > An unhandled exception occurred while processing the request. > > > NullReferenceException: Object reference not set to an instance of an object. > > > model.SecondViewModel.Mode = mode; > > > Do I need to initialize my first and second model separately. Please note that I am still not using my "mode" in my view yet.<issue_comment>username_1: Yes you need to initialize them "separately". Otherwise model.SecondViewModel is null and when you try to access one of its properties you'll get an exception. You may initialize them inside the CombinedViewModel Constructor as follow : ``` public CombinedViewModel () // Could request parameters like default Mode / FirstName / LastName { this.FirstViewModel = new FirstViewModel(); this.SecondViewModel = new SecondViewModel(); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Yes, you have to initialize the child models before you can access them. You can do it explicitly in the controller's action method: ``` public IActionResult Index(string environment, string mode) { var model = new CombinedViewModel (); model.Environment = environment; model.SecondViewModel = new SecondViewModel(); model.SecondViewModel.Mode = mode; return View(model); } ``` Another way to go is to set some default value in the constructor of the `CombinedViewModel` class: ``` public class CombinedViewModel : ViewModelBase { public FirstViewModel FirstViewModel { get;set;} public SecondViewModel SecondViewModel { get; set; } public CombinedViewModel() { this.FirstViewModel = new FirstViewModel(); this.SecondViewModel = new SecondViewModel(); } } ``` Upvotes: 1
2018/03/21
540
2,096
<issue_start>username_0: I have Python 2.7 installed (as default in Windows 7 64bit) and also have Python 3 installed in an environment (called Python3). I would like to use Spyder as my IDE. I have installed Spyder3 in my Python3 environment, but when I open Spyder 3 (from within my Python 3 env), then it opens Spyder for python 2.7 and not python 3.5 as I would've hoped for.). I don't know why. I have done `TOOLS--Preferences--Python Interpreter -- Use the following Python interpreter: C:\Users\16082834\AppData\Local\Continuum\Anaconda2\envs\Python3\python.exe`, but this didn't work either. Many of us are running multiple python environments; I am sure some of you might have managed to use Spyder for these different environments. Please tell me how I can get Python 3 using this method.<issue_comment>username_1: One possible way is to run `activate Python3` and then run `pip install Spyder`. Upvotes: 2 <issue_comment>username_2: So, when you create a new environment with: conda create --name python36 python=3.6 anaconda This will create an env. called python36 and the package to be installed is anaconda (which basically contains everything you'll need for python). Be sure that your new env. actually is running the ecorrect python version by doing the following: activate python environmentwith: active python36 then type: python this will indicate what python version is running in your env. It turns out, for some reason, my environment was running python2.7 and not 3.6 The cool thing is that anaconda distribution comes with spyder. Just be sure that you run Spyder from within your environment. So to do this: activate python36 then type: spyder It will automatically open spyder3 for python3. My initial issue was therefore that even though i created a python3 environment, it was still running python2.7. But after removing the old python3 environment and creating a new python3 env. and installing the desired libraries/packages it now works perfect. I have a 2.7 and 3.6 environment which can both be edited with spyder2 and spyder3 IDE Upvotes: 1
2018/03/21
900
3,374
<issue_start>username_0: I have seen a few questions similar to this but all revolve around webpack, which I am not currently using. I have a Vue template: ``` var question = Vue.component('question', { props: { scenario: { type: Object } }, beforeMount: function () { this.retrieveScenario(); }, methods: { postChoice: function () { Post("Study", "PostScenarioChoice") }, retrieveScenario: function () { Get("ScenariosVue", "GetScenario", 1, this, (c, data) => { this.scenario = data; }, (c, errors) => { console.log(errors); } ); } }, template: ` ![]() ![]() ` }); ``` The Ajax retrieval returns an object with the following: ``` returned Object { scenarioId: 1, description: "Dog vs Bolard", scenarioLeftImg: "images\\Scenarios\\bolard_dog_Left.png", scenarioRightImg: "images\\Scenarios\\bolard_dog_Right.png", participantScenarios: [], scenarioTypesScenarios: [] } ``` However, the Html, doesn't add the src tag to the tag and I'm really not sure why because the data's clearly available. Much Help would be greatly appreciated.<issue_comment>username_1: Your main issue is that due to the limitations of Javascript, [Vue cannot detect property additions in Objects](https://v2.vuejs.org/v2/guide/reactivity.html). Change to ``` retrieveScenario: function () { Get("ScenariosVue", "GetScenario", 1, this, (c, data) => { Vue.set(this.data, 'scenarios', data); }, (c, errors) => { console.log(errors); } ); } ``` Please be aware that it is considered really bad practice to have components modify their `props`. Rather mirror those props into your vm's data() function in the `created()` hook of your component, then modify that. If you need the "modified" props outside of your component, emit an event telling those components props has changed. Also replace the backslashes in your path by slashes: ``` scenarioLeftImg: "images\\Scenarios\\bolard_dog_Left.png", scenarioRightImg: "images\\Scenarios\\bolard_dog_Right.png", ``` has to be ``` scenarioLeftImg: "images/Scenarios/bolard_dog_Left.png", scenarioRightImg: "images/Scenarios/bolard_dog_Right.png", ``` Upvotes: 0 <issue_comment>username_2: This is happening because Vue's template system doesn't "watch" properties (or nested properties) of an object for changes. If you need to do this, then you can either use the `computed` property with a `watch` on the computed property, or you can just create two `props` instead of the single `prop`. Here is what I would do to change your code: ```js var question = Vue.component('question', { props: { // Replace this prop with the two below. // scenario: { type: Object } scenarioLeftImg: { type: String }, scenarioRightImg: { type: String } }, beforeMount: function () { this.retrieveScenario(); }, methods: { postChoice: function () { Post("Study", "PostScenarioChoice") }, retrieveScenario: function () { Get("ScenariosVue", "GetScenario", 1, this, (c, data) => { this.scenario = data; }, (c, errors) => { console.log(errors); } ); } }, template: ` ![]() ![]() ` }); ``` Upvotes: 1
2018/03/21
233
961
<issue_start>username_0: I am working on a university project with a friend, and we decided to host the thing in a GitHub repo. I am using the Code::Blocks IDE. It would be rather sensible if I could pull and push to my branch of the project on Git directly from within Code::Blocks, but I have not been able to figure out how. Is there a plugin or some other tool that would allow me to do this?<issue_comment>username_1: Netbeans has a Portable Version, put it on a USB and you will be fine :) Upvotes: 2 <issue_comment>username_2: You can use GitHub Desktop, but it is not automated. You can work in Code::Blocks and GitHub Desktop will show the files have changed (as long as you use the same directory/files for Code::Blocks and GitHub Desktop). You will then have to manually push the files back to GitHub. Upvotes: 3 [selected_answer]<issue_comment>username_3: Use codeblock for your coding and use atom to push and pull your project code. Upvotes: 1
2018/03/21
824
3,221
<issue_start>username_0: I have a little JS/Jquery issue with my portfolio website and I still consider myself a mediocre programmer. I have five buttons on my portfolio website, each representing one of my projects. I also have a div with five matching text contents (as a description for each of the projects) and an image/link as a visual description of the project with link on the image so the user can go to the project URL. ``` Content One ----------- Content Two ----------- Content Three ------------- Content Four ------------ Content Five ------------ [Background One](about.html) [Background Two](about.html) [Background Three](about.html) [Background Four](about.html) [Background Five](about.html) * WORK * WORK * WORK * WORK * WORK ``` The idea is: when a user enters the page, it will be showing the first project (meaning the first description and first image with the link will be active and showing - probably having class "is-active"). When the user clicks any of the buttons, it will hide the description and image that's being shown already and show the one matching the project button (So if I click the third button, it will hide the first description and first image and show the third description and third image) I am not really good with arrays and Each functions, plus I am baffled by how to remove the "is-active" class form all non-desired elements and then add that class to the elements I want to show. NOTE: If you would use a different HTML markup, it's more than welcome. This is just first iteration and I have been stuck on this for past day.<issue_comment>username_1: Using your current setup, you could try something like this: ``` $(document).ready(function() { $('.work-ul button').each(function(i) { $(this).click(function(o) { $('.work-content h2, div.moving-zone a').hide(); $('.work-content h2:eq('+i+'), div.moving-zone a:eq('+i+')').show(); }); }); }); ``` You'll want some initial styles/class to hide all but perhaps your first portfolio item. Upvotes: 0 <issue_comment>username_2: I like to use the `data-*` attributes for this situation. Give the button a `data-id` attribute. Give the corresponding elements (header and anchor) a `data-content` attribute with the same value as above. Then on the click of the button, first hide all the elements with a `data-content` attribute, the show the ones which `data-content` attribute corresponds with the `data-id` attribute. So might be able to lose some `id` attributes, but that you should judge yourself. ```js $(function() { $('.button').on('click', function() { var id = $(this).data('id'); $('[data-content]').hide(); $('[data-content="'+id+'"]').show(); }); }); ``` ```css .con-hidden, .is-hidden { display: none; } ``` ```html Content One ----------- Content Two ----------- Content Three ------------- Content Four ------------ Content Five ------------ [Background One](about.html) [Background Two](about.html) [Background Three](about.html) [Background Four](about.html) [Background Five](about.html) * WORK * WORK * WORK * WORK * WORK ``` Upvotes: -1 [selected_answer]
2018/03/21
594
2,085
<issue_start>username_0: I have one question on how to solve MISRA 2004 11.3 violation. The code is as follows: ``` tm_uint8 read( tm_uint8* data) { data[0] = *((tm_uint8*)0x00003DD2); data[1] = *((tm_uint8*)0x00003DD3); data[2] = *((tm_uint8*)0x00003DD4); } ``` I want to write the value stored at the physical address. It compiles but I have a MISRA violation for 11.3. I want to solve it. Can anyone help me with that?<issue_comment>username_1: The rationale behind this rule is that MISRA worries about misaligned access when casting from an integer to a pointer. In your case, I assume `tm_uint8_t` is 1 byte, so alignment shouldn't be an issue here. In that case, the warning is simply a false positive and you can ignore it. This is an advisory rule, so you don't need to raise a deviation. There is no other work-around, except never working with absolute addresses. Which is most likely not an option here. As you can tell, this rule is very cumbersome when writing hardware-related code, there is just no way such code can follow the rule. Upvotes: 2 <issue_comment>username_2: Note: MISRA-C:2004 Rule 11.3 is equivalent to MISRA C:2012 Rule 11.4 It is accepted that some MISRA C/C++ Rules may cause a violation to be raised, in situations where the method used is necessary. Because of this, MISRA C provides a mechanism for Deviating a Rule - and this would be the appropriate route for you to follow... please do not try and find a way around the Rule using "clever" code! As highlighted by this question, accessing specific memory (and/or I/O devices) is one particular case. In fact, one of the examples included in MISRA C:2012 shows this exact use case as being non-compliant with the Rule. In 2016, the MISRA C Working Group published additional guidance on Compliance, including enhancing the Deviation process... this gives help on what is a justifiable Deviation - and accessing hardware is one of those! In due course, it is planned to provide more "layered" guidance... but that will not be immediate. [Please note profile for disclaimer] Upvotes: 1
2018/03/21
583
2,366
<issue_start>username_0: I encountered a solution (.Net Full framework) Where there are no package.config in the solution and Feeds coming from In house Nuget servers. Where list of packages are maintained, if not in Package.Config?<issue_comment>username_1: > > Where is the list of packages are maintained, if not in Package.Config? > > > First, you should make sure you have that solution have already installed the nuget package, once you install a package, NuGet will add `Package.Config` file to your project to record the dependency in either your project file or a packages.config file. If you confirm that your solution has a nuget package installed, but there is no `Package.Config` file, your nuget package should use another management method: [PackageReference](https://learn.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files) Edit your project, you will find following PackageReference list: ``` ``` See [NuGet is now fully integrated into MSBuild](https://blog.nuget.org/20170316/NuGet-now-fully-integrated-into-MSBuild.html) for more details: > > In the past, NuGet packages were managed in two different ways - > packages.config and project.json - each with their own sets of > advantages and limitations. With Visual Studio 2017 and .NET Core, we > have improved the NuGet package management experience by introducing > the PackageReference feature in MSBuild. PackageReference brings new > and improved capabilities such as deep MSBuild integration, improved > performance for everyday tasks such as install and restore, > multi-targeting and more. > > > Upvotes: 4 [selected_answer]<issue_comment>username_2: The packages.config file could be somewhere else? In that case look in your msbuild project file (i.e. \*.csproj, \*.vbproj, \*.vcxproj) and see where the references to that nuget assembly are coming from. Then look in that directory for the packages.config file. It might be more complicated than that, in which case, it's useful to do a global search for packages.config in your repo, to see where they reside (If they do exist at all). This is a common practice: To have one project specify the nuget package, and all the other projects borrow it. As Jon said, this is really dependent on how the folks at your company and department set up your builds and dependencies. Upvotes: 1
2018/03/21
769
2,856
<issue_start>username_0: I am making an object-oriented text adventure engine code, and my main goal is to make it user-friendly, but powerful. One of the classes in the code currently takes 15 arguments. However, in each instance of the class, only a few of the arguments are actually defined and many of them end up being left blank. For the purpose of creating more concise code and also to make the experience of using the engine more user-friendly, I am wondering if there is any way to make some of the parameters in the class optional to fill out. The goal of this would be that when you create an instance of the said class, you would only need to define the arguments that you need for that specific instance, instead of having to also define all the other arguments as valueless. In other words, I am wondering if this is possible: ``` class sampleClass: def __init__(self, arg1, optional1) self.arg1 = arg1 self.optional1 = optional1 var = sampleClass(value) var = sampleClass(value2, value3) ``` In the above case, the "optional1" variable can be defined or can be left blank. I have also looked into the posts on \*args and \*\*kwargs on this site, and it seems to me that both arguments can each take multiple values, but none of them have the option to take no values. In conclusion, is it possible to have completely optional arguments in a python class which can be defined or left blank and no error message will result? Also, sorry for anything wrong I have done in this post. This is my first question on Stack Overflow, so I am new to the site. Please tell me if there is anything I can improve on to ask better questions.<issue_comment>username_1: A class init method is just the same as any other function, and its arguments can default to None. ``` def __init__(self, arg1, optional1=None): ``` Upvotes: 2 <issue_comment>username_2: Try this: [Use of \*args and \*\*kwargs](https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/) \*\*kwargs allows you to pass keyworded variable length of arguments to a function. You should use \*\*kwargs if you want to handle named arguments in a function. ``` def manyArgs(*arg): print("Was called with ", len(arg), " arguments: ", arg) def main(): manyArgs() if __name__ == "__main__": main() ``` if i run this without any arguments it prints the following line: ``` Was called with 0 arguments: () ``` Upvotes: 1 <issue_comment>username_3: > > I have also looked into the posts on \*args and \*\*kwargs on this site, and it seems to me that both arguments can each take multiple values, but none of them have the option to take no values. > > > That's not correct. ``` >>> def f(*args, **kwargs): ... print("Args: %r" % (args,)) ... print("Kwargs: %r" % (kwargs,)) ... >>> f() Args: () Kwargs: {} ``` Upvotes: 1
2018/03/21
605
2,069
<issue_start>username_0: I have developed a tool using pyspark. In that tool, the user provides a dict of model parameters, which is then passed to an spark.ml model such as Logistic Regression in the form of LogisticRegression(\*\*params). Since I am transferring to Scala now, I was wondering how this can be done in Spark using Scala? Coming from Python, my intuition is to pass a Scala Map such as: ``` val params = Map("regParam" -> 100) val model = new LogisticRegression().set(params) ``` Obviously, it's not as trivial as that. It seem as in scala, we need to set every single parameter separately, like: ``` val model = new LogisticRegression() .setRegParam(0.3) ``` I really want to avoid being forced to iterate over all user input parameters and set the appropriate parameters with tons of if clauses. Any ideas how to solve this as elegantly as in Python?<issue_comment>username_1: A class init method is just the same as any other function, and its arguments can default to None. ``` def __init__(self, arg1, optional1=None): ``` Upvotes: 2 <issue_comment>username_2: Try this: [Use of \*args and \*\*kwargs](https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/) \*\*kwargs allows you to pass keyworded variable length of arguments to a function. You should use \*\*kwargs if you want to handle named arguments in a function. ``` def manyArgs(*arg): print("Was called with ", len(arg), " arguments: ", arg) def main(): manyArgs() if __name__ == "__main__": main() ``` if i run this without any arguments it prints the following line: ``` Was called with 0 arguments: () ``` Upvotes: 1 <issue_comment>username_3: > > I have also looked into the posts on \*args and \*\*kwargs on this site, and it seems to me that both arguments can each take multiple values, but none of them have the option to take no values. > > > That's not correct. ``` >>> def f(*args, **kwargs): ... print("Args: %r" % (args,)) ... print("Kwargs: %r" % (kwargs,)) ... >>> f() Args: () Kwargs: {} ``` Upvotes: 1
2018/03/21
980
3,625
<issue_start>username_0: For text drawing on canvas, a fairly simple construction can be used: ``` void drawName(Canvas context, String name, double x, double y) { TextSpan span = new TextSpan( style: new TextStyle(color: Colors.blue[800], fontSize: 24.0, fontFamily: 'Roboto'), text: name); TextPainter tp = new TextPainter( text: span, textAlign: TextAlign.left, textDirection: ` ` TextDirection.ltr); tp.layout(); tp.paint(context, new Offset(x, y)); } ``` Is it possible to draw text at an angle, for example 45 degrees, or 90 degrees (vertically from the bottom up)?<issue_comment>username_1: It sounds like you are looking for a Transformation. There is a general [Transform Widget](https://docs.flutter.io/flutter/widgets/Transform-class.html), but there is also a more specific [RotatedBox Widget](https://docs.flutter.io/flutter/widgets/RotatedBox-class.html) that sounds like it will be a perfect fit for you. ``` new RotatedBox( quarterTurns: 3, child: const Text('Hello World!'), ) ``` If you need more control over the rotation (to use something other than 90 degree increments) you should be able to achieve this the [Transform Widget](https://docs.flutter.io/flutter/widgets/Transform-class.html) and a [Matrix4.rotationZ](https://docs.flutter.io/flutter/vector_math_64/Matrix4/Matrix4.rotationZ.html) ``` new Container( color: Colors.blue, child: new Transform( transform: new Matrix4.rotationZ(-0.785398), child: new Container( padding: const EdgeInsets.all(8.0), color: const Color(0xFFE8581C), child: const Text('Apartment for rent!'), ), ), ) ``` Upvotes: 0 <issue_comment>username_2: To rotate text on a canvas, you can use canvas transforms rather than rotating the entire canvas. That looks something like this: ``` @override void paint(Canvas canvas, Size size) { // save is optional, only needed you want to draw other things non-rotated & translated canvas.save(); canvas.translate(100.0, 100.0); canvas.rotate(3.14159/4.0); TextSpan span = new TextSpan( style: new TextStyle(color: Colors.blue[800], fontSize: 24.0, fontFamily: 'Roboto'), text: "text"); TextPainter tp = new TextPainter( text: span, textDirection: TextDirection.ltr); tp.layout(); tp.paint(canvas, new Offset(0.0, 0.0)); // optional, if you saved earlier canvas.restore(); } ``` Note that I'm translating then rotating, because if you translate after or even use the offset you'll probably get a different result than what you want. Also, once you start using transforms (translate & rotate) you probably want to save the transform state and then restore after you draw whatever you want transformed, at least if you're drawing anything other than the rotated text. Upvotes: 2 <issue_comment>username_3: A function that draws text at a specified angle: ``` void drawText(Canvas context, String name, double x, double y, double angleRotationInRadians) { context.save(); context.translate(x, y); context.rotate(angleRotationInRadians); TextSpan span = new TextSpan( style: new TextStyle(color: Colors.blue[800], fontSize: 24.0, fontFamily: 'Roboto'), text: name); TextPainter tp = new TextPainter( text: span, textAlign: TextAlign.left, textDirection: TextDirection.ltr); tp.layout(); tp.paint(context, new Offset(0.0,0.0)); context.restore(); } ``` PS."username_2", thank a lot for your help. Upvotes: 0
2018/03/21
301
1,047
<issue_start>username_0: I have this htaccess file in the '*public\_html*' folder: ``` RewriteEngine On RewriteRule ^asset/(.*)$ asset.php?code=$1 [NC] ``` Essentially, the rewrite condition should work as follows. When a user clicks on a link *../asset/XXX*, the `asset.php` file generates a new webpage containing details of the *XXX* asset. The lookup is not working as I think the *htaccess* file cannot find the '`asset.php`' file. The asset.php file is located in *'public\_html/wp-content/themes/theme1/asset.php'* How can I modify the htaccess file to lookup this file?<issue_comment>username_1: Have you tried: `RewriteRule ^asset/(.*)$ wp-content/themes/theme1/asset.php?code=$1 [NC]` Upvotes: 2 <issue_comment>username_2: The rewrite is from your directory where the htaccess file is located. So add the path to the destination file. ``` RewriteEngine On RewriteRule ^asset/(.*)$ wp-content/themes/theme1/asset.php?code=$1 [NC] ``` Perhaps you can set the RewriteBase to `/`. Sometimes that fixes some problems. Upvotes: 1
2018/03/21
267
943
<issue_start>username_0: The [Bing Autosuggest API](https://azure.microsoft.com/en-us/services/cognitive-services/autosuggest/) lists charges as being per transaction like this: > > Features: Up to 100 transactions per second; > Unit: Transactions; > Price: $3 per 10,000 transactions > > > But nowhere in the documentation or FAQ does it define what constitutes a transaction. Can someone clarify what is considered a transaction? Is one transaction equal to one API call?<issue_comment>username_1: Have you tried: `RewriteRule ^asset/(.*)$ wp-content/themes/theme1/asset.php?code=$1 [NC]` Upvotes: 2 <issue_comment>username_2: The rewrite is from your directory where the htaccess file is located. So add the path to the destination file. ``` RewriteEngine On RewriteRule ^asset/(.*)$ wp-content/themes/theme1/asset.php?code=$1 [NC] ``` Perhaps you can set the RewriteBase to `/`. Sometimes that fixes some problems. Upvotes: 1
2018/03/21
646
2,200
<issue_start>username_0: Im trying to make a spell checker which will read in a dictionary (`words.txt`) and then read in a text file (`text.txt`). Then by using a binary search it will compare the 2 files so see which words are spelled incorrectly in the text file. My trouble lies with converting the text file all to lowercase so it can be compared to the dictionary which has been converted to lowercase. The regular expression is in there because theres words in the text such as `long,` and the regex would take out the comma. The error message i recieve is : `Traceback (most recent call last): File "C:\Users\S\Coursework\searchBinary.py", line 25, in content = re.findall("[\w']+", content) File "C:\Users\S\AppData\Local\Programs\Python\Python36-32\lib\re.py", line 222, in findall return \_compile(pattern, flags).findall(string) TypeError: expected string or bytes-like object` ``` import re def binS(lo,hi,target): if (lo>=hi): return False mid = (lo+hi) // 2 piv = words[mid] if piv==target: return True if piv ```<issue_comment>username_1: You require a string or bytes-like object but you are passing it a list. If you run `print(type(content))` you’ll get class 'list' Try to recombine the text as a string before running the regex and it should work. Use `content = ' '.join(content)` ``` import re def binS(lo,hi,target): if (lo>=hi): return False mid = (lo+hi) // 2 piv = words[mid] if piv==target: return True if piv ``` I have a dictionary file named dictionary.txt and I put “Hello worl my nae is Bob” into temp.txt. My output is: > > worl nae > > > Upvotes: 2 [selected_answer]<issue_comment>username_2: The error is clearly due to the wrong type of object passed to the `re.findall` function, as already pointed out. I wanted to suggest a different approach you could try: avoid using the regular expressions altogether and replace the punctuation in the text with something like this... ``` for ch in '.,:;?!"·$%&/+*#@<=>-_\\`|^´~()[]{}': text = text.replace(ch, " ") ``` ... and then get the list of words simply by doing: ``` words = text.split() ``` Upvotes: 0