qid
int64
1
74.7M
question
stringlengths
10
43.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
33.7k
response_k
stringlengths
0
40.5k
62,672,746
I've updated my .NET core 3.1+Angular 9.1 to Angular 10.0.2, steps I used: 1. update Vs TypeScript to [3.9.5](https://marketplace.visualstudio.com/items?itemName=TypeScriptTeam.typescript-395) 2. run `ng update @angular/core @angular/cli` After that VS 2019 v 16.6.3 shows no intellisense and validation,project runs without problems. If I open the project in VS Code all work fine I've found the problem is just after I run `ng update @angular/cli` reverting project to 9.1 all works fine thanks
2020/07/01
[ "https://Stackoverflow.com/questions/62672746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3492996/" ]
I experienced the same issue after upgrading a project to Angular 10. It appears to be an issue with the latest version of Visual Studio 2019 not handling the changes to the tsconfig.json file and the introduction tsconfig.base.json. As a workaround until this is resolved in VS 2019 I copied the contents of tsconfig.base.json up to tsconfig.json and commented out the upgraded config. I now have and file that looks like this and the old functionality is restored ``` /* This is a "Solution Style" tsconfig.json file, and is used by editors and TypeScript’s language server to improve development experience. It is not intended to be used to perform a compilation. To learn more about this file see: https://angular.io/config/solution-tsconfig. removed this as causes vs 2019 to fail - the config details are copied from base so when this is sort we can revert "files": [], "references": [ { "path": "./src/tsconfig.app.json" }, { "path": "./src/tsconfig.spec.json" }, { "path": "./src/tsconfig.server.json" }, { "path": "./e2e/tsconfig.e2e.json" } ] */ { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "module": "esnext", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2017", "dom" ] }, "angularCompilerOptions": { "enableIvy": true } } ```
**Update** This seems to be working in visual studio `16.7.1` --- I faced the same issue when updated to angular 10. It seems to be a [known issue](https://developercommunity.visualstudio.com/comments/1113710/view.html) and the fix is already available in the preview. Until the fix is available to the public, following changes in `tsconfig.json` resolve the issue for me. ``` { "extends": "./tsconfig.base.json" } ```
62,672,746
I've updated my .NET core 3.1+Angular 9.1 to Angular 10.0.2, steps I used: 1. update Vs TypeScript to [3.9.5](https://marketplace.visualstudio.com/items?itemName=TypeScriptTeam.typescript-395) 2. run `ng update @angular/core @angular/cli` After that VS 2019 v 16.6.3 shows no intellisense and validation,project runs without problems. If I open the project in VS Code all work fine I've found the problem is just after I run `ng update @angular/cli` reverting project to 9.1 all works fine thanks
2020/07/01
[ "https://Stackoverflow.com/questions/62672746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3492996/" ]
**Update** This seems to be working in visual studio `16.7.1` --- I faced the same issue when updated to angular 10. It seems to be a [known issue](https://developercommunity.visualstudio.com/comments/1113710/view.html) and the fix is already available in the preview. Until the fix is available to the public, following changes in `tsconfig.json` resolve the issue for me. ``` { "extends": "./tsconfig.base.json" } ```
I had the exact same problem after I migrated from Angular 9 to Angular 10. I found the following worked for me: **TL;DR** ========= In all the 'project' level tsconfig files (tsconfig.app.json, tsconfig.spec.json, tsconfig.e2e.json) just change the 'extends' property from: ``` { "extends": "../tsconfig.json" ... } ``` To the following: ``` { "extends": "../tsconfig.base.json" ... } ``` **Full Version** ================ Before running `ng update` I had the following structure: ``` ClientApp |_ tsconfig.json |_ src |_ tsconfig.app.json |_ tsconfig.spec.json |_ e2e |_ tsconfig.e2e.json ``` After running `ng update` I had the following structure: ``` ClientApp |_ tsconfig.json |_ tsconfig.base.json |_ src |_ tsconfig.app.json |_ tsconfig.spec.json |_ e2e |_ tsconfig.e2e.json ``` After reading the Angular migration notes I noticed my version of `tsconfig.json` and `tsconfig.base.json` were identical. This still worked but it didn't match what Angular were describing in the notes. So I decided to change my `tsconfig.json. manually to the following: ``` { "files": [], "references": [ { "path": "./src/tsconfig.app.json" }, { "path": "./src/tsconfig.spec.json" }, { "path": "./e2e/tsconfig.e2e.json" } ] } ``` And like everyone else it broke my app. So I had a look at the 'project' level tsconfig files and noticed the 'extends' property was still point to `tsconfig.json` and not to `tsconfig.base.json`. After updating my 'project' level tsconfig files to pointing to the `tsconfig.base.json` file everything just worked. Happy days! :-) I am guessing the `ng update` should "automagically" find and update all the 'project' level tsconfig files but it looks like it doesn't. The fix however is fairly straight forward though. --- Update ====== Although changing extends property did resolve my compilation issues. When I closed and reopened Visual Studio the next day the IntelliSense started to fail. Only by making the `tsconfig.json` to be the same as the `tsconfig.base.json` could I get both the compilation and IntelliSense working.
62,672,754
When I checked the document in the email, I was able to select the Signature design registered in the sand box account. But there is no Signature information in embedded app, so how can I get it? [enter image description here](https://i.stack.imgur.com/rxSHw.jpg)
2020/07/01
[ "https://Stackoverflow.com/questions/62672754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10747925/" ]
I experienced the same issue after upgrading a project to Angular 10. It appears to be an issue with the latest version of Visual Studio 2019 not handling the changes to the tsconfig.json file and the introduction tsconfig.base.json. As a workaround until this is resolved in VS 2019 I copied the contents of tsconfig.base.json up to tsconfig.json and commented out the upgraded config. I now have and file that looks like this and the old functionality is restored ``` /* This is a "Solution Style" tsconfig.json file, and is used by editors and TypeScript’s language server to improve development experience. It is not intended to be used to perform a compilation. To learn more about this file see: https://angular.io/config/solution-tsconfig. removed this as causes vs 2019 to fail - the config details are copied from base so when this is sort we can revert "files": [], "references": [ { "path": "./src/tsconfig.app.json" }, { "path": "./src/tsconfig.spec.json" }, { "path": "./src/tsconfig.server.json" }, { "path": "./e2e/tsconfig.e2e.json" } ] */ { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "module": "esnext", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2017", "dom" ] }, "angularCompilerOptions": { "enableIvy": true } } ```
I had the exact same problem after I migrated from Angular 9 to Angular 10. I found the following worked for me: **TL;DR** ========= In all the 'project' level tsconfig files (tsconfig.app.json, tsconfig.spec.json, tsconfig.e2e.json) just change the 'extends' property from: ``` { "extends": "../tsconfig.json" ... } ``` To the following: ``` { "extends": "../tsconfig.base.json" ... } ``` **Full Version** ================ Before running `ng update` I had the following structure: ``` ClientApp |_ tsconfig.json |_ src |_ tsconfig.app.json |_ tsconfig.spec.json |_ e2e |_ tsconfig.e2e.json ``` After running `ng update` I had the following structure: ``` ClientApp |_ tsconfig.json |_ tsconfig.base.json |_ src |_ tsconfig.app.json |_ tsconfig.spec.json |_ e2e |_ tsconfig.e2e.json ``` After reading the Angular migration notes I noticed my version of `tsconfig.json` and `tsconfig.base.json` were identical. This still worked but it didn't match what Angular were describing in the notes. So I decided to change my `tsconfig.json. manually to the following: ``` { "files": [], "references": [ { "path": "./src/tsconfig.app.json" }, { "path": "./src/tsconfig.spec.json" }, { "path": "./e2e/tsconfig.e2e.json" } ] } ``` And like everyone else it broke my app. So I had a look at the 'project' level tsconfig files and noticed the 'extends' property was still point to `tsconfig.json` and not to `tsconfig.base.json`. After updating my 'project' level tsconfig files to pointing to the `tsconfig.base.json` file everything just worked. Happy days! :-) I am guessing the `ng update` should "automagically" find and update all the 'project' level tsconfig files but it looks like it doesn't. The fix however is fairly straight forward though. --- Update ====== Although changing extends property did resolve my compilation issues. When I closed and reopened Visual Studio the next day the IntelliSense started to fail. Only by making the `tsconfig.json` to be the same as the `tsconfig.base.json` could I get both the compilation and IntelliSense working.
62,672,754
When I checked the document in the email, I was able to select the Signature design registered in the sand box account. But there is no Signature information in embedded app, so how can I get it? [enter image description here](https://i.stack.imgur.com/rxSHw.jpg)
2020/07/01
[ "https://Stackoverflow.com/questions/62672754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10747925/" ]
I experienced the same issue after upgrading a project to Angular 10. It appears to be an issue with the latest version of Visual Studio 2019 not handling the changes to the tsconfig.json file and the introduction tsconfig.base.json. As a workaround until this is resolved in VS 2019 I copied the contents of tsconfig.base.json up to tsconfig.json and commented out the upgraded config. I now have and file that looks like this and the old functionality is restored ``` /* This is a "Solution Style" tsconfig.json file, and is used by editors and TypeScript’s language server to improve development experience. It is not intended to be used to perform a compilation. To learn more about this file see: https://angular.io/config/solution-tsconfig. removed this as causes vs 2019 to fail - the config details are copied from base so when this is sort we can revert "files": [], "references": [ { "path": "./src/tsconfig.app.json" }, { "path": "./src/tsconfig.spec.json" }, { "path": "./src/tsconfig.server.json" }, { "path": "./e2e/tsconfig.e2e.json" } ] */ { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "module": "esnext", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2017", "dom" ] }, "angularCompilerOptions": { "enableIvy": true } } ```
**Update** This seems to be working in visual studio `16.7.1` --- I faced the same issue when updated to angular 10. It seems to be a [known issue](https://developercommunity.visualstudio.com/comments/1113710/view.html) and the fix is already available in the preview. Until the fix is available to the public, following changes in `tsconfig.json` resolve the issue for me. ``` { "extends": "./tsconfig.base.json" } ```
62,672,754
When I checked the document in the email, I was able to select the Signature design registered in the sand box account. But there is no Signature information in embedded app, so how can I get it? [enter image description here](https://i.stack.imgur.com/rxSHw.jpg)
2020/07/01
[ "https://Stackoverflow.com/questions/62672754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10747925/" ]
**Update** This seems to be working in visual studio `16.7.1` --- I faced the same issue when updated to angular 10. It seems to be a [known issue](https://developercommunity.visualstudio.com/comments/1113710/view.html) and the fix is already available in the preview. Until the fix is available to the public, following changes in `tsconfig.json` resolve the issue for me. ``` { "extends": "./tsconfig.base.json" } ```
I had the exact same problem after I migrated from Angular 9 to Angular 10. I found the following worked for me: **TL;DR** ========= In all the 'project' level tsconfig files (tsconfig.app.json, tsconfig.spec.json, tsconfig.e2e.json) just change the 'extends' property from: ``` { "extends": "../tsconfig.json" ... } ``` To the following: ``` { "extends": "../tsconfig.base.json" ... } ``` **Full Version** ================ Before running `ng update` I had the following structure: ``` ClientApp |_ tsconfig.json |_ src |_ tsconfig.app.json |_ tsconfig.spec.json |_ e2e |_ tsconfig.e2e.json ``` After running `ng update` I had the following structure: ``` ClientApp |_ tsconfig.json |_ tsconfig.base.json |_ src |_ tsconfig.app.json |_ tsconfig.spec.json |_ e2e |_ tsconfig.e2e.json ``` After reading the Angular migration notes I noticed my version of `tsconfig.json` and `tsconfig.base.json` were identical. This still worked but it didn't match what Angular were describing in the notes. So I decided to change my `tsconfig.json. manually to the following: ``` { "files": [], "references": [ { "path": "./src/tsconfig.app.json" }, { "path": "./src/tsconfig.spec.json" }, { "path": "./e2e/tsconfig.e2e.json" } ] } ``` And like everyone else it broke my app. So I had a look at the 'project' level tsconfig files and noticed the 'extends' property was still point to `tsconfig.json` and not to `tsconfig.base.json`. After updating my 'project' level tsconfig files to pointing to the `tsconfig.base.json` file everything just worked. Happy days! :-) I am guessing the `ng update` should "automagically" find and update all the 'project' level tsconfig files but it looks like it doesn't. The fix however is fairly straight forward though. --- Update ====== Although changing extends property did resolve my compilation issues. When I closed and reopened Visual Studio the next day the IntelliSense started to fail. Only by making the `tsconfig.json` to be the same as the `tsconfig.base.json` could I get both the compilation and IntelliSense working.
62,672,756
I am trying to read the value from application.properties in one of the util library Filter we write. My code is as below. ``` public class AuthorizationFilter extends GenericFilterBean { @Value ("${application.identifier}") private String appId; ... } ``` However the value appId is not read from application.properties though it is defined. The issue occurs only with Filter classes. Any pointers on how to fix this?
2020/07/01
[ "https://Stackoverflow.com/questions/62672756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13524846/" ]
I experienced the same issue after upgrading a project to Angular 10. It appears to be an issue with the latest version of Visual Studio 2019 not handling the changes to the tsconfig.json file and the introduction tsconfig.base.json. As a workaround until this is resolved in VS 2019 I copied the contents of tsconfig.base.json up to tsconfig.json and commented out the upgraded config. I now have and file that looks like this and the old functionality is restored ``` /* This is a "Solution Style" tsconfig.json file, and is used by editors and TypeScript’s language server to improve development experience. It is not intended to be used to perform a compilation. To learn more about this file see: https://angular.io/config/solution-tsconfig. removed this as causes vs 2019 to fail - the config details are copied from base so when this is sort we can revert "files": [], "references": [ { "path": "./src/tsconfig.app.json" }, { "path": "./src/tsconfig.spec.json" }, { "path": "./src/tsconfig.server.json" }, { "path": "./e2e/tsconfig.e2e.json" } ] */ { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "module": "esnext", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2017", "dom" ] }, "angularCompilerOptions": { "enableIvy": true } } ```
I had the exact same problem after I migrated from Angular 9 to Angular 10. I found the following worked for me: **TL;DR** ========= In all the 'project' level tsconfig files (tsconfig.app.json, tsconfig.spec.json, tsconfig.e2e.json) just change the 'extends' property from: ``` { "extends": "../tsconfig.json" ... } ``` To the following: ``` { "extends": "../tsconfig.base.json" ... } ``` **Full Version** ================ Before running `ng update` I had the following structure: ``` ClientApp |_ tsconfig.json |_ src |_ tsconfig.app.json |_ tsconfig.spec.json |_ e2e |_ tsconfig.e2e.json ``` After running `ng update` I had the following structure: ``` ClientApp |_ tsconfig.json |_ tsconfig.base.json |_ src |_ tsconfig.app.json |_ tsconfig.spec.json |_ e2e |_ tsconfig.e2e.json ``` After reading the Angular migration notes I noticed my version of `tsconfig.json` and `tsconfig.base.json` were identical. This still worked but it didn't match what Angular were describing in the notes. So I decided to change my `tsconfig.json. manually to the following: ``` { "files": [], "references": [ { "path": "./src/tsconfig.app.json" }, { "path": "./src/tsconfig.spec.json" }, { "path": "./e2e/tsconfig.e2e.json" } ] } ``` And like everyone else it broke my app. So I had a look at the 'project' level tsconfig files and noticed the 'extends' property was still point to `tsconfig.json` and not to `tsconfig.base.json`. After updating my 'project' level tsconfig files to pointing to the `tsconfig.base.json` file everything just worked. Happy days! :-) I am guessing the `ng update` should "automagically" find and update all the 'project' level tsconfig files but it looks like it doesn't. The fix however is fairly straight forward though. --- Update ====== Although changing extends property did resolve my compilation issues. When I closed and reopened Visual Studio the next day the IntelliSense started to fail. Only by making the `tsconfig.json` to be the same as the `tsconfig.base.json` could I get both the compilation and IntelliSense working.
62,672,756
I am trying to read the value from application.properties in one of the util library Filter we write. My code is as below. ``` public class AuthorizationFilter extends GenericFilterBean { @Value ("${application.identifier}") private String appId; ... } ``` However the value appId is not read from application.properties though it is defined. The issue occurs only with Filter classes. Any pointers on how to fix this?
2020/07/01
[ "https://Stackoverflow.com/questions/62672756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13524846/" ]
I experienced the same issue after upgrading a project to Angular 10. It appears to be an issue with the latest version of Visual Studio 2019 not handling the changes to the tsconfig.json file and the introduction tsconfig.base.json. As a workaround until this is resolved in VS 2019 I copied the contents of tsconfig.base.json up to tsconfig.json and commented out the upgraded config. I now have and file that looks like this and the old functionality is restored ``` /* This is a "Solution Style" tsconfig.json file, and is used by editors and TypeScript’s language server to improve development experience. It is not intended to be used to perform a compilation. To learn more about this file see: https://angular.io/config/solution-tsconfig. removed this as causes vs 2019 to fail - the config details are copied from base so when this is sort we can revert "files": [], "references": [ { "path": "./src/tsconfig.app.json" }, { "path": "./src/tsconfig.spec.json" }, { "path": "./src/tsconfig.server.json" }, { "path": "./e2e/tsconfig.e2e.json" } ] */ { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "module": "esnext", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2017", "dom" ] }, "angularCompilerOptions": { "enableIvy": true } } ```
**Update** This seems to be working in visual studio `16.7.1` --- I faced the same issue when updated to angular 10. It seems to be a [known issue](https://developercommunity.visualstudio.com/comments/1113710/view.html) and the fix is already available in the preview. Until the fix is available to the public, following changes in `tsconfig.json` resolve the issue for me. ``` { "extends": "./tsconfig.base.json" } ```
62,672,756
I am trying to read the value from application.properties in one of the util library Filter we write. My code is as below. ``` public class AuthorizationFilter extends GenericFilterBean { @Value ("${application.identifier}") private String appId; ... } ``` However the value appId is not read from application.properties though it is defined. The issue occurs only with Filter classes. Any pointers on how to fix this?
2020/07/01
[ "https://Stackoverflow.com/questions/62672756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13524846/" ]
**Update** This seems to be working in visual studio `16.7.1` --- I faced the same issue when updated to angular 10. It seems to be a [known issue](https://developercommunity.visualstudio.com/comments/1113710/view.html) and the fix is already available in the preview. Until the fix is available to the public, following changes in `tsconfig.json` resolve the issue for me. ``` { "extends": "./tsconfig.base.json" } ```
I had the exact same problem after I migrated from Angular 9 to Angular 10. I found the following worked for me: **TL;DR** ========= In all the 'project' level tsconfig files (tsconfig.app.json, tsconfig.spec.json, tsconfig.e2e.json) just change the 'extends' property from: ``` { "extends": "../tsconfig.json" ... } ``` To the following: ``` { "extends": "../tsconfig.base.json" ... } ``` **Full Version** ================ Before running `ng update` I had the following structure: ``` ClientApp |_ tsconfig.json |_ src |_ tsconfig.app.json |_ tsconfig.spec.json |_ e2e |_ tsconfig.e2e.json ``` After running `ng update` I had the following structure: ``` ClientApp |_ tsconfig.json |_ tsconfig.base.json |_ src |_ tsconfig.app.json |_ tsconfig.spec.json |_ e2e |_ tsconfig.e2e.json ``` After reading the Angular migration notes I noticed my version of `tsconfig.json` and `tsconfig.base.json` were identical. This still worked but it didn't match what Angular were describing in the notes. So I decided to change my `tsconfig.json. manually to the following: ``` { "files": [], "references": [ { "path": "./src/tsconfig.app.json" }, { "path": "./src/tsconfig.spec.json" }, { "path": "./e2e/tsconfig.e2e.json" } ] } ``` And like everyone else it broke my app. So I had a look at the 'project' level tsconfig files and noticed the 'extends' property was still point to `tsconfig.json` and not to `tsconfig.base.json`. After updating my 'project' level tsconfig files to pointing to the `tsconfig.base.json` file everything just worked. Happy days! :-) I am guessing the `ng update` should "automagically" find and update all the 'project' level tsconfig files but it looks like it doesn't. The fix however is fairly straight forward though. --- Update ====== Although changing extends property did resolve my compilation issues. When I closed and reopened Visual Studio the next day the IntelliSense started to fail. Only by making the `tsconfig.json` to be the same as the `tsconfig.base.json` could I get both the compilation and IntelliSense working.
62,672,772
I'm having troubles figuring how to make a circle doodle(like a hand drawn sketch) appear on a link when hovered. In a perfect world it should be an animated svg path, but at this point just to appear works for me. Here is what exactly I'm trying to achieve: [![enter image description here](https://i.stack.imgur.com/OH1Sz.jpg)](https://i.stack.imgur.com/OH1Sz.jpg) I've tried with background-image set to opacity:0 and when hover on opacity:1, but the issue is that when the link is longer the background image doesn't cover it all. Also I've tried with borders, but then I can't add a custom border shape, to look like a circle sketch you do with a pen. Here is an example I found online: [click here](https://elementor.com/blog/introducing-animated-headline/) , the "Circle Me" example, under "Highlighted headlines" I hope that this all makes sense, Thank you!
2020/07/01
[ "https://Stackoverflow.com/questions/62672772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2013488/" ]
You can learn how to do that by using Chrome DevTools or other similars from your reference site. ```html <div class='button'> <button>Click Me</button> <svg preserveAspectRatio="none"> <path fill="none" d="..." /> </svg> </div> ``` ```css .button { position: relative; display: inline-block; cursor: pointer; } .button button { padding: 8px 16px; border: none; background: none; outline: none; } .button svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; } .button path { stroke: #db3157; stroke-width: 8px; stroke-dasharray: 0 1500; } .button:hover path { animation: draw 1s forwards; } @keyframes draw { from { stroke-dasharray: 0 1500; } to { stroke-dasharray: 1500 1500; } } ``` Example on [JSFiddle](https://jsfiddle.net/mjwkyc5o/)
**HTMl** ``` <html> <head> <style> </style> </head> <body> <a href="#" class="circle">Test</a> </body> </html> ``` **CSS** ``` .circle{ width:50px; height:50px; padding: 4em 4em; } .circle:hover { border-radius: 100%; background: green; display:inline-block; line-height:100px; width:50px; height:50px; } ``` Just try this and let me know if it is working for you. I wanted to help you.
62,672,775
I got this number `1.12412` and I want to `round it to 1.12415` or `1.12410 (muliple of 5 in last decimal)` If using the `Round(X,4)` function I get `1.1241 (4 decimals)`. Is there a function that can make that happen? Thanks! There is an answer in stack but using c# not python
2020/07/01
[ "https://Stackoverflow.com/questions/62672775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10467327/" ]
My way to do that is to specify rounding unit first and then simple trick as below: ``` import numpy as np rounding_unit = 0.00005 np.round(1.12412/rounding_unit) * rounding_unit ```
You may: 1. Multiply your number by 2 2. Use `Round(X,4)` 3. Divide the result by 2 4. profit!!!
62,672,809
Consider the following code: ``` ConcurrentHashMap<String, Value> map = new ConcurrentHashMap<>(); boolean foo(String key) { Value value = map.get(key); if (value == null) { value = map.putIfAbsent(key, new Value()); if (value == null) { // do some stuff return true; } } // do some other stuff return false; } ``` Assume that `foo()` is called by multiple threads concurrently. Also assume that calling `new Value()` is expensive. The code is verbose and can still result in redundant `Value` objects created. Can the above logic be implemented in a way that guarantees no redundant `Value` objects are created (i.e. `new Value()` is called at most once)? I'm looking for a clean implementation- minimal code without acquiring locks explicitly. `computeIfAbsent` could have been a good alternative, however its return semantics are not in line with the required logic.
2020/07/01
[ "https://Stackoverflow.com/questions/62672809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3525027/" ]
One solution is to store `Future<Value>` instead of `Value` in the map: ``` ConcurrentHashMap<String, Future<Value>> map = new ConcurrentHashMap<>(); boolean foo(String key) { Future<Value> value = map.get(key); if (value == null) { value = map.putIfAbsent(key, new FutureTask<Value>(() -> new Value())); if (value == null) { // do some stuff return true; } } // do some other stuff return false; } ``` You can access the underlying value by calling `value.get()`, which will block until the computation is complete. There is a chance that more than one FutureTask is created, but only one will reach the map and only one computation of `new Value()` will be done.
First let's fix the fact that you are not acting atomically, and do a needless look-up. Two threads could both simultaneously pass the first `value == null` check. Not really a problem now (except 2 `Value`s will be created, which is slow), but a bug waiting to happen if someone adds an else clause to the second `value == null` check. It's cleaner this way too. ``` boolean foo(String key) { Value value = map.putIfAbsent(key, new Value()); if (value == null) { // do some stuff return true; } else { // do some other stuff return false; } } ``` Now let's address the fact that `Value` creation is slow (sounds like you are abusing constructor, but anyway). ``` boolean foo(String key) { final AtomicBoolean wasCreated = new AtomicBoolean(false); final Value value = map.computeIfAbsent(key, k -> { wasCreated.set(true); return new Value(); }); if (wasCreated.get()) { // do some stuff return true; } else { // do some other stuff return false; } } ```
62,672,809
Consider the following code: ``` ConcurrentHashMap<String, Value> map = new ConcurrentHashMap<>(); boolean foo(String key) { Value value = map.get(key); if (value == null) { value = map.putIfAbsent(key, new Value()); if (value == null) { // do some stuff return true; } } // do some other stuff return false; } ``` Assume that `foo()` is called by multiple threads concurrently. Also assume that calling `new Value()` is expensive. The code is verbose and can still result in redundant `Value` objects created. Can the above logic be implemented in a way that guarantees no redundant `Value` objects are created (i.e. `new Value()` is called at most once)? I'm looking for a clean implementation- minimal code without acquiring locks explicitly. `computeIfAbsent` could have been a good alternative, however its return semantics are not in line with the required logic.
2020/07/01
[ "https://Stackoverflow.com/questions/62672809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3525027/" ]
Some minimal code that does the job: ``` boolean foo(String key) { AtomicBoolean flag = new AtomicBoolean(); Value value = map.computeIfAbsent(key, k -> {flag.set(true); return new Value();}); if (flag.get()) { // do some stuff } else { // do some other stuff } return flag.get(); } ```
First let's fix the fact that you are not acting atomically, and do a needless look-up. Two threads could both simultaneously pass the first `value == null` check. Not really a problem now (except 2 `Value`s will be created, which is slow), but a bug waiting to happen if someone adds an else clause to the second `value == null` check. It's cleaner this way too. ``` boolean foo(String key) { Value value = map.putIfAbsent(key, new Value()); if (value == null) { // do some stuff return true; } else { // do some other stuff return false; } } ``` Now let's address the fact that `Value` creation is slow (sounds like you are abusing constructor, but anyway). ``` boolean foo(String key) { final AtomicBoolean wasCreated = new AtomicBoolean(false); final Value value = map.computeIfAbsent(key, k -> { wasCreated.set(true); return new Value(); }); if (wasCreated.get()) { // do some stuff return true; } else { // do some other stuff return false; } } ```
62,672,809
Consider the following code: ``` ConcurrentHashMap<String, Value> map = new ConcurrentHashMap<>(); boolean foo(String key) { Value value = map.get(key); if (value == null) { value = map.putIfAbsent(key, new Value()); if (value == null) { // do some stuff return true; } } // do some other stuff return false; } ``` Assume that `foo()` is called by multiple threads concurrently. Also assume that calling `new Value()` is expensive. The code is verbose and can still result in redundant `Value` objects created. Can the above logic be implemented in a way that guarantees no redundant `Value` objects are created (i.e. `new Value()` is called at most once)? I'm looking for a clean implementation- minimal code without acquiring locks explicitly. `computeIfAbsent` could have been a good alternative, however its return semantics are not in line with the required logic.
2020/07/01
[ "https://Stackoverflow.com/questions/62672809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3525027/" ]
First let's fix the fact that you are not acting atomically, and do a needless look-up. Two threads could both simultaneously pass the first `value == null` check. Not really a problem now (except 2 `Value`s will be created, which is slow), but a bug waiting to happen if someone adds an else clause to the second `value == null` check. It's cleaner this way too. ``` boolean foo(String key) { Value value = map.putIfAbsent(key, new Value()); if (value == null) { // do some stuff return true; } else { // do some other stuff return false; } } ``` Now let's address the fact that `Value` creation is slow (sounds like you are abusing constructor, but anyway). ``` boolean foo(String key) { final AtomicBoolean wasCreated = new AtomicBoolean(false); final Value value = map.computeIfAbsent(key, k -> { wasCreated.set(true); return new Value(); }); if (wasCreated.get()) { // do some stuff return true; } else { // do some other stuff return false; } } ```
Consider your method `foo` ( which is literally a wrapper for putIfAbsent ). ``` String key = "test"; if(foo(key)){ //Positive Branch. } else{ //Negative Branch. } ``` Now, in a multi-threaded environment, thread A calls and completes foo and adds a new value. It is going down the Positive branch. Before it enters the Positive branch, it gets scheduled for later. Thread B calls and completes foo, it continues executing and goes down the Negative branch. The Negative branch is getting executed before the Positive branch, which in my mind is not wanted. In your particular case it might be OK. `compute` might be a better replacement. ``` map.compute( key, ( k, old ) -> { if(old==null){ Value v = new Value(); //positive branch. return v; } else{ //negative branch. return old; } }); ``` Now you would be acting atomically on whether or not the value exists.
62,672,809
Consider the following code: ``` ConcurrentHashMap<String, Value> map = new ConcurrentHashMap<>(); boolean foo(String key) { Value value = map.get(key); if (value == null) { value = map.putIfAbsent(key, new Value()); if (value == null) { // do some stuff return true; } } // do some other stuff return false; } ``` Assume that `foo()` is called by multiple threads concurrently. Also assume that calling `new Value()` is expensive. The code is verbose and can still result in redundant `Value` objects created. Can the above logic be implemented in a way that guarantees no redundant `Value` objects are created (i.e. `new Value()` is called at most once)? I'm looking for a clean implementation- minimal code without acquiring locks explicitly. `computeIfAbsent` could have been a good alternative, however its return semantics are not in line with the required logic.
2020/07/01
[ "https://Stackoverflow.com/questions/62672809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3525027/" ]
One solution is to store `Future<Value>` instead of `Value` in the map: ``` ConcurrentHashMap<String, Future<Value>> map = new ConcurrentHashMap<>(); boolean foo(String key) { Future<Value> value = map.get(key); if (value == null) { value = map.putIfAbsent(key, new FutureTask<Value>(() -> new Value())); if (value == null) { // do some stuff return true; } } // do some other stuff return false; } ``` You can access the underlying value by calling `value.get()`, which will block until the computation is complete. There is a chance that more than one FutureTask is created, but only one will reach the map and only one computation of `new Value()` will be done.
One way is to use local state and update it in `computeIfAbsent`'s mapping function: ``` boolean foo(String key) { boolean[] b = { false }; map.computeIfAbsent(key, k -> { // do some stuff b[0] = true; return new Value(); }); return b[0]; } ``` Because `mappingFunction` is only run if the key is not present in the map, you can guarantee that the heavy `new Value()` is only called when necessary and that the return value is set to `true` only when there was no mapping before the call.
62,672,809
Consider the following code: ``` ConcurrentHashMap<String, Value> map = new ConcurrentHashMap<>(); boolean foo(String key) { Value value = map.get(key); if (value == null) { value = map.putIfAbsent(key, new Value()); if (value == null) { // do some stuff return true; } } // do some other stuff return false; } ``` Assume that `foo()` is called by multiple threads concurrently. Also assume that calling `new Value()` is expensive. The code is verbose and can still result in redundant `Value` objects created. Can the above logic be implemented in a way that guarantees no redundant `Value` objects are created (i.e. `new Value()` is called at most once)? I'm looking for a clean implementation- minimal code without acquiring locks explicitly. `computeIfAbsent` could have been a good alternative, however its return semantics are not in line with the required logic.
2020/07/01
[ "https://Stackoverflow.com/questions/62672809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3525027/" ]
Some minimal code that does the job: ``` boolean foo(String key) { AtomicBoolean flag = new AtomicBoolean(); Value value = map.computeIfAbsent(key, k -> {flag.set(true); return new Value();}); if (flag.get()) { // do some stuff } else { // do some other stuff } return flag.get(); } ```
One way is to use local state and update it in `computeIfAbsent`'s mapping function: ``` boolean foo(String key) { boolean[] b = { false }; map.computeIfAbsent(key, k -> { // do some stuff b[0] = true; return new Value(); }); return b[0]; } ``` Because `mappingFunction` is only run if the key is not present in the map, you can guarantee that the heavy `new Value()` is only called when necessary and that the return value is set to `true` only when there was no mapping before the call.
62,672,809
Consider the following code: ``` ConcurrentHashMap<String, Value> map = new ConcurrentHashMap<>(); boolean foo(String key) { Value value = map.get(key); if (value == null) { value = map.putIfAbsent(key, new Value()); if (value == null) { // do some stuff return true; } } // do some other stuff return false; } ``` Assume that `foo()` is called by multiple threads concurrently. Also assume that calling `new Value()` is expensive. The code is verbose and can still result in redundant `Value` objects created. Can the above logic be implemented in a way that guarantees no redundant `Value` objects are created (i.e. `new Value()` is called at most once)? I'm looking for a clean implementation- minimal code without acquiring locks explicitly. `computeIfAbsent` could have been a good alternative, however its return semantics are not in line with the required logic.
2020/07/01
[ "https://Stackoverflow.com/questions/62672809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3525027/" ]
One way is to use local state and update it in `computeIfAbsent`'s mapping function: ``` boolean foo(String key) { boolean[] b = { false }; map.computeIfAbsent(key, k -> { // do some stuff b[0] = true; return new Value(); }); return b[0]; } ``` Because `mappingFunction` is only run if the key is not present in the map, you can guarantee that the heavy `new Value()` is only called when necessary and that the return value is set to `true` only when there was no mapping before the call.
Consider your method `foo` ( which is literally a wrapper for putIfAbsent ). ``` String key = "test"; if(foo(key)){ //Positive Branch. } else{ //Negative Branch. } ``` Now, in a multi-threaded environment, thread A calls and completes foo and adds a new value. It is going down the Positive branch. Before it enters the Positive branch, it gets scheduled for later. Thread B calls and completes foo, it continues executing and goes down the Negative branch. The Negative branch is getting executed before the Positive branch, which in my mind is not wanted. In your particular case it might be OK. `compute` might be a better replacement. ``` map.compute( key, ( k, old ) -> { if(old==null){ Value v = new Value(); //positive branch. return v; } else{ //negative branch. return old; } }); ``` Now you would be acting atomically on whether or not the value exists.
62,672,809
Consider the following code: ``` ConcurrentHashMap<String, Value> map = new ConcurrentHashMap<>(); boolean foo(String key) { Value value = map.get(key); if (value == null) { value = map.putIfAbsent(key, new Value()); if (value == null) { // do some stuff return true; } } // do some other stuff return false; } ``` Assume that `foo()` is called by multiple threads concurrently. Also assume that calling `new Value()` is expensive. The code is verbose and can still result in redundant `Value` objects created. Can the above logic be implemented in a way that guarantees no redundant `Value` objects are created (i.e. `new Value()` is called at most once)? I'm looking for a clean implementation- minimal code without acquiring locks explicitly. `computeIfAbsent` could have been a good alternative, however its return semantics are not in line with the required logic.
2020/07/01
[ "https://Stackoverflow.com/questions/62672809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3525027/" ]
One solution is to store `Future<Value>` instead of `Value` in the map: ``` ConcurrentHashMap<String, Future<Value>> map = new ConcurrentHashMap<>(); boolean foo(String key) { Future<Value> value = map.get(key); if (value == null) { value = map.putIfAbsent(key, new FutureTask<Value>(() -> new Value())); if (value == null) { // do some stuff return true; } } // do some other stuff return false; } ``` You can access the underlying value by calling `value.get()`, which will block until the computation is complete. There is a chance that more than one FutureTask is created, but only one will reach the map and only one computation of `new Value()` will be done.
Consider your method `foo` ( which is literally a wrapper for putIfAbsent ). ``` String key = "test"; if(foo(key)){ //Positive Branch. } else{ //Negative Branch. } ``` Now, in a multi-threaded environment, thread A calls and completes foo and adds a new value. It is going down the Positive branch. Before it enters the Positive branch, it gets scheduled for later. Thread B calls and completes foo, it continues executing and goes down the Negative branch. The Negative branch is getting executed before the Positive branch, which in my mind is not wanted. In your particular case it might be OK. `compute` might be a better replacement. ``` map.compute( key, ( k, old ) -> { if(old==null){ Value v = new Value(); //positive branch. return v; } else{ //negative branch. return old; } }); ``` Now you would be acting atomically on whether or not the value exists.
62,672,809
Consider the following code: ``` ConcurrentHashMap<String, Value> map = new ConcurrentHashMap<>(); boolean foo(String key) { Value value = map.get(key); if (value == null) { value = map.putIfAbsent(key, new Value()); if (value == null) { // do some stuff return true; } } // do some other stuff return false; } ``` Assume that `foo()` is called by multiple threads concurrently. Also assume that calling `new Value()` is expensive. The code is verbose and can still result in redundant `Value` objects created. Can the above logic be implemented in a way that guarantees no redundant `Value` objects are created (i.e. `new Value()` is called at most once)? I'm looking for a clean implementation- minimal code without acquiring locks explicitly. `computeIfAbsent` could have been a good alternative, however its return semantics are not in line with the required logic.
2020/07/01
[ "https://Stackoverflow.com/questions/62672809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3525027/" ]
Some minimal code that does the job: ``` boolean foo(String key) { AtomicBoolean flag = new AtomicBoolean(); Value value = map.computeIfAbsent(key, k -> {flag.set(true); return new Value();}); if (flag.get()) { // do some stuff } else { // do some other stuff } return flag.get(); } ```
Consider your method `foo` ( which is literally a wrapper for putIfAbsent ). ``` String key = "test"; if(foo(key)){ //Positive Branch. } else{ //Negative Branch. } ``` Now, in a multi-threaded environment, thread A calls and completes foo and adds a new value. It is going down the Positive branch. Before it enters the Positive branch, it gets scheduled for later. Thread B calls and completes foo, it continues executing and goes down the Negative branch. The Negative branch is getting executed before the Positive branch, which in my mind is not wanted. In your particular case it might be OK. `compute` might be a better replacement. ``` map.compute( key, ( k, old ) -> { if(old==null){ Value v = new Value(); //positive branch. return v; } else{ //negative branch. return old; } }); ``` Now you would be acting atomically on whether or not the value exists.
62,672,824
I have a problem using Pandas. When I execute `autos.info()` it returns: ``` RangeIndex: 371528 entries, 0 to 371527 Data columns (total 20 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 dateCrawled 371528 non-null object 1 name 371528 non-null object 2 seller 371528 non-null object 3 offerType 371528 non-null object 4 price 371528 non-null int64 5 abtest 371528 non-null object 6 vehicleType 333659 non-null object 7 yearOfRegistration 371528 non-null int64 8 gearbox 351319 non-null object 9 powerPS 371528 non-null int64 10 model 351044 non-null object 11 kilometer 371528 non-null int64 12 monthOfRegistration 371528 non-null int64 13 fuelType 338142 non-null object 14 brand 371528 non-null object 15 notRepairedDamage 299468 non-null object 16 dateCreated 371528 non-null object 17 nrOfPictures 371528 non-null int64 18 postalCode 371528 non-null int64 19 lastSeen 371528 non-null object dtypes: int64(7), object(13) memory usage: 56.7+ MB ``` But when I execute `autos["price"].describe()` it returns: ``` count 3.715280e+05 mean 1.729514e+04 std 3.587954e+06 min 0.000000e+00 25% 1.150000e+03 50% 2.950000e+03 75% 7.200000e+03 max 2.147484e+09 Name: price, dtype: float64 ``` I don't understand why there is this type incongruence between the type of the column price. Any suggestions?
2020/07/01
[ "https://Stackoverflow.com/questions/62672824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8632130/" ]
The return value of `Series.describe()` is a Series with the descriptive statistics. The `dtype` you see in the Series is **not** the `dtype` of the original column but the `dtype` of the statistics - which is `float`. The `name` of the result is `price` because that is set as the name of the Series `autos["price"]`.
If I control the number of display digits, will I get the data I want? ``` pd.set_option('display.float_format', lambda x: '%.5f' % x) df['X'].describe().apply("{0:.5f}".format) ```
62,672,828
I'm using angular date range picker and getting a issue: Can't bind to 'rangePicker' since it isn't a known property of 'mat-date-range-input'. 1. If 'mat-date-range-input' is an Angular component and it has 'rangePicker' input, then verify that it is part of this module. 2. If 'mat-date-range-input' is a Web Component then add 'CUSTOM\_ELEMENTS\_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. I have added imports, exports, providers in app.module.ts too: ``` imports: [ MatNativeDateModule, MatDatepickerModule, FormsModule, ReactiveFormsModule ], exports:[ MatDatepickerModule, MatNativeDateModule ], providers: [ MatDatepickerModule, MatNativeDateModule, ] ``` date range picker in html: ``` <mat-form-field appearance="fill"> <mat-label>Enter a date range</mat-label> <mat-date-range-input [rangePicker]="picker"> <input matStartDate placeholder="Start date"> <input matEndDate placeholder="End date"> </mat-date-range-input> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-date-range-picker #picker></mat-date-range-picker> </mat-form-field> ``` Should I add any thing else in module.ts?
2020/07/01
[ "https://Stackoverflow.com/questions/62672828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12113049/" ]
As I understand you have to have @angular/material": "^10.0.2 - not older
Indeed, I would suggest you check both @angular/material and other @angular packages like: cdk, common, compiler, core... Check if the versions match to the 10.y.z. I had the same problem and all I needed to do was to update to the version 10.y.z of each package.
62,672,828
I'm using angular date range picker and getting a issue: Can't bind to 'rangePicker' since it isn't a known property of 'mat-date-range-input'. 1. If 'mat-date-range-input' is an Angular component and it has 'rangePicker' input, then verify that it is part of this module. 2. If 'mat-date-range-input' is a Web Component then add 'CUSTOM\_ELEMENTS\_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. I have added imports, exports, providers in app.module.ts too: ``` imports: [ MatNativeDateModule, MatDatepickerModule, FormsModule, ReactiveFormsModule ], exports:[ MatDatepickerModule, MatNativeDateModule ], providers: [ MatDatepickerModule, MatNativeDateModule, ] ``` date range picker in html: ``` <mat-form-field appearance="fill"> <mat-label>Enter a date range</mat-label> <mat-date-range-input [rangePicker]="picker"> <input matStartDate placeholder="Start date"> <input matEndDate placeholder="End date"> </mat-date-range-input> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-date-range-picker #picker></mat-date-range-picker> </mat-form-field> ``` Should I add any thing else in module.ts?
2020/07/01
[ "https://Stackoverflow.com/questions/62672828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12113049/" ]
As I understand you have to have @angular/material": "^10.0.2 - not older
I have the same problem and it has been fixed after updating the dependency as below. package.json ``` "dependencies": { "@angular/animations": "~10.1.3", "@angular/cdk": "^10.2.3", "@angular/common": "~10.1.3", "@angular/compiler": "~10.1.3", "@angular/core": "~10.1.3", "@angular/forms": "~10.1.3", "@angular/material": "^10.2.3", "@angular/platform-browser": "~10.1.3", "@angular/platform-browser-dynamic": "~10.1.3", "@angular/router": "~10.1.3", "hammerjs": "^2.0.8", "rxjs": "~6.4.0", "tslib": "^1.10.0", "zone.js": "~0.9.1" }, "devDependencies": { "@angular-devkit/build-angular": "~0.1001.3", "@angular/cli": "~10.1.3", "@angular/compiler-cli": "~10.1.3", "@types/node": "^12.11.1", "@types/jasmine": "~3.5.0", "@types/jasminewd2": "~2.0.3", "codelyzer": "^6.0.0", "jasmine-core": "~3.6.0", "jasmine-spec-reporter": "~5.0.0", "karma": "~5.0.0", "karma-chrome-launcher": "~3.1.0", "karma-coverage-istanbul-reporter": "~3.0.2", "karma-jasmine": "~4.0.0", "karma-jasmine-html-reporter": "^1.5.0", "protractor": "~7.0.0", "ts-node": "~8.3.0", "tslint": "~6.1.0", "typescript": "~4.0.2" } ``` Be sure to remove the node module and reinstall it after the dependency update.
62,672,828
I'm using angular date range picker and getting a issue: Can't bind to 'rangePicker' since it isn't a known property of 'mat-date-range-input'. 1. If 'mat-date-range-input' is an Angular component and it has 'rangePicker' input, then verify that it is part of this module. 2. If 'mat-date-range-input' is a Web Component then add 'CUSTOM\_ELEMENTS\_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. I have added imports, exports, providers in app.module.ts too: ``` imports: [ MatNativeDateModule, MatDatepickerModule, FormsModule, ReactiveFormsModule ], exports:[ MatDatepickerModule, MatNativeDateModule ], providers: [ MatDatepickerModule, MatNativeDateModule, ] ``` date range picker in html: ``` <mat-form-field appearance="fill"> <mat-label>Enter a date range</mat-label> <mat-date-range-input [rangePicker]="picker"> <input matStartDate placeholder="Start date"> <input matEndDate placeholder="End date"> </mat-date-range-input> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-date-range-picker #picker></mat-date-range-picker> </mat-form-field> ``` Should I add any thing else in module.ts?
2020/07/01
[ "https://Stackoverflow.com/questions/62672828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12113049/" ]
Indeed, I would suggest you check both @angular/material and other @angular packages like: cdk, common, compiler, core... Check if the versions match to the 10.y.z. I had the same problem and all I needed to do was to update to the version 10.y.z of each package.
I have the same problem and it has been fixed after updating the dependency as below. package.json ``` "dependencies": { "@angular/animations": "~10.1.3", "@angular/cdk": "^10.2.3", "@angular/common": "~10.1.3", "@angular/compiler": "~10.1.3", "@angular/core": "~10.1.3", "@angular/forms": "~10.1.3", "@angular/material": "^10.2.3", "@angular/platform-browser": "~10.1.3", "@angular/platform-browser-dynamic": "~10.1.3", "@angular/router": "~10.1.3", "hammerjs": "^2.0.8", "rxjs": "~6.4.0", "tslib": "^1.10.0", "zone.js": "~0.9.1" }, "devDependencies": { "@angular-devkit/build-angular": "~0.1001.3", "@angular/cli": "~10.1.3", "@angular/compiler-cli": "~10.1.3", "@types/node": "^12.11.1", "@types/jasmine": "~3.5.0", "@types/jasminewd2": "~2.0.3", "codelyzer": "^6.0.0", "jasmine-core": "~3.6.0", "jasmine-spec-reporter": "~5.0.0", "karma": "~5.0.0", "karma-chrome-launcher": "~3.1.0", "karma-coverage-istanbul-reporter": "~3.0.2", "karma-jasmine": "~4.0.0", "karma-jasmine-html-reporter": "^1.5.0", "protractor": "~7.0.0", "ts-node": "~8.3.0", "tslint": "~6.1.0", "typescript": "~4.0.2" } ``` Be sure to remove the node module and reinstall it after the dependency update.
62,672,842
I'm working on predicting if any task breaches a given deadline or not(Binary Classification Problem) I've used Logistic Regression, Random Forest and XGBoost. All of them give an F1 score of around 56% for the class label 1(i.e the F1 score of the positive class only). I've used: * StandardScaler() * GridSearchCV for Hyperparameter Tuning * Recursive Feature Elimination(for feature selection) * SMOTE(the dataset is imbalanced so I used SMOTE to create new examples from existing examples) to try and improve the F score of this model. I've also created an ensemble model using `EnsembleVoteClassifier`.As you can see from the picture, the weighted F score is 94% however the F score for class 1 (i.e positive class which says that the task will cross the deadline) is just 57%. [![enter image description here](https://i.stack.imgur.com/vMVQd.png)](https://i.stack.imgur.com/vMVQd.png) After applying all those methods mentioned above, I have been able to improve the f1 score of label 1 from 6% to 57%. However, I'm not sure what else to do to further improve the F score of the label 1.
2020/07/01
[ "https://Stackoverflow.com/questions/62672842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11911694/" ]
As I understand you have to have @angular/material": "^10.0.2 - not older
Indeed, I would suggest you check both @angular/material and other @angular packages like: cdk, common, compiler, core... Check if the versions match to the 10.y.z. I had the same problem and all I needed to do was to update to the version 10.y.z of each package.
62,672,842
I'm working on predicting if any task breaches a given deadline or not(Binary Classification Problem) I've used Logistic Regression, Random Forest and XGBoost. All of them give an F1 score of around 56% for the class label 1(i.e the F1 score of the positive class only). I've used: * StandardScaler() * GridSearchCV for Hyperparameter Tuning * Recursive Feature Elimination(for feature selection) * SMOTE(the dataset is imbalanced so I used SMOTE to create new examples from existing examples) to try and improve the F score of this model. I've also created an ensemble model using `EnsembleVoteClassifier`.As you can see from the picture, the weighted F score is 94% however the F score for class 1 (i.e positive class which says that the task will cross the deadline) is just 57%. [![enter image description here](https://i.stack.imgur.com/vMVQd.png)](https://i.stack.imgur.com/vMVQd.png) After applying all those methods mentioned above, I have been able to improve the f1 score of label 1 from 6% to 57%. However, I'm not sure what else to do to further improve the F score of the label 1.
2020/07/01
[ "https://Stackoverflow.com/questions/62672842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11911694/" ]
As I understand you have to have @angular/material": "^10.0.2 - not older
I have the same problem and it has been fixed after updating the dependency as below. package.json ``` "dependencies": { "@angular/animations": "~10.1.3", "@angular/cdk": "^10.2.3", "@angular/common": "~10.1.3", "@angular/compiler": "~10.1.3", "@angular/core": "~10.1.3", "@angular/forms": "~10.1.3", "@angular/material": "^10.2.3", "@angular/platform-browser": "~10.1.3", "@angular/platform-browser-dynamic": "~10.1.3", "@angular/router": "~10.1.3", "hammerjs": "^2.0.8", "rxjs": "~6.4.0", "tslib": "^1.10.0", "zone.js": "~0.9.1" }, "devDependencies": { "@angular-devkit/build-angular": "~0.1001.3", "@angular/cli": "~10.1.3", "@angular/compiler-cli": "~10.1.3", "@types/node": "^12.11.1", "@types/jasmine": "~3.5.0", "@types/jasminewd2": "~2.0.3", "codelyzer": "^6.0.0", "jasmine-core": "~3.6.0", "jasmine-spec-reporter": "~5.0.0", "karma": "~5.0.0", "karma-chrome-launcher": "~3.1.0", "karma-coverage-istanbul-reporter": "~3.0.2", "karma-jasmine": "~4.0.0", "karma-jasmine-html-reporter": "^1.5.0", "protractor": "~7.0.0", "ts-node": "~8.3.0", "tslint": "~6.1.0", "typescript": "~4.0.2" } ``` Be sure to remove the node module and reinstall it after the dependency update.
62,672,842
I'm working on predicting if any task breaches a given deadline or not(Binary Classification Problem) I've used Logistic Regression, Random Forest and XGBoost. All of them give an F1 score of around 56% for the class label 1(i.e the F1 score of the positive class only). I've used: * StandardScaler() * GridSearchCV for Hyperparameter Tuning * Recursive Feature Elimination(for feature selection) * SMOTE(the dataset is imbalanced so I used SMOTE to create new examples from existing examples) to try and improve the F score of this model. I've also created an ensemble model using `EnsembleVoteClassifier`.As you can see from the picture, the weighted F score is 94% however the F score for class 1 (i.e positive class which says that the task will cross the deadline) is just 57%. [![enter image description here](https://i.stack.imgur.com/vMVQd.png)](https://i.stack.imgur.com/vMVQd.png) After applying all those methods mentioned above, I have been able to improve the f1 score of label 1 from 6% to 57%. However, I'm not sure what else to do to further improve the F score of the label 1.
2020/07/01
[ "https://Stackoverflow.com/questions/62672842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11911694/" ]
Indeed, I would suggest you check both @angular/material and other @angular packages like: cdk, common, compiler, core... Check if the versions match to the 10.y.z. I had the same problem and all I needed to do was to update to the version 10.y.z of each package.
I have the same problem and it has been fixed after updating the dependency as below. package.json ``` "dependencies": { "@angular/animations": "~10.1.3", "@angular/cdk": "^10.2.3", "@angular/common": "~10.1.3", "@angular/compiler": "~10.1.3", "@angular/core": "~10.1.3", "@angular/forms": "~10.1.3", "@angular/material": "^10.2.3", "@angular/platform-browser": "~10.1.3", "@angular/platform-browser-dynamic": "~10.1.3", "@angular/router": "~10.1.3", "hammerjs": "^2.0.8", "rxjs": "~6.4.0", "tslib": "^1.10.0", "zone.js": "~0.9.1" }, "devDependencies": { "@angular-devkit/build-angular": "~0.1001.3", "@angular/cli": "~10.1.3", "@angular/compiler-cli": "~10.1.3", "@types/node": "^12.11.1", "@types/jasmine": "~3.5.0", "@types/jasminewd2": "~2.0.3", "codelyzer": "^6.0.0", "jasmine-core": "~3.6.0", "jasmine-spec-reporter": "~5.0.0", "karma": "~5.0.0", "karma-chrome-launcher": "~3.1.0", "karma-coverage-istanbul-reporter": "~3.0.2", "karma-jasmine": "~4.0.0", "karma-jasmine-html-reporter": "^1.5.0", "protractor": "~7.0.0", "ts-node": "~8.3.0", "tslint": "~6.1.0", "typescript": "~4.0.2" } ``` Be sure to remove the node module and reinstall it after the dependency update.
62,672,857
I created a Maven project on IntelliJ and it runs correctly. Now, I would like to launch my project with Docker and without using IntelliJ. I used this command to launch my project : `docker run -it --rm --name my-maven-project -v /var/www/html/Recommandation:/usr/src/mymaven -p 88:88 -w /usr/src/mymaven maven:latest mvn clean install` It comes from the Maven Docker Hub : <https://hub.docker.com/_/maven/> With this command, the project is built but does not run. So I add this at the end : `docker run -it --rm --name my-maven-project -v /var/www/html/Recommandation/:/usr/src/mymaven -p 88:88 -w /usr/src/mymaven maven:latest mvn clean install java target/Recommandation-1.0-SNAPSHOT.jar org.exemple.demo.App` But now, the project is no longer being built: ```sh [INFO] ------------------< org.exemple.demo:Recommandation >------------------- [INFO] Building Recommandation 1.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 0.201 s [INFO] Finished at: 2020-07-01T08:28:09Z [INFO] ------------------------------------------------------------------------ [ERROR] Unknown lifecycle phase "java". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException ``` Here my pom.xml : ```xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.exemple.demo</groupId> <artifactId>Recommandation</artifactId> <version>1.0-SNAPSHOT</version> <build> <defaultGoal>install</defaultGoal> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> <configuration> <archive> <manifest> <mainClass>org.exemple.demo.App</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build> <packaging>jar</packaging> <name>Recommandation</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>7</maven.compiler.source> <maven.compiler.target>7</maven.compiler.target> </properties> <dependencies> ... </dependencies> </project> ``` Can you tell me how to properly execute my Maven project through Docker? I did not find any information to solve this problem by myself. --- Edit ---- Indeed I have already tried with && but I have the impression that because of this, it is the host who executes the command and not the container. Something like this is happening : ```sh $ docker run -it --rm --name my-maven-project -v /var/www/html/Recommandation/:/usr/src/mymaven -p 88:88 -w /usr/src/mymaven maven:latest mvn clean install $ java target/Recommandation-1.0-SNAPSHOT.jar org.exemple.demo.App ``` `Error: unable to find or load main class target.Recommandation-1.0-SNAPSHOT.jar` This is the same problem with `;` I also tried this : `docker run -it --rm --name my-maven-project -v /var/www/html/Recommandation/:/usr/src/mymaven -p 88:88 -w /usr/src/mymaven maven:latest bash -c "mvn clean install && java target/Recommandation-1.0-SNAPSHOT.jar org.exemple.demo.App"` ```sh [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 41.383 s [INFO] Finished at: 2020-07-01T10:33:16Z [INFO] ------------------------------------------------------------------------ Error: Could not find or load main class target.Recommandation-1.0-SNAPSHOT.jar Caused by: java.lang.ClassNotFoundException: target.Recommandation-1.0-SNAPSHOT.jar ```
2020/07/01
[ "https://Stackoverflow.com/questions/62672857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10867361/" ]
This is not a Maven problem. The way you pass your commands to docker is just a little bit wrong. Basically your try to execute this command inside your container: ``` mvn clean install java target/Recommandation-1.0-SNAPSHOT.jar org.exemple.demo.App ``` If you try to execute this on your Host you will receive the same error as in your container. You want to execute two separate commands in your container: 1. build your project 2. execute the Jar To achieve this you have to chain both commands. Because you only want to execute your JAR-File if the build was successful you have to use the `&&` Operator. ``` mvn clean install && java target/Recommandation-1.0-SNAPSHOT.jar org.exemple.demo.App ``` For more details have a look at this Post here: [10 Useful Chaining Operators in Linux with Practical Examples](https://www.tecmint.com/chaining-operators-in-linux-with-practical-examples/) BTW. You don't need to execute the `install` goal. `package` should be sufficient. --- Edit ---- As you can now see in your output the project was compiled successfully but your JAR-File could not be executed. This is because you are missing the `-jar` parameter. (I also didn't noticed this in my original answer.) Therefore you should execute the following command: ``` mvn clean install && java -jar target/Recommandation-1.0-SNAPSHOT.jar org.exemple.demo.App ``` --- Edit2 ----- Regarding your comment > > Indeed I have already tried with && but I have the impression that because of this, it is the host who executes the command and not the container. > > > You are completely right - that was kind of misleading explanation by me. If you want to pass this to the `docker run` command you have to do the following: ``` docker run [your_parameters] maven:latest /bin/bash -c "mvn clean install && java -jar target/Recommandation-1.0-SNAPSHOT.jar org.exemple.demo.App" ```
Probably the issue is with command ``` docker run -it --rm --name my-maven-project -v /var/www/html/Recommandation/:/usr/src/mymaven -p 88:88 -w /usr/src/mymaven maven:latest mvn clean install java target/Recommandation-1.0-SNAPSHOT.jar org.exemple.demo.App ``` Maven thinks it should execute `clean` `install` and than `java` (which is not known to maven) Try separating with `;` ``` docker run -it --rm --name my-maven-project -v /var/www/html/Recommandation/:/usr/src/mymaven -p 88:88 -w /usr/src/mymaven maven:latest mvn clean install; java target/Recommandation-1.0-SNAPSHOT.jar org.exemple.demo.App ``` Now if you want to run both commands in Docker, probably better would be wrapping this in a simple bash script and executing from the docker entry point.
62,672,875
I want to setting the default logging level to error on springboot [enter image description here](https://i.stack.imgur.com/25Zp9.png) But the console still has the dubug and info output. It seems that logging.level.root=error doesn't work.
2020/07/01
[ "https://Stackoverflow.com/questions/62672875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845880/" ]
Be carefull if you are using Spring Boot Devtools, the properties defined in `$HOME/.config/spring-boot` folder will override all other properties as specified in Spring Boot documentation : <https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html>
I found a environment variable named debug,even though its value is a string not true,which caused the problem.Actually,I tried to remove the variable before,but I didn't restart the eclipse.Now,I remove the varibale named DEBUG and restart the eclipse,and it success.
62,672,888
I have a form that contains 3 TextFormFields. I have a "save" button and a "cancel" button. If the user clicks "cancel" I want to clear the TextFormFields. Can anyone tell me how to do this? Thanks. ``` body: SingleChildScrollView( child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 15), Text( 'Display Name', style: _style, textAlign: TextAlign.right, ), SizedBox(height: 5), TextFormField( autofocus: true, initialValue: _displayName, validator: (value) { if (value.isEmpty) { return 'please enter your display name'; } return null; }, onSaved: (value) { _displayName = value; }, decoration: _textFormFieldDecoration( hintText: 'your display name', padding: 12.0, ), ), ``` ... ``` RaisedButton( color: kMainColor80, child: Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 16)), onPressed: () { setState(() { _displayName = ''; _mobileNumber = ''; _emailAddress = ''; }); }, ), ```
2020/07/01
[ "https://Stackoverflow.com/questions/62672888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13247321/" ]
you need to add a controller to your TextFormField: ``` TextFormField( controller: nameController, decoration: kTextFieldDecoration.copyWith( labelText: 'name', icon: Icon(FontAwesomeIcons.user), ), validator: (value) { if (value.isEmpty) { return 'Please enter Name'; } return null; }, ), ``` on your setState() ``` setState(() { nameController.text = ""; }); ```
1. You have to add controller to each text field `final TextEditingController _nameController = TextEditingController();` 2. Pass your controller to the text field `controller: _nameController,` 3. Now you can clear your text form field using `_nameController.clear()`
62,672,888
I have a form that contains 3 TextFormFields. I have a "save" button and a "cancel" button. If the user clicks "cancel" I want to clear the TextFormFields. Can anyone tell me how to do this? Thanks. ``` body: SingleChildScrollView( child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 15), Text( 'Display Name', style: _style, textAlign: TextAlign.right, ), SizedBox(height: 5), TextFormField( autofocus: true, initialValue: _displayName, validator: (value) { if (value.isEmpty) { return 'please enter your display name'; } return null; }, onSaved: (value) { _displayName = value; }, decoration: _textFormFieldDecoration( hintText: 'your display name', padding: 12.0, ), ), ``` ... ``` RaisedButton( color: kMainColor80, child: Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 16)), onPressed: () { setState(() { _displayName = ''; _mobileNumber = ''; _emailAddress = ''; }); }, ), ```
2020/07/01
[ "https://Stackoverflow.com/questions/62672888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13247321/" ]
You can use the `controller`. So, your code should be like: 1st, initialize `TextEditingController` variable somewhere inside the top of your class: ``` final myController = TextEditingController(); ``` And then put that controller inside each `TextFormField`. (Note: I only see your first `TextFormField` in the code you provided. So, I only put it once. Make sure to put it on each `TexFormField`) ``` body: SingleChildScrollView( child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 15), Text( 'Display Name', style: _style, textAlign: TextAlign.right, ), SizedBox(height: 5), TextFormField( controller: myController, // PUT HERE autofocus: true, initialValue: _displayName, validator: (value) { if (value.isEmpty) { return 'please enter your display name'; } return null; }, onSaved: (value) { _displayName = value; }, decoration: _textFormFieldDecoration( hintText: 'your display name', padding: 12.0, ), ), ``` And then, inside the button, call that controller: ``` RaisedButton( color: kMainColor80, child: Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 16)), onPressed: () { setState(() { myController.clear(); }); }, ), ``` If you want each `TextFormField` to have their own controller, you can create 3 different controllers variable. And thet call each one of them inside you button
1. You have to add controller to each text field `final TextEditingController _nameController = TextEditingController();` 2. Pass your controller to the text field `controller: _nameController,` 3. Now you can clear your text form field using `_nameController.clear()`
62,672,888
I have a form that contains 3 TextFormFields. I have a "save" button and a "cancel" button. If the user clicks "cancel" I want to clear the TextFormFields. Can anyone tell me how to do this? Thanks. ``` body: SingleChildScrollView( child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 15), Text( 'Display Name', style: _style, textAlign: TextAlign.right, ), SizedBox(height: 5), TextFormField( autofocus: true, initialValue: _displayName, validator: (value) { if (value.isEmpty) { return 'please enter your display name'; } return null; }, onSaved: (value) { _displayName = value; }, decoration: _textFormFieldDecoration( hintText: 'your display name', padding: 12.0, ), ), ``` ... ``` RaisedButton( color: kMainColor80, child: Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 16)), onPressed: () { setState(() { _displayName = ''; _mobileNumber = ''; _emailAddress = ''; }); }, ), ```
2020/07/01
[ "https://Stackoverflow.com/questions/62672888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13247321/" ]
1. You have to add controller to each text field `final TextEditingController _nameController = TextEditingController();` 2. Pass your controller to the text field `controller: _nameController,` 3. Now you can clear your text form field using `_nameController.clear()`
you can do this very easy. just use a `TextEditingController` like this : ``` @override void initState() { super.initState(); this.display_name_field = new TextEditingController(); } ``` and when you click on cancel btn you can run this : ``` this.display_name_field.clear(); ``` I hope I was able to help.
62,672,888
I have a form that contains 3 TextFormFields. I have a "save" button and a "cancel" button. If the user clicks "cancel" I want to clear the TextFormFields. Can anyone tell me how to do this? Thanks. ``` body: SingleChildScrollView( child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 15), Text( 'Display Name', style: _style, textAlign: TextAlign.right, ), SizedBox(height: 5), TextFormField( autofocus: true, initialValue: _displayName, validator: (value) { if (value.isEmpty) { return 'please enter your display name'; } return null; }, onSaved: (value) { _displayName = value; }, decoration: _textFormFieldDecoration( hintText: 'your display name', padding: 12.0, ), ), ``` ... ``` RaisedButton( color: kMainColor80, child: Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 16)), onPressed: () { setState(() { _displayName = ''; _mobileNumber = ''; _emailAddress = ''; }); }, ), ```
2020/07/01
[ "https://Stackoverflow.com/questions/62672888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13247321/" ]
You can use the `controller`. So, your code should be like: 1st, initialize `TextEditingController` variable somewhere inside the top of your class: ``` final myController = TextEditingController(); ``` And then put that controller inside each `TextFormField`. (Note: I only see your first `TextFormField` in the code you provided. So, I only put it once. Make sure to put it on each `TexFormField`) ``` body: SingleChildScrollView( child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 15), Text( 'Display Name', style: _style, textAlign: TextAlign.right, ), SizedBox(height: 5), TextFormField( controller: myController, // PUT HERE autofocus: true, initialValue: _displayName, validator: (value) { if (value.isEmpty) { return 'please enter your display name'; } return null; }, onSaved: (value) { _displayName = value; }, decoration: _textFormFieldDecoration( hintText: 'your display name', padding: 12.0, ), ), ``` And then, inside the button, call that controller: ``` RaisedButton( color: kMainColor80, child: Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 16)), onPressed: () { setState(() { myController.clear(); }); }, ), ``` If you want each `TextFormField` to have their own controller, you can create 3 different controllers variable. And thet call each one of them inside you button
you need to add a controller to your TextFormField: ``` TextFormField( controller: nameController, decoration: kTextFieldDecoration.copyWith( labelText: 'name', icon: Icon(FontAwesomeIcons.user), ), validator: (value) { if (value.isEmpty) { return 'Please enter Name'; } return null; }, ), ``` on your setState() ``` setState(() { nameController.text = ""; }); ```
62,672,888
I have a form that contains 3 TextFormFields. I have a "save" button and a "cancel" button. If the user clicks "cancel" I want to clear the TextFormFields. Can anyone tell me how to do this? Thanks. ``` body: SingleChildScrollView( child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 15), Text( 'Display Name', style: _style, textAlign: TextAlign.right, ), SizedBox(height: 5), TextFormField( autofocus: true, initialValue: _displayName, validator: (value) { if (value.isEmpty) { return 'please enter your display name'; } return null; }, onSaved: (value) { _displayName = value; }, decoration: _textFormFieldDecoration( hintText: 'your display name', padding: 12.0, ), ), ``` ... ``` RaisedButton( color: kMainColor80, child: Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 16)), onPressed: () { setState(() { _displayName = ''; _mobileNumber = ''; _emailAddress = ''; }); }, ), ```
2020/07/01
[ "https://Stackoverflow.com/questions/62672888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13247321/" ]
you need to add a controller to your TextFormField: ``` TextFormField( controller: nameController, decoration: kTextFieldDecoration.copyWith( labelText: 'name', icon: Icon(FontAwesomeIcons.user), ), validator: (value) { if (value.isEmpty) { return 'Please enter Name'; } return null; }, ), ``` on your setState() ``` setState(() { nameController.text = ""; }); ```
you can do this very easy. just use a `TextEditingController` like this : ``` @override void initState() { super.initState(); this.display_name_field = new TextEditingController(); } ``` and when you click on cancel btn you can run this : ``` this.display_name_field.clear(); ``` I hope I was able to help.
62,672,888
I have a form that contains 3 TextFormFields. I have a "save" button and a "cancel" button. If the user clicks "cancel" I want to clear the TextFormFields. Can anyone tell me how to do this? Thanks. ``` body: SingleChildScrollView( child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 15), Text( 'Display Name', style: _style, textAlign: TextAlign.right, ), SizedBox(height: 5), TextFormField( autofocus: true, initialValue: _displayName, validator: (value) { if (value.isEmpty) { return 'please enter your display name'; } return null; }, onSaved: (value) { _displayName = value; }, decoration: _textFormFieldDecoration( hintText: 'your display name', padding: 12.0, ), ), ``` ... ``` RaisedButton( color: kMainColor80, child: Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 16)), onPressed: () { setState(() { _displayName = ''; _mobileNumber = ''; _emailAddress = ''; }); }, ), ```
2020/07/01
[ "https://Stackoverflow.com/questions/62672888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13247321/" ]
You can use the `controller`. So, your code should be like: 1st, initialize `TextEditingController` variable somewhere inside the top of your class: ``` final myController = TextEditingController(); ``` And then put that controller inside each `TextFormField`. (Note: I only see your first `TextFormField` in the code you provided. So, I only put it once. Make sure to put it on each `TexFormField`) ``` body: SingleChildScrollView( child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 15), Text( 'Display Name', style: _style, textAlign: TextAlign.right, ), SizedBox(height: 5), TextFormField( controller: myController, // PUT HERE autofocus: true, initialValue: _displayName, validator: (value) { if (value.isEmpty) { return 'please enter your display name'; } return null; }, onSaved: (value) { _displayName = value; }, decoration: _textFormFieldDecoration( hintText: 'your display name', padding: 12.0, ), ), ``` And then, inside the button, call that controller: ``` RaisedButton( color: kMainColor80, child: Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 16)), onPressed: () { setState(() { myController.clear(); }); }, ), ``` If you want each `TextFormField` to have their own controller, you can create 3 different controllers variable. And thet call each one of them inside you button
you can do this very easy. just use a `TextEditingController` like this : ``` @override void initState() { super.initState(); this.display_name_field = new TextEditingController(); } ``` and when you click on cancel btn you can run this : ``` this.display_name_field.clear(); ``` I hope I was able to help.
62,672,893
Currently i'm using Unity 2018.1.4f1, I'm trying to migrate the project to Unity 2019.4.1f1, but `Unity.System.NetworkManager` is not supported The problem occurs at the modules: ``` NetworkDisconnection NetworkMessageInfo NetworkPlayer ``` Can I use this module in version 2019.4?
2020/07/01
[ "https://Stackoverflow.com/questions/62672893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
you need to add a controller to your TextFormField: ``` TextFormField( controller: nameController, decoration: kTextFieldDecoration.copyWith( labelText: 'name', icon: Icon(FontAwesomeIcons.user), ), validator: (value) { if (value.isEmpty) { return 'Please enter Name'; } return null; }, ), ``` on your setState() ``` setState(() { nameController.text = ""; }); ```
1. You have to add controller to each text field `final TextEditingController _nameController = TextEditingController();` 2. Pass your controller to the text field `controller: _nameController,` 3. Now you can clear your text form field using `_nameController.clear()`
62,672,893
Currently i'm using Unity 2018.1.4f1, I'm trying to migrate the project to Unity 2019.4.1f1, but `Unity.System.NetworkManager` is not supported The problem occurs at the modules: ``` NetworkDisconnection NetworkMessageInfo NetworkPlayer ``` Can I use this module in version 2019.4?
2020/07/01
[ "https://Stackoverflow.com/questions/62672893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use the `controller`. So, your code should be like: 1st, initialize `TextEditingController` variable somewhere inside the top of your class: ``` final myController = TextEditingController(); ``` And then put that controller inside each `TextFormField`. (Note: I only see your first `TextFormField` in the code you provided. So, I only put it once. Make sure to put it on each `TexFormField`) ``` body: SingleChildScrollView( child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 15), Text( 'Display Name', style: _style, textAlign: TextAlign.right, ), SizedBox(height: 5), TextFormField( controller: myController, // PUT HERE autofocus: true, initialValue: _displayName, validator: (value) { if (value.isEmpty) { return 'please enter your display name'; } return null; }, onSaved: (value) { _displayName = value; }, decoration: _textFormFieldDecoration( hintText: 'your display name', padding: 12.0, ), ), ``` And then, inside the button, call that controller: ``` RaisedButton( color: kMainColor80, child: Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 16)), onPressed: () { setState(() { myController.clear(); }); }, ), ``` If you want each `TextFormField` to have their own controller, you can create 3 different controllers variable. And thet call each one of them inside you button
1. You have to add controller to each text field `final TextEditingController _nameController = TextEditingController();` 2. Pass your controller to the text field `controller: _nameController,` 3. Now you can clear your text form field using `_nameController.clear()`
62,672,893
Currently i'm using Unity 2018.1.4f1, I'm trying to migrate the project to Unity 2019.4.1f1, but `Unity.System.NetworkManager` is not supported The problem occurs at the modules: ``` NetworkDisconnection NetworkMessageInfo NetworkPlayer ``` Can I use this module in version 2019.4?
2020/07/01
[ "https://Stackoverflow.com/questions/62672893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
1. You have to add controller to each text field `final TextEditingController _nameController = TextEditingController();` 2. Pass your controller to the text field `controller: _nameController,` 3. Now you can clear your text form field using `_nameController.clear()`
you can do this very easy. just use a `TextEditingController` like this : ``` @override void initState() { super.initState(); this.display_name_field = new TextEditingController(); } ``` and when you click on cancel btn you can run this : ``` this.display_name_field.clear(); ``` I hope I was able to help.
62,672,893
Currently i'm using Unity 2018.1.4f1, I'm trying to migrate the project to Unity 2019.4.1f1, but `Unity.System.NetworkManager` is not supported The problem occurs at the modules: ``` NetworkDisconnection NetworkMessageInfo NetworkPlayer ``` Can I use this module in version 2019.4?
2020/07/01
[ "https://Stackoverflow.com/questions/62672893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use the `controller`. So, your code should be like: 1st, initialize `TextEditingController` variable somewhere inside the top of your class: ``` final myController = TextEditingController(); ``` And then put that controller inside each `TextFormField`. (Note: I only see your first `TextFormField` in the code you provided. So, I only put it once. Make sure to put it on each `TexFormField`) ``` body: SingleChildScrollView( child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 15), Text( 'Display Name', style: _style, textAlign: TextAlign.right, ), SizedBox(height: 5), TextFormField( controller: myController, // PUT HERE autofocus: true, initialValue: _displayName, validator: (value) { if (value.isEmpty) { return 'please enter your display name'; } return null; }, onSaved: (value) { _displayName = value; }, decoration: _textFormFieldDecoration( hintText: 'your display name', padding: 12.0, ), ), ``` And then, inside the button, call that controller: ``` RaisedButton( color: kMainColor80, child: Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 16)), onPressed: () { setState(() { myController.clear(); }); }, ), ``` If you want each `TextFormField` to have their own controller, you can create 3 different controllers variable. And thet call each one of them inside you button
you need to add a controller to your TextFormField: ``` TextFormField( controller: nameController, decoration: kTextFieldDecoration.copyWith( labelText: 'name', icon: Icon(FontAwesomeIcons.user), ), validator: (value) { if (value.isEmpty) { return 'Please enter Name'; } return null; }, ), ``` on your setState() ``` setState(() { nameController.text = ""; }); ```
62,672,893
Currently i'm using Unity 2018.1.4f1, I'm trying to migrate the project to Unity 2019.4.1f1, but `Unity.System.NetworkManager` is not supported The problem occurs at the modules: ``` NetworkDisconnection NetworkMessageInfo NetworkPlayer ``` Can I use this module in version 2019.4?
2020/07/01
[ "https://Stackoverflow.com/questions/62672893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
you need to add a controller to your TextFormField: ``` TextFormField( controller: nameController, decoration: kTextFieldDecoration.copyWith( labelText: 'name', icon: Icon(FontAwesomeIcons.user), ), validator: (value) { if (value.isEmpty) { return 'Please enter Name'; } return null; }, ), ``` on your setState() ``` setState(() { nameController.text = ""; }); ```
you can do this very easy. just use a `TextEditingController` like this : ``` @override void initState() { super.initState(); this.display_name_field = new TextEditingController(); } ``` and when you click on cancel btn you can run this : ``` this.display_name_field.clear(); ``` I hope I was able to help.
62,672,893
Currently i'm using Unity 2018.1.4f1, I'm trying to migrate the project to Unity 2019.4.1f1, but `Unity.System.NetworkManager` is not supported The problem occurs at the modules: ``` NetworkDisconnection NetworkMessageInfo NetworkPlayer ``` Can I use this module in version 2019.4?
2020/07/01
[ "https://Stackoverflow.com/questions/62672893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use the `controller`. So, your code should be like: 1st, initialize `TextEditingController` variable somewhere inside the top of your class: ``` final myController = TextEditingController(); ``` And then put that controller inside each `TextFormField`. (Note: I only see your first `TextFormField` in the code you provided. So, I only put it once. Make sure to put it on each `TexFormField`) ``` body: SingleChildScrollView( child: Form( key: _formKey, child: Padding( padding: const EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 15), Text( 'Display Name', style: _style, textAlign: TextAlign.right, ), SizedBox(height: 5), TextFormField( controller: myController, // PUT HERE autofocus: true, initialValue: _displayName, validator: (value) { if (value.isEmpty) { return 'please enter your display name'; } return null; }, onSaved: (value) { _displayName = value; }, decoration: _textFormFieldDecoration( hintText: 'your display name', padding: 12.0, ), ), ``` And then, inside the button, call that controller: ``` RaisedButton( color: kMainColor80, child: Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 16)), onPressed: () { setState(() { myController.clear(); }); }, ), ``` If you want each `TextFormField` to have their own controller, you can create 3 different controllers variable. And thet call each one of them inside you button
you can do this very easy. just use a `TextEditingController` like this : ``` @override void initState() { super.initState(); this.display_name_field = new TextEditingController(); } ``` and when you click on cancel btn you can run this : ``` this.display_name_field.clear(); ``` I hope I was able to help.
62,672,902
I need to transfrm an array into another array but can't find a good way to do this. An error message tells me I can't push into `found[0].children`, but I feel like all the way I'm doing it wrong and dirty; would you tell me how you manage this kind of issue? I would like to transform the array: ``` const input = [ {value: "29-08-2020 16:00", visible: 0}, {value: "29-08-2020 16:30", visible: 1}, {value: "29-08-2020 17:00", visible: 0}, {value: "30-08-2020 15:00", visible: 1}, {value: "30-08-2020 15:30", visible: 1} ]; ``` Into the array: ``` const output = [ { id: '29/08/2020', label: '29/08/2020', children: [ { id: '16:00', label: '16:00', isDisabled: true }, { id: '16:30', label: '16:30' }, { id: '17:00', label: '17:00', isDisabled: true } ], }, { id: '30/08/2020', label: '30/08/2020', children: [ { id: '15:00', label: '15:00' }, { id: '15:30', label: '15:30' } ] } ]; ``` Here is what I tried, but I am not satisfied at all with this idea, which doesn't seem like the good way... ``` function dateoptions(dateslist) { var options: any[] = []; dateslist.forEach(element => { var tab = element.value.split(' '); var dt = tab[0]; var time = tab[1]; var found = options.filter(opt=> opt.id==dt); if (found.length>0) { // I can't do this: found[0].children.push({ 'id': time, 'label': time, disabled: element.visible==0 }); } else { options.push({ 'id': dt, 'label': dt, 'children': {'id':time, 'label': time, disabled: element.visible==0} }); } }); return options; } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62672902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2434153/" ]
Your general idea is good, I'd use a map1 for simplicity of the lookup and create an empty entry (with empty children array) when not found: ```js function dateoptions (datelist) { const dateObjects = new Map() for (const { value, visible } of datelist) { const [date, time] = value.split(' ') if (!dateObjects.has(date)) { dateObjects.set(date, { id: date, label: date, children: [] }) } dateObjects.get(date).children.push({ id: time, label: time, ...!visible ? { isDisabled: true } : {} }) } return Array.from(dateObjects.values()) } ``` --- **1:** Why not an object? Because the iteration order of object values is not defined, even though practically all current browsers use insertion order. For a map it is defined.
You could reduce the array and iterate the result set for a same group. ```js const data = [{ value: "29-08-2020 16:00", visible: 0 }, { value: "29-08-2020 16:30", visible: 1 }, { value: "29-08-2020 17:00", visible: 0 }, { value: "30-08-2020 15:00", visible: 1 }, { value: "30-08-2020 15:30", visible: 1 }], result = data.reduce((r, { value, visible }) => { let [date, time] = value.split(' '), temp = r.find(q => q.id === date); if (!temp) r.push(temp = { id: date, label: date, children: [] }); temp.children.push({ id: time, label: time, ...(!visible && { isDisabled: !visible }) }); return r; }, []); console.log(result); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
62,672,902
I need to transfrm an array into another array but can't find a good way to do this. An error message tells me I can't push into `found[0].children`, but I feel like all the way I'm doing it wrong and dirty; would you tell me how you manage this kind of issue? I would like to transform the array: ``` const input = [ {value: "29-08-2020 16:00", visible: 0}, {value: "29-08-2020 16:30", visible: 1}, {value: "29-08-2020 17:00", visible: 0}, {value: "30-08-2020 15:00", visible: 1}, {value: "30-08-2020 15:30", visible: 1} ]; ``` Into the array: ``` const output = [ { id: '29/08/2020', label: '29/08/2020', children: [ { id: '16:00', label: '16:00', isDisabled: true }, { id: '16:30', label: '16:30' }, { id: '17:00', label: '17:00', isDisabled: true } ], }, { id: '30/08/2020', label: '30/08/2020', children: [ { id: '15:00', label: '15:00' }, { id: '15:30', label: '15:30' } ] } ]; ``` Here is what I tried, but I am not satisfied at all with this idea, which doesn't seem like the good way... ``` function dateoptions(dateslist) { var options: any[] = []; dateslist.forEach(element => { var tab = element.value.split(' '); var dt = tab[0]; var time = tab[1]; var found = options.filter(opt=> opt.id==dt); if (found.length>0) { // I can't do this: found[0].children.push({ 'id': time, 'label': time, disabled: element.visible==0 }); } else { options.push({ 'id': dt, 'label': dt, 'children': {'id':time, 'label': time, disabled: element.visible==0} }); } }); return options; } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62672902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2434153/" ]
You could reduce the array and iterate the result set for a same group. ```js const data = [{ value: "29-08-2020 16:00", visible: 0 }, { value: "29-08-2020 16:30", visible: 1 }, { value: "29-08-2020 17:00", visible: 0 }, { value: "30-08-2020 15:00", visible: 1 }, { value: "30-08-2020 15:30", visible: 1 }], result = data.reduce((r, { value, visible }) => { let [date, time] = value.split(' '), temp = r.find(q => q.id === date); if (!temp) r.push(temp = { id: date, label: date, children: [] }); temp.children.push({ id: time, label: time, ...(!visible && { isDisabled: !visible }) }); return r; }, []); console.log(result); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
The following solution is supported even in Internet Explorer 6. ```js var input = [ {value: "29-08-2020 16:00", visible: 0}, {value: "29-08-2020 16:30", visible: 1}, {value: "29-08-2020 17:00", visible: 0}, {value: "30-08-2020 15:00", visible: 1}, {value: "30-08-2020 15:30", visible: 1} ]; function dateTransform(datelist) { var ret = [], dateObjects = {}, i; for(i in datelist) { var obj = datelist[i], ar = obj.value.split(' '), date = ar[0].split('-').join('/'), child = {id: ar[1], label: ar[1]}; if(!dateObjects[date]) dateObjects[date] = {id: date, label: date, children: []}; if(!obj.visible) child.isDisabled = !0; dateObjects[date].children.push(child) } for(i in dateObjects) ret.push(dateObjects[i]); return ret } //JSON.stringify is supported first in Internet Explorer 8 version console.log(JSON.stringify(dateTransform(input), 0, '\t')); ```
62,672,902
I need to transfrm an array into another array but can't find a good way to do this. An error message tells me I can't push into `found[0].children`, but I feel like all the way I'm doing it wrong and dirty; would you tell me how you manage this kind of issue? I would like to transform the array: ``` const input = [ {value: "29-08-2020 16:00", visible: 0}, {value: "29-08-2020 16:30", visible: 1}, {value: "29-08-2020 17:00", visible: 0}, {value: "30-08-2020 15:00", visible: 1}, {value: "30-08-2020 15:30", visible: 1} ]; ``` Into the array: ``` const output = [ { id: '29/08/2020', label: '29/08/2020', children: [ { id: '16:00', label: '16:00', isDisabled: true }, { id: '16:30', label: '16:30' }, { id: '17:00', label: '17:00', isDisabled: true } ], }, { id: '30/08/2020', label: '30/08/2020', children: [ { id: '15:00', label: '15:00' }, { id: '15:30', label: '15:30' } ] } ]; ``` Here is what I tried, but I am not satisfied at all with this idea, which doesn't seem like the good way... ``` function dateoptions(dateslist) { var options: any[] = []; dateslist.forEach(element => { var tab = element.value.split(' '); var dt = tab[0]; var time = tab[1]; var found = options.filter(opt=> opt.id==dt); if (found.length>0) { // I can't do this: found[0].children.push({ 'id': time, 'label': time, disabled: element.visible==0 }); } else { options.push({ 'id': dt, 'label': dt, 'children': {'id':time, 'label': time, disabled: element.visible==0} }); } }); return options; } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62672902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2434153/" ]
Your general idea is good, I'd use a map1 for simplicity of the lookup and create an empty entry (with empty children array) when not found: ```js function dateoptions (datelist) { const dateObjects = new Map() for (const { value, visible } of datelist) { const [date, time] = value.split(' ') if (!dateObjects.has(date)) { dateObjects.set(date, { id: date, label: date, children: [] }) } dateObjects.get(date).children.push({ id: time, label: time, ...!visible ? { isDisabled: true } : {} }) } return Array.from(dateObjects.values()) } ``` --- **1:** Why not an object? Because the iteration order of object values is not defined, even though practically all current browsers use insertion order. For a map it is defined.
The following solution is supported even in Internet Explorer 6. ```js var input = [ {value: "29-08-2020 16:00", visible: 0}, {value: "29-08-2020 16:30", visible: 1}, {value: "29-08-2020 17:00", visible: 0}, {value: "30-08-2020 15:00", visible: 1}, {value: "30-08-2020 15:30", visible: 1} ]; function dateTransform(datelist) { var ret = [], dateObjects = {}, i; for(i in datelist) { var obj = datelist[i], ar = obj.value.split(' '), date = ar[0].split('-').join('/'), child = {id: ar[1], label: ar[1]}; if(!dateObjects[date]) dateObjects[date] = {id: date, label: date, children: []}; if(!obj.visible) child.isDisabled = !0; dateObjects[date].children.push(child) } for(i in dateObjects) ret.push(dateObjects[i]); return ret } //JSON.stringify is supported first in Internet Explorer 8 version console.log(JSON.stringify(dateTransform(input), 0, '\t')); ```
62,672,910
I'm new to both xpath and html so I'm probably missing something fundamental here. I have a html where I want to extract all the items displayed below. (I'm using scrapy to do my requests, I just need the proper xpath to get the data) [enter image description here](https://i.stack.imgur.com/C5GzR.png) Here I just want to loop through all these items and from there and get some data from inside each item. ``` for item in response.xpath("//ul[@class='feedArticleList XSText']/li[@class='item']"): yield {'name': item.xpath("//div[@class='intro lhNormal']").get()} ``` The problem is that this get only gives me the first item for all the loops. If I instead use .getall() I then get all the items for every loop (which in my view shouldn't work since I thought I only selected one item at the time in each iteration). Thanks in advance!
2020/07/01
[ "https://Stackoverflow.com/questions/62672910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12601746/" ]
Your general idea is good, I'd use a map1 for simplicity of the lookup and create an empty entry (with empty children array) when not found: ```js function dateoptions (datelist) { const dateObjects = new Map() for (const { value, visible } of datelist) { const [date, time] = value.split(' ') if (!dateObjects.has(date)) { dateObjects.set(date, { id: date, label: date, children: [] }) } dateObjects.get(date).children.push({ id: time, label: time, ...!visible ? { isDisabled: true } : {} }) } return Array.from(dateObjects.values()) } ``` --- **1:** Why not an object? Because the iteration order of object values is not defined, even though practically all current browsers use insertion order. For a map it is defined.
You could reduce the array and iterate the result set for a same group. ```js const data = [{ value: "29-08-2020 16:00", visible: 0 }, { value: "29-08-2020 16:30", visible: 1 }, { value: "29-08-2020 17:00", visible: 0 }, { value: "30-08-2020 15:00", visible: 1 }, { value: "30-08-2020 15:30", visible: 1 }], result = data.reduce((r, { value, visible }) => { let [date, time] = value.split(' '), temp = r.find(q => q.id === date); if (!temp) r.push(temp = { id: date, label: date, children: [] }); temp.children.push({ id: time, label: time, ...(!visible && { isDisabled: !visible }) }); return r; }, []); console.log(result); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
62,672,910
I'm new to both xpath and html so I'm probably missing something fundamental here. I have a html where I want to extract all the items displayed below. (I'm using scrapy to do my requests, I just need the proper xpath to get the data) [enter image description here](https://i.stack.imgur.com/C5GzR.png) Here I just want to loop through all these items and from there and get some data from inside each item. ``` for item in response.xpath("//ul[@class='feedArticleList XSText']/li[@class='item']"): yield {'name': item.xpath("//div[@class='intro lhNormal']").get()} ``` The problem is that this get only gives me the first item for all the loops. If I instead use .getall() I then get all the items for every loop (which in my view shouldn't work since I thought I only selected one item at the time in each iteration). Thanks in advance!
2020/07/01
[ "https://Stackoverflow.com/questions/62672910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12601746/" ]
You could reduce the array and iterate the result set for a same group. ```js const data = [{ value: "29-08-2020 16:00", visible: 0 }, { value: "29-08-2020 16:30", visible: 1 }, { value: "29-08-2020 17:00", visible: 0 }, { value: "30-08-2020 15:00", visible: 1 }, { value: "30-08-2020 15:30", visible: 1 }], result = data.reduce((r, { value, visible }) => { let [date, time] = value.split(' '), temp = r.find(q => q.id === date); if (!temp) r.push(temp = { id: date, label: date, children: [] }); temp.children.push({ id: time, label: time, ...(!visible && { isDisabled: !visible }) }); return r; }, []); console.log(result); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
The following solution is supported even in Internet Explorer 6. ```js var input = [ {value: "29-08-2020 16:00", visible: 0}, {value: "29-08-2020 16:30", visible: 1}, {value: "29-08-2020 17:00", visible: 0}, {value: "30-08-2020 15:00", visible: 1}, {value: "30-08-2020 15:30", visible: 1} ]; function dateTransform(datelist) { var ret = [], dateObjects = {}, i; for(i in datelist) { var obj = datelist[i], ar = obj.value.split(' '), date = ar[0].split('-').join('/'), child = {id: ar[1], label: ar[1]}; if(!dateObjects[date]) dateObjects[date] = {id: date, label: date, children: []}; if(!obj.visible) child.isDisabled = !0; dateObjects[date].children.push(child) } for(i in dateObjects) ret.push(dateObjects[i]); return ret } //JSON.stringify is supported first in Internet Explorer 8 version console.log(JSON.stringify(dateTransform(input), 0, '\t')); ```
62,672,910
I'm new to both xpath and html so I'm probably missing something fundamental here. I have a html where I want to extract all the items displayed below. (I'm using scrapy to do my requests, I just need the proper xpath to get the data) [enter image description here](https://i.stack.imgur.com/C5GzR.png) Here I just want to loop through all these items and from there and get some data from inside each item. ``` for item in response.xpath("//ul[@class='feedArticleList XSText']/li[@class='item']"): yield {'name': item.xpath("//div[@class='intro lhNormal']").get()} ``` The problem is that this get only gives me the first item for all the loops. If I instead use .getall() I then get all the items for every loop (which in my view shouldn't work since I thought I only selected one item at the time in each iteration). Thanks in advance!
2020/07/01
[ "https://Stackoverflow.com/questions/62672910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12601746/" ]
Your general idea is good, I'd use a map1 for simplicity of the lookup and create an empty entry (with empty children array) when not found: ```js function dateoptions (datelist) { const dateObjects = new Map() for (const { value, visible } of datelist) { const [date, time] = value.split(' ') if (!dateObjects.has(date)) { dateObjects.set(date, { id: date, label: date, children: [] }) } dateObjects.get(date).children.push({ id: time, label: time, ...!visible ? { isDisabled: true } : {} }) } return Array.from(dateObjects.values()) } ``` --- **1:** Why not an object? Because the iteration order of object values is not defined, even though practically all current browsers use insertion order. For a map it is defined.
The following solution is supported even in Internet Explorer 6. ```js var input = [ {value: "29-08-2020 16:00", visible: 0}, {value: "29-08-2020 16:30", visible: 1}, {value: "29-08-2020 17:00", visible: 0}, {value: "30-08-2020 15:00", visible: 1}, {value: "30-08-2020 15:30", visible: 1} ]; function dateTransform(datelist) { var ret = [], dateObjects = {}, i; for(i in datelist) { var obj = datelist[i], ar = obj.value.split(' '), date = ar[0].split('-').join('/'), child = {id: ar[1], label: ar[1]}; if(!dateObjects[date]) dateObjects[date] = {id: date, label: date, children: []}; if(!obj.visible) child.isDisabled = !0; dateObjects[date].children.push(child) } for(i in dateObjects) ret.push(dateObjects[i]); return ret } //JSON.stringify is supported first in Internet Explorer 8 version console.log(JSON.stringify(dateTransform(input), 0, '\t')); ```
62,672,913
This is my first question here and I'm beginner in coding so forgive me if my question is not very clear. I have stored wages in Room database column called "wage" and the datatype is double. There is wages from different days and I would like to show total from those double numbers in my Activity. If tried many different ways to do it, but I just can't get it to work without different errors. It would be ideal if I could store that sum total into a variable so I can use it easily and probably subtract some value from it if necessary. I use Repository and ViewModel to access my database and RecyclerView, Adapter and CardView to show different data in my MainActivity. I hope I don't need to use these to access this sum-number but get as direct access to it as possible. This is my @entity ``` @Entity (tableName = "shift_table") public class Shift implements Serializable { @PrimaryKey(autoGenerate = true) private int id; @ColumnInfo(name = "date") private String date; @ColumnInfo(name = "start") private String start; @ColumnInfo(name = "end") private String end; @ColumnInfo (name = "hours") private String hours; @ColumnInfo (name = "wage") private double wage; public Shift(String date, String start, String end, String hours, double wage) { this.date = date; this.start = start; this.end = end; this.hours = hours; this.wage = wage; } public void setId(int id) { this.id = id; } public int getId() { return id; } public String getDate() { return date; } public String getStart() { return start; } public String getEnd() { return end; } public String getHours() { return hours; } public double getWage() { return wage; } } ``` This is my @Dao ``` @Dao public interface ShiftDao { @Insert void insert (Shift shift); @Update void update (Shift shift); @Delete void delete (Shift shift); @Query("DELETE FROM shift_table") void deleteAllShifts(); @Query("SELECT * FROM shift_table ORDER BY id DESC") LiveData<List<Shift>> getAllShifts(); @Query("SELECT SUM(wage) FROM shift_table") What here? } ``` How I can get that SUM from wage-column to variable and show it in TextView?
2020/07/01
[ "https://Stackoverflow.com/questions/62672913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845850/" ]
It should be something like this, in your DAO: ``` @Query("SELECT SUM(" + "wage" + ") as wagesSum "+ " FROM " + "shift_table") double getWageSum(); ``` Now, a few suggestions: 1. Put your column names into final constants, like this: public final String COLUMN\_DATE\_NAME = "date"; @ColumnInfo(name = COLUMN\_DATE\_NAME) private String date; This way, it will be easier for you to access the constants statically in DAO, and if in the future you might want to change the name of that column, you would change it only in the constant. Also, please do the same for the table name. These constants will help you when you write possible future migrations as well. Happy coding!
here is some of my kotlin code, enjoy :) DAO ``` @Query("SELECT SUM(column) FROM table") fun getSum(): Int ``` Repository ``` private val mDao: Dao init { val database = getInstance(mApplication) mDao = database.dao() } private class sumAsyncTask(private val mDao: Dao) : AsyncTask<Void, Void, Int>() { protected override fun doInBackground(vararg voids: Void): Int { return mDao.getSum() } } fun getSum(): Int { return sumAsyncTask(mDao).execute().get() } ``` There might be other ways to do this async, this is what i use. PS: as for the Doubles, you might want to store them as Long / SQL Integer instead (see [Create Room Entity for a Table which has a field with LONG datatype in Sqlite](https://stackoverflow.com/questions/54035138/create-room-entity-for-a-table-which-has-a-field-with-long-datatype-in-sqlite/54049286)) This can be done by simply multiplying by 100 (then you have cents if your wages represent money) before storing in the database
62,672,913
This is my first question here and I'm beginner in coding so forgive me if my question is not very clear. I have stored wages in Room database column called "wage" and the datatype is double. There is wages from different days and I would like to show total from those double numbers in my Activity. If tried many different ways to do it, but I just can't get it to work without different errors. It would be ideal if I could store that sum total into a variable so I can use it easily and probably subtract some value from it if necessary. I use Repository and ViewModel to access my database and RecyclerView, Adapter and CardView to show different data in my MainActivity. I hope I don't need to use these to access this sum-number but get as direct access to it as possible. This is my @entity ``` @Entity (tableName = "shift_table") public class Shift implements Serializable { @PrimaryKey(autoGenerate = true) private int id; @ColumnInfo(name = "date") private String date; @ColumnInfo(name = "start") private String start; @ColumnInfo(name = "end") private String end; @ColumnInfo (name = "hours") private String hours; @ColumnInfo (name = "wage") private double wage; public Shift(String date, String start, String end, String hours, double wage) { this.date = date; this.start = start; this.end = end; this.hours = hours; this.wage = wage; } public void setId(int id) { this.id = id; } public int getId() { return id; } public String getDate() { return date; } public String getStart() { return start; } public String getEnd() { return end; } public String getHours() { return hours; } public double getWage() { return wage; } } ``` This is my @Dao ``` @Dao public interface ShiftDao { @Insert void insert (Shift shift); @Update void update (Shift shift); @Delete void delete (Shift shift); @Query("DELETE FROM shift_table") void deleteAllShifts(); @Query("SELECT * FROM shift_table ORDER BY id DESC") LiveData<List<Shift>> getAllShifts(); @Query("SELECT SUM(wage) FROM shift_table") What here? } ``` How I can get that SUM from wage-column to variable and show it in TextView?
2020/07/01
[ "https://Stackoverflow.com/questions/62672913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845850/" ]
It should be something like this, in your DAO: ``` @Query("SELECT SUM(" + "wage" + ") as wagesSum "+ " FROM " + "shift_table") double getWageSum(); ``` Now, a few suggestions: 1. Put your column names into final constants, like this: public final String COLUMN\_DATE\_NAME = "date"; @ColumnInfo(name = COLUMN\_DATE\_NAME) private String date; This way, it will be easier for you to access the constants statically in DAO, and if in the future you might want to change the name of that column, you would change it only in the constant. Also, please do the same for the table name. These constants will help you when you write possible future migrations as well. Happy coding!
You can get sum of double column like below example. Sum of double column value will be store in `BigDecimal`. For more details you can check [documentation](https://developer.android.com/topic/libraries/architecture/livedata#extend_livedata). ``` @Query("SELECT SUM(column) FROM table") LiveData<BigDecimal> getSum(); ```
62,672,931
I have an array with 3 players and an other array with several powers. ``` String[] array_Player = {"Celine", "Amelia", "Olivia"}; int[] array_power_1 = {4,2,10}; ``` The player who has the smallest "power" will have 2 points, the best will have 6 pts. I would like to get this result: ``` Celine | power 4 => points 4 Amelia | power 2 => points 2 Olivia | power 10 => points 6 ``` Here is my resultat for now: ``` Celine | power 4 => points 2 Amelia | power 2 => points 4 Olivia | power 10 => points 6 ``` My points are not correctly attributed. I think my array\_point\_power() method is not correct? ``` public static void array_point_power(String[] array_Player, int[] array_point){ int points = 2; for(int i=0; i<array_Player.length; i++){ array_point[i] = points; points = points + 2; } } ``` Here is my code: ``` import java.util.*; class Main { public static void main(String[] args) { String[] array_Player = {"Celine", "Amelia", "Olivia"}; int[] array_power_1 = {4,2,10}; int[] array_point_1 = new int[3]; System.out.println("Round 1 : "); array_point_power(array_Player, array_point_1); affichage_round(array_Player, array_power_1, array_point_1); } public static void array_point_power(String[] array_Player, int[] array_point){ int points = 2; for(int i=0; i<array_Player.length; i++){ array_point[i] = points; points = points + 2; } } public static void affichage_round(String[] array_Player, int[] array_power, int[] array_point) { for(int i=0; i<array_Player.length; i++){ System.out.println("Joueur " + array_Player[i] + " | Puissances " + array_power[i] + " | Points " + array_point[i] ); } } } ``` Thank you for your help.
2020/07/01
[ "https://Stackoverflow.com/questions/62672931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It should be something like this, in your DAO: ``` @Query("SELECT SUM(" + "wage" + ") as wagesSum "+ " FROM " + "shift_table") double getWageSum(); ``` Now, a few suggestions: 1. Put your column names into final constants, like this: public final String COLUMN\_DATE\_NAME = "date"; @ColumnInfo(name = COLUMN\_DATE\_NAME) private String date; This way, it will be easier for you to access the constants statically in DAO, and if in the future you might want to change the name of that column, you would change it only in the constant. Also, please do the same for the table name. These constants will help you when you write possible future migrations as well. Happy coding!
here is some of my kotlin code, enjoy :) DAO ``` @Query("SELECT SUM(column) FROM table") fun getSum(): Int ``` Repository ``` private val mDao: Dao init { val database = getInstance(mApplication) mDao = database.dao() } private class sumAsyncTask(private val mDao: Dao) : AsyncTask<Void, Void, Int>() { protected override fun doInBackground(vararg voids: Void): Int { return mDao.getSum() } } fun getSum(): Int { return sumAsyncTask(mDao).execute().get() } ``` There might be other ways to do this async, this is what i use. PS: as for the Doubles, you might want to store them as Long / SQL Integer instead (see [Create Room Entity for a Table which has a field with LONG datatype in Sqlite](https://stackoverflow.com/questions/54035138/create-room-entity-for-a-table-which-has-a-field-with-long-datatype-in-sqlite/54049286)) This can be done by simply multiplying by 100 (then you have cents if your wages represent money) before storing in the database
62,672,931
I have an array with 3 players and an other array with several powers. ``` String[] array_Player = {"Celine", "Amelia", "Olivia"}; int[] array_power_1 = {4,2,10}; ``` The player who has the smallest "power" will have 2 points, the best will have 6 pts. I would like to get this result: ``` Celine | power 4 => points 4 Amelia | power 2 => points 2 Olivia | power 10 => points 6 ``` Here is my resultat for now: ``` Celine | power 4 => points 2 Amelia | power 2 => points 4 Olivia | power 10 => points 6 ``` My points are not correctly attributed. I think my array\_point\_power() method is not correct? ``` public static void array_point_power(String[] array_Player, int[] array_point){ int points = 2; for(int i=0; i<array_Player.length; i++){ array_point[i] = points; points = points + 2; } } ``` Here is my code: ``` import java.util.*; class Main { public static void main(String[] args) { String[] array_Player = {"Celine", "Amelia", "Olivia"}; int[] array_power_1 = {4,2,10}; int[] array_point_1 = new int[3]; System.out.println("Round 1 : "); array_point_power(array_Player, array_point_1); affichage_round(array_Player, array_power_1, array_point_1); } public static void array_point_power(String[] array_Player, int[] array_point){ int points = 2; for(int i=0; i<array_Player.length; i++){ array_point[i] = points; points = points + 2; } } public static void affichage_round(String[] array_Player, int[] array_power, int[] array_point) { for(int i=0; i<array_Player.length; i++){ System.out.println("Joueur " + array_Player[i] + " | Puissances " + array_power[i] + " | Points " + array_point[i] ); } } } ``` Thank you for your help.
2020/07/01
[ "https://Stackoverflow.com/questions/62672931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It should be something like this, in your DAO: ``` @Query("SELECT SUM(" + "wage" + ") as wagesSum "+ " FROM " + "shift_table") double getWageSum(); ``` Now, a few suggestions: 1. Put your column names into final constants, like this: public final String COLUMN\_DATE\_NAME = "date"; @ColumnInfo(name = COLUMN\_DATE\_NAME) private String date; This way, it will be easier for you to access the constants statically in DAO, and if in the future you might want to change the name of that column, you would change it only in the constant. Also, please do the same for the table name. These constants will help you when you write possible future migrations as well. Happy coding!
You can get sum of double column like below example. Sum of double column value will be store in `BigDecimal`. For more details you can check [documentation](https://developer.android.com/topic/libraries/architecture/livedata#extend_livedata). ``` @Query("SELECT SUM(column) FROM table") LiveData<BigDecimal> getSum(); ```
62,672,936
Consider i have the table A which doesn't store the timestamp of the new rows inserted. Is there any query to get the count of rows inserted on the table A for the specified time frame. EX: Get records between 6 PM to 9 PM yesterday or get the record count inserted in last 4hrs.
2020/07/01
[ "https://Stackoverflow.com/questions/62672936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13531001/" ]
You can use the `ORA_ROWSCN` pseudo column to get the system change number of the last operation (not insert) on your table --> Convert it to `timestamp` and then use it in `WHERE` clause to get the desired data as follows: ``` SELECT SCN_TO_TIMESTAMP(ORA_ROWSCN) LAST_OPERATION_TIME, T.* FROM YOUR_TABLE T WHERE SCN_TO_TIMESTAMP(ORA_ROWSCN) BETWEEN START_TIMESTAM AND END_TIMESTAMP; ``` You can learn more about the `ORA_ROWSCN` from [oracle documentation](https://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns007.htm).
If there are archive logs for the search period. You must use the utility LogMiner. ``` EXECUTE DBMS_LOGMNR.add_logfile(LOGFILENAME => '/oracle/app/oracle/product/11.2/admin/edcu/arc_redo_log/1_39306_769799469.dbf', OPTIONS => DBMS_LOGMNR.NEW); EXECUTE DBMS_LOGMNR.add_logfile(LOGFILENAME => '/oracle/app/oracle/product/11.2/admin/edcu/arc_redo_log/1_39307_769799469.dbf', OPTIONS => DBMS_LOGMNR.addfile); EXECUTE DBMS_LOGMNR.add_logfile(LOGFILENAME => '/oracle/app/oracle/product/11.2/admin/edcu/arc_redo_log/1_39308_769799469.dbf', OPTIONS => DBMS_LOGMNR.addfile); EXECUTE DBMS_LOGMNR.add_logfile(LOGFILENAME => '/oracle/app/oracle/product/11.2/admin/edcu/arc_redo_log/1_39309_769799469.dbf', OPTIONS => DBMS_LOGMNR.addfile); EXECUTE DBMS_LOGMNR.START_LOGMNR(OPTIONS => DBMS_LOGMNR.DICT_FROM_ONLINE_CATALOG); SELECT to_char(timestamp,'DD-MM-YYYY HH24:MI:SS'), operation,username, os_username, machine_name, session_info, sql_redo FROM v$logmnr_contents where seg_owner='MANAGER' and seg_name='TEST2' 02-07-2020 09:40:20 DDL MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN create table test2 (p1 number); 02-07-2020 09:40:47 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1") values (HEXTORAW('c117')); 02-07-2020 09:40:53 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1") values (HEXTORAW('c119')); 02-07-2020 09:40:57 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1") values (HEXTORAW('c137')); 02-07-2020 09:41:01 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1") values (HEXTORAW('c20219')); 02-07-2020 09:41:45 DDL MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN alter table test2 add (p2 varchar2(200)); 02-07-2020 09:42:12 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c20219'),HEXTORAW('746573743220746573743120')); 02-07-2020 09:42:24 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c2021a'),HEXTORAW('746573743420746573743420')); 02-07-2020 09:46:24 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c2021a'),HEXTORAW('746573743420746573743420')); 02-07-2020 09:46:25 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c2021a'),HEXTORAW('746573743420746573743420')); 02-07-2020 09:46:26 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c2021a'),HEXTORAW('746573743420746573743420')); 02-07-2020 09:46:27 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c2021a'),HEXTORAW('746573743420746573743420')); 02-07-2020 09:46:28 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c2021a'),HEXTORAW('746573743420746573743420')); 02-07-2020 09:54:37 DDL MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN comment on table test2 is 'test'; 02-07-2020 10:16:36 DDL MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN alter table test2 add (p3 varchar2(100)); 02-07-2020 10:17:07 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("P1","P2","P3") values ('125','test6','test4 '); 02-07-2020 10:17:08 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("P1","P2","P3") values ('125','test6','test4 '); ' ```
62,672,937
I have an up and running rancher cluster (Airgap mode) in my own server. As I know after you launch the cluster, you cannot change your network provider. Is there any solution that I'll be change my network plugin from flannel to weave? I don't want bootstrap a new cluster again.
2020/07/01
[ "https://Stackoverflow.com/questions/62672937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11628841/" ]
You can use the `ORA_ROWSCN` pseudo column to get the system change number of the last operation (not insert) on your table --> Convert it to `timestamp` and then use it in `WHERE` clause to get the desired data as follows: ``` SELECT SCN_TO_TIMESTAMP(ORA_ROWSCN) LAST_OPERATION_TIME, T.* FROM YOUR_TABLE T WHERE SCN_TO_TIMESTAMP(ORA_ROWSCN) BETWEEN START_TIMESTAM AND END_TIMESTAMP; ``` You can learn more about the `ORA_ROWSCN` from [oracle documentation](https://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns007.htm).
If there are archive logs for the search period. You must use the utility LogMiner. ``` EXECUTE DBMS_LOGMNR.add_logfile(LOGFILENAME => '/oracle/app/oracle/product/11.2/admin/edcu/arc_redo_log/1_39306_769799469.dbf', OPTIONS => DBMS_LOGMNR.NEW); EXECUTE DBMS_LOGMNR.add_logfile(LOGFILENAME => '/oracle/app/oracle/product/11.2/admin/edcu/arc_redo_log/1_39307_769799469.dbf', OPTIONS => DBMS_LOGMNR.addfile); EXECUTE DBMS_LOGMNR.add_logfile(LOGFILENAME => '/oracle/app/oracle/product/11.2/admin/edcu/arc_redo_log/1_39308_769799469.dbf', OPTIONS => DBMS_LOGMNR.addfile); EXECUTE DBMS_LOGMNR.add_logfile(LOGFILENAME => '/oracle/app/oracle/product/11.2/admin/edcu/arc_redo_log/1_39309_769799469.dbf', OPTIONS => DBMS_LOGMNR.addfile); EXECUTE DBMS_LOGMNR.START_LOGMNR(OPTIONS => DBMS_LOGMNR.DICT_FROM_ONLINE_CATALOG); SELECT to_char(timestamp,'DD-MM-YYYY HH24:MI:SS'), operation,username, os_username, machine_name, session_info, sql_redo FROM v$logmnr_contents where seg_owner='MANAGER' and seg_name='TEST2' 02-07-2020 09:40:20 DDL MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN create table test2 (p1 number); 02-07-2020 09:40:47 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1") values (HEXTORAW('c117')); 02-07-2020 09:40:53 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1") values (HEXTORAW('c119')); 02-07-2020 09:40:57 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1") values (HEXTORAW('c137')); 02-07-2020 09:41:01 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1") values (HEXTORAW('c20219')); 02-07-2020 09:41:45 DDL MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN alter table test2 add (p2 varchar2(200)); 02-07-2020 09:42:12 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c20219'),HEXTORAW('746573743220746573743120')); 02-07-2020 09:42:24 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c2021a'),HEXTORAW('746573743420746573743420')); 02-07-2020 09:46:24 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c2021a'),HEXTORAW('746573743420746573743420')); 02-07-2020 09:46:25 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c2021a'),HEXTORAW('746573743420746573743420')); 02-07-2020 09:46:26 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c2021a'),HEXTORAW('746573743420746573743420')); 02-07-2020 09:46:27 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c2021a'),HEXTORAW('746573743420746573743420')); 02-07-2020 09:46:28 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("COL 1","COL 2") values (HEXTORAW('c2021a'),HEXTORAW('746573743420746573743420')); 02-07-2020 09:54:37 DDL MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN comment on table test2 is 'test'; 02-07-2020 10:16:36 DDL MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN alter table test2 add (p3 varchar2(100)); 02-07-2020 10:17:07 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("P1","P2","P3") values ('125','test6','test4 '); 02-07-2020 10:17:08 INSERT MANAGER DeminDV HOME\DEMIN login_username=MANAGER client_info= OS_username=DeminDV Machine_name=HOME\DEMIN insert into "MANAGER"."TEST2"("P1","P2","P3") values ('125','test6','test4 '); ' ```
62,672,947
I'm following a tutorial on Laravel, adding to a DB via a form. At the end of a function that saves to a DB, it returns back to the page where the form is, but I want to be taken to another page where the information is displayed. In the tutorial I created a controller with a function that returns a view containing all the database info - that element works fine however I can't seem to find a way of calling this function directly after saving to the database. I can also return any other view which just displays static view ( just html with no data handling ). Is what I'm trying to achieve possible? ``` public function store(){ $li = new \App\LTest1(); $li->creator = request('creator'); $li->title = request('title'); $li->views = request('views'); $li->save(); return back(); // this works // return view('info'); // this works //return ('Listings@showList'); this doesnt work = how do i call a function in a controller??? } // routing Route::get('info', function () { return view('info'); // i can get to this static page from my store() function }); Route::get('thedataviewpage', 'Listings@showList'); // you can route to this but not from the store() function ```
2020/07/01
[ "https://Stackoverflow.com/questions/62672947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8639588/" ]
[Redirect](https://laravel.com/docs/5.2/responses#redirects) is the thing you need here ``` public function store() { $li = new \App\LTest1(); $li->creator = request('creator'); $li->title = request('title'); $li->views = request('views'); $li->save(); return redirect('info'); // Redirect to the info route } ```
Take this example. Be sure to add the proper route name and a proper message. `return redirect()->route('put here the route name')->with('success', 'Created.');'`
62,672,947
I'm following a tutorial on Laravel, adding to a DB via a form. At the end of a function that saves to a DB, it returns back to the page where the form is, but I want to be taken to another page where the information is displayed. In the tutorial I created a controller with a function that returns a view containing all the database info - that element works fine however I can't seem to find a way of calling this function directly after saving to the database. I can also return any other view which just displays static view ( just html with no data handling ). Is what I'm trying to achieve possible? ``` public function store(){ $li = new \App\LTest1(); $li->creator = request('creator'); $li->title = request('title'); $li->views = request('views'); $li->save(); return back(); // this works // return view('info'); // this works //return ('Listings@showList'); this doesnt work = how do i call a function in a controller??? } // routing Route::get('info', function () { return view('info'); // i can get to this static page from my store() function }); Route::get('thedataviewpage', 'Listings@showList'); // you can route to this but not from the store() function ```
2020/07/01
[ "https://Stackoverflow.com/questions/62672947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8639588/" ]
[Redirect](https://laravel.com/docs/5.2/responses#redirects) is the thing you need here ``` public function store() { $li = new \App\LTest1(); $li->creator = request('creator'); $li->title = request('title'); $li->views = request('views'); $li->save(); return redirect('info'); // Redirect to the info route } ```
to return to a controller action just use ``` return redirect()->action('Listings@showList'); ``` or you can use route to call that controller action ``` return redirect('/thedataviewpage'); ```
62,672,975
So I have this selection list with radio buttons that looks like this: [![selection list](https://i.stack.imgur.com/OBGw7.png)](https://i.stack.imgur.com/OBGw7.png) What I try to do is when 'AT' is selected I Want to be able to select 1 more option. for example if 'AT' is checked I also want to be able to check 'Herstart'. so this condition only needs to happen when 'AT' is selected. this is a picture of the console on how the radio buttons are build : [![radio build](https://i.stack.imgur.com/vgztF.png)](https://i.stack.imgur.com/vgztF.png) I was thinking on something like `if(data-status =="AT"){ allow to check one more radio button}` but here I am stuck on what to write in the if block. this is also not my code so it's even harder to come with a solution. anyone can point me in the right direction ? kind regards
2020/07/01
[ "https://Stackoverflow.com/questions/62672975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13686387/" ]
[Redirect](https://laravel.com/docs/5.2/responses#redirects) is the thing you need here ``` public function store() { $li = new \App\LTest1(); $li->creator = request('creator'); $li->title = request('title'); $li->views = request('views'); $li->save(); return redirect('info'); // Redirect to the info route } ```
Take this example. Be sure to add the proper route name and a proper message. `return redirect()->route('put here the route name')->with('success', 'Created.');'`
62,672,975
So I have this selection list with radio buttons that looks like this: [![selection list](https://i.stack.imgur.com/OBGw7.png)](https://i.stack.imgur.com/OBGw7.png) What I try to do is when 'AT' is selected I Want to be able to select 1 more option. for example if 'AT' is checked I also want to be able to check 'Herstart'. so this condition only needs to happen when 'AT' is selected. this is a picture of the console on how the radio buttons are build : [![radio build](https://i.stack.imgur.com/vgztF.png)](https://i.stack.imgur.com/vgztF.png) I was thinking on something like `if(data-status =="AT"){ allow to check one more radio button}` but here I am stuck on what to write in the if block. this is also not my code so it's even harder to come with a solution. anyone can point me in the right direction ? kind regards
2020/07/01
[ "https://Stackoverflow.com/questions/62672975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13686387/" ]
[Redirect](https://laravel.com/docs/5.2/responses#redirects) is the thing you need here ``` public function store() { $li = new \App\LTest1(); $li->creator = request('creator'); $li->title = request('title'); $li->views = request('views'); $li->save(); return redirect('info'); // Redirect to the info route } ```
to return to a controller action just use ``` return redirect()->action('Listings@showList'); ``` or you can use route to call that controller action ``` return redirect('/thedataviewpage'); ```
62,673,020
In my case, I have a **Stack** containing **Icon** and **Card** I want the icon to appear in the right corner in case **LTR** and in the left corner in case **RTL** I have the following code: ``` Stack( children: <Widget>[ Card( color: Colors.white, elevation: 4, margin: EdgeInsets.only(top: 8, right: 8, left: 8), child: Container( height: 100, width: double.infinity, child: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('text 1'), Text('text 2'), Text('text 3'), ], ), ), ), ), Positioned( top: 10, left: 10, child: Icon( Icons.ac_unit, size: 50, ), ) ], ); ``` The result in **RTL** mode is : [![enter image description here](https://i.stack.imgur.com/nL7VC.jpg)](https://i.stack.imgur.com/nL7VC.jpg) The result in **LTR** mode is : [![enter image description here](https://i.stack.imgur.com/xEJhv.jpg)](https://i.stack.imgur.com/xEJhv.jpg) **How can I fix this**
2020/07/01
[ "https://Stackoverflow.com/questions/62673020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10498374/" ]
try this ``` Positioned.directional(textDirection:Directionality.of(context) , top: 10, end: 10, child: Icon( Icons.ac_unit, size: 50, ), ) ```
**UPDATE** Put the icon inside a Container with maxWidth and set the alignment like below ``` alignment: isRTL? Alignment.centerLeft: Alignment.centerRight; ``` set the alignment property of Stack like this. when the Language is changed to RTL just call ``` setState((){ isRTL = true; }) ``` in a stateful widget. vice versa if you want to change it to LTR
62,673,049
I have a form in a modal (bootstrap4 theme for a wordpress site) in php. After a user submits the form in this modal, the page "reloads" and the "Form submitted successfully" message replaces the form. This means that when a user clicks the button to open the modal again, there is no form there; just a success message. How do I prevent this behaviour? I want to "reset" the form for a user to a clean form so they can submit again and again each time. This is the site code in context: <https://github.com/bettersg/mediaspin/blob/master/articlemodal.php> And this is the form itself: ``` <div class="fade modal pg-show-modal" id="article_modal" tabindex="-1" role="dialog" aria-labelledby="article_modal" aria-hidden="true"> <div class="modal-dialog" role="document"> <?php $mailer = new PG_Article_Form_Mailer(); ?> <?php $mailer->process( array( 'form_id' => 'article_form_mailer_id', 'send_to_email' => true, 'save_to_post_type' => true, 'post_type' => 'article', 'captcha' => true, 'captcha_key' => get_theme_mod( 'captcha_key' ), 'captcha_secret' => get_theme_mod( 'captcha_secret' ) ) ); ?> <?php if( !$mailer->processed || $mailer->error) : ?> <form action="#" class="wordpress-ajax-form" method="post" onsubmit="event.stopImmediatePropagation();event.stopPropagation();"> <div class="modal-content" id="article_form_mailer_id"> <div class="modal-header"> <h5 class="modal-title" id="article_modallabel"><?php _e( 'New Article Submission for Current Issue', 'mediaspintheme' ); ?></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <?php global $post; ?> <input type="hidden" placeholder="CurrentIssue" name="issue" value="<?php echo $post->ID; ?>"></input> <div class="form-group"> <label for="message-text" class="form-control-label"> <?php _e( 'Link to news article (not social media or forum post) that spins it:', 'mediaspintheme' ); ?> </label> <input type="text" class="form-control" id="article1" required placeholder="https://linkhere.com (do not post social media or forum links)" name="article1" value="<?php echo ( isset( $_POST['article1'] ) ? $_POST['article1'] : '' ); ?>"> </div> <div class="g-recaptcha" style="margin:10px 0;" data-sitekey="<?php echo get_theme_mod( 'captcha_key' ) ?>"></div> <input type="hidden" name="article_form_mailer_id" value="1"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> <?php _e( 'Close', 'mediaspintheme' ); ?> </button> <button type="submit" class="btn btn-primary"> <?php _e( 'SUBMIT', 'mediaspintheme' ); ?> </button> </div> </div> </form> <?php endif; ?> </div> </div> <?php if( $mailer->processed ) : ?> <?php echo $mailer->message; ?> <?php endif; ?> ``` I suspect it is because of the way the if statement ( `<?php if( !$mailer->processed || $mailer->error) : ?>`) is framed around the form but i'm not sure what the correct approach is. Any advice on how to change the if statement or to move it such that it does not cause the form to disappear after successful submission? The form submits properly and everything works. But this interface quirk is annoying.
2020/07/01
[ "https://Stackoverflow.com/questions/62673049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7265928/" ]
You are not using if in the correct way. In your structure, the form is displayed only when there has been an error or is never been sent. To solve, refactor as follows: ``` <?php if( $mailer->processed ) : ?> <?php echo $mailer->message; ?> <?php endif; ?> <div class="fade modal pg-show-modal" id="article_modal" tabindex="-1" role="dialog" aria-labelledby="article_modal" aria-hidden="true"> <div class="modal-dialog" role="document"> <?php $mailer = new PG_Article_Form_Mailer(); ?> <?php $mailer->process( array( 'form_id' => 'article_form_mailer_id', 'send_to_email' => true, 'save_to_post_type' => true, 'post_type' => 'article', 'captcha' => true, 'captcha_key' => get_theme_mod( 'captcha_key' ), 'captcha_secret' => get_theme_mod( 'captcha_secret' ) ) ); ?> <form action="#" class="wordpress-ajax-form" method="post" onsubmit="event.stopImmediatePropagation();event.stopPropagation();"> <div class="modal-content" id="article_form_mailer_id"> <div class="modal-header"> <h5 class="modal-title" id="article_modallabel"><?php _e( 'New Article Submission for Current Issue', 'mediaspintheme' ); ?></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <?php global $post; ?> <input type="hidden" placeholder="CurrentIssue" name="issue" value="<?php echo $post->ID; ?>"></input> <div class="form-group"> <label for="message-text" class="form-control-label"> <?php _e( 'Link to news article (not social media or forum post) that spins it:', 'mediaspintheme' ); ?> </label> <input type="text" class="form-control" id="article1" required placeholder="https://linkhere.com (do not post social media or forum links)" name="article1" value="<?php echo ( isset( $_POST['article1'] ) ? $_POST['article1'] : '' ); ?>"> </div> <div class="g-recaptcha" style="margin:10px 0;" data-sitekey="<?php echo get_theme_mod( 'captcha_key' ) ?>"></div> <input type="hidden" name="article_form_mailer_id" value="1"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> <?php _e( 'Close', 'mediaspintheme' ); ?> </button> <button type="submit" class="btn btn-primary"> <?php _e( 'SUBMIT', 'mediaspintheme' ); ?> </button> </div> </div> </form> </div> </div> ```
You could deal with jQuery and AJAX. ``` $('.wordpress-ajax-form').on('submit', function(e) { // Prevent page reloading e.preventDefault(); $.ajax({ type: 'POST', url: 'youScript.php', data: { 'youWillGetThisValueInPhpWithThisName': $('.your-input').val(), // others inputs } }); }); ```
62,673,071
I'm working on a website and came upon a strange problem with i18next that I can't seem to solve. I want i18next to save the current language in a cookie but only when the user has accepted to store cookies (custom cookie banner component) Currently, I have the following code: ### i18n.js ``` import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import Backend from 'i18next-xhr-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) .init({ whitelist: ['en', 'fr', 'nl'], fallbackLng: 'en', interpolation: { escapeValue: false, }, ns: [ 'common', ], react: { wait: true, }, detection: { caches: ['cookie'], lookupFromPathIndex: 0, }, }); ``` ### index.js ``` import React, { Suspense } from 'react'; import ReactDOM from 'react-dom'; import './i18n'; ... ``` My problem is with the `caches: ['cookie']` property. I want it to be include "cookie" but only after the user has clicked on an "I Agree" button somewhere on the website. Is there a way to first load the i18next with an empty caches array and reload the object when the user clicked on "I Agree". On the next page visit (when the user accepted cookies) i18next should know it can read from the language cookie as well. But I think when I know how to fix the first issue I can solve this issue easily.
2020/07/01
[ "https://Stackoverflow.com/questions/62673071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3699263/" ]
You are not using if in the correct way. In your structure, the form is displayed only when there has been an error or is never been sent. To solve, refactor as follows: ``` <?php if( $mailer->processed ) : ?> <?php echo $mailer->message; ?> <?php endif; ?> <div class="fade modal pg-show-modal" id="article_modal" tabindex="-1" role="dialog" aria-labelledby="article_modal" aria-hidden="true"> <div class="modal-dialog" role="document"> <?php $mailer = new PG_Article_Form_Mailer(); ?> <?php $mailer->process( array( 'form_id' => 'article_form_mailer_id', 'send_to_email' => true, 'save_to_post_type' => true, 'post_type' => 'article', 'captcha' => true, 'captcha_key' => get_theme_mod( 'captcha_key' ), 'captcha_secret' => get_theme_mod( 'captcha_secret' ) ) ); ?> <form action="#" class="wordpress-ajax-form" method="post" onsubmit="event.stopImmediatePropagation();event.stopPropagation();"> <div class="modal-content" id="article_form_mailer_id"> <div class="modal-header"> <h5 class="modal-title" id="article_modallabel"><?php _e( 'New Article Submission for Current Issue', 'mediaspintheme' ); ?></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <?php global $post; ?> <input type="hidden" placeholder="CurrentIssue" name="issue" value="<?php echo $post->ID; ?>"></input> <div class="form-group"> <label for="message-text" class="form-control-label"> <?php _e( 'Link to news article (not social media or forum post) that spins it:', 'mediaspintheme' ); ?> </label> <input type="text" class="form-control" id="article1" required placeholder="https://linkhere.com (do not post social media or forum links)" name="article1" value="<?php echo ( isset( $_POST['article1'] ) ? $_POST['article1'] : '' ); ?>"> </div> <div class="g-recaptcha" style="margin:10px 0;" data-sitekey="<?php echo get_theme_mod( 'captcha_key' ) ?>"></div> <input type="hidden" name="article_form_mailer_id" value="1"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> <?php _e( 'Close', 'mediaspintheme' ); ?> </button> <button type="submit" class="btn btn-primary"> <?php _e( 'SUBMIT', 'mediaspintheme' ); ?> </button> </div> </div> </form> </div> </div> ```
You could deal with jQuery and AJAX. ``` $('.wordpress-ajax-form').on('submit', function(e) { // Prevent page reloading e.preventDefault(); $.ajax({ type: 'POST', url: 'youScript.php', data: { 'youWillGetThisValueInPhpWithThisName': $('.your-input').val(), // others inputs } }); }); ```
62,673,074
I want to download the sign language dataset from [Kaggle](https://www.kaggle.com/datamunge/sign-language-mnist) to my Colab. So far I always used wget and the specific zip file link, for example: ``` !wget --no-check-certificate \ https://storage.googleapis.com/laurencemoroney-blog.appspot.com/rps.zip \ -O /tmp/rps.zip ``` However, when I right-click the download button at Kaggle and select copy link to get the path copied to my clipboard and I output it I get: <https://www.kaggle.com/datamunge/sign-language-mnist/download> When I use this link in my browser I am asked to download it. I can see that the filename is 3258\_5337\_bundle\_archive.zip So I tried: ``` !wget --no-check-certificate \ https://www.kaggle.com/datamunge/sign-language-mnist/download3258_5337_bundle_archive.zip \ -O /tmp/kds.zip ``` and also tried: ``` !wget --no-check-certificate \ https://www.kaggle.com/datamunge/sign-language-mnist/download3258_5337_bundle_archive.zip \ -O /tmp/kds.zip ``` I get as output: [![exa](https://i.stack.imgur.com/zadwH.png)](https://i.stack.imgur.com/zadwH.png) So it does not work. File coudln't be found or the returned zip archive is not 101mb large, but just a few kb. Also when trying to unzip it, it does not work. How can I download this file into my colab (directly with wget?)?
2020/07/01
[ "https://Stackoverflow.com/questions/62673074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2165335/" ]
Kaggle recommends using their own API instead of wget or rsync. First, make an API token for Kaggle. On Kaggle's website go to "My Account", Scroll to API section and click on "Create New API Token" - It will download kaggle.json file on your machine. Then run the following in Google Colab: ``` from google.colab import files files.upload() # Browse for the kaggle.json file that you downloaded # Make directory named kaggle, copy kaggle.json file there, and change the permissions of the file. ! mkdir ~/.kaggle ! cp kaggle.json ~/.kaggle/ ! chmod 600 ~/.kaggle/kaggle.json # You can check if everything's okay by running this command. ! kaggle datasets list # Download and unzip sign-language-mnist dataset into '/usr/local' ! kaggle datasets download -d datamunge/sign-language-mnist --path '/usr/local' --unzip ``` Used info from here: <https://www.kaggle.com/general/74235>
This is the simplest way I came up to do it (if you participate in competition just change datasets to competitions): ``` import os os.environ['KAGGLE_USERNAME'] = "xxxx" os.environ['KAGGLE_KEY'] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" !kaggle datasets download -d iarunava/happy-house-dataset ```
62,673,091
I'm toying around with instance control flow and static control flow, notice the code below ``` class A { { m1(); } A(){ System.out.println("A constructor"); } void m1(){ System.out.println("A m1"); } } public class Main extends A { public static void main(String[] args) throws Exception { Main m = new Main(); } void m1(){ System.out.println("Main m1"); } } ``` The output for the code is: Main m1 A constructor I know this is because: First, static blocks and variables were identified top-to-bottom parent-to-child, in this case there was just a `main()` that was static. Second, the static blocks and variable assignments are executed, so `main()`'s execution starts, and there is an attempt to create a new `Main` object. So third, the instance blocks and variables of parent class will be identified. Then they will be executed top-bottom. (After that the constructor of the parent class will run, then the instance blocks and variables of child class will be identified, following which they will be executed top-bottom and finally the child class' constructor will execute). So the instance block inside A, calls `m1()`. Then, A's constructor executes. Finally, control flow is returned to `main()` and program terminates. Now, the call to `m1()` from A invoked `m1()` of `Main`. However, had I made both the `m1()` methods static, everything else remaining same, the call to `m1()` from the instance block of A would then have invoked `m1()` of A. I have two questions(Why? Purely for academic reasons, I'm still learning Java): 1. When both the `m1()` methods are non-static, is it possible to invoke A's m1() from the instance block of A? I tried doing a `this.m1()` but that still invoked Main's m1().(Why?) 2. When both the `m1()` methods are static, is it possible to invoke Main's m1() from the instance block of A? (I'm guessing no but I'm not certain). I know in the first case, it's overriding taking place, and in the second case it's method hiding. But I'm still not sure how to answer my questions based on that knowledge.
2020/07/01
[ "https://Stackoverflow.com/questions/62673091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12279039/" ]
After compilation is done java 8 compiler your code looks like this: ``` class A { A() { this.m1(); // at runtime this refers to Main class instance System.out.println("A constructor"); } void m1() { System.out.println("A m1"); } } public class Main extends A { public Main() { } public static void main(String[] args) throws Exception { Main m = new Main(); m.m1(); } void m1() { System.out.println("Main m1"); } } ``` Now to answer your first question: No. You cannot unless you are creating an instance of A(actual object of A). To your second question: after making both m1's static compilation looks like this: ``` class A { A() { m1(); // resolves to A's m1 System.out.println("A constructor"); } static void m1() { System.out.println("A m1"); } } public class Main extends A { public Main() { } public static void main(String[] args) throws Exception { new Main(); } static void m1() { System.out.println("Main m1"); } } ``` Now no matter which instance(A or Main) you create you will see A's m1 excuted.
1.(When two methods are instance method) If you are inside the A (parent) class, if you call `m1()`; or `this.m1();` you will call the A version of the `m1()` method but if you are inside the main class (child), if you call `m1();` you will call the main version of m1 although if you call `super.m1();` you will be calling the A version of m1 method. 2.(If the methods are static) you can call each version wherever you want, without and object of a class, for example, you can invoke main´s m1 method inside the A block with the following line `Main.m1(); // ClassName.StaticMethodName();`
62,673,115
I am currently working with Darknet on Yolov4, with 1 class. I need to export those weights to onnx format, for tensorRT inference. I've tried multiple technics, using [ultralytics](https://github.com/ultralytics/yolov3) to convert or [going from tensorflow to onnx](https://github.com/hunglc007/tensorflow-yolov4-tflite). But none seems to work. Is there a direct way to do it?
2020/07/01
[ "https://Stackoverflow.com/questions/62673115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9333287/" ]
Check this GitHub repo: <https://github.com/Tianxiaomo/pytorch-YOLOv4> Running the `demo_darknet2onnx.py` script you'll be able to generate the ONNX model from the `.cfg` and `.weights` darknet files. Usage example: `python demo_darknet2onnx.py <cfgFile> <weightFile> <imageFile> <batchSize>` You can also decide the batch size for the inference calls of the converted model.
The following repo exports yolov3 models from darknet to onnx, for tensorRT inference. You can use this as reference for your model. <https://github.com/jkjung-avt/tensorrt_demos/tree/master/yolo>
62,673,115
I am currently working with Darknet on Yolov4, with 1 class. I need to export those weights to onnx format, for tensorRT inference. I've tried multiple technics, using [ultralytics](https://github.com/ultralytics/yolov3) to convert or [going from tensorflow to onnx](https://github.com/hunglc007/tensorflow-yolov4-tflite). But none seems to work. Is there a direct way to do it?
2020/07/01
[ "https://Stackoverflow.com/questions/62673115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9333287/" ]
The following repo exports yolov3 models from darknet to onnx, for tensorRT inference. You can use this as reference for your model. <https://github.com/jkjung-avt/tensorrt_demos/tree/master/yolo>
You can convert scaled YOLO-yolov4,yolov4-csp.yolov4x-mish,yolov4-P5 etc models into onxx & its perfectly work fine. <https://github.com/linghu8812/tensorrt_inference>
62,673,115
I am currently working with Darknet on Yolov4, with 1 class. I need to export those weights to onnx format, for tensorRT inference. I've tried multiple technics, using [ultralytics](https://github.com/ultralytics/yolov3) to convert or [going from tensorflow to onnx](https://github.com/hunglc007/tensorflow-yolov4-tflite). But none seems to work. Is there a direct way to do it?
2020/07/01
[ "https://Stackoverflow.com/questions/62673115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9333287/" ]
Check this GitHub repo: <https://github.com/Tianxiaomo/pytorch-YOLOv4> Running the `demo_darknet2onnx.py` script you'll be able to generate the ONNX model from the `.cfg` and `.weights` darknet files. Usage example: `python demo_darknet2onnx.py <cfgFile> <weightFile> <imageFile> <batchSize>` You can also decide the batch size for the inference calls of the converted model.
You can convert scaled YOLO-yolov4,yolov4-csp.yolov4x-mish,yolov4-P5 etc models into onxx & its perfectly work fine. <https://github.com/linghu8812/tensorrt_inference>
62,673,139
I am using Django 2.2 and Python 3.6. I deployed a Django REST server using AWS EB, but I get the following error. It works fine on the local side, but an error occurs in the EB instance. As a result of my analysis, request.user is recognized normally on the local, but on the EB it is marked as an anonymous user. I am using the same code, but why does this happen? ``` REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 10, "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework_simplejwt.authentication.JWTAuthentication", ], } ``` I changed the above code to the below code because it is a problem of AUTHENTICATION\_CLASSES, but I still get an error. ``` REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 10, "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework_simplejwt.authentication.JWTAuthentication", "rest_framework.authentication.BasicAuthentication", "rest_framework.authentication.SessionAuthentication", ], } ``` **Error Detail** ``` AttributeError 'AnonymousUser' object has no attribute 'is_admin' users/permissions.py in has_permission at line 26 def has_permission(self, request, view): print("=" * 50) print(request.user) print("=" * 50) return bool(request.user and request.user.is_admin) ``` **Timeline** ``` > GET /api/v1/users/ HTTP/1.1 > Host: instance.ap-northeast-2.elasticbeanstalk.com > User-Agent: insomnia/2020.2.2 > Content-Type: application/json > Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkzNjA4Nzg5LCJqdGkiOiJmZGY5YmM4MWM3M2I0YTU3YmZkODg2YmU5ZWVlMGEzZCIsInVzZXJfaWQiOjN9.kLv3H7ygzVomI2DgU84I900m4CydhL48Ob86SX5IEaQ ``` **users/models.py** ``` class User(AbstractBaseUser, TimeStampedModel): objects = UserManager() GENDER_MALE = "male" GENDER_FEMALE = "female" GENDER_OTHER = "other" GENDER_CHOICES = ( (GENDER_MALE, "Male"), (GENDER_FEMALE, "Female"), (GENDER_OTHER, "Other"), ) email = models.EmailField(unique=True) username = models.CharField(max_length=20, unique=True) gender = models.CharField(max_length=5, choices=GENDER_CHOICES) birth = models.DateField() avatar = models.ImageField(upload_to="user_avatars/%Y/%m/%d", blank=True) is_admin = models.BooleanField(default=False) ``` **users/views.py** ``` from .permissions import IsSelf, IsAdminOrSelf, IsAdminUser class UsersViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def get_permissions(self): if self.action == "list": permission_classes = [IsAdminUser] elif self.action == "create" or self.action == "retrieve": permission_classes = [AllowAny] elif self.action == "destroy": permission_classes = [IsAdminOrSelf] else: permission_classes = [IsSelf] ``` **users/permissions.py** ``` from rest_framework.permissions import BasePermission class IsSelf(BasePermission): def has_object_permission(self, request, view, user): return bool(user == request.user) class IsAdminOrSelf(BasePermission): def has_object_permission(self, request, view, user): is_self = bool(user == request.user) is_admin = request.user.is_admin return is_self or is_admin class IsAdminUser(BasePermission): """ Allows access only to admin users. """ def has_permission(self, request, view): print("=" * 50) print(request.user) print("=" * 50) return bool(request.user and request.user.is_admin) ``` **Server Traceback** ``` Traceback: File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/viewsets.py" in view 114. return self.dispatch(request, *args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch 505. response = self.handle_exception(exc) File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception 465. self.raise_uncaught_exception(exc) File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py" in raise_uncaught_exception 476. raise exc File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch 493. self.initial(request, *args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/sentry_sdk/integrations/django/__init__.py" in sentry_patched_drf_initial 258. return old_drf_initial(self, request, *args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py" in initial 411. self.check_permissions(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py" in check_permissions 332. if not permission.has_permission(request, self): File "/opt/python/current/app/users/permissions.py" in has_permission 26. return bool(request.user and request.user.is_admin) Exception Type: AttributeError at /api/v1/users/ Exception Value: 'AnonymousUser' object has no attribute 'is_admin' Request information: USER: AnonymousUser GET: No GET data POST: No POST data FILES: No FILES data COOKIES: No cookie data ``` **JWT Auth users/urls.py** ``` from rest_framework.routers import DefaultRouter from rest_framework_simplejwt import views as jwt_views from django.urls import path from . import views urlpatterns = [ path("token/", jwt_views.TokenObtainPairView.as_view(), name="token_obtain_pair"), path("token/refresh/", jwt_views.TokenRefreshView.as_view(), name="token_refresh"), ] ``` Session-based authentication seems to work. [![session-based](https://i.stack.imgur.com/OmXeh.png)](https://i.stack.imgur.com/OmXeh.png) In my opinion, the Authorization header doesn't seem to work. ``` # code class IsAdminUser(BasePermission): """ Allows access only to admin users. """ def has_permission(self, request, view): print("=" * 50) print(request.auth) print(request.data) print(request.user) print("=" * 50) return bool(request.user and request.user.is_admin) # result in AWS EB [Wed Jul 01 20:37:28.712785 2020] [:error] [pid 3995] ================================================== [Wed Jul 01 20:37:28.712834 2020] [:error] [pid 3995] None [Wed Jul 01 20:37:28.713505 2020] [:error] [pid 3995] <QueryDict: {}> [Wed Jul 01 20:37:28.713522 2020] [:error] [pid 3995] AnonymousUser [Wed Jul 01 20:37:28.713529 2020] [:error] [pid 3995] ================================================== # result in localhost System check identified no issues (0 silenced). July 01, 2020 - 20:43:04 Django version 2.2.12, using settings 'config.settings' Starting development server at http://127.0.0.1:9000/ Quit the server with CONTROL-C. ================================================== eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkzNjA1MzM0LCJqdGkiOiIyOTY3ZTQ3MDEzY2Q0MDNlODQxN2VjNTNkMDU4ZDRjZiIsInVzZXJfaWQiOjF9.3czMFSzMR-g-vraPnOhhf0UCWamlIpSLuD0I1RBJOnA <QueryDict: {}> 1 : tim ================================================== [01/Jul/2020 20:43:13] "GET /api/v1/users/ HTTP/1.1" 200 1768 ``` What the hell is the problem..
2020/07/01
[ "https://Stackoverflow.com/questions/62673139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9688343/" ]
The first problem is that `AnonymousUser` does not have an `is_admin` property in django. You can maybe check `is_superuser` or check if your user is authenticated before calling `is_admin` on it. See [How to check if a user is logged in (how to properly use user.is\_authenticated)?](https://stackoverflow.com/questions/3644902/how-to-check-if-a-user-is-logged-in-how-to-properly-use-user-is-authenticated) for that. About the difference between local and distant, I would guess that you're logged in on your local app but not on your distant app. This is why `AnonymousUser` gets returned by `request.user` on your distant app.
The problem I encountered was the same as the cause in this [question](https://stackoverflow.com/questions/62686560/is-there-an-aws-inbound-policy-that-interferes-with-authorization-bearer-toke). This is also a known issue on the AWS forums. **You can fix it in the following way:** ``` # .ebextensions/wsgihacks.config files: "/etc/httpd/conf.d/wsgihacks.conf": mode: "000644" owner: root group: root content: | WSGIPassAuthorization on ``` Original thread: <https://forums.aws.amazon.com/message.jspa?messageID=376244>
62,673,143
I have a grid of 3 items per row. And I need to have lines between the items... I've been struggling with the :nth selectors but I can't get it working the correct way. Maybe someone can help me with this? See the image for a visual indication of what I need. [![enter image description here](https://i.stack.imgur.com/Ti3qK.jpg)](https://i.stack.imgur.com/Ti3qK.jpg)
2020/07/01
[ "https://Stackoverflow.com/questions/62673143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5301942/" ]
You can: * Make a grid using CSS grid * Use `::after` to add a line after each box * Use `::nth-child(3n)` to hide this `::after` line for every 3rd box (last box in the row) using `display:none` I've written up a little example here: <https://codepen.io/annaazzam/pen/xxZPpXg>
try this. ```css hr{ /and add some width and height and border to this / } ``` ```html <div class="container"> <div class="row"> <div class="col-sm"> One of three columns </div> <hr> <div class="col-sm"> One of three columns </div> <hr> <div class="col-sm"> One of three columns </div> </div> </div> ```
62,673,143
I have a grid of 3 items per row. And I need to have lines between the items... I've been struggling with the :nth selectors but I can't get it working the correct way. Maybe someone can help me with this? See the image for a visual indication of what I need. [![enter image description here](https://i.stack.imgur.com/Ti3qK.jpg)](https://i.stack.imgur.com/Ti3qK.jpg)
2020/07/01
[ "https://Stackoverflow.com/questions/62673143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5301942/" ]
You can achieve it targeting each item except the last of a row and using a ::pseudo-element ```css .row { display: flex; } .item { width: 33.3%; height: 100px; padding: 6rem; margin: 1rem; background-color: #777; position: relative; } .item:not(:nth-child(3n))::after{ display: block; content: ""; position: absolute; height: 100%; width: 2px; right: -1rem; top: 0; border-right: 1px solid blue; } ``` ```html <div class="grid"> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </div> ```
try this. ```css hr{ /and add some width and height and border to this / } ``` ```html <div class="container"> <div class="row"> <div class="col-sm"> One of three columns </div> <hr> <div class="col-sm"> One of three columns </div> <hr> <div class="col-sm"> One of three columns </div> </div> </div> ```
62,673,143
I have a grid of 3 items per row. And I need to have lines between the items... I've been struggling with the :nth selectors but I can't get it working the correct way. Maybe someone can help me with this? See the image for a visual indication of what I need. [![enter image description here](https://i.stack.imgur.com/Ti3qK.jpg)](https://i.stack.imgur.com/Ti3qK.jpg)
2020/07/01
[ "https://Stackoverflow.com/questions/62673143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5301942/" ]
You can: * Make a grid using CSS grid * Use `::after` to add a line after each box * Use `::nth-child(3n)` to hide this `::after` line for every 3rd box (last box in the row) using `display:none` I've written up a little example here: <https://codepen.io/annaazzam/pen/xxZPpXg>
You can achieve it targeting each item except the last of a row and using a ::pseudo-element ```css .row { display: flex; } .item { width: 33.3%; height: 100px; padding: 6rem; margin: 1rem; background-color: #777; position: relative; } .item:not(:nth-child(3n))::after{ display: block; content: ""; position: absolute; height: 100%; width: 2px; right: -1rem; top: 0; border-right: 1px solid blue; } ``` ```html <div class="grid"> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </div> ```
62,673,212
I'm studying Python and I'd like to have some hints on how to write it as I read about the implementation of a fetch(url) function as follows: ``` _cache = {} def fetch(url): user = os.environ['USER'] if user not in _cache: _cache[user] = {} if url not in _cache[user]: _cache[user][url] = requests.get(url).content return _cache[user][url] ``` and I'm trying to figure out how to modify this kind of function in order it checks wether a user has fetched some url or not, assuming that fetching a resource from web might take 0.1 seconds, while fetching it on the cache provides an instant result. It should be something like ``` import sys # ignore sys.path.insert(0,'.') # ignore from Root.fetch import fetch def did_fetch(user, url): pass #return if url has been fatched by user ``` with the function to be implemented inside
2020/07/01
[ "https://Stackoverflow.com/questions/62673212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13621771/" ]
You can: * Make a grid using CSS grid * Use `::after` to add a line after each box * Use `::nth-child(3n)` to hide this `::after` line for every 3rd box (last box in the row) using `display:none` I've written up a little example here: <https://codepen.io/annaazzam/pen/xxZPpXg>
try this. ```css hr{ /and add some width and height and border to this / } ``` ```html <div class="container"> <div class="row"> <div class="col-sm"> One of three columns </div> <hr> <div class="col-sm"> One of three columns </div> <hr> <div class="col-sm"> One of three columns </div> </div> </div> ```
62,673,212
I'm studying Python and I'd like to have some hints on how to write it as I read about the implementation of a fetch(url) function as follows: ``` _cache = {} def fetch(url): user = os.environ['USER'] if user not in _cache: _cache[user] = {} if url not in _cache[user]: _cache[user][url] = requests.get(url).content return _cache[user][url] ``` and I'm trying to figure out how to modify this kind of function in order it checks wether a user has fetched some url or not, assuming that fetching a resource from web might take 0.1 seconds, while fetching it on the cache provides an instant result. It should be something like ``` import sys # ignore sys.path.insert(0,'.') # ignore from Root.fetch import fetch def did_fetch(user, url): pass #return if url has been fatched by user ``` with the function to be implemented inside
2020/07/01
[ "https://Stackoverflow.com/questions/62673212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13621771/" ]
You can achieve it targeting each item except the last of a row and using a ::pseudo-element ```css .row { display: flex; } .item { width: 33.3%; height: 100px; padding: 6rem; margin: 1rem; background-color: #777; position: relative; } .item:not(:nth-child(3n))::after{ display: block; content: ""; position: absolute; height: 100%; width: 2px; right: -1rem; top: 0; border-right: 1px solid blue; } ``` ```html <div class="grid"> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </div> ```
try this. ```css hr{ /and add some width and height and border to this / } ``` ```html <div class="container"> <div class="row"> <div class="col-sm"> One of three columns </div> <hr> <div class="col-sm"> One of three columns </div> <hr> <div class="col-sm"> One of three columns </div> </div> </div> ```
62,673,212
I'm studying Python and I'd like to have some hints on how to write it as I read about the implementation of a fetch(url) function as follows: ``` _cache = {} def fetch(url): user = os.environ['USER'] if user not in _cache: _cache[user] = {} if url not in _cache[user]: _cache[user][url] = requests.get(url).content return _cache[user][url] ``` and I'm trying to figure out how to modify this kind of function in order it checks wether a user has fetched some url or not, assuming that fetching a resource from web might take 0.1 seconds, while fetching it on the cache provides an instant result. It should be something like ``` import sys # ignore sys.path.insert(0,'.') # ignore from Root.fetch import fetch def did_fetch(user, url): pass #return if url has been fatched by user ``` with the function to be implemented inside
2020/07/01
[ "https://Stackoverflow.com/questions/62673212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13621771/" ]
You can: * Make a grid using CSS grid * Use `::after` to add a line after each box * Use `::nth-child(3n)` to hide this `::after` line for every 3rd box (last box in the row) using `display:none` I've written up a little example here: <https://codepen.io/annaazzam/pen/xxZPpXg>
You can achieve it targeting each item except the last of a row and using a ::pseudo-element ```css .row { display: flex; } .item { width: 33.3%; height: 100px; padding: 6rem; margin: 1rem; background-color: #777; position: relative; } .item:not(:nth-child(3n))::after{ display: block; content: ""; position: absolute; height: 100%; width: 2px; right: -1rem; top: 0; border-right: 1px solid blue; } ``` ```html <div class="grid"> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </div> ```
62,673,214
I have three documents indexed with title "manage", "manager", and "management". I am searching by following query: ``` query: { query_string: { "query": "manage*", "fields": ["title"], } } } ``` I am getting same **score** for all three documents. I want document with `"title": "manage"` first, then manager and management.
2020/07/01
[ "https://Stackoverflow.com/questions/62673214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9396994/" ]
You can: * Make a grid using CSS grid * Use `::after` to add a line after each box * Use `::nth-child(3n)` to hide this `::after` line for every 3rd box (last box in the row) using `display:none` I've written up a little example here: <https://codepen.io/annaazzam/pen/xxZPpXg>
try this. ```css hr{ /and add some width and height and border to this / } ``` ```html <div class="container"> <div class="row"> <div class="col-sm"> One of three columns </div> <hr> <div class="col-sm"> One of three columns </div> <hr> <div class="col-sm"> One of three columns </div> </div> </div> ```
62,673,214
I have three documents indexed with title "manage", "manager", and "management". I am searching by following query: ``` query: { query_string: { "query": "manage*", "fields": ["title"], } } } ``` I am getting same **score** for all three documents. I want document with `"title": "manage"` first, then manager and management.
2020/07/01
[ "https://Stackoverflow.com/questions/62673214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9396994/" ]
You can achieve it targeting each item except the last of a row and using a ::pseudo-element ```css .row { display: flex; } .item { width: 33.3%; height: 100px; padding: 6rem; margin: 1rem; background-color: #777; position: relative; } .item:not(:nth-child(3n))::after{ display: block; content: ""; position: absolute; height: 100%; width: 2px; right: -1rem; top: 0; border-right: 1px solid blue; } ``` ```html <div class="grid"> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </div> ```
try this. ```css hr{ /and add some width and height and border to this / } ``` ```html <div class="container"> <div class="row"> <div class="col-sm"> One of three columns </div> <hr> <div class="col-sm"> One of three columns </div> <hr> <div class="col-sm"> One of three columns </div> </div> </div> ```
62,673,214
I have three documents indexed with title "manage", "manager", and "management". I am searching by following query: ``` query: { query_string: { "query": "manage*", "fields": ["title"], } } } ``` I am getting same **score** for all three documents. I want document with `"title": "manage"` first, then manager and management.
2020/07/01
[ "https://Stackoverflow.com/questions/62673214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9396994/" ]
You can: * Make a grid using CSS grid * Use `::after` to add a line after each box * Use `::nth-child(3n)` to hide this `::after` line for every 3rd box (last box in the row) using `display:none` I've written up a little example here: <https://codepen.io/annaazzam/pen/xxZPpXg>
You can achieve it targeting each item except the last of a row and using a ::pseudo-element ```css .row { display: flex; } .item { width: 33.3%; height: 100px; padding: 6rem; margin: 1rem; background-color: #777; position: relative; } .item:not(:nth-child(3n))::after{ display: block; content: ""; position: absolute; height: 100%; width: 2px; right: -1rem; top: 0; border-right: 1px solid blue; } ``` ```html <div class="grid"> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </div> ```
62,673,222
I am a beginner. I have started learning custom views these days, and there are almost no problems in the process. When I went to Google to solve this problem, some people proposed solutions, but none of them was successful. I use a custom view written by Kotlin. This is my custom view class,and the name is MyView.kt ``` package com.example.demos import android.R import android.content.Context import android.content.res.TypedArray import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.util.AttributeSet import android.view.View import kotlin.math.min class MyView : View { // init private lateinit var arcPaint: Paint private lateinit var progressTextPaint: Paint // private lateinit var arcPaintColor: Color private var arcPaintColor = Color.BLACK // private lateinit var progressTextPaintColor: Color private var progressTextPaintColor = Color.BLACK private var angle = 0f private var progress: Float = angle / 3.6f // get/set fun setArcPaintColor(color: Int) { arcPaintColor = color } fun getArcPaintColor(): Int { return arcPaintColor } fun setProgressTextPaintColor(color: Int) { progressTextPaintColor = color } fun getProgressTextPaintColor(): Int { return progressTextPaintColor } fun setAngle(float: Float) { angle = float progress = angle / 3.6f invalidate() } fun getAngle(): Float { return angle } fun setProgress(float: Float) { progress = float angle = progress * 3.6f invalidate() } fun getProgress(): Float { return progress } /*call method initPaint()*/ constructor(context: Context) : super(context) { initPaint() } constructor(context: Context, attributeSet: AttributeSet?) : super(context, attributeSet) { initPaint() } constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) : super( context, attributeSet, defStyleAttr ) { arcPaintColor = typedArray.getColor(R.styleable.arcPaintColor,) initPaint() } /*override onDraw(),draw view*/ override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) drawView(canvas) } //init paints private fun initPaint() { arcPaint = Paint(Paint.ANTI_ALIAS_FLAG).also { it.color = arcPaintColor it.strokeWidth = 5f it.strokeWidth = 40f it.style = Paint.Style.STROKE it.strokeCap = Paint.Cap.ROUND } progressTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).also { it.color = progressTextPaintColor // it.color = Color.GREEN // it.setStrokeWidth(5f) it.style = Paint.Style.FILL it.textSize = 50f } } /*draw view*/ private fun drawView(canvas: Canvas?) { val displayWidth = width val displayHeight = height /*get center of circle*/ val centerX = (displayWidth / 2).toFloat() val centerY = (displayHeight / 2).toFloat() /*get radius*/ val radius = min(displayWidth, displayHeight) / 4 val rectF = RectF( centerX - radius, centerY - radius, centerX + radius, centerY + radius ) canvas?.drawArc( rectF, 0f, angle, false, arcPaint ) canvas?.drawText( "${String.format("%.1f", progress)}%", centerX - progressTextPaint.measureText("${String.format("%.1f", progress)}%") / 2, centerY, progressTextPaint ) } } ``` This is my xml file of custom attributes ``` <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyView"> <attr name="arcPaintColor" format="color"/> <attr name="progressTextPaintColor" format="color"/> </declare-styleable> </resources> ``` [the xml file of my custom attribute](https://i.stack.imgur.com/isv8S.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62673222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13845917/" ]
The issue is that you are importing android.R You need to import the [you package name].R version instead.
You are not picking up the custom attributes correctly. This is how it should be done: ``` val typedArray = context.theme.obtainStyledAttributes( attributeSet, R.styleable.MyView, 0, 0 ) arcPaintColor = typedArray.getColor(R.styleable.MyView_arcPaintColor, 0) typedArray.recycle() // Important! initPaint() ``` You will have to make sure that this code executes in each of your constructors. The first zero will be replace by `defStyleAttr` when that is available. I suggest that you integrate the above code into `initPaint()`. See the [documentation](https://developer.android.com/reference/android/content/res/Resources.Theme#obtainStyledAttributes(android.util.AttributeSet,%20int%5B%5D,%20int,%20int)) for `obtainStyledAttributes()`.
62,673,288
I want to count the occurrences of unique email adresses. In each csv file, multiple people can have the same last or first name. Only the emails are unique. There are only three columns (excel: A,B,C). file1.csv ``` |---------------------|------------------|---------------| | A | B | C | |---------------------|------------------|---------------| | Last Name | First Name | Mail | |---------------------|------------------|---------------| | Johnson | Emma | e.j@abc.com | |---------------------|------------------|---------------| | Johnson | Max | m.j@abc.com | |---------------------|------------------|---------------| | ... | ... | ... | |---------------------|------------------|---------------| ``` file2.csv ``` |---------------------|------------------|---------------| | Last Name | First Name | Mail | |---------------------|------------------|---------------| | Smith | Linda | l.s@abc.com| |---------------------|------------------|---------------| | Johnson | Max | m.j@abc.com| |---------------------|------------------|---------------| | ... | ... | ... | |---------------------|------------------|---------------| ``` ... file89.csv ``` |---------------------|------------------|---------------| | Last Name | First Name | Mail | |---------------------|------------------|---------------| | Miller | Jeremy | je.m@abc.com| |---------------------|------------------|---------------| | Johnson | Max | m.j@abc.com| |---------------------|------------------|---------------| | ... | ... | ... | |---------------------|------------------|---------------| ``` The program should create an output csv file (can be a .txt file too), that counts the occurences (>2) of the unique mail adress and outputs the first and last name. output.csv ``` |---------------------|------------------|---------------|---------------| | Last Name | First Name | Mail | Occurrence | |---------------------|------------------|---------------|---------------| | Johnson | Max | m.j@abc.com| 3 | |---------------------|------------------|---------------|---------------| | ... | ... | ... | ... | |---------------------|------------------|---------------|---------------| ``` possible algorithm: ``` create new temprary csv file : temp.csv for (i = 1; i <= 89; i++) append content of file[i] into temp.csv //now we have one csv file, instead of 89 count occurence of unique email in temp.csv if occurence > 2 save column[0], column[1], column[2] and occurence into output.csv ```
2020/07/01
[ "https://Stackoverflow.com/questions/62673288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4045456/" ]
The issue is that you are importing android.R You need to import the [you package name].R version instead.
You are not picking up the custom attributes correctly. This is how it should be done: ``` val typedArray = context.theme.obtainStyledAttributes( attributeSet, R.styleable.MyView, 0, 0 ) arcPaintColor = typedArray.getColor(R.styleable.MyView_arcPaintColor, 0) typedArray.recycle() // Important! initPaint() ``` You will have to make sure that this code executes in each of your constructors. The first zero will be replace by `defStyleAttr` when that is available. I suggest that you integrate the above code into `initPaint()`. See the [documentation](https://developer.android.com/reference/android/content/res/Resources.Theme#obtainStyledAttributes(android.util.AttributeSet,%20int%5B%5D,%20int,%20int)) for `obtainStyledAttributes()`.
62,673,293
I have table with names with eomonth history. I need to join another table that has information about "tests" performed on names: [![enter image description here](https://i.stack.imgur.com/mMELu.png)](https://i.stack.imgur.com/mMELu.png) The result table should show the latest ID and date of performed test but the date of test cannot be greater than the data month: [![enter image description here](https://i.stack.imgur.com/dUBBh.png)](https://i.stack.imgur.com/dUBBh.png) Any ideas how to perform this?
2020/07/01
[ "https://Stackoverflow.com/questions/62673293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9926138/" ]
I am guessing that you want the most recent `EOMONTH` from the second table for each row in the first table. If that is the correct interpretation, then you can simply use `apply`: ``` select t1.*, t2.* from table1 t1 outer apply (select top (1) t2.* from table2 t2 where t2.test_id = t1.test_id and t2.eomonth <= t1.test_date order by t2.eomonth desc ) t2; ```
This join works perfectly: ``` from table1 a left join table2 b on a.name = b.name and a.eomonth >= b.id_date and a.eomonth < LAG(b.id_date,1,'3000-01-01') OVER (PARTITION BY name ORDER BY b.id_date desc) ```
62,673,303
I am using jquery.tagsinput.js for taginput. I want to get index of removed data. I could not do it .My code below ,how can I solve it? Thank you ```html <div class="control-group"> <label class="control-label col-md-12 col-sm-12 col-xs-12">Input Tags</label> <div class="col-md-12col-sm-12 col-xs-12"> <input id="tags_1" type="text" name="category_properties" class="tags form-control" value="<?php echo $getcategory['category_properties'];?>" on-tag-removed="" ; /> <div id="suggestions-container" style="position: relative; float: left; width: 250px; margin: 10px;"></div> </div> </div> ``` ```js $(document).ready(function () { $("#tags_1").tagsInput({ width: "auto", onRemoveTag: () => {}, }); }); ```
2020/07/01
[ "https://Stackoverflow.com/questions/62673303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5044692/" ]
I am guessing that you want the most recent `EOMONTH` from the second table for each row in the first table. If that is the correct interpretation, then you can simply use `apply`: ``` select t1.*, t2.* from table1 t1 outer apply (select top (1) t2.* from table2 t2 where t2.test_id = t1.test_id and t2.eomonth <= t1.test_date order by t2.eomonth desc ) t2; ```
This join works perfectly: ``` from table1 a left join table2 b on a.name = b.name and a.eomonth >= b.id_date and a.eomonth < LAG(b.id_date,1,'3000-01-01') OVER (PARTITION BY name ORDER BY b.id_date desc) ```
62,673,316
The below line works fine for me in python3. How can I fix it for python 2. ``` word, *vector = line.split() ``` Error in Python 2: > > > ``` > word, *vector = line.split() > ^ SyntaxError: invalid syntax > > ``` > >
2020/07/01
[ "https://Stackoverflow.com/questions/62673316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1797926/" ]
Why not: ``` arr = line.split() word = arr[0] vector = arr[1:] ``` ?
I found another solution: ``` import re word, vector = re.split('', line)[0], re.split('', line)[1:] ```
62,673,316
The below line works fine for me in python3. How can I fix it for python 2. ``` word, *vector = line.split() ``` Error in Python 2: > > > ``` > word, *vector = line.split() > ^ SyntaxError: invalid syntax > > ``` > >
2020/07/01
[ "https://Stackoverflow.com/questions/62673316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1797926/" ]
This does the trick without polluting the namespace... ``` word, vector = (lambda x,*y:(x, y))(*line.split()) ``` however I don't think many Python programmers would love it
I found another solution: ``` import re word, vector = re.split('', line)[0], re.split('', line)[1:] ```
62,673,342
I have lots of small files. To save file handles and improve IO efficiency, these files are packed into a big single file. However, for some reason, these small files should be able to update in runtime. So Updating and reading different parts of a big single file at the same time by different threads is required. Because of the memory limit, mmap is not a good choice. I have to implement it by myself. But I'm concerned about is it safe to read and write different parts of a single file at the same time on iOS/Android. How can I make sure the block which is being writing will not read by other thread. Should I implement the whole feature by thread locks or there has been some mature technic to do the same work? By the way, I use C++ for my project. But Java & Obj-C is also an option. User case example: My project is an RPG game. When people see an item that is not stored in the original package, the game will load it from the server and save it into the disk automatically and immediately. One item corresponding to a single file. Each file almost 300KB~1.5MB. There are 3000~5000 items on the server. In the worst case, people will save thousands of files locally. The good thing is my user can load the items on demand to save the storage. And when updating only changed items will be redownloaded. But thousands of files will lead to a high risk of running out of FD or other resources. That's why I would like to pack these small files into a single big package file. But I still want to keep the ability to update/add a single file.
2020/07/01
[ "https://Stackoverflow.com/questions/62673342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1549192/" ]
Why not: ``` arr = line.split() word = arr[0] vector = arr[1:] ``` ?
I found another solution: ``` import re word, vector = re.split('', line)[0], re.split('', line)[1:] ```
62,673,342
I have lots of small files. To save file handles and improve IO efficiency, these files are packed into a big single file. However, for some reason, these small files should be able to update in runtime. So Updating and reading different parts of a big single file at the same time by different threads is required. Because of the memory limit, mmap is not a good choice. I have to implement it by myself. But I'm concerned about is it safe to read and write different parts of a single file at the same time on iOS/Android. How can I make sure the block which is being writing will not read by other thread. Should I implement the whole feature by thread locks or there has been some mature technic to do the same work? By the way, I use C++ for my project. But Java & Obj-C is also an option. User case example: My project is an RPG game. When people see an item that is not stored in the original package, the game will load it from the server and save it into the disk automatically and immediately. One item corresponding to a single file. Each file almost 300KB~1.5MB. There are 3000~5000 items on the server. In the worst case, people will save thousands of files locally. The good thing is my user can load the items on demand to save the storage. And when updating only changed items will be redownloaded. But thousands of files will lead to a high risk of running out of FD or other resources. That's why I would like to pack these small files into a single big package file. But I still want to keep the ability to update/add a single file.
2020/07/01
[ "https://Stackoverflow.com/questions/62673342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1549192/" ]
This does the trick without polluting the namespace... ``` word, vector = (lambda x,*y:(x, y))(*line.split()) ``` however I don't think many Python programmers would love it
I found another solution: ``` import re word, vector = re.split('', line)[0], re.split('', line)[1:] ```
62,673,374
i'm pretty new to python but i know how to use most of the things in it, included random.choice. I want to choose a random file name from 2 files [list](https://i.stack.imgur.com/zeMzN.jpg). To do so, i'm using this line of code: ``` minio = Minio('myip', access_key='mykey', secret_key='mykey', ) images = minio.list_objects('mybucket', recursive=True) for img2 in images: names = img2.object_name print(random.choice([names])) ``` Everytime i try to run it, it prints always the same file's name *(c81d9307-7666-447d-bcfb-2c13a40de5ca.png)* I tried to put the "print" function in the "for" block, but it prints out both of the files' names
2020/07/01
[ "https://Stackoverflow.com/questions/62673374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13834756/" ]
You are setting the variable `names` to one specific instsance of images right now. That means it is only a single value. Try adding them to an array or similar instead. For example: ``` names = [img2.object_name for img2 in images] print(random.choice(names)) ```
``` minio = Minio('myip', access_key='mykey', secret_key='mykey', ) images = minio.list_objects('mybucket', recursive=True) names = [] for img2 in images: names.append(img2.object_name) print(random.choice([names])) ``` Try this, the problem may that your names was not list varible
62,673,374
i'm pretty new to python but i know how to use most of the things in it, included random.choice. I want to choose a random file name from 2 files [list](https://i.stack.imgur.com/zeMzN.jpg). To do so, i'm using this line of code: ``` minio = Minio('myip', access_key='mykey', secret_key='mykey', ) images = minio.list_objects('mybucket', recursive=True) for img2 in images: names = img2.object_name print(random.choice([names])) ``` Everytime i try to run it, it prints always the same file's name *(c81d9307-7666-447d-bcfb-2c13a40de5ca.png)* I tried to put the "print" function in the "for" block, but it prints out both of the files' names
2020/07/01
[ "https://Stackoverflow.com/questions/62673374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13834756/" ]
You are setting the variable `names` to one specific instsance of images right now. That means it is only a single value. Try adding them to an array or similar instead. For example: ``` names = [img2.object_name for img2 in images] print(random.choice(names)) ```
If you want to choose one of the file names, try this : ``` minio = Minio('myip', access_key='mykey', secret_key='mykey', ) images = minio.list_objects('mybucket', recursive=True) names = [] for img2 in images: names.append(img2.object_name) print(random.choice(names)) ``` The first code tries to randomly select a value from the array, `[names]`, but this only contain a single value, the value of the `names` variable after the last iteration of the for loop. Instead of doing that, create an array, `names` and append the values of `img2.object_name` from each iteration of the for loop to this array. And use this array to get the random name.
62,673,374
i'm pretty new to python but i know how to use most of the things in it, included random.choice. I want to choose a random file name from 2 files [list](https://i.stack.imgur.com/zeMzN.jpg). To do so, i'm using this line of code: ``` minio = Minio('myip', access_key='mykey', secret_key='mykey', ) images = minio.list_objects('mybucket', recursive=True) for img2 in images: names = img2.object_name print(random.choice([names])) ``` Everytime i try to run it, it prints always the same file's name *(c81d9307-7666-447d-bcfb-2c13a40de5ca.png)* I tried to put the "print" function in the "for" block, but it prints out both of the files' names
2020/07/01
[ "https://Stackoverflow.com/questions/62673374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13834756/" ]
You are setting the variable `names` to one specific instsance of images right now. That means it is only a single value. Try adding them to an array or similar instead. For example: ``` names = [img2.object_name for img2 in images] print(random.choice(names)) ```
Your `names` is just a simple variable that contains the most recently seen image name, rather than a list full of them. The very last line of your script works as the one below: ``` value = 2 print(random.choice([value])) ``` which always prints 2. To get what you want, you need a list of all images. Here is your code with a simple fix: ``` names = [] for img2 in images: names.append(img2.object_name) print(random.choice(names)) ``` These code can be made considerably shorter with [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions): ``` names = [img2.object_name for img2 in images] print(random.choice([names])) ```
62,673,404
I am trying to run shell script in which I am matching two string values but getting above error. Can you please help me how to resolve this? Example: run command: ``` sh script.sh AMPIL Group_1 ``` So here `Group_1` is a `Execution_order` I am using below shell script: ``` if [ $Execution_Order == "Group_1" ] then rm sqoop_queries_meta_data_Group_1.txt echo $sqoop_queries >> sqoop_queries_meta_data_Group_1.txt elif [ $Execution_Order == "Group_2" ] then rm sqoop_queries_meta_data_Group_2.txt echo $sqoop_queries >> sqoop_queries_meta_data_Group_2.txt else rm sqoop_queries_meta_data.txt echo $sqoop_queries >> sqoop_queries_meta_data.txt fi ``` If else part is not working and giving the above error. Can you please correct me?
2020/07/01
[ "https://Stackoverflow.com/questions/62673404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13387656/" ]
The string comparison operator of the `test` command, (i.e. the `[ ... ]` syntax is defined as a single equals sign. Some shells (including `bash`) also accept the double-equals but it's not part of the original POSIX spec. Thus, you might want to change your queries to: ``` if [ "$Execution_Order" = "Group_1" ] then rm sqoop_queries_meta_data_Group_1.txt echo "$sqoop_queries" >> sqoop_queries_meta_data_Group_1.txt elif [ "$Execution_Order" = "Group_2" ] then rm sqoop_queries_meta_data_Group_2.txt echo "$sqoop_queries" >> sqoop_queries_meta_data_Group_2.txt else rm sqoop_queries_meta_data.txt echo "$sqoop_queries" >> sqoop_queries_meta_data.txt fi ```
I don't see why you need an `elif` in this special example. Also, I don't understand why you first remove a file and then append to that very file. How about ``` eo="${Execution_Order:+_$Execution_Order}" echo "$sqoop_queries" > "sqoop_queries_meta_data$eo.txt" ``` ? The main difference is that if `Execution_Order` would be, say, Group\_3, it would create a file sqoop\_queries\_meta\_data\_Group3 in my solution, while it would write to sqoop\_queries\_meta\_data.txt in your attempt, but if this is a problem in your context, this can easily be fixed. Explanation: The `:+` sets `eo` to empty, if `Execution_Order` is empty, and to `_$Execution_Order` otherwise.
62,673,412
I have a component called CustomTextBox In my CustomTextBox.ts , written as ``` @Input('id') _id:string @Input('class') _class:string ``` In my CustomTextBox.htm, By Using Property Binding, written as ``` <textarea [id]="_id" [class]="_class"></textarea> ``` I can able to call the component as any one of the below option from app component ``` <CustomTextBox></CustomTextBox> <CustomTextBox id="sampleid"></CustomTextBox> <CustomTextBox class="sampleid"></CustomTextBox> ``` id and class are optional But when Called `<CustomTextBox></CustomTextBox>` Generating the code as below ``` <CustomTextBox id="undefined" class="undefined"></CustomTextBox> ``` how can i make property as optional if the values are null or undefined Stackbitz Solution <https://stackblitz.com/edit/angular-ivy-v1sybw>
2020/07/01
[ "https://Stackoverflow.com/questions/62673412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3729363/" ]
Try to write this in your template ``` <textarea [attr.id]="_id?_id:null" [attr.class]="_class?_class:null"></textarea> ``` This will check if your `_id` and your `_class` are set, if not the return value will be `null`, this will have the effect of removing the attribute and so not showing an undefined value.
You can add a default value to both your `@Input` just like any other property: ``` @Input('id') _id:string = "defaultId"; @Input('class') _class:string = "defaultClass" ``` When an `@input` value is `undefined` it will take the default value. If you want to completely hide the `CustomTextBox` in case no `_id` or `_class` are provided you can try: ``` showTextBox: boolean = false; ngOnInit(): void { if(_id !== undefined && _class !== undefined){ showTextBox= true; } } ``` and in your html file: ``` <CustomTextBox *ngIf ="showTextBox"></CustomTextBox> ```
62,673,415
Context ------- My project looks like this: ``` +-- screens | +-- main_screen.dart | +-- details_screen.dart | +-- summary_screen.dart +-- viewmodels | +-- main_screen_viewmodel.dart | +-- details_screen_viewmodel.dart | +-- summary_screen_viewmodel.dart +-- services | +-- caching.dart | +-- api.dart +-- lib.dart ``` Screens use a ViewModel that contains all of the data it requires; any change to the model results in a rebuild of the view: ```dart // main_screen.dart class _MainScreenState extends State<MainScreen> { final model = MainScreenViewModel(); Widget build(BuildContext context) { return ChangeNotifierProvider<MainScreenViewModel>( create: (BuildContext context) => widget.model, child: Consumer<MainScreenViewModel>( builder: (context, model, child) => Text(model.welcomeMessage) ) ); } } ``` This all looks like a fairly standard Provider implementation; time to describe my issue. Problem ------- I have a class called `Caching` that handles the caching of API requests. When a change is made to a resource (e.g. Transactions), I'd like to trigger a refresh of all my viewmodels so the UI displays the updated data. How can I access the ViewModels from within my Caching class to trigger the update?
2020/07/01
[ "https://Stackoverflow.com/questions/62673415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2022751/" ]
I used to handle this using `StreamController`, For example : Inside my view model i have this portion of code, this line to create listener for the Stream `_basketService.historiesStreamNotifier.listen((value) async {await fetchData();});` inside the service declare my `StreamController` : ``` StreamController<int> _historiesStreamControllerNotifier = StreamController<int>.broadcast(); Stream<int> get historiesStreamNotifier => _historiesStreamControllerNotifier.stream; ``` so whenever i need to refresh my view model from my service i simply call `_historiesStreamControllerNotifier.sink.add(0);` This will trigger the callback defined with `.listen(...)`
On your Services that must update e.g Service A & Service B add this ``` final StreamController<int> _dataStreamController = StreamController<int>.broadcast(); Stream<int> get dataStream => _dataStreamController.stream; ``` On your BASE Model, add a listen() method, so its gonna be accessible to all viewmodels ``` void listen() { final aService = locator<ServiceA>(); final bService = locator<ServiceB>(); aService.dataStream.listen((_) async { notifyListeners(); }); bService.dataStream.listen((_) async { notifyListeners(); }); } ``` On View ``` BaseView<BViewModel>( onModelReady: (viewModel) { viewModel.listen(); },builder: (context, viewModel, child) { return AlignedGridView.count( ... ``` On Services again, once you updated something on service and you want to notify all listening viewmodels on that change ``` ... some successful api request ... _dataStreamController.sink.add(0); ```
62,673,442
Try out the enumerate function for yourself in this quick exercise. Complete the `skip_elements()` function to return every other element from the list, this time using the `enumerate()` function to check if an element is on an even position or an odd position. ``` def skip_elements(elements): # code goes here return ___ print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] ``` My below solution is only returning *"a"* and *"orange"* I guess that the `for` loop is not working correctly? What am I missing? ``` def skip_elements(elements): # code goes here for i,alpha in enumerate(elements): if i%2==0: return alpha ```
2020/07/01
[ "https://Stackoverflow.com/questions/62673442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5800724/" ]
You are using return, which exits the loop. If you just want to print you will want something like: ``` def skip_elements(elements): # code goes here for i,alpha in enumerate(elements): if i%2==0: print(alpha) ``` If you want to return a list: ``` def skip_elements(elements): even_elements = [] for i,alpha in enumerate(elements): if i%2==0: even_elements.append(alpha) return even_elements ```
Use the slice property of the a list [start:stop:step] ``` ["a", "b", "c", "d", "e", "f", "g"][::2] ```
62,673,442
Try out the enumerate function for yourself in this quick exercise. Complete the `skip_elements()` function to return every other element from the list, this time using the `enumerate()` function to check if an element is on an even position or an odd position. ``` def skip_elements(elements): # code goes here return ___ print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] ``` My below solution is only returning *"a"* and *"orange"* I guess that the `for` loop is not working correctly? What am I missing? ``` def skip_elements(elements): # code goes here for i,alpha in enumerate(elements): if i%2==0: return alpha ```
2020/07/01
[ "https://Stackoverflow.com/questions/62673442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5800724/" ]
The for loop is working properly the problem is that you are doing a return.When we do a return the control comes out of the loop. If you want to return the elements you can store them in a list and then return ``` def skip_elements(elements): # code goes here elements = [] for i,alpha in enumerate(elements): if i%2==0: elements.append(alpha) return elements ```
You are using return, which exits the loop. If you just want to print you will want something like: ``` def skip_elements(elements): # code goes here for i,alpha in enumerate(elements): if i%2==0: print(alpha) ``` If you want to return a list: ``` def skip_elements(elements): even_elements = [] for i,alpha in enumerate(elements): if i%2==0: even_elements.append(alpha) return even_elements ```
62,673,442
Try out the enumerate function for yourself in this quick exercise. Complete the `skip_elements()` function to return every other element from the list, this time using the `enumerate()` function to check if an element is on an even position or an odd position. ``` def skip_elements(elements): # code goes here return ___ print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] ``` My below solution is only returning *"a"* and *"orange"* I guess that the `for` loop is not working correctly? What am I missing? ``` def skip_elements(elements): # code goes here for i,alpha in enumerate(elements): if i%2==0: return alpha ```
2020/07/01
[ "https://Stackoverflow.com/questions/62673442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5800724/" ]
The for loop is working properly the problem is that you are doing a return.When we do a return the control comes out of the loop. If you want to return the elements you can store them in a list and then return ``` def skip_elements(elements): # code goes here elements = [] for i,alpha in enumerate(elements): if i%2==0: elements.append(alpha) return elements ```
Use the slice property of the a list [start:stop:step] ``` ["a", "b", "c", "d", "e", "f", "g"][::2] ```
62,673,464
Apache Ignite Version: 2.8.0 While starting the first ignite cache node, below code snippets, give expected output. When the second ignite cache joins the cluster, the entries object in the first code snippet is empty while in the second snippet iter.hasNext() gives false. 1. The ignite cluster is started with ShareNothing persistance. 2. Cache mode is set to CacheMode.REPLICATED. 3. Both the nodes are in server mode. 4. call to size() in both instances give a non-zero value. 5. call to localSize() gives non-zero value in the first instance, but 0 in second instance. ``` Map results = new HashMap(); QueryCursor<Cache.Entry> entries = binaryCache.query(new ScanQuery(null)); logger.log(Level.DEBUG, "CacheSize from entrySet: [%s]", binaryCache.size()); // Outputs non zero number. try { for (Cache.Entry e : entries) { results.put(e.getKey(), e.getValue()); } } catch (IOException e) { throw new RuntimeException("Error deserializing ignite entry", e); } return results.entrySet(); ``` OR ``` Map results = new HashMap(); Iterator<Cache.Entry<Object, BinaryObject>> iter = binaryCache.iterator(); logger.log(Level.DEBUG, "CacheSize from entrySet: [%s]", binaryCache.size()); // Outputs non zero number. try { while(iter.hasNext()) { Cache.Entry e = iter.next(); results.put(e.getKey(), e.getValue()); } } catch (IOException e) { throw new RuntimeException("Error deserializing ignite entry", e); } return results.entrySet(); ``` As null is passed to ScanQuery, ideally, all the entries from the cache should be fetched.
2020/07/01
[ "https://Stackoverflow.com/questions/62673464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4385765/" ]
You are using return, which exits the loop. If you just want to print you will want something like: ``` def skip_elements(elements): # code goes here for i,alpha in enumerate(elements): if i%2==0: print(alpha) ``` If you want to return a list: ``` def skip_elements(elements): even_elements = [] for i,alpha in enumerate(elements): if i%2==0: even_elements.append(alpha) return even_elements ```
Use the slice property of the a list [start:stop:step] ``` ["a", "b", "c", "d", "e", "f", "g"][::2] ```
62,673,464
Apache Ignite Version: 2.8.0 While starting the first ignite cache node, below code snippets, give expected output. When the second ignite cache joins the cluster, the entries object in the first code snippet is empty while in the second snippet iter.hasNext() gives false. 1. The ignite cluster is started with ShareNothing persistance. 2. Cache mode is set to CacheMode.REPLICATED. 3. Both the nodes are in server mode. 4. call to size() in both instances give a non-zero value. 5. call to localSize() gives non-zero value in the first instance, but 0 in second instance. ``` Map results = new HashMap(); QueryCursor<Cache.Entry> entries = binaryCache.query(new ScanQuery(null)); logger.log(Level.DEBUG, "CacheSize from entrySet: [%s]", binaryCache.size()); // Outputs non zero number. try { for (Cache.Entry e : entries) { results.put(e.getKey(), e.getValue()); } } catch (IOException e) { throw new RuntimeException("Error deserializing ignite entry", e); } return results.entrySet(); ``` OR ``` Map results = new HashMap(); Iterator<Cache.Entry<Object, BinaryObject>> iter = binaryCache.iterator(); logger.log(Level.DEBUG, "CacheSize from entrySet: [%s]", binaryCache.size()); // Outputs non zero number. try { while(iter.hasNext()) { Cache.Entry e = iter.next(); results.put(e.getKey(), e.getValue()); } } catch (IOException e) { throw new RuntimeException("Error deserializing ignite entry", e); } return results.entrySet(); ``` As null is passed to ScanQuery, ideally, all the entries from the cache should be fetched.
2020/07/01
[ "https://Stackoverflow.com/questions/62673464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4385765/" ]
The for loop is working properly the problem is that you are doing a return.When we do a return the control comes out of the loop. If you want to return the elements you can store them in a list and then return ``` def skip_elements(elements): # code goes here elements = [] for i,alpha in enumerate(elements): if i%2==0: elements.append(alpha) return elements ```
You are using return, which exits the loop. If you just want to print you will want something like: ``` def skip_elements(elements): # code goes here for i,alpha in enumerate(elements): if i%2==0: print(alpha) ``` If you want to return a list: ``` def skip_elements(elements): even_elements = [] for i,alpha in enumerate(elements): if i%2==0: even_elements.append(alpha) return even_elements ```
62,673,464
Apache Ignite Version: 2.8.0 While starting the first ignite cache node, below code snippets, give expected output. When the second ignite cache joins the cluster, the entries object in the first code snippet is empty while in the second snippet iter.hasNext() gives false. 1. The ignite cluster is started with ShareNothing persistance. 2. Cache mode is set to CacheMode.REPLICATED. 3. Both the nodes are in server mode. 4. call to size() in both instances give a non-zero value. 5. call to localSize() gives non-zero value in the first instance, but 0 in second instance. ``` Map results = new HashMap(); QueryCursor<Cache.Entry> entries = binaryCache.query(new ScanQuery(null)); logger.log(Level.DEBUG, "CacheSize from entrySet: [%s]", binaryCache.size()); // Outputs non zero number. try { for (Cache.Entry e : entries) { results.put(e.getKey(), e.getValue()); } } catch (IOException e) { throw new RuntimeException("Error deserializing ignite entry", e); } return results.entrySet(); ``` OR ``` Map results = new HashMap(); Iterator<Cache.Entry<Object, BinaryObject>> iter = binaryCache.iterator(); logger.log(Level.DEBUG, "CacheSize from entrySet: [%s]", binaryCache.size()); // Outputs non zero number. try { while(iter.hasNext()) { Cache.Entry e = iter.next(); results.put(e.getKey(), e.getValue()); } } catch (IOException e) { throw new RuntimeException("Error deserializing ignite entry", e); } return results.entrySet(); ``` As null is passed to ScanQuery, ideally, all the entries from the cache should be fetched.
2020/07/01
[ "https://Stackoverflow.com/questions/62673464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4385765/" ]
The for loop is working properly the problem is that you are doing a return.When we do a return the control comes out of the loop. If you want to return the elements you can store them in a list and then return ``` def skip_elements(elements): # code goes here elements = [] for i,alpha in enumerate(elements): if i%2==0: elements.append(alpha) return elements ```
Use the slice property of the a list [start:stop:step] ``` ["a", "b", "c", "d", "e", "f", "g"][::2] ```
62,673,494
I have a dataFrame like this: [enter image description here](https://i.stack.imgur.com/uPiBk.png) I wonder how to drop the whole row if any specific columns contain a specific value? For example, If columns Q1, Q2 or Q3 contain zero, delete the whole row. But if columns Q4 or Q5 contain zero, do not delete the row. [enter image description here](https://i.stack.imgur.com/uPiBk.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62673494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12208928/" ]
Use [`loc`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html) to filter with [`eq`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html) and [`any`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.any.html) along axis 1, and logical NOT operator `~`: ``` df.loc[~df[['Q1', 'Q2', 'Q3']].eq(0).any(1)] ``` ### Example ``` import pandas as pd import numpy as np np.random.seed(0) df = pd.DataFrame(np.random.randn(5,5), columns=['Q1', 'Q2', 'Q3', 'Q4', 'Q5']) df.loc[1,'Q1'] = 0 df.loc[4, 'Q2'] = 0 df.loc[3, 'Q5'] = 0 ``` [out] ``` Q1 Q2 Q3 Q4 Q5 0 1.764052 0.400157 0.978738 2.240893 1.867558 1 0.000000 0.950088 -0.151357 -0.103219 0.410599 2 0.144044 1.454274 0.761038 0.121675 0.443863 3 0.333674 1.494079 -0.205158 0.313068 0.000000 4 -2.552990 0.000000 0.864436 -0.742165 2.269755 ``` --- ``` # Should drop rows 1 and 4, but leave row 3 df.loc[~df[['Q1', 'Q2', 'Q3']].eq(0).any(1)] ``` [out] ``` Q1 Q2 Q3 Q4 Q5 0 1.764052 0.400157 0.978738 2.240893 1.867558 2 0.144044 1.454274 0.761038 0.121675 0.443863 3 0.333674 1.494079 -0.205158 0.313068 0.000000 ```
We can consider this a conditional filtering problem. We want to only keep rows, where the columns Q1, Q2 and Q3 are non-zero: ``` df_new = df[(df["Q1"] != 0) & (df["Q2"] != 0) & (df["Q3"] != 0)] ``` This `df_new` now only contains rows that you want.