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,674,857
I have a Dictionary like this ``` D={'Physician procedure note':a,'Dentistry Procedure note':b,'Podiatry Procedure note':c} ``` I want to search This dictionary with key "Procedure report" in the above dictionary. I want to find out near the closest key in the dictionary and extract value. ``` I have used this approach search_key = 'Procedure report' # Using items() + list comprehension # Substring Key match in dictionary result = [val for key, val in D.items() if search_key in key] # printing result print("Values for substring keys : " + str(result)) ``` I am getting empty List. How can i change this.
2020/07/01
[ "https://Stackoverflow.com/questions/62674857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10437321/" ]
You can try ``` result = [val for key, val in D.items() if any([s.lower() in key.lower() for s in search_key.split(" ")])] print(result) ``` Output ``` ['a', 'b', 'c'] ```
You can also do it by checking set intersection: ``` search_key = set('Procedure report'.lower().split(" ")) print([v for k, v in D.items() if search_key.intersection(set(k.lower().split(" ")))]) # ['a', 'b', 'c'] ```
62,674,857
I have a Dictionary like this ``` D={'Physician procedure note':a,'Dentistry Procedure note':b,'Podiatry Procedure note':c} ``` I want to search This dictionary with key "Procedure report" in the above dictionary. I want to find out near the closest key in the dictionary and extract value. ``` I have used this approach search_key = 'Procedure report' # Using items() + list comprehension # Substring Key match in dictionary result = [val for key, val in D.items() if search_key in key] # printing result print("Values for substring keys : " + str(result)) ``` I am getting empty List. How can i change this.
2020/07/01
[ "https://Stackoverflow.com/questions/62674857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10437321/" ]
You can try ``` result = [val for key, val in D.items() if any([s.lower() in key.lower() for s in search_key.split(" ")])] print(result) ``` Output ``` ['a', 'b', 'c'] ```
Assume you want to retrieve a list of values with corresponding keys match against search keys (partially), then `if search_key in key` won't work as that requires a full match. One way you can do is ```py # construct a set of search keywords keywords = set(search_key.upper().split(" ")) D_filter = list(filter(lambda x: keywords.intersection(set(x[0].upper().split(" "))), D.items())) result = [term[1] for term in D_filter] ```
62,674,880
With the official [CameraX](https://codelabs.developers.google.com/codelabs/camerax-getting-started/#0) example on fourth step - Implement Preview use case: ``` // Used to bind the lifecycle of cameras to the lifecycle owner val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() ``` I've got a crash: ``` 2020-07-01 12:37:41.054 1767-1803/com.example.camera2 W/CameraX: CameraX initialize() failed androidx.camera.core.InitializationException: java.lang.NumberFormatException: For input string: "/dev/video0" at androidx.camera.core.CameraX.lambda$initInternal$7$CameraX(CameraX.java:1056) at androidx.camera.core.-$$Lambda$CameraX$PC4SOFGjuqUVT4bexY644vLmWFE.run(Unknown Source:8) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:764) Caused by: java.lang.NumberFormatException: For input string: "/dev/video0" at java.lang.Integer.parseInt(Integer.java:604) at java.lang.Integer.parseInt(Integer.java:650) at androidx.camera.camera2.internal.SupportedSurfaceCombination.getRecordSize(SupportedSurfaceCombination.java:1127) at androidx.camera.camera2.internal.SupportedSurfaceCombination.generateSurfaceSizeDefinition(SupportedSurfaceCombination.java:1086) at androidx.camera.camera2.internal.SupportedSurfaceCombination.<init>(SupportedSurfaceCombination.java:109) at androidx.camera.camera2.internal.Camera2DeviceSurfaceManager.init(Camera2DeviceSurfaceManager.java:87) at androidx.camera.camera2.internal.Camera2DeviceSurfaceManager.<init>(Camera2DeviceSurfaceManager.java:75) at androidx.camera.camera2.internal.Camera2DeviceSurfaceManager.<init>(Camera2DeviceSurfaceManager.java:67) at androidx.camera.camera2.Camera2Config.lambda$defaultConfig$0(Camera2Config.java:59) at androidx.camera.camera2.-$$Lambda$Camera2Config$mYXXnxW6sa_oF7xhp51ozRSO_ck.newInstance(Unknown Source:0) at androidx.camera.core.CameraX.lambda$initInternal$7$CameraX(CameraX.java:1034) at androidx.camera.core.-$$Lambda$CameraX$PC4SOFGjuqUVT4bexY644vLmWFE.run(Unknown Source:8)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)  at java.lang.Thread.run(Thread.java:764)  2020-07-01 12:38:11.142 1767-1767/com.example.camera2 D/AndroidRuntime: Shutting down VM 2020-07-01 12:38:11.346 1767-1767/com.example.camera2 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.camera2, PID: 1767 java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:503) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)  Caused by: java.util.concurrent.ExecutionException: androidx.camera.core.InitializationException: java.lang.NumberFormatException: For input string: "/dev/video0" at androidx.concurrent.futures.AbstractResolvableFuture.getDoneValue(AbstractResolvableFuture.java:518) at androidx.concurrent.futures.AbstractResolvableFuture.get(AbstractResolvableFuture.java:475) at androidx.concurrent.futures.CallbackToFutureAdapter$SafeFuture.get(CallbackToFutureAdapter.java:199) at androidx.camera.core.impl.utils.futures.FutureChain.get(FutureChain.java:155) at androidx.camera.core.impl.utils.futures.ChainingListenableFuture.get(ChainingListenableFuture.java:105) at com.example.camera2.MainActivity$startCamera$1.run(MainActivity.kt:75) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6718) at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)  Caused by: androidx.camera.core.InitializationException: java.lang.NumberFormatException: For input string: "/dev/video0" at androidx.camera.core.CameraX.lambda$initInternal$7$CameraX(CameraX.java:1056) at androidx.camera.core.-$$Lambda$CameraX$PC4SOFGjuqUVT4bexY644vLmWFE.run(Unknown Source:8) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:764) Caused by: java.lang.NumberFormatException: For input string: "/dev/video0" at java.lang.Integer.parseInt(Integer.java:604) at java.lang.Integer.parseInt(Integer.java:650) at androidx.camera.camera2.internal.SupportedSurfaceCombination.getRecordSize(SupportedSurfaceCombination.java:1127) at androidx.camera.camera2.internal.SupportedSurfaceCombination.generateSurfaceSizeDefinition(SupportedSurfaceCombination.java:1086) at androidx.camera.camera2.internal.SupportedSurfaceCombination.<init>(SupportedSurfaceCombination.java:109) at androidx.camera.camera2.internal.Camera2DeviceSurfaceManager.init(Camera2DeviceSurfaceManager.java:87) at androidx.camera.camera2.internal.Camera2DeviceSurfaceManager.<init>(Camera2DeviceSurfaceManager.java:75) at androidx.camera.camera2.internal.Camera2DeviceSurfaceManager.<init>(Camera2DeviceSurfaceManager.java:67) at androidx.camera.camera2.Camera2Config.lambda$defaultConfig$0(Camera2Config.java:59) at androidx.camera.camera2.-$$Lambda$Camera2Config$mYXXnxW6sa_oF7xhp51ozRSO_ck.newInstance(Unknown Source:0) at androidx.camera.core.CameraX.lambda$initInternal$7$CameraX(CameraX.java:1034) at androidx.camera.core.-$$Lambda$CameraX$PC4SOFGjuqUVT4bexY644vLmWFE.run(Unknown Source:8)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)  at java.lang.Thread.run(Thread.java:764)  2020-07-01 12:38:11.481 1767-1767/com.example.camera2 I/Process: Sending signal. PID: 1767 SIG: 9 ``` I'm using non stock device with two cameras that works fine with Camera2Basic example. In the project sets the latest camerax libs.: ``` compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { def camerax_version = '1.0.0-beta06' implementation "androidx.camera:camera-core:${camerax_version}" implementation "androidx.camera:camera-camera2:$camerax_version" implementation "androidx.camera:camera-lifecycle:$camerax_version" implementation 'androidx.camera:camera-view:1.0.0-alpha13' implementation 'androidx.camera:camera-extensions:1.0.0-alpha13' ``` I've tried setup manually [CameraXConfig.Provider](https://developer.android.com/training/camerax/preview#configuration), but with the same issue on get cameraProviderFuture. Anybody have an example of manually configuration ProcessCameraProvider with binding to specific camera device? Maybe any ideas how to setup preview with specific camera?
2020/07/01
[ "https://Stackoverflow.com/questions/62674880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4926156/" ]
You can try ``` result = [val for key, val in D.items() if any([s.lower() in key.lower() for s in search_key.split(" ")])] print(result) ``` Output ``` ['a', 'b', 'c'] ```
You can also do it by checking set intersection: ``` search_key = set('Procedure report'.lower().split(" ")) print([v for k, v in D.items() if search_key.intersection(set(k.lower().split(" ")))]) # ['a', 'b', 'c'] ```
62,674,880
With the official [CameraX](https://codelabs.developers.google.com/codelabs/camerax-getting-started/#0) example on fourth step - Implement Preview use case: ``` // Used to bind the lifecycle of cameras to the lifecycle owner val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() ``` I've got a crash: ``` 2020-07-01 12:37:41.054 1767-1803/com.example.camera2 W/CameraX: CameraX initialize() failed androidx.camera.core.InitializationException: java.lang.NumberFormatException: For input string: "/dev/video0" at androidx.camera.core.CameraX.lambda$initInternal$7$CameraX(CameraX.java:1056) at androidx.camera.core.-$$Lambda$CameraX$PC4SOFGjuqUVT4bexY644vLmWFE.run(Unknown Source:8) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:764) Caused by: java.lang.NumberFormatException: For input string: "/dev/video0" at java.lang.Integer.parseInt(Integer.java:604) at java.lang.Integer.parseInt(Integer.java:650) at androidx.camera.camera2.internal.SupportedSurfaceCombination.getRecordSize(SupportedSurfaceCombination.java:1127) at androidx.camera.camera2.internal.SupportedSurfaceCombination.generateSurfaceSizeDefinition(SupportedSurfaceCombination.java:1086) at androidx.camera.camera2.internal.SupportedSurfaceCombination.<init>(SupportedSurfaceCombination.java:109) at androidx.camera.camera2.internal.Camera2DeviceSurfaceManager.init(Camera2DeviceSurfaceManager.java:87) at androidx.camera.camera2.internal.Camera2DeviceSurfaceManager.<init>(Camera2DeviceSurfaceManager.java:75) at androidx.camera.camera2.internal.Camera2DeviceSurfaceManager.<init>(Camera2DeviceSurfaceManager.java:67) at androidx.camera.camera2.Camera2Config.lambda$defaultConfig$0(Camera2Config.java:59) at androidx.camera.camera2.-$$Lambda$Camera2Config$mYXXnxW6sa_oF7xhp51ozRSO_ck.newInstance(Unknown Source:0) at androidx.camera.core.CameraX.lambda$initInternal$7$CameraX(CameraX.java:1034) at androidx.camera.core.-$$Lambda$CameraX$PC4SOFGjuqUVT4bexY644vLmWFE.run(Unknown Source:8)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)  at java.lang.Thread.run(Thread.java:764)  2020-07-01 12:38:11.142 1767-1767/com.example.camera2 D/AndroidRuntime: Shutting down VM 2020-07-01 12:38:11.346 1767-1767/com.example.camera2 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.camera2, PID: 1767 java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:503) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)  Caused by: java.util.concurrent.ExecutionException: androidx.camera.core.InitializationException: java.lang.NumberFormatException: For input string: "/dev/video0" at androidx.concurrent.futures.AbstractResolvableFuture.getDoneValue(AbstractResolvableFuture.java:518) at androidx.concurrent.futures.AbstractResolvableFuture.get(AbstractResolvableFuture.java:475) at androidx.concurrent.futures.CallbackToFutureAdapter$SafeFuture.get(CallbackToFutureAdapter.java:199) at androidx.camera.core.impl.utils.futures.FutureChain.get(FutureChain.java:155) at androidx.camera.core.impl.utils.futures.ChainingListenableFuture.get(ChainingListenableFuture.java:105) at com.example.camera2.MainActivity$startCamera$1.run(MainActivity.kt:75) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6718) at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)  Caused by: androidx.camera.core.InitializationException: java.lang.NumberFormatException: For input string: "/dev/video0" at androidx.camera.core.CameraX.lambda$initInternal$7$CameraX(CameraX.java:1056) at androidx.camera.core.-$$Lambda$CameraX$PC4SOFGjuqUVT4bexY644vLmWFE.run(Unknown Source:8) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:764) Caused by: java.lang.NumberFormatException: For input string: "/dev/video0" at java.lang.Integer.parseInt(Integer.java:604) at java.lang.Integer.parseInt(Integer.java:650) at androidx.camera.camera2.internal.SupportedSurfaceCombination.getRecordSize(SupportedSurfaceCombination.java:1127) at androidx.camera.camera2.internal.SupportedSurfaceCombination.generateSurfaceSizeDefinition(SupportedSurfaceCombination.java:1086) at androidx.camera.camera2.internal.SupportedSurfaceCombination.<init>(SupportedSurfaceCombination.java:109) at androidx.camera.camera2.internal.Camera2DeviceSurfaceManager.init(Camera2DeviceSurfaceManager.java:87) at androidx.camera.camera2.internal.Camera2DeviceSurfaceManager.<init>(Camera2DeviceSurfaceManager.java:75) at androidx.camera.camera2.internal.Camera2DeviceSurfaceManager.<init>(Camera2DeviceSurfaceManager.java:67) at androidx.camera.camera2.Camera2Config.lambda$defaultConfig$0(Camera2Config.java:59) at androidx.camera.camera2.-$$Lambda$Camera2Config$mYXXnxW6sa_oF7xhp51ozRSO_ck.newInstance(Unknown Source:0) at androidx.camera.core.CameraX.lambda$initInternal$7$CameraX(CameraX.java:1034) at androidx.camera.core.-$$Lambda$CameraX$PC4SOFGjuqUVT4bexY644vLmWFE.run(Unknown Source:8)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)  at java.lang.Thread.run(Thread.java:764)  2020-07-01 12:38:11.481 1767-1767/com.example.camera2 I/Process: Sending signal. PID: 1767 SIG: 9 ``` I'm using non stock device with two cameras that works fine with Camera2Basic example. In the project sets the latest camerax libs.: ``` compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { def camerax_version = '1.0.0-beta06' implementation "androidx.camera:camera-core:${camerax_version}" implementation "androidx.camera:camera-camera2:$camerax_version" implementation "androidx.camera:camera-lifecycle:$camerax_version" implementation 'androidx.camera:camera-view:1.0.0-alpha13' implementation 'androidx.camera:camera-extensions:1.0.0-alpha13' ``` I've tried setup manually [CameraXConfig.Provider](https://developer.android.com/training/camerax/preview#configuration), but with the same issue on get cameraProviderFuture. Anybody have an example of manually configuration ProcessCameraProvider with binding to specific camera device? Maybe any ideas how to setup preview with specific camera?
2020/07/01
[ "https://Stackoverflow.com/questions/62674880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4926156/" ]
You can try ``` result = [val for key, val in D.items() if any([s.lower() in key.lower() for s in search_key.split(" ")])] print(result) ``` Output ``` ['a', 'b', 'c'] ```
Assume you want to retrieve a list of values with corresponding keys match against search keys (partially), then `if search_key in key` won't work as that requires a full match. One way you can do is ```py # construct a set of search keywords keywords = set(search_key.upper().split(" ")) D_filter = list(filter(lambda x: keywords.intersection(set(x[0].upper().split(" "))), D.items())) result = [term[1] for term in D_filter] ```
62,674,886
I would like to fetch data from multiple files with a single async function. Currently my code is like this: ``` const fetchExternalData = async() => { const resp1 = await fetch('file1.txt'); const resp2 = await fetch('file2.txt'); return resp1.text(); // How could I return the content from file2.txt as well? } fetchExternalData().then((response) => { console.log(response); // Data from file1.txt // How could I access the data from file2.txt? } ``` This way, I can work with the data from the first file, but how could I access the data from more files this way? Hope the question is understandable. Any help will be greatly appreciated.
2020/07/01
[ "https://Stackoverflow.com/questions/62674886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11758432/" ]
Here's one way you could go about this using `Promise.all`: ```js const fetchExternalData = () => { return Promise.all([ fetch("file1.txt"), fetch("file2.txt") ]) .then( results => Promise.all( results.map(result => result.text()) ) ) } ``` Then, when calling your `fetchExternalData` function, you will get an array of items with data from both of your files: ```js fetchExternalData().then( (response) => { // [file1data, file2data] } ) ``` Here's an example: ```js const fetchExternalData = () => { return Promise.all([ fetch("https://jsonplaceholder.typicode.com/todos/1"), fetch("https://jsonplaceholder.typicode.com/todos/2") ]).then(results => { return Promise.all(results.map(result => result.json())); }); }; fetchExternalData() .then(result => { // console.log(result); }) .catch(console.error); ``` Alternatively, if you'd want to return an `object` instead of an `array`, you could do something like the following: ```js const fetchExternalData = items => { return Promise.all( items.map(item => fetch(`https://jsonplaceholder.typicode.com/todos/${item.id}`) ) ) .then( responses => Promise.all( responses.map(response => response.json()) ) ) // use `Array.reduce` to map your responses to appropriate keys .then(results => results.reduce((acc, result, idx) => { const key = items[idx].key; // use destructing assignment to add // a new key/value pair to the final object return { ...acc, [key]: result }; }, {}) ); }; fetchExternalData([ { id: 1, key: "todo1" }, { id: 2, key: "todo2" } ]) .then(result => { console.log("result", result); console.log('todo1', result["todo1"]); }) .catch(console.error); ``` References: * [Promise.all - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) * [Array.reduce - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) * [Destructing assignment - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
return multiple values by putting it in an object. like this: ``` const fetchExternalData = async() => { const resp1 = await fetch('file1.txt'); const resp2 = await fetch('file2.txt'); return ({res1: resp1.text(), res2: resp2.text()}); } ```
62,674,906
I have two 2D numpy arrays with the same shape: ``` idx = np.array([[1, 2, 5, 6],[1, 3, 5, 2]]) val = np.array([[0.1, 0.5, 0.3, 0.2], [0.1, 0., 0.8, 0.2]]) ``` I know that we can use `np.bincount` setting `val` as weights: ``` np.bincount(idx.reshape(-1), weights=val.reshape(-1)) ``` But this is not exactly what I want. `np.bincount` put zeros where the indexes do not exist. In the example, the results are: ``` array([0. , 0.2, 0.7, 0. , 0. , 1.1, 0.2]) ``` But I do not want these extra zeros for the non-exists indexes. I want the weighted counts corresponds to `np.unique(idx)` ``` array([1, 2, 3, 5, 6]) ``` And my expected results are: ``` array([0.2, 0.7, 0., 1.1, 0.2]) ``` Anyone has an idea to do it efficiently? My `idx` and `val` are very large with more than 1 Million elements.
2020/07/01
[ "https://Stackoverflow.com/questions/62674906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694518/" ]
Here's one way you could go about this using `Promise.all`: ```js const fetchExternalData = () => { return Promise.all([ fetch("file1.txt"), fetch("file2.txt") ]) .then( results => Promise.all( results.map(result => result.text()) ) ) } ``` Then, when calling your `fetchExternalData` function, you will get an array of items with data from both of your files: ```js fetchExternalData().then( (response) => { // [file1data, file2data] } ) ``` Here's an example: ```js const fetchExternalData = () => { return Promise.all([ fetch("https://jsonplaceholder.typicode.com/todos/1"), fetch("https://jsonplaceholder.typicode.com/todos/2") ]).then(results => { return Promise.all(results.map(result => result.json())); }); }; fetchExternalData() .then(result => { // console.log(result); }) .catch(console.error); ``` Alternatively, if you'd want to return an `object` instead of an `array`, you could do something like the following: ```js const fetchExternalData = items => { return Promise.all( items.map(item => fetch(`https://jsonplaceholder.typicode.com/todos/${item.id}`) ) ) .then( responses => Promise.all( responses.map(response => response.json()) ) ) // use `Array.reduce` to map your responses to appropriate keys .then(results => results.reduce((acc, result, idx) => { const key = items[idx].key; // use destructing assignment to add // a new key/value pair to the final object return { ...acc, [key]: result }; }, {}) ); }; fetchExternalData([ { id: 1, key: "todo1" }, { id: 2, key: "todo2" } ]) .then(result => { console.log("result", result); console.log('todo1', result["todo1"]); }) .catch(console.error); ``` References: * [Promise.all - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) * [Array.reduce - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) * [Destructing assignment - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
return multiple values by putting it in an object. like this: ``` const fetchExternalData = async() => { const resp1 = await fetch('file1.txt'); const resp2 = await fetch('file2.txt'); return ({res1: resp1.text(), res2: resp2.text()}); } ```
62,674,917
We are trying to start [metricbeat](https://www.elastic.co/guide/en/beats/metricbeat/current/metricbeat-reference-yml.html) on typhoon kubernetes cluster. But after startup its not able to get some pod specific events like restart etc because of the following ### Corresponding metricbeat.yaml snippet ```yaml # State metrics from kube-state-metrics service: - module: kubernetes enabled: true metricsets: - state_node - state_deployment - state_replicaset - state_statefulset - state_pod - state_container - state_cronjob - state_resourcequota - state_service - state_persistentvolume - state_persistentvolumeclaim - state_storageclass # Uncomment this to get k8s events: #- event period: 10s hosts: ["kube-state-metrics:8080"] ``` ### Error which we are facing ```sh 2020-07-01T10:31:02.486Z ERROR [kubernetes.state_statefulset] state_statefulset/state_statefulset.go:97 error making http request: Get http://kube-state-metrics:8080/metrics: lookup kube-state-metrics on *.*.*.*:53: no such host 2020-07-01T10:31:02.611Z WARN [transport] transport/tcp.go:52 DNS lookup failure "kube-state-metrics": lookup kube-state-metrics on *.*.*.*:53: no such host 2020-07-01T10:31:02.611Z INFO module/wrapper.go:259 Error fetching data for metricset kubernetes.state_node: error doing HTTP request to fetch 'state_node' Metricset data: error making http request: Get http://kube-state-metrics:8080/metrics: lookup kube-state-metrics on *.*.*.*:53: no such host 2020-07-01T10:31:03.313Z ERROR process_summary/process_summary.go:102 Unknown or unexpected state <P> for process with pid 19 2020-07-01T10:31:03.313Z ERROR process_summary/process_summary.go:102 Unknown or unexpected state <P> for process with pid 20 ``` I can add some other info which is required for this.
2020/07/01
[ "https://Stackoverflow.com/questions/62674917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5761011/" ]
Make sure you have the Kube-State-Metrics deployed in your cluster in the kube-system namespace to make this work. Metricbeat will not come with this by default. Please refer [this](https://www.elastic.co/guide/en/beats/metricbeat/current/running-on-kubernetes.html) for detailed deployment instructions.
If your `kube-state-metrics` is deployed to another namespace, Kubernetes cannot resolve the name. E.g. we have `kube-state-metrics` deployed to the `monitoring` namespace: ``` $ kubectl get pods -A | grep kube-state-metrics monitoring kube-state-metrics-765c7c7f95-v7mmp 3/3 Running 17 10d ``` You could set `hosts` option to the full name, including namespace, like this: ``` - module: kubernetes enabled: true metricsets: - state_node - state_deployment - state_replicaset - state_statefulset - state_pod - state_container - state_cronjob - state_resourcequota - state_service - state_persistentvolume - state_persistentvolumeclaim - state_storageclass hosts: ["kube-state-metrics.<your_namespace>:8080"] ```
62,674,953
In my react hooks component I am rendering data from an array of objects. ``` const lineInfo = [ { id: '001', line: 's-1125026', arrival: '7:30', departure: '8:00', authorization: 'User 1', }, { id: '002', line: 's-1125027', arrival: '8:01', departure: '8:50', authorization: 'User 1', }, ``` In the `.map()` I'm returning data using this data: ``` <div> {lineInfo.map((line) => ( <Row key={`line_${line.id}`}> // remaining code removed for length ``` The list returns fine, so now I am trying to remove a row from the list. **Remove func** ``` const [list, setList] = useState(lineInfo); function handleRemove(id) { console.log('id' id); const newList = list.filter((line) => line.id !== id); setList(newList); } ``` **Remove Button** ``` <Button className={style.close_button} onClick={() => handleRemove(line.id)} > <img src={close} alt="trash" /> </Button> </Row> ``` The problem I am running into is that in my console log, is that only the line.id is being removed from the array instead of the whole row of data. 1. How do I remove all the data belonging to a particular id? 2. Even though the console log shows that the text is removed, why is the text that is displayed in my row not removed from the view? I'm not too familiar with hooks and have only been able to find examples of my particular problem with class components. Thanks in advance.
2020/07/01
[ "https://Stackoverflow.com/questions/62674953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1391595/" ]
You should display the defined state with the hook. in this case the `list` , and not the `lineInfo`. ``` <div> {list.map((line) => ( <Row key={`line_${line.id}`}> // remaining code removed for length ```
You should not render lineInfo, render the list from local state instead: ```js const { useState, useCallback } = React; const lineInfo = [ { id: '001', line: 's-1125026', arrival: '7:30', departure: '8:00', authorization: 'User 1', }, { id: '002', line: 's-1125027', arrival: '8:01', departure: '8:50', authorization: 'User 1', }, ]; //make row pure component using React.memo const Row = React.memo(function Row({ item, remove }) { return ( <div> <pre>{JSON.stringify(item, undefined, 2)}</pre> <button onClick={() => remove(item.id)}> remove </button> </div> ); }); const App = () => { const [list, setList] = useState(lineInfo); //make remove a callback that is only created // on App mount using useCallback with no dependencies const remove = useCallback( (removeId) => //pass callback to setList so list is not a dependency // of this callback setList((list) => list.filter(({ id }) => id !== removeId) ), [] ); return ( <ul> {list.map((line) => ( <Row key={`line_${line.id}`} item={line} remove={remove} /> ))} </ul> ); }; ReactDOM.render(<App />, document.getElementById('root')); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div> ```
62,674,955
I need your help with an access issue with neofetch on my macOS. Here the thing, I recently install neofetch on my terminal (oh-my-zsh), it works but, between the firts line (last login) and the logo that displays : > > mkdir: /Users/'MYUSERNAME'/.config/neofetch/: Permission denied > /usr/local/bin/Neofetch: line 4476: > /Users/'MYUSERNAME'/.config/neofetch/config.conf: Permission denied > > > And I don't know why, of course, I did many types of research on google before asking you. Do you have an idea?
2020/07/01
[ "https://Stackoverflow.com/questions/62674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13432342/" ]
You need to change the permissions for your config directory: `sudo chmod -R 666 /Users/YOURUSERNAME/.config` 666 means Read-Write for all users.
Doing the same as garritfra did but with that last directory line you have there worked for me on a windows 10 machine though. It may work for the mac as well? ``` sudo chmod -R 666 /Users/MYUSERNAME/.config/neofetch/config.conf ``` Replace MYUSERNAME with whatever is shown in the error.
62,674,955
I need your help with an access issue with neofetch on my macOS. Here the thing, I recently install neofetch on my terminal (oh-my-zsh), it works but, between the firts line (last login) and the logo that displays : > > mkdir: /Users/'MYUSERNAME'/.config/neofetch/: Permission denied > /usr/local/bin/Neofetch: line 4476: > /Users/'MYUSERNAME'/.config/neofetch/config.conf: Permission denied > > > And I don't know why, of course, I did many types of research on google before asking you. Do you have an idea?
2020/07/01
[ "https://Stackoverflow.com/questions/62674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13432342/" ]
You need to change the permissions for your config directory: `sudo chmod -R 666 /Users/YOURUSERNAME/.config` 666 means Read-Write for all users.
I was having the same issue and was able to solve this in the following way: 1. Open up Finder 2. Reveal hidden folders & files by pressing CMD+>+SHIFT 3. Locate the .config folder and right click it and click 'get info'. 4. Under the sharing & permissions section click the small plus and just add the entire Administrators group and remember to change the permissions to read & write for the entire group. [neofetch](https://i.stack.imgur.com/IxCYQ.png)
62,674,955
I need your help with an access issue with neofetch on my macOS. Here the thing, I recently install neofetch on my terminal (oh-my-zsh), it works but, between the firts line (last login) and the logo that displays : > > mkdir: /Users/'MYUSERNAME'/.config/neofetch/: Permission denied > /usr/local/bin/Neofetch: line 4476: > /Users/'MYUSERNAME'/.config/neofetch/config.conf: Permission denied > > > And I don't know why, of course, I did many types of research on google before asking you. Do you have an idea?
2020/07/01
[ "https://Stackoverflow.com/questions/62674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13432342/" ]
You need to change the permissions for your config directory: `sudo chmod -R 666 /Users/YOURUSERNAME/.config` 666 means Read-Write for all users.
Here is a bulletproof one-liner that solves the issue: ``` sudo chmod -R 710 $HOME/.config ``` Execute this command in a terminal session. After restarting your terminal or, alternatively, sourcing your shell configuration file (assuming you have added the `neofetch` command to that file) with: `source ~/.zshrc` (replacing `~/.zshrc` with the path to your shell configuration file if you are using a different one), the error prompt should disappear. Note that this only gives 'execute' permission to the 'group' class. There is no need, as the currently accepted answer suggests, to give 666 or 777 modes as that needlessly makes your system less secure (not to mention even no. octal figures such as 666 don't even work as they fail to give the required 'execute' permission, which requires an odd number bit). Modes such as `730`, `750`, and `770` will work, but unless something changes in neofetch's future update that demands it, it is unnecessarily too generous and I wouldn't advise it. Finally, there is absolutely no reason to give users in the 'other' class any permission to the `~/.config` directory (unless you have a very compelling reason to), and hence the last permission bit (3rd digit in the mode represented by octal numbers) should always remain 0.
62,674,955
I need your help with an access issue with neofetch on my macOS. Here the thing, I recently install neofetch on my terminal (oh-my-zsh), it works but, between the firts line (last login) and the logo that displays : > > mkdir: /Users/'MYUSERNAME'/.config/neofetch/: Permission denied > /usr/local/bin/Neofetch: line 4476: > /Users/'MYUSERNAME'/.config/neofetch/config.conf: Permission denied > > > And I don't know why, of course, I did many types of research on google before asking you. Do you have an idea?
2020/07/01
[ "https://Stackoverflow.com/questions/62674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13432342/" ]
Doing the same as garritfra did but with that last directory line you have there worked for me on a windows 10 machine though. It may work for the mac as well? ``` sudo chmod -R 666 /Users/MYUSERNAME/.config/neofetch/config.conf ``` Replace MYUSERNAME with whatever is shown in the error.
I was having the same issue and was able to solve this in the following way: 1. Open up Finder 2. Reveal hidden folders & files by pressing CMD+>+SHIFT 3. Locate the .config folder and right click it and click 'get info'. 4. Under the sharing & permissions section click the small plus and just add the entire Administrators group and remember to change the permissions to read & write for the entire group. [neofetch](https://i.stack.imgur.com/IxCYQ.png)
62,674,955
I need your help with an access issue with neofetch on my macOS. Here the thing, I recently install neofetch on my terminal (oh-my-zsh), it works but, between the firts line (last login) and the logo that displays : > > mkdir: /Users/'MYUSERNAME'/.config/neofetch/: Permission denied > /usr/local/bin/Neofetch: line 4476: > /Users/'MYUSERNAME'/.config/neofetch/config.conf: Permission denied > > > And I don't know why, of course, I did many types of research on google before asking you. Do you have an idea?
2020/07/01
[ "https://Stackoverflow.com/questions/62674955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13432342/" ]
Doing the same as garritfra did but with that last directory line you have there worked for me on a windows 10 machine though. It may work for the mac as well? ``` sudo chmod -R 666 /Users/MYUSERNAME/.config/neofetch/config.conf ``` Replace MYUSERNAME with whatever is shown in the error.
Here is a bulletproof one-liner that solves the issue: ``` sudo chmod -R 710 $HOME/.config ``` Execute this command in a terminal session. After restarting your terminal or, alternatively, sourcing your shell configuration file (assuming you have added the `neofetch` command to that file) with: `source ~/.zshrc` (replacing `~/.zshrc` with the path to your shell configuration file if you are using a different one), the error prompt should disappear. Note that this only gives 'execute' permission to the 'group' class. There is no need, as the currently accepted answer suggests, to give 666 or 777 modes as that needlessly makes your system less secure (not to mention even no. octal figures such as 666 don't even work as they fail to give the required 'execute' permission, which requires an odd number bit). Modes such as `730`, `750`, and `770` will work, but unless something changes in neofetch's future update that demands it, it is unnecessarily too generous and I wouldn't advise it. Finally, there is absolutely no reason to give users in the 'other' class any permission to the `~/.config` directory (unless you have a very compelling reason to), and hence the last permission bit (3rd digit in the mode represented by octal numbers) should always remain 0.
62,674,979
I wrote the below function to pop up an IE window to handle the user authentication of the OAuth2.0 authorization code flow in PowerShell which works but when calling it as a function, it doesn't stay in the while loop to wait for the URL of the IE window to change and to filter out the OAuth2.0 authorization code and then close the window. Is there a way to keep the function "open" for longer and to make sure it waits for the URL of the IE window to change? *All remarks regarding the function are welcome...* ``` function Show-OAuth2AuthCodeWindow { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, HelpMessage = "The OAuth2 authorization code URL pointing towards the oauth2/v2.0/authorize endpoint as documented here: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow")] [System.Uri] $URL ) try { # create an Internet Explorer object to display the OAuth 2 authorization code browser window to authenticate $InternetExplorer = New-Object -ComObject InternetExplorer.Application $InternetExplorer.Width = "600" $InternetExplorer.Height = "500" $InternetExplorer.AddressBar = $false # disable the address bar $InternetExplorer.ToolBar = $false # disable the tool bar $InternetExplorer.StatusBar = $false # disable the status bar # store the Console Window Handle (HWND) of the created Internet Explorer object $InternetExplorerHWND = $InternetExplorer.HWND # make the browser window visible and navigate to the OAuth2 authorization code URL supplied in the $URL parameter $InternetExplorer.Navigate($URL) # give Internet Explorer some time to start up Start-Sleep -Seconds 1 # get the Internet Explorer window as application object $InternetExplorerWindow = (New-Object -ComObject Shell.Application).Windows() | Where-Object {($_.LocationURL -match "(^https?://.+)") -and ($_.HWND -eq $InternetExplorerHWND)} # wait for the URL of the Internet Explorer window to hold the OAuth2 authorization code after a successful authentication and close the window while (($InternetExplorerWindow = (New-Object -ComObject Shell.Application).Windows() | Where-Object {($_.LocationURL -match "(^https?://.+)") -and ($_.HWND -eq $InternetExplorerHWND)})) { Write-Host $InternetExplorerWindow.LocationURL if (($InternetExplorerWindow.LocationURL).StartsWith($RedirectURI.ToString() + "?code=")) { $OAuth2AuthCode = $InternetExplorerWindow.LocationURL $OAuth2AuthCode = $OAuth2AuthCode -replace (".*code=") -replace ("&.*") $InternetExplorerWindow.Quit() } } # return the OAuth2 Authorization Code return $OAuth2AuthCode } catch { Write-Host -ForegroundColor Red "Could not create a browser window for the OAuth2 authentication" } } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62674979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1826131/" ]
The following example does what you want with a WebBrowser control, which allows you to register a Navigating event handler to catch the authorization code obtained from your authorization server. [PowerShell OAuth2 client](https://github.com/globalsign/OAuth-2.0-client-examples/blob/master/PowerShell/Powershell-example.ps1)
My guess is that the function has no idea what `$RedirectURI` is. You should make that a second parameter to the function or it should be (at least) [Script scoped](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-7#scope-modifiers) I'd prefer using a second parameter, but if you do scoping, you should be able to use it inside the function with `$script:RedirectURI`
62,674,979
I wrote the below function to pop up an IE window to handle the user authentication of the OAuth2.0 authorization code flow in PowerShell which works but when calling it as a function, it doesn't stay in the while loop to wait for the URL of the IE window to change and to filter out the OAuth2.0 authorization code and then close the window. Is there a way to keep the function "open" for longer and to make sure it waits for the URL of the IE window to change? *All remarks regarding the function are welcome...* ``` function Show-OAuth2AuthCodeWindow { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, HelpMessage = "The OAuth2 authorization code URL pointing towards the oauth2/v2.0/authorize endpoint as documented here: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow")] [System.Uri] $URL ) try { # create an Internet Explorer object to display the OAuth 2 authorization code browser window to authenticate $InternetExplorer = New-Object -ComObject InternetExplorer.Application $InternetExplorer.Width = "600" $InternetExplorer.Height = "500" $InternetExplorer.AddressBar = $false # disable the address bar $InternetExplorer.ToolBar = $false # disable the tool bar $InternetExplorer.StatusBar = $false # disable the status bar # store the Console Window Handle (HWND) of the created Internet Explorer object $InternetExplorerHWND = $InternetExplorer.HWND # make the browser window visible and navigate to the OAuth2 authorization code URL supplied in the $URL parameter $InternetExplorer.Navigate($URL) # give Internet Explorer some time to start up Start-Sleep -Seconds 1 # get the Internet Explorer window as application object $InternetExplorerWindow = (New-Object -ComObject Shell.Application).Windows() | Where-Object {($_.LocationURL -match "(^https?://.+)") -and ($_.HWND -eq $InternetExplorerHWND)} # wait for the URL of the Internet Explorer window to hold the OAuth2 authorization code after a successful authentication and close the window while (($InternetExplorerWindow = (New-Object -ComObject Shell.Application).Windows() | Where-Object {($_.LocationURL -match "(^https?://.+)") -and ($_.HWND -eq $InternetExplorerHWND)})) { Write-Host $InternetExplorerWindow.LocationURL if (($InternetExplorerWindow.LocationURL).StartsWith($RedirectURI.ToString() + "?code=")) { $OAuth2AuthCode = $InternetExplorerWindow.LocationURL $OAuth2AuthCode = $OAuth2AuthCode -replace (".*code=") -replace ("&.*") $InternetExplorerWindow.Quit() } } # return the OAuth2 Authorization Code return $OAuth2AuthCode } catch { Write-Host -ForegroundColor Red "Could not create a browser window for the OAuth2 authentication" } } ```
2020/07/01
[ "https://Stackoverflow.com/questions/62674979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1826131/" ]
**Answer from this [blog post](https://medium.com/@sachin.hebballi/auth-code-flow-using-powershell-c8dacf460409)** I managed to get the Auth code flow working using the headless chrome. All you need are these two components. * [Chrome/edge driver](https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver) * [Selenium driver](https://www.selenium.dev/downloads/) Once you have these setup, you need to use the below Powershell commands to generate token using Auth code flow ``` $SeleniumWebDriverFullPath = ".\WebDriver.dll" # Full path to selenium web driver $ClientId = "" $Scopes = "" $RedirectUri = "" $authCodeUri = "$($AuthorizeEndpoint.TrimEnd("/"))?client_id=$ClientId&scope=$Scopes&redirect_uri=$RedirectUri&response_type=code Write-Host $authCodeUri Import-Module $SeleniumWebDriverFullPath $ChromeOptions = New-Object OpenQA.Selenium.Edge.EdgeOptions $ChromeOptions.AddArgument('headless') $ChromeOptions.AcceptInsecureCertificates = $True $ChromeDriver = New-Object OpenQA.Selenium.Edge.EdgeDriver($ChromeOptions); $ChromeDriver.Navigate().GoToUrl($authCodeUri); while (!$ChromeDriver.Url.Contains("code")) { Start-Sleep 1 } Write-Host $ChromeDriver.Url $ParsedQueryString = [System.Web.HttpUtility]::ParseQueryString($ChromeDriver.Url) $Code = $ParsedQueryString[0] Write-Host "Received code: $Code" Write-Host "Exchanging code for a token" $tokenrequest = @{ "client_id" = $ClientId; "grant_type" = "authorization_code"; "redirect_uri" = $RedirectUri; "code" = $ParsedQueryString[0] } $token = Invoke-RestMethod -Method Post -Uri $AuthTokenEndpoint -Body $tokenrequest $tokenString = $token | ConvertTo-Json ```
My guess is that the function has no idea what `$RedirectURI` is. You should make that a second parameter to the function or it should be (at least) [Script scoped](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-7#scope-modifiers) I'd prefer using a second parameter, but if you do scoping, you should be able to use it inside the function with `$script:RedirectURI`
62,674,980
When using ListTile there are gaps on left and right sides on leading property. Is it possible to reduce them? [![enter image description here](https://i.stack.imgur.com/fDkYD.jpg)](https://i.stack.imgur.com/fDkYD.jpg) ``` child: ListTile( leading: GestureDetector( onTap: _onPressed, child: Container( width: 48, height: 48, color: Colors.amberAccent, child: Icon( Icons.label_outline, size: 32, ), ) ```
2020/07/01
[ "https://Stackoverflow.com/questions/62674980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5829191/" ]
You can play with the following attributes: ``` ListTile( dense: true, minLeadingWidth: X, horizontalTitleGap: Y, contentPadding: EdgeInsets.all(Z), ... ```
You can copy `ListTile` and make a custom one. To change the padding or width of the leading, there are 2 variables you might want to change: `_minLeadingWidth` and `_horizontalTitleGap`
62,674,984
Trying simple deployment with parameters from a PS script: ``` $prefix = "xxx" $location = "switzerlandnorth" az deployment group create ` --name $timestamp ` --resource-group $resourceGroupName ` --mode incremental ` --verbose ` --template-file .\src\ops\scripts\arm.json ` --parameters "{ `"location`": { `"value`": `"$location`" },`"projectPrefix`": { `"value`": `"$prefix`" } }" ``` Response with error: ``` Unable to parse parameter: { location: { value: switzerlandnorth }, projectPrefix: { value: xxx } } ``` **Running from a PS1 script**.
2020/07/01
[ "https://Stackoverflow.com/questions/62674984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248304/" ]
As we can see in the error that it is unable to parse the parameters. The correct way to pass the parameters to the `az deployment group create` command is: ``` az deployment group create ` --name $timestamp ` --resource-group $resourceGroupName ` --mode "incremental" ` --verbose ` --template-file ".\src\ops\scripts\arm.json" ` --parameters '{ \"location\": { \"value\": \"switzerlandnorth\" },\"projectPrefix\": { \"value\": \"xxx\" } }' ``` **Update:** If you want to pass the PowerShell variables in the Parameters you can do something like below - ``` $location = "switzerlandnorth" $projectPrefix = "xxx" $params = '{ \"location\": { \"value\": \" ' + $location + '\" },\"projectPrefix\": { \"value\": \"' + $projectprefix + '\" } }' az deployment group create ` --name $timestamp ` --resource-group $resourceGroupName ` --mode "incremental" ` --verbose ` --template-file ".\src\ops\scripts\arm.json" ` --parameters $params ``` Hope this helps!
Another way you can think of this is using objects/hashtables in PS and then converting to JSON, e.g. ``` $param = @{ location = "switzerlandnorth" prefix = "foo" } $paramJSON = ($param | ConvertTo-Json -Depth 30 -Compress).Replace('"', '\"') # escape quotes in order to pass the command via pwsh.exe az deployment group create -g $resourceGroupName--template-file "azuredeploy.json" -p $paramJson ``` This is a similar example: <https://gist.github.com/bmoore-msft/d578c815f319af7eb20d9d97df9bf657>
62,674,984
Trying simple deployment with parameters from a PS script: ``` $prefix = "xxx" $location = "switzerlandnorth" az deployment group create ` --name $timestamp ` --resource-group $resourceGroupName ` --mode incremental ` --verbose ` --template-file .\src\ops\scripts\arm.json ` --parameters "{ `"location`": { `"value`": `"$location`" },`"projectPrefix`": { `"value`": `"$prefix`" } }" ``` Response with error: ``` Unable to parse parameter: { location: { value: switzerlandnorth }, projectPrefix: { value: xxx } } ``` **Running from a PS1 script**.
2020/07/01
[ "https://Stackoverflow.com/questions/62674984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248304/" ]
As we can see in the error that it is unable to parse the parameters. The correct way to pass the parameters to the `az deployment group create` command is: ``` az deployment group create ` --name $timestamp ` --resource-group $resourceGroupName ` --mode "incremental" ` --verbose ` --template-file ".\src\ops\scripts\arm.json" ` --parameters '{ \"location\": { \"value\": \"switzerlandnorth\" },\"projectPrefix\": { \"value\": \"xxx\" } }' ``` **Update:** If you want to pass the PowerShell variables in the Parameters you can do something like below - ``` $location = "switzerlandnorth" $projectPrefix = "xxx" $params = '{ \"location\": { \"value\": \" ' + $location + '\" },\"projectPrefix\": { \"value\": \"' + $projectprefix + '\" } }' az deployment group create ` --name $timestamp ` --resource-group $resourceGroupName ` --mode "incremental" ` --verbose ` --template-file ".\src\ops\scripts\arm.json" ` --parameters $params ``` Hope this helps!
I'll throw in my two cents here because previous answers are slim on what we are actually doing here. In short the `az deployment group create` command wants the `--parameters` argument to be a double serialized JSON string {scoff}. In order to create a value that can be handled by `az deployment group create` we would need to do something like this: ``` $stupidlyFormattedParam = @{ someAppSetting1 = @{ value = "setting 1" } someAppSetting2 = @{ value = "setting 2" } } | ConvertTo-Json -Compress -Depth 10 | ConvertTo-Json az deployment group create --name someName--resource-group someGroup --parameters $stupidlyFormattedParam --template-file .\someFile.json ```
62,674,984
Trying simple deployment with parameters from a PS script: ``` $prefix = "xxx" $location = "switzerlandnorth" az deployment group create ` --name $timestamp ` --resource-group $resourceGroupName ` --mode incremental ` --verbose ` --template-file .\src\ops\scripts\arm.json ` --parameters "{ `"location`": { `"value`": `"$location`" },`"projectPrefix`": { `"value`": `"$prefix`" } }" ``` Response with error: ``` Unable to parse parameter: { location: { value: switzerlandnorth }, projectPrefix: { value: xxx } } ``` **Running from a PS1 script**.
2020/07/01
[ "https://Stackoverflow.com/questions/62674984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248304/" ]
Another way you can think of this is using objects/hashtables in PS and then converting to JSON, e.g. ``` $param = @{ location = "switzerlandnorth" prefix = "foo" } $paramJSON = ($param | ConvertTo-Json -Depth 30 -Compress).Replace('"', '\"') # escape quotes in order to pass the command via pwsh.exe az deployment group create -g $resourceGroupName--template-file "azuredeploy.json" -p $paramJson ``` This is a similar example: <https://gist.github.com/bmoore-msft/d578c815f319af7eb20d9d97df9bf657>
I'll throw in my two cents here because previous answers are slim on what we are actually doing here. In short the `az deployment group create` command wants the `--parameters` argument to be a double serialized JSON string {scoff}. In order to create a value that can be handled by `az deployment group create` we would need to do something like this: ``` $stupidlyFormattedParam = @{ someAppSetting1 = @{ value = "setting 1" } someAppSetting2 = @{ value = "setting 2" } } | ConvertTo-Json -Compress -Depth 10 | ConvertTo-Json az deployment group create --name someName--resource-group someGroup --parameters $stupidlyFormattedParam --template-file .\someFile.json ```
62,674,993
I want to delete a Folder named "testfolder" and all the subfolders and files in it. I want to give the "testfolder" path as a parameter when calling the python file. For example ...... (testfolder location) and there it should delete the "testfolder" when the folder exists
2020/07/01
[ "https://Stackoverflow.com/questions/62674993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12937657/" ]
I guess this might be what you're looking for ``` import os import shutil pathLocation = # Whatever your path location is if os.path.exists(pathLocation): shutil.rmtree(pathLocation) else: print('the path doesn\'t exist') ```
Better to use absolute path and import only the rmtree function from shutil import rmtree as this is a large package the above line will only import the required function. ``` from shutil import rmtree rmtree('directory-absolute-path') ```
62,674,993
I want to delete a Folder named "testfolder" and all the subfolders and files in it. I want to give the "testfolder" path as a parameter when calling the python file. For example ...... (testfolder location) and there it should delete the "testfolder" when the folder exists
2020/07/01
[ "https://Stackoverflow.com/questions/62674993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12937657/" ]
You can use shutil.rmtree() for removing folders and argparse to get parameters. ``` import shutil import argparse import os def remove_folder(folder_path='./testfolder/'): if os.path.exists(folder_path): shutil.rmtree(folder_path) print(f'{folder_path} and its subfolders are removed succesfully.') else: print(f'There is no such folder like {folder_path}') if __name__ == "__main__": parser = argparse.ArgumentParser(description='Python Folder Remover') parser.add_argument('--remove', '-r', metavar='path', required=True) args = parser.parse_args() if args.remove: remove_folder(args.remove) ``` You can save above script as 'remove.py' and call it from command prompt like: ``` python remove.py --remove "testfolder" ```
Better to use absolute path and import only the rmtree function from shutil import rmtree as this is a large package the above line will only import the required function. ``` from shutil import rmtree rmtree('directory-absolute-path') ```
62,674,997
I have a Pandas dataframe with some correlations in the form of: ``` A B D 0.78 0.49 E 0.93 0.67 ``` Is there a fast way in Python to get a list of tuples like: [(A, D, 0.78), (A, E, 0.93), (B, D, 0.49), (B, E, 0.67)] Thanks in advance for your help.
2020/07/01
[ "https://Stackoverflow.com/questions/62674997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13792697/" ]
Use [`DataFrame.unstack`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html) for reshape, then convert `Series` to `DataFrame` and last convert nested lists to tuples: ``` L = [tuple(x) for x in df.unstack().reset_index().to_numpy()] ``` Or: ``` L = list(map(tuple, df.unstack().reset_index().to_numpy())) ``` Another idea, thank you @Datanovice: ``` L = list(df.unstack().reset_index().itertuples(name=None,index=None)) ``` --- ``` print (L) [('A', 'D', 0.78), ('A', 'E', 0.93), ('B', 'D', 0.49), ('B', 'E', 0.67)] ``` If order should be swapped, thank you @Ch3steR: ``` L = list(df.reset_index().melt(id_vars='index').itertuples(name=None,index=None)) print (L) [('D', 'A', 0.78), ('E', 'A', 0.93), ('D', 'B', 0.49), ('E', 'B', 0.67)] ```
Try this, ``` import pandas as pd dt = {'a': [1, 2], 'b': [3, 4]} cols = ['a', 'b'] rows = ['d', 'e'] df = pd.DataFrame(dt, index=rows) print(df) a b d 1 3 e 2 4 result = [] for c in cols: for r in rows: result.append((c, r, df[c][r])) print(result) [('a', 'd', 1), ('a', 'e', 2), ('b', 'd', 3), ('b', 'e', 4)] ```
62,674,997
I have a Pandas dataframe with some correlations in the form of: ``` A B D 0.78 0.49 E 0.93 0.67 ``` Is there a fast way in Python to get a list of tuples like: [(A, D, 0.78), (A, E, 0.93), (B, D, 0.49), (B, E, 0.67)] Thanks in advance for your help.
2020/07/01
[ "https://Stackoverflow.com/questions/62674997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13792697/" ]
Use [`DataFrame.unstack`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html) for reshape, then convert `Series` to `DataFrame` and last convert nested lists to tuples: ``` L = [tuple(x) for x in df.unstack().reset_index().to_numpy()] ``` Or: ``` L = list(map(tuple, df.unstack().reset_index().to_numpy())) ``` Another idea, thank you @Datanovice: ``` L = list(df.unstack().reset_index().itertuples(name=None,index=None)) ``` --- ``` print (L) [('A', 'D', 0.78), ('A', 'E', 0.93), ('B', 'D', 0.49), ('B', 'E', 0.67)] ``` If order should be swapped, thank you @Ch3steR: ``` L = list(df.reset_index().melt(id_vars='index').itertuples(name=None,index=None)) print (L) [('D', 'A', 0.78), ('E', 'A', 0.93), ('D', 'B', 0.49), ('E', 'B', 0.67)] ```
Sure, it is possible. I would do that like this: ``` import pandas as pd import numpy as np # Creating example DF tab = pd.DataFrame(data={'A': (1,2), 'B': (3,4)}) tab.index=['C', 'D'] # Values to tuples np.array(tab.apply(lambda x: [(x.index[i], x.name,y) for i, y in enumerate(x)])).ravel() ```
62,675,000
I have a CSV file can contain around million records, how can I remove columns starting with \_ and generate a resulting csv For the sake of simplicity, consider i have the below csv ``` Sr.No Col1 Col2 _Col3 Col4 _Col5 1 txt png 676766 win 8787 2 jpg pdf 565657 lin 8787 3 pdf jpg 786786 lin 9898 ``` --- I would want the output to be ``` Sr.No Col1 Col2 Col4 1 txt png win 2 jpg pdf lin 3 pdf jpg lin ``` Do i need to read the entire file to achive this or is there a better approach to do this. ``` const csv = require('csv-parser'); const fs = require('fs'); fs.createReadStream('data.csv') .pipe(csv()) .on('data', (row) => { // generate a new csv with removing specific column }) .on('end', () => { console.log('CSV file successfully processed'); }); ``` Any help on how can i achieve this would be helpful. Thanks.
2020/07/01
[ "https://Stackoverflow.com/questions/62675000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1858727/" ]
To anyone who stumbles on the post I was able to transform the csv's using below code using `fs` and `csv` modules. ``` await fs.createReadStream(m.path) .pipe(csv.parse({delimiter: '\t', columns: true})) .pipe(csv.transform((input) => { delete input['_Col3']; console.log(input); return input; })) .pipe(csv.stringify({header: true})) .pipe(fs.createWriteStream(transformedPath)) .on('finish', () => { console.log('finish....'); }).on('error', () => { console.log('error.....'); }); ``` Source: <https://gist.github.com/donmccurdy/6cbcd8cee74301f92b4400b376efda1d>
Actually you can handle that by using two npm packages. <https://www.npmjs.com/package/csvtojson> to convert your library to JSON format then use this <https://www.npmjs.com/package/json2csv> with the second library. If you know what are the exact fields you want. you can pass parameters to specifically select the fields you want. ``` const { Parser } = require('json2csv'); const fields = ['field1', 'field2', 'field3']; const opts = { fields }; try { const parser = new Parser(opts); const csv = parser.parse(myData); console.log(csv); } catch (err) { console.error(err); } ``` Or you can modify the JSON object manually to drop those columns
62,675,000
I have a CSV file can contain around million records, how can I remove columns starting with \_ and generate a resulting csv For the sake of simplicity, consider i have the below csv ``` Sr.No Col1 Col2 _Col3 Col4 _Col5 1 txt png 676766 win 8787 2 jpg pdf 565657 lin 8787 3 pdf jpg 786786 lin 9898 ``` --- I would want the output to be ``` Sr.No Col1 Col2 Col4 1 txt png win 2 jpg pdf lin 3 pdf jpg lin ``` Do i need to read the entire file to achive this or is there a better approach to do this. ``` const csv = require('csv-parser'); const fs = require('fs'); fs.createReadStream('data.csv') .pipe(csv()) .on('data', (row) => { // generate a new csv with removing specific column }) .on('end', () => { console.log('CSV file successfully processed'); }); ``` Any help on how can i achieve this would be helpful. Thanks.
2020/07/01
[ "https://Stackoverflow.com/questions/62675000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1858727/" ]
To anyone who stumbles on the post I was able to transform the csv's using below code using `fs` and `csv` modules. ``` await fs.createReadStream(m.path) .pipe(csv.parse({delimiter: '\t', columns: true})) .pipe(csv.transform((input) => { delete input['_Col3']; console.log(input); return input; })) .pipe(csv.stringify({header: true})) .pipe(fs.createWriteStream(transformedPath)) .on('finish', () => { console.log('finish....'); }).on('error', () => { console.log('error.....'); }); ``` Source: <https://gist.github.com/donmccurdy/6cbcd8cee74301f92b4400b376efda1d>
Try this with csv lib ``` const csv = require('csv'); const fs = require('fs'); const csvString=`col1,col2 value1,value2` csv.parse(csvString, {columns: true}) .pipe(csv.transform(({col1,col2}) => ({col1}))) // remove col2 .pipe(csv.stringify({header:true})) .pipe(fs.createWriteStream('./file.csv')) ```
62,675,000
I have a CSV file can contain around million records, how can I remove columns starting with \_ and generate a resulting csv For the sake of simplicity, consider i have the below csv ``` Sr.No Col1 Col2 _Col3 Col4 _Col5 1 txt png 676766 win 8787 2 jpg pdf 565657 lin 8787 3 pdf jpg 786786 lin 9898 ``` --- I would want the output to be ``` Sr.No Col1 Col2 Col4 1 txt png win 2 jpg pdf lin 3 pdf jpg lin ``` Do i need to read the entire file to achive this or is there a better approach to do this. ``` const csv = require('csv-parser'); const fs = require('fs'); fs.createReadStream('data.csv') .pipe(csv()) .on('data', (row) => { // generate a new csv with removing specific column }) .on('end', () => { console.log('CSV file successfully processed'); }); ``` Any help on how can i achieve this would be helpful. Thanks.
2020/07/01
[ "https://Stackoverflow.com/questions/62675000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1858727/" ]
To anyone who stumbles on the post I was able to transform the csv's using below code using `fs` and `csv` modules. ``` await fs.createReadStream(m.path) .pipe(csv.parse({delimiter: '\t', columns: true})) .pipe(csv.transform((input) => { delete input['_Col3']; console.log(input); return input; })) .pipe(csv.stringify({header: true})) .pipe(fs.createWriteStream(transformedPath)) .on('finish', () => { console.log('finish....'); }).on('error', () => { console.log('error.....'); }); ``` Source: <https://gist.github.com/donmccurdy/6cbcd8cee74301f92b4400b376efda1d>
With this function I accomplished the column removal from a CSV ``` removeCol(csv, col) { let lines = csv.split("\n"); let headers = lines[0].split(","); let colNameToRemove = headers.find(h=> h.trim() === col); let index = headers.indexOf(colNameToRemove); let newLines = []; lines.map((line)=>{ let fields = line.split(","); fields.splice(index, 1) newLines.push(fields) }) let arrData = ''; for (let index = 0; index < newLines.length; index++) { const element = newLines[index]; arrData += element.join(',') + '\n' } return arrData; } ```
62,675,004
I am trying to code a Siamese networks in Keras and Tensorflow, using this Jupiter Notebook as reference: <https://github.com/hlamba28/One-Shot-Learning-with-Siamese-Networks/blob/master/Siamese%20on%20Omniglot%20Dataset.ipynb> When I create the model: ``` model = get_siamese_model((105, 105, 1)) ``` I got this error: ``` Traceback (most recent call last): File "main.py", line 164, in <module> model = get_siamese_model((105, 105, 1)) File "main.py", line 129, in get_siamese_model kernel_initializer=initialize_weights, kernel_regularizer=l2(2e-4))) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/training/tracking/base.py", line 456, in _method_wrapper result = method(self, *args, **kwargs) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/keras/engine/sequential.py", line 198, in add layer(x) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 897, in __call__ self._maybe_build(inputs) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 2416, in _maybe_build self.build(input_shapes) # pylint:disable=not-callable File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/keras/layers/convolutional.py", line 163, in build dtype=self.dtype) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 577, in add_weight caching_device=caching_device) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/training/tracking/base.py", line 743, in _add_variable_with_custom_getter **kwargs_for_getter) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer_utils.py", line 141, in make_variable shape=variable_shape if variable_shape else None) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/ops/variables.py", line 259, in __call__ return cls._variable_v1_call(*args, **kwargs) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/ops/variables.py", line 220, in _variable_v1_call shape=shape) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/ops/variables.py", line 198, in <lambda> previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/ops/variable_scope.py", line 2598, in default_variable_creator shape=shape) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/ops/variables.py", line 263, in __call__ return super(VariableMetaclass, cls).__call__(*args, **kwargs) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/ops/resource_variable_ops.py", line 1434, in __init__ distribute_strategy=distribute_strategy) File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/ops/resource_variable_ops.py", line 1567, in _init_from_args initial_value() if init_from_fn else initial_value, File "/home/fabio/.local/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer_utils.py", line 121, in <lambda> init_val = lambda: initializer(shape, dtype=dtype) TypeError: initialize_weights() got an unexpected keyword argument 'dtype' ``` What the error means? And how can I solve that?
2020/07/01
[ "https://Stackoverflow.com/questions/62675004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4266956/" ]
Keras internally calls supplied `initializer` as below ``` weight = K.variable(initializer(shape, dtype=dtype), dtype=dtype, ...... ``` As you can see the second argument of your custom `initializer` should be `dtype` not `name` **Fix** ``` def initialize_weights(shape, dtype=None): return np.random.normal(loc = 0.0, scale = 1e-2, size = shape) def initialize_bias(shape, dtype=None): return np.random.normal(loc = 0.5, scale = 1e-2, size = shape) ``` Now ``` model = get_siamese_model((105, 105, 1)) model.summary() ``` Will build the model succesfully output ``` __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_7 (InputLayer) (None, 105, 105, 1) 0 __________________________________________________________________________________________________ input_8 (InputLayer) (None, 105, 105, 1) 0 __________________________________________________________________________________________________ sequential_4 (Sequential) (None, 4096) 38947648 input_7[0][0] input_8[0][0] __________________________________________________________________________________________________ lambda_2 (Lambda) (None, 4096) 0 sequential_4[1][0] sequential_4[2][0] __________________________________________________________________________________________________ dense_4 (Dense) (None, 1) 4097 lambda_2[0][0] ================================================================================================== Total params: 38,951,745 Trainable params: 38,951,745 Non-trainable params: 0 _________________________ ```
For some reason this is calling the v2 tf.keras initializers instead of the compat.v1 initializers. You are using v1 tensorflow but trying to call a keyword from v2. To fix this please follow the steps to migrate to tensor flow V2 in the following link. <https://www.tensorflow.org/guide/migrate>
62,675,056
I'd like, as succinctly (yet clearly) as possible to transform a `List<Triple<String, String, String>` to a `Triple<List<String>, List<String>, List<String>>`. For instance, say the method performing the transformation is called `turnOver`, I'd expect: ```kotlin val matches = listOf( Triple("a", "1", "foo"), Triple("b", "2", "bar"), Triple("c", "3", "baz"), Triple("d", "4", "qux") ) val expected = Triple( listOf("a", "b", "c", "d"), listOf("1", "2", "3", "4"), listOf("foo", "bar", "baz", "qux") ) matches.turnOver() == expected // true ``` How to write a succinct, clear, and possibly functional `turnOver` function? It's ok to use Arrow-Kt, I already got it as project dependency.
2020/07/01
[ "https://Stackoverflow.com/questions/62675056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1916413/" ]
``` fun turnOver(matches: List<Triple<String, String, String>>) = Triple( matches.map { it.first }, matches.map { it.second }, matches.map { it.third }, ) ``` would be one obvious solution I reckon.
To the best of my knowledge, there is no way in kotlin stdlib to create a Pair or a Triple out of an iterable, array, or sequence. I believe this is deliberate. So I guess the one above is the clearest possible solution.
62,675,059
Hello folks I have run into issue where I use a group of Apache Ignite (2.8.1) server nodes in .NET core to create a data grid and run queries to the grid via an Apache ignite java client. I have not problem at all writing data in binary mode to the grid and ask queries via the think layer provided. I use DBeaver to run queries and everything is fine as expected. The issue rise while I am trying to query data from a java client which complains about a conflict in cache ": Conflicts during configuration merge for cache MY\_CAHE". Find the error message below: ``` Caused by: class org.apache.ignite.spi.IgniteSpiException: Conflicts during configuration merge for cache 'DOTNET_BINARY_CACHE' : TRADE conflict: keyType is different: local=Apache.Ignite.Core.Cache.Affinity.AffinityKey, received=org.apache.ignite.cache.affinity.AffinityKey valType is different: local=Servicing.Agent4.Service.Implementation.Misc.Ignite.Trade, received=Servicing.Agent4.Core.Java.Models.Trade ``` Find my implemnetation in .NET and Java below: ``` public static class IgniteUtils { const string CACHE_NAME = "DOTNET_BINARY_CACHE"; public static IgniteConfiguration DefaultIgniteConfig() { return new IgniteConfiguration { BinaryConfiguration = new BinaryConfiguration { NameMapper = new BinaryBasicNameMapper { IsSimpleName = true }, CompactFooter = true, TypeConfigurations = new[] { new BinaryTypeConfiguration(typeof(Trade)) { Serializer = new IgniteTradeSerializer() } } }, // omit jvm and network options IncludedEventTypes = EventType.All, Logger = new IgniteNLogLogger(), CacheConfiguration = new[]{ new CacheConfiguration{ Name = CACHE_NAME, CacheMode = CacheMode.Partitioned, Backups = 0, QueryEntities = new[] { new QueryEntity(typeof(AffinityKey), typeof(Trade))} } } }; } } ``` The setup of Apache Ignite is happen on class: ``` public class IgniteService { public void Start() { IIgnite _ignite = Ignition.Start(IgniteUtils.DefaultIgniteConfig()); // Create new cache and configure queries for Trade binary types. // Note that there are no such classes defined. var cache0 = _ignite.GetOrCreateCache<AffinityKey, Trade>("DOTNET_BINARY_CACHE"); // Switch to binary mode to work with data in serialized form. var cache = cache0.WithKeepBinary<AffinityKey, IBinaryObject>(); // Clean up caches on all nodes before run. cache.Clear(); // Populate cache with sample data entries. IBinary binary = cache.Ignite.GetBinary(); cache[new AffinityKey(1, 1)] = binary.GetBuilder("TRADE") .SetField("Symbol", "James Wilson") .SetField("Id", 1) .SetField("Login", 123) .SetField("SourceId", 1) .Build(); } ``` Domain class below: ``` public class Trade { [QuerySqlField(IsIndexed = true)] public int Id { set; get; } [QueryTextField] public string Symbol { set; get; } [QuerySqlField] public int Login { set; get; } [QuerySqlField(IsIndexed = true)] public int SourceId { get; set; } //omit constructor } ``` The Java client code ``` public class IgniteScheduler { final String CACHE_NAME = "DOTNET_BINARY_CACHE"; @PostConstruct public void start() { IgniteConfiguration cfg = new IgniteConfiguration(); // Enable client mode. cfg.setClientMode(true); CacheConfiguration<AffinityKey<Integer>, Trade> cacheCfg = new CacheConfiguration<>(); cacheCfg.setName(CACHE_NAME); cacheCfg.setCacheMode(CacheMode.PARTITIONED); cacheCfg.setBackups(0); cacheCfg.setQueryEntities(Arrays.asList(new QueryEntity(AffinityKey.class, Trade.class))); // Setting up an IP Finder to ensure the client can locate the servers. TcpDiscoveryMulticastIpFinder ipFinder = new TcpDiscoveryMulticastIpFinder(); ipFinder.setAddresses(Collections.singletonList("127.0.0.1:47500..47509")); cfg.setDiscoverySpi(new TcpDiscoverySpi().setIpFinder(ipFinder)); cfg.setCacheConfiguration(cacheCfg); // Configure Ignite to connect with .NET nodes cfg.setBinaryConfiguration(new BinaryConfiguration() .setNameMapper(new BinaryBasicNameMapper(true)) .setCompactFooter(true) BinaryTypeConfiguration(Trade.class.getSimpleName()))) ); // Start Ignite in client mode. Ignite ignite = Ignition.start(cfg); // omit functional code } ``` Domain class below: ``` @Data public class Trade implements Serializable { @QuerySqlField(index = true) public int Id; @QueryTextField public String Symbol; @QuerySqlField public int Login; //@AffinityKeyMapped does not work as well @QuerySqlField(index = true) public int SourceId; // omit constructor } ``` Debugging Info * OS: Windows 10 10.0 amd64 * VM information: Java(TM) SE Runtime Environment 11.0.5+10-LTS Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 11.0.5+10-LTS * Apache Ignite 2.8.1 version
2020/07/01
[ "https://Stackoverflow.com/questions/62675059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5629014/" ]
1. You don't need to provide cache configuration on all nodes. Cache configuration should be provided once on the node that starts the cache. Remove `setCacheConfiguration` on Java side and simply call `ignite.cache(CACHE_NAME)` there. 2. The exception is caused by the fact that `NameMapper` does not apply to query entities, `KeyType` and `ValueType` always use full type name (with namespace). Normally this is not an issue, and you can omit namespace in queries: `select name from Trade` works in your example (given that Trade has Name property). Working example: <https://gist.github.com/ptupitsyn/a2c13f47e19ccfc9c0b548cf4d4fa629>
It looks like simple name marshaller is not working in your case. It is possible that you start your nodes with some other configuration and not the pair specified above, since it seems to define simple name marshaller. Also, maybe it's just that you don't need to define cache configuration twice. Pick one place to define it (I'd choose Java side), cache will be defined for all nodes of your cluster, anyway.
62,675,080
The linux command for viewing csv file in terminal is: ``` cat filename.csv ``` What i use in a windows command prompt for the same thing I can open the csv file in excel through cmd but i can't view it in the cmd. I searched a lot and couldn't get..
2020/07/01
[ "https://Stackoverflow.com/questions/62675080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13372541/" ]
For simply viewing a file, use the `more` command for better control, and it works on both Linux and Windows.
In Windows, in the command prompt you can simply use the `type` syntax to display the csv file content: ``` c:\>type [filename.csv] ```
62,675,083
I'm having an issue while uploading file to laravel either its pdf or image always return to `null` This is the View ``` {!! Form::open(['action' => 'TransactionInController@store', 'method' => 'POST', 'autocomplete' => 'off', 'class' => 'form-horizontal', 'enctype' => 'multipart/form-data']) !!} <div class="row"> {{ Form::label('Device Document', '', ['class' => 'col-sm-2 col-form-label']) }} <div class="col-sm-7"> {{ Form::file('device_document') }} <p style="color: red;">@error('device_document') {{ $message }} @enderror</p> </div> </div> {!! Form::close() !!} ``` and this is the Controller i use ``` public function store(Request $request) { $this->validate($request, [ 'device_document' => 'nullable|max:8192|mimes:pdf' ]); $transactionsin = new TransactionIn; $imageName = $request->input('device_document'); $request->image->move(public_path('document-image'), $imageName); $transactionsin->save(); return redirect('/transactionsin'); } ``` i know its been asked before and i already try several way to upload file this error. This is the error message i get while running the code > > Call to a member function move() on null > > > but if i change the code in controller into something more simple like this ``` public function store(Request $request) { $this->validate($request, [ 'device_document' => 'nullable|max:8192|mimes:pdf' ]); $transactionsin = new TransactionIn; $transactionsin->device_document = $request->input('device_document'); $transactionsin->save(); return redirect('/transactionsin'); } ``` it will not return any error message but it will saved as `null` in the database.
2020/07/01
[ "https://Stackoverflow.com/questions/62675083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13703933/" ]
For simply viewing a file, use the `more` command for better control, and it works on both Linux and Windows.
In Windows, in the command prompt you can simply use the `type` syntax to display the csv file content: ``` c:\>type [filename.csv] ```
62,675,085
I have a table (umt\_date) which generates dates and I need to use this date in the second query to get all data greater than equal to the date in umt\_date table ``` umt_date ---------------------------- |processdate||processname| ---------------------------- | 2020-06-01 | A | ---------------------------- | 2020-06-01 | B | ``` when I perform the sql ``` select * from main_table where processdate >= (select processdate from umt_date where processname='A') ``` I get the following error **SQL Error [40000] [42000]: Error while compiling statement: FAILED: SemanticException Line 0:-1 Unsupported SubQuery Expression 'processdate': Only SubQuery expressions that are top level conjuncts are allowed** Since we do not have any common columns we cannot perform a join as well. Whats the alternative for this ?
2020/07/01
[ "https://Stackoverflow.com/questions/62675085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1197295/" ]
If subquery returns single row, use cross join: ``` select m.* from main_table m cross join (select processdate from umt_date where processname='A') t where m.processdate >= t.processdate ``` And if the subquery returns more than one row, use join on some condition. cross join is not good in this case because it will duplicate data, though WHERE may filter duplicated rows
You could try using `WITH` clause like below ``` WITH PROCESSA_SUBQ AS( select processdate from umt_date where processname='A' ) SELECT a.* FROM main_table as a INNER JOIN PROCESSA_SUBQ as b ON 1=1 -- always true join condition, can be ignored. where a.processdate >= b.processdate ``` or you could get a boolean condition check too: ``` WITH PROCESSA_SUBQ AS( select processdate from umt_date where processname='A' ) SELECT X.* FROM ( SELECT a.*, (a.processdate>=b.processdate) as check FROM main_table as a INNER JOIN PROCESSA_SUBQ as b ON 1=1 -- always true join condition, can be ignored. ) as X where X.check = true ```
62,675,090
In need the Object with maximum a+b value from myArray ```js var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; ``` Right now I have something that returns me the index: ```js var max = [], maxIndex; myArray.map(x=>max.push(x.a + x.b)) maxIndex = max.indexOf( Math.max.apply(Math, max)) ``` I need something that returns the Object and not its index, so far working with ```js var maxObject = myArray.map(x=>x.a + x.b).reduce((x,y)=>x>y) ``` returning `false`.
2020/07/01
[ "https://Stackoverflow.com/questions/62675090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803358/" ]
You can use `reduce` like below ```js var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; const finalResult = myArray.reduce((result, obj) => { let sum = obj.a + obj.b; if(result.sum < sum) { return {sum, obj: {...obj}} } return result; }, {sum: 0, obj: {}}) console.log(finalResult.obj) ``` Hope this helps.
You may try something like that: ```js let myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; let max = myArray[0].a + myArray[0].b; let maxObject = {...myArray[0]}; myArray.map((obj) => { if(max < obj.a + obj.b) { max = obj.a + obj.b; maxObject = {...obj} } }); console.log(maxObject); // { a: 10, b: 7 } ```
62,675,090
In need the Object with maximum a+b value from myArray ```js var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; ``` Right now I have something that returns me the index: ```js var max = [], maxIndex; myArray.map(x=>max.push(x.a + x.b)) maxIndex = max.indexOf( Math.max.apply(Math, max)) ``` I need something that returns the Object and not its index, so far working with ```js var maxObject = myArray.map(x=>x.a + x.b).reduce((x,y)=>x>y) ``` returning `false`.
2020/07/01
[ "https://Stackoverflow.com/questions/62675090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803358/" ]
No need for map as reduce will itterate over you array. ``` var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; var biggestSumObj = myArray.reduce((total,current)=>{ if((current.a + current.b) > (total.a + total.b)){ return current; } return total; }); console.log(biggestSumObj); ``` fiddle: [return biggest object](https://jsfiddle.net/ut2xqh0m/1/)
You may try something like that: ```js let myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; let max = myArray[0].a + myArray[0].b; let maxObject = {...myArray[0]}; myArray.map((obj) => { if(max < obj.a + obj.b) { max = obj.a + obj.b; maxObject = {...obj} } }); console.log(maxObject); // { a: 10, b: 7 } ```
62,675,090
In need the Object with maximum a+b value from myArray ```js var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; ``` Right now I have something that returns me the index: ```js var max = [], maxIndex; myArray.map(x=>max.push(x.a + x.b)) maxIndex = max.indexOf( Math.max.apply(Math, max)) ``` I need something that returns the Object and not its index, so far working with ```js var maxObject = myArray.map(x=>x.a + x.b).reduce((x,y)=>x>y) ``` returning `false`.
2020/07/01
[ "https://Stackoverflow.com/questions/62675090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803358/" ]
You can use `reduce` like below ```js var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; const finalResult = myArray.reduce((result, obj) => { let sum = obj.a + obj.b; if(result.sum < sum) { return {sum, obj: {...obj}} } return result; }, {sum: 0, obj: {}}) console.log(finalResult.obj) ``` Hope this helps.
Based on your code, after you found the index of the object with the highest summed values , you simply return the array in that index: ```js var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; var max = [], maxIndex; var result; myArray.map(x => max.push(x.a + x.b)) maxIndex = max.indexOf(Math.max.apply(Math, max)) result = myArray[maxIndex]; console.log(result); ```
62,675,090
In need the Object with maximum a+b value from myArray ```js var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; ``` Right now I have something that returns me the index: ```js var max = [], maxIndex; myArray.map(x=>max.push(x.a + x.b)) maxIndex = max.indexOf( Math.max.apply(Math, max)) ``` I need something that returns the Object and not its index, so far working with ```js var maxObject = myArray.map(x=>x.a + x.b).reduce((x,y)=>x>y) ``` returning `false`.
2020/07/01
[ "https://Stackoverflow.com/questions/62675090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803358/" ]
No need for map as reduce will itterate over you array. ``` var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; var biggestSumObj = myArray.reduce((total,current)=>{ if((current.a + current.b) > (total.a + total.b)){ return current; } return total; }); console.log(biggestSumObj); ``` fiddle: [return biggest object](https://jsfiddle.net/ut2xqh0m/1/)
Based on your code, after you found the index of the object with the highest summed values , you simply return the array in that index: ```js var myArray = [{a:5,b:10},{a:10,b:7},{a:8,b:5}]; var max = [], maxIndex; var result; myArray.map(x => max.push(x.a + x.b)) maxIndex = max.indexOf(Math.max.apply(Math, max)) result = myArray[maxIndex]; console.log(result); ```
62,675,096
Okay so I've tried almost everything; staticfiles dir, static root, collect staticfiles. I don't know where I'm going wrong or what I'm missing. Please help guys, I've been going over this for the past 3 days. My HTML ``` {% load static %} <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1", shrink-to-fit="no" /> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> ``` settings.py ``` STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, "static") ``` [Screenshot](https://i.stack.imgur.com/D2ScP.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62675096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13812017/" ]
``` "STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),]" ``` On this variable, just write 'S' after DIR it might solve your problem, like this: ``` STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] ```
Have you load your static directory? try this ``` {% load static %} ```
62,675,096
Okay so I've tried almost everything; staticfiles dir, static root, collect staticfiles. I don't know where I'm going wrong or what I'm missing. Please help guys, I've been going over this for the past 3 days. My HTML ``` {% load static %} <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1", shrink-to-fit="no" /> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> ``` settings.py ``` STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, "static") ``` [Screenshot](https://i.stack.imgur.com/D2ScP.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62675096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13812017/" ]
You just need to rerun the server again! Tap `ctr` c to stop the server. Then type this in the terminal to run the server again: python manage.py runserver
Have you load your static directory? try this ``` {% load static %} ```
62,675,096
Okay so I've tried almost everything; staticfiles dir, static root, collect staticfiles. I don't know where I'm going wrong or what I'm missing. Please help guys, I've been going over this for the past 3 days. My HTML ``` {% load static %} <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1", shrink-to-fit="no" /> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> ``` settings.py ``` STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, "static") ``` [Screenshot](https://i.stack.imgur.com/D2ScP.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62675096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13812017/" ]
I wonder if you are not serving the static files correctly, the same happens if you want to run the admin page. I'm dealing with the same and trying to solve this from the official page: <https://docs.djangoproject.com/en/3.1/howto/static-files/deployment/> regards!
Have you load your static directory? try this ``` {% load static %} ```
62,675,096
Okay so I've tried almost everything; staticfiles dir, static root, collect staticfiles. I don't know where I'm going wrong or what I'm missing. Please help guys, I've been going over this for the past 3 days. My HTML ``` {% load static %} <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1", shrink-to-fit="no" /> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> ``` settings.py ``` STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, "static") ``` [Screenshot](https://i.stack.imgur.com/D2ScP.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62675096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13812017/" ]
``` "STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),]" ``` On this variable, just write 'S' after DIR it might solve your problem, like this: ``` STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] ```
You just need to rerun the server again! Tap `ctr` c to stop the server. Then type this in the terminal to run the server again: python manage.py runserver
62,675,096
Okay so I've tried almost everything; staticfiles dir, static root, collect staticfiles. I don't know where I'm going wrong or what I'm missing. Please help guys, I've been going over this for the past 3 days. My HTML ``` {% load static %} <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1", shrink-to-fit="no" /> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> ``` settings.py ``` STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, "static") ``` [Screenshot](https://i.stack.imgur.com/D2ScP.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62675096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13812017/" ]
``` "STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),]" ``` On this variable, just write 'S' after DIR it might solve your problem, like this: ``` STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] ```
I wonder if you are not serving the static files correctly, the same happens if you want to run the admin page. I'm dealing with the same and trying to solve this from the official page: <https://docs.djangoproject.com/en/3.1/howto/static-files/deployment/> regards!
62,675,107
It is quite simple to split a string using .split() since this ignores a plural number of whitespaces and treats them as a single tab of whitespace. But when using `string_name.split(" ")`, with whitespace the result is somewhat confusing. Try ``` string = "Hi Raghav" string.split(" ") ``` returns a list containing all the words and (n-1) empty strings where n is the number of single whitespaces between the two words. If the string was to contain a full sentence then the number of empty strings would have been 1 less than the number of single whitespaces between each word. Why does this happen? Shouldn't there be half as much empty strings as the number of single whitespace because every alternate whitespace will disappear since it's an argument in split ![enter image description here](https://i.stack.imgur.com/6UA8V.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62675107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13287593/" ]
``` "STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),]" ``` On this variable, just write 'S' after DIR it might solve your problem, like this: ``` STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] ```
Have you load your static directory? try this ``` {% load static %} ```
62,675,107
It is quite simple to split a string using .split() since this ignores a plural number of whitespaces and treats them as a single tab of whitespace. But when using `string_name.split(" ")`, with whitespace the result is somewhat confusing. Try ``` string = "Hi Raghav" string.split(" ") ``` returns a list containing all the words and (n-1) empty strings where n is the number of single whitespaces between the two words. If the string was to contain a full sentence then the number of empty strings would have been 1 less than the number of single whitespaces between each word. Why does this happen? Shouldn't there be half as much empty strings as the number of single whitespace because every alternate whitespace will disappear since it's an argument in split ![enter image description here](https://i.stack.imgur.com/6UA8V.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62675107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13287593/" ]
You just need to rerun the server again! Tap `ctr` c to stop the server. Then type this in the terminal to run the server again: python manage.py runserver
Have you load your static directory? try this ``` {% load static %} ```
62,675,107
It is quite simple to split a string using .split() since this ignores a plural number of whitespaces and treats them as a single tab of whitespace. But when using `string_name.split(" ")`, with whitespace the result is somewhat confusing. Try ``` string = "Hi Raghav" string.split(" ") ``` returns a list containing all the words and (n-1) empty strings where n is the number of single whitespaces between the two words. If the string was to contain a full sentence then the number of empty strings would have been 1 less than the number of single whitespaces between each word. Why does this happen? Shouldn't there be half as much empty strings as the number of single whitespace because every alternate whitespace will disappear since it's an argument in split ![enter image description here](https://i.stack.imgur.com/6UA8V.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62675107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13287593/" ]
I wonder if you are not serving the static files correctly, the same happens if you want to run the admin page. I'm dealing with the same and trying to solve this from the official page: <https://docs.djangoproject.com/en/3.1/howto/static-files/deployment/> regards!
Have you load your static directory? try this ``` {% load static %} ```
62,675,107
It is quite simple to split a string using .split() since this ignores a plural number of whitespaces and treats them as a single tab of whitespace. But when using `string_name.split(" ")`, with whitespace the result is somewhat confusing. Try ``` string = "Hi Raghav" string.split(" ") ``` returns a list containing all the words and (n-1) empty strings where n is the number of single whitespaces between the two words. If the string was to contain a full sentence then the number of empty strings would have been 1 less than the number of single whitespaces between each word. Why does this happen? Shouldn't there be half as much empty strings as the number of single whitespace because every alternate whitespace will disappear since it's an argument in split ![enter image description here](https://i.stack.imgur.com/6UA8V.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62675107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13287593/" ]
``` "STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),]" ``` On this variable, just write 'S' after DIR it might solve your problem, like this: ``` STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] ```
You just need to rerun the server again! Tap `ctr` c to stop the server. Then type this in the terminal to run the server again: python manage.py runserver
62,675,107
It is quite simple to split a string using .split() since this ignores a plural number of whitespaces and treats them as a single tab of whitespace. But when using `string_name.split(" ")`, with whitespace the result is somewhat confusing. Try ``` string = "Hi Raghav" string.split(" ") ``` returns a list containing all the words and (n-1) empty strings where n is the number of single whitespaces between the two words. If the string was to contain a full sentence then the number of empty strings would have been 1 less than the number of single whitespaces between each word. Why does this happen? Shouldn't there be half as much empty strings as the number of single whitespace because every alternate whitespace will disappear since it's an argument in split ![enter image description here](https://i.stack.imgur.com/6UA8V.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62675107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13287593/" ]
``` "STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),]" ``` On this variable, just write 'S' after DIR it might solve your problem, like this: ``` STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] ```
I wonder if you are not serving the static files correctly, the same happens if you want to run the admin page. I'm dealing with the same and trying to solve this from the official page: <https://docs.djangoproject.com/en/3.1/howto/static-files/deployment/> regards!
62,675,109
I have a game where I shoot bullets at an object and I delete the object that gets hit by the bullet and bullet that are off screen as well. For example: ``` std::vector<object> object_list; for(size_t i = 0; i < object_list.size(); i++) { if(object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else object_list[i].draw(); } ``` The problem with this is that when i remove an object, the size of the vector decreases so when it check the conditions, it fails and i get an error such as " vector subscript out of range." I could just choose not to render the asteroid by rendering those that haven't been hit, but the problem with that is that the no. of objects increases when hit(splits up) so eventually the program is going to get slower. I've used a similar concept for the off screen bullets but I can't find a way around it. I'm looking for a solution to this or better way of removing elements. Both object and bullet are classes.
2020/07/01
[ "https://Stackoverflow.com/questions/62675109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13705262/" ]
Same idea as the other answers but this code is a little easier with iterators ``` for (auto i = object_list.begin(); i != object_list.end(); ) { if (i->hit()) { i = object_list.erase(i); } else { i->draw(); ++i; } } ``` `vector::erase` returns an iterator to the next element, which you can use to continue the loop.
You could do something like this: ``` for (size_t i = 0; i < object_list.size(); ) { if (object_list[i].hit()) object_list.erase(object_list.begin() + i) else { object_list[i].draw() ++i; } } ```
62,675,109
I have a game where I shoot bullets at an object and I delete the object that gets hit by the bullet and bullet that are off screen as well. For example: ``` std::vector<object> object_list; for(size_t i = 0; i < object_list.size(); i++) { if(object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else object_list[i].draw(); } ``` The problem with this is that when i remove an object, the size of the vector decreases so when it check the conditions, it fails and i get an error such as " vector subscript out of range." I could just choose not to render the asteroid by rendering those that haven't been hit, but the problem with that is that the no. of objects increases when hit(splits up) so eventually the program is going to get slower. I've used a similar concept for the off screen bullets but I can't find a way around it. I'm looking for a solution to this or better way of removing elements. Both object and bullet are classes.
2020/07/01
[ "https://Stackoverflow.com/questions/62675109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13705262/" ]
Same idea as the other answers but this code is a little easier with iterators ``` for (auto i = object_list.begin(); i != object_list.end(); ) { if (i->hit()) { i = object_list.erase(i); } else { i->draw(); ++i; } } ``` `vector::erase` returns an iterator to the next element, which you can use to continue the loop.
Let us say you are at i=5 and that object has been hit, after deleting that element, the obj at i=6 is shifted to i=5, and you haven't checked it, so just add `i--;` after your erase statement. Another way to do it would be - ``` for(size_t i = 0; i < object_list.size();) { if(object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else { object_list[i].draw(); i++; } } ``` Also, it could possibly be faster to just remove the object from the vector where you execute the code that marks the object as hit, that way you just need to draw all the objects which are left out in the list. Some more background into how you are doing all this would be helpful to decide something specific which would be better :)
62,675,109
I have a game where I shoot bullets at an object and I delete the object that gets hit by the bullet and bullet that are off screen as well. For example: ``` std::vector<object> object_list; for(size_t i = 0; i < object_list.size(); i++) { if(object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else object_list[i].draw(); } ``` The problem with this is that when i remove an object, the size of the vector decreases so when it check the conditions, it fails and i get an error such as " vector subscript out of range." I could just choose not to render the asteroid by rendering those that haven't been hit, but the problem with that is that the no. of objects increases when hit(splits up) so eventually the program is going to get slower. I've used a similar concept for the off screen bullets but I can't find a way around it. I'm looking for a solution to this or better way of removing elements. Both object and bullet are classes.
2020/07/01
[ "https://Stackoverflow.com/questions/62675109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13705262/" ]
Same idea as the other answers but this code is a little easier with iterators ``` for (auto i = object_list.begin(); i != object_list.end(); ) { if (i->hit()) { i = object_list.erase(i); } else { i->draw(); ++i; } } ``` `vector::erase` returns an iterator to the next element, which you can use to continue the loop.
The shown code does *not* fail or give a vector subscript out of range - it just does not consider every object, as it skips over the element after the removed one. For very short and concise solutions employing concepts from C++11 and later, see the [answer by Equod](https://stackoverflow.com/a/62675321/671366) or [the one by dfri](https://stackoverflow.com/a/62675503/671366) For better understanding the issue, and/or if you have to stick to for loops with indices, you basically have two options: 1. Iterate over the vector in reverse direction (i.e. start at the last element), then items *after* the current one being shifted is not a problem; ``` for (int i=object_list.size()-1; i>=0; --i) { if (object_list[i].hit()) { object_list.erase(object_list.begin() + i) } else { object_list[i].draw() } } ``` 2. Or, if the order is important (as I could imagine with items to draw), and you have to iterate from front to back, then *only increase the counter* `i` if you have *not* erased the current element: ``` for (int i=0; i<object_list.size(); /* No increase here... */ ) { if (object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else { object_list[i].draw(); ++i; // ...just here if we didn't remove the element } } ```
62,675,109
I have a game where I shoot bullets at an object and I delete the object that gets hit by the bullet and bullet that are off screen as well. For example: ``` std::vector<object> object_list; for(size_t i = 0; i < object_list.size(); i++) { if(object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else object_list[i].draw(); } ``` The problem with this is that when i remove an object, the size of the vector decreases so when it check the conditions, it fails and i get an error such as " vector subscript out of range." I could just choose not to render the asteroid by rendering those that haven't been hit, but the problem with that is that the no. of objects increases when hit(splits up) so eventually the program is going to get slower. I've used a similar concept for the off screen bullets but I can't find a way around it. I'm looking for a solution to this or better way of removing elements. Both object and bullet are classes.
2020/07/01
[ "https://Stackoverflow.com/questions/62675109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13705262/" ]
### Functional approach using the range-v3 library (C++20) > > [...] I'm looking for a solution to this **or better way of removing elements.** > > > Using the [`ranges::actions::remove_if`](https://ericniebler.github.io/range-v3/structranges_1_1actions_1_1remove__if__fn.html) action from the [range-v3](https://ericniebler.github.io/range-v3/) library, you can use a functional programming style approach to mutate the `object_list` container in-place: ``` object_list |= ranges::actions::remove_if( [](const auto& obj) { return obj.hit(); }); ``` followed by subsequent `ranges:for_each` invocation to draw the object: ``` ranges::for_each(object_list, [](const auto& obj){ obj.draw(); }); ``` [**DEMO**](https://godbolt.org/z/v9JsqN).
The shown code does *not* fail or give a vector subscript out of range - it just does not consider every object, as it skips over the element after the removed one. For very short and concise solutions employing concepts from C++11 and later, see the [answer by Equod](https://stackoverflow.com/a/62675321/671366) or [the one by dfri](https://stackoverflow.com/a/62675503/671366) For better understanding the issue, and/or if you have to stick to for loops with indices, you basically have two options: 1. Iterate over the vector in reverse direction (i.e. start at the last element), then items *after* the current one being shifted is not a problem; ``` for (int i=object_list.size()-1; i>=0; --i) { if (object_list[i].hit()) { object_list.erase(object_list.begin() + i) } else { object_list[i].draw() } } ``` 2. Or, if the order is important (as I could imagine with items to draw), and you have to iterate from front to back, then *only increase the counter* `i` if you have *not* erased the current element: ``` for (int i=0; i<object_list.size(); /* No increase here... */ ) { if (object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else { object_list[i].draw(); ++i; // ...just here if we didn't remove the element } } ```
62,675,109
I have a game where I shoot bullets at an object and I delete the object that gets hit by the bullet and bullet that are off screen as well. For example: ``` std::vector<object> object_list; for(size_t i = 0; i < object_list.size(); i++) { if(object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else object_list[i].draw(); } ``` The problem with this is that when i remove an object, the size of the vector decreases so when it check the conditions, it fails and i get an error such as " vector subscript out of range." I could just choose not to render the asteroid by rendering those that haven't been hit, but the problem with that is that the no. of objects increases when hit(splits up) so eventually the program is going to get slower. I've used a similar concept for the off screen bullets but I can't find a way around it. I'm looking for a solution to this or better way of removing elements. Both object and bullet are classes.
2020/07/01
[ "https://Stackoverflow.com/questions/62675109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13705262/" ]
You should split for loop in 2 parts: 1. remove all "hit" elements: ``` object_list.erase(std::remove_if(object_list.begin(), object_list.end(), [](auto&& item) { return item.hit(); }), object_list.end()); ``` 2. draw remaining: ``` std::for_each(object_list.begin(), object_list.end(), [](auto&& item) { item.draw(); }); ``` It's safer and more readable.
I suspect that `std::vector` is not the container you want (but, of course, I don't know the entire code). Each call to erase implies reallocation of the right-part of the vector (and then copies of you objects), it could be very costly. And your actual problem is the symptom of a design problem. From what I see, `std::list` is probably better: ``` std::list<object> objects; // ... for(std::list<object>::iterator it = objects.begin(); it != objects.end();) { if(it->hit()) objects.erase(it++); // No object copied else { it->draw(); ++it; } } ```
62,675,109
I have a game where I shoot bullets at an object and I delete the object that gets hit by the bullet and bullet that are off screen as well. For example: ``` std::vector<object> object_list; for(size_t i = 0; i < object_list.size(); i++) { if(object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else object_list[i].draw(); } ``` The problem with this is that when i remove an object, the size of the vector decreases so when it check the conditions, it fails and i get an error such as " vector subscript out of range." I could just choose not to render the asteroid by rendering those that haven't been hit, but the problem with that is that the no. of objects increases when hit(splits up) so eventually the program is going to get slower. I've used a similar concept for the off screen bullets but I can't find a way around it. I'm looking for a solution to this or better way of removing elements. Both object and bullet are classes.
2020/07/01
[ "https://Stackoverflow.com/questions/62675109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13705262/" ]
### Functional approach using the range-v3 library (C++20) > > [...] I'm looking for a solution to this **or better way of removing elements.** > > > Using the [`ranges::actions::remove_if`](https://ericniebler.github.io/range-v3/structranges_1_1actions_1_1remove__if__fn.html) action from the [range-v3](https://ericniebler.github.io/range-v3/) library, you can use a functional programming style approach to mutate the `object_list` container in-place: ``` object_list |= ranges::actions::remove_if( [](const auto& obj) { return obj.hit(); }); ``` followed by subsequent `ranges:for_each` invocation to draw the object: ``` ranges::for_each(object_list, [](const auto& obj){ obj.draw(); }); ``` [**DEMO**](https://godbolt.org/z/v9JsqN).
You could do something like this: ``` for (size_t i = 0; i < object_list.size(); ) { if (object_list[i].hit()) object_list.erase(object_list.begin() + i) else { object_list[i].draw() ++i; } } ```
62,675,109
I have a game where I shoot bullets at an object and I delete the object that gets hit by the bullet and bullet that are off screen as well. For example: ``` std::vector<object> object_list; for(size_t i = 0; i < object_list.size(); i++) { if(object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else object_list[i].draw(); } ``` The problem with this is that when i remove an object, the size of the vector decreases so when it check the conditions, it fails and i get an error such as " vector subscript out of range." I could just choose not to render the asteroid by rendering those that haven't been hit, but the problem with that is that the no. of objects increases when hit(splits up) so eventually the program is going to get slower. I've used a similar concept for the off screen bullets but I can't find a way around it. I'm looking for a solution to this or better way of removing elements. Both object and bullet are classes.
2020/07/01
[ "https://Stackoverflow.com/questions/62675109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13705262/" ]
You should split for loop in 2 parts: 1. remove all "hit" elements: ``` object_list.erase(std::remove_if(object_list.begin(), object_list.end(), [](auto&& item) { return item.hit(); }), object_list.end()); ``` 2. draw remaining: ``` std::for_each(object_list.begin(), object_list.end(), [](auto&& item) { item.draw(); }); ``` It's safer and more readable.
### Functional approach using the range-v3 library (C++20) > > [...] I'm looking for a solution to this **or better way of removing elements.** > > > Using the [`ranges::actions::remove_if`](https://ericniebler.github.io/range-v3/structranges_1_1actions_1_1remove__if__fn.html) action from the [range-v3](https://ericniebler.github.io/range-v3/) library, you can use a functional programming style approach to mutate the `object_list` container in-place: ``` object_list |= ranges::actions::remove_if( [](const auto& obj) { return obj.hit(); }); ``` followed by subsequent `ranges:for_each` invocation to draw the object: ``` ranges::for_each(object_list, [](const auto& obj){ obj.draw(); }); ``` [**DEMO**](https://godbolt.org/z/v9JsqN).
62,675,109
I have a game where I shoot bullets at an object and I delete the object that gets hit by the bullet and bullet that are off screen as well. For example: ``` std::vector<object> object_list; for(size_t i = 0; i < object_list.size(); i++) { if(object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else object_list[i].draw(); } ``` The problem with this is that when i remove an object, the size of the vector decreases so when it check the conditions, it fails and i get an error such as " vector subscript out of range." I could just choose not to render the asteroid by rendering those that haven't been hit, but the problem with that is that the no. of objects increases when hit(splits up) so eventually the program is going to get slower. I've used a similar concept for the off screen bullets but I can't find a way around it. I'm looking for a solution to this or better way of removing elements. Both object and bullet are classes.
2020/07/01
[ "https://Stackoverflow.com/questions/62675109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13705262/" ]
### Functional approach using the range-v3 library (C++20) > > [...] I'm looking for a solution to this **or better way of removing elements.** > > > Using the [`ranges::actions::remove_if`](https://ericniebler.github.io/range-v3/structranges_1_1actions_1_1remove__if__fn.html) action from the [range-v3](https://ericniebler.github.io/range-v3/) library, you can use a functional programming style approach to mutate the `object_list` container in-place: ``` object_list |= ranges::actions::remove_if( [](const auto& obj) { return obj.hit(); }); ``` followed by subsequent `ranges:for_each` invocation to draw the object: ``` ranges::for_each(object_list, [](const auto& obj){ obj.draw(); }); ``` [**DEMO**](https://godbolt.org/z/v9JsqN).
Let us say you are at i=5 and that object has been hit, after deleting that element, the obj at i=6 is shifted to i=5, and you haven't checked it, so just add `i--;` after your erase statement. Another way to do it would be - ``` for(size_t i = 0; i < object_list.size();) { if(object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else { object_list[i].draw(); i++; } } ``` Also, it could possibly be faster to just remove the object from the vector where you execute the code that marks the object as hit, that way you just need to draw all the objects which are left out in the list. Some more background into how you are doing all this would be helpful to decide something specific which would be better :)
62,675,109
I have a game where I shoot bullets at an object and I delete the object that gets hit by the bullet and bullet that are off screen as well. For example: ``` std::vector<object> object_list; for(size_t i = 0; i < object_list.size(); i++) { if(object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else object_list[i].draw(); } ``` The problem with this is that when i remove an object, the size of the vector decreases so when it check the conditions, it fails and i get an error such as " vector subscript out of range." I could just choose not to render the asteroid by rendering those that haven't been hit, but the problem with that is that the no. of objects increases when hit(splits up) so eventually the program is going to get slower. I've used a similar concept for the off screen bullets but I can't find a way around it. I'm looking for a solution to this or better way of removing elements. Both object and bullet are classes.
2020/07/01
[ "https://Stackoverflow.com/questions/62675109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13705262/" ]
You could do something like this: ``` for (size_t i = 0; i < object_list.size(); ) { if (object_list[i].hit()) object_list.erase(object_list.begin() + i) else { object_list[i].draw() ++i; } } ```
I suspect that `std::vector` is not the container you want (but, of course, I don't know the entire code). Each call to erase implies reallocation of the right-part of the vector (and then copies of you objects), it could be very costly. And your actual problem is the symptom of a design problem. From what I see, `std::list` is probably better: ``` std::list<object> objects; // ... for(std::list<object>::iterator it = objects.begin(); it != objects.end();) { if(it->hit()) objects.erase(it++); // No object copied else { it->draw(); ++it; } } ```
62,675,109
I have a game where I shoot bullets at an object and I delete the object that gets hit by the bullet and bullet that are off screen as well. For example: ``` std::vector<object> object_list; for(size_t i = 0; i < object_list.size(); i++) { if(object_list[i].hit()) { object_list.erase(object_list.begin() + i); } else object_list[i].draw(); } ``` The problem with this is that when i remove an object, the size of the vector decreases so when it check the conditions, it fails and i get an error such as " vector subscript out of range." I could just choose not to render the asteroid by rendering those that haven't been hit, but the problem with that is that the no. of objects increases when hit(splits up) so eventually the program is going to get slower. I've used a similar concept for the off screen bullets but I can't find a way around it. I'm looking for a solution to this or better way of removing elements. Both object and bullet are classes.
2020/07/01
[ "https://Stackoverflow.com/questions/62675109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13705262/" ]
### Functional approach using the range-v3 library (C++20) > > [...] I'm looking for a solution to this **or better way of removing elements.** > > > Using the [`ranges::actions::remove_if`](https://ericniebler.github.io/range-v3/structranges_1_1actions_1_1remove__if__fn.html) action from the [range-v3](https://ericniebler.github.io/range-v3/) library, you can use a functional programming style approach to mutate the `object_list` container in-place: ``` object_list |= ranges::actions::remove_if( [](const auto& obj) { return obj.hit(); }); ``` followed by subsequent `ranges:for_each` invocation to draw the object: ``` ranges::for_each(object_list, [](const auto& obj){ obj.draw(); }); ``` [**DEMO**](https://godbolt.org/z/v9JsqN).
I suspect that `std::vector` is not the container you want (but, of course, I don't know the entire code). Each call to erase implies reallocation of the right-part of the vector (and then copies of you objects), it could be very costly. And your actual problem is the symptom of a design problem. From what I see, `std::list` is probably better: ``` std::list<object> objects; // ... for(std::list<object>::iterator it = objects.begin(); it != objects.end();) { if(it->hit()) objects.erase(it++); // No object copied else { it->draw(); ++it; } } ```
62,675,110
So I'm using Visual studio code's cmd terminal because my pc has cmd blocked and when i go do the install command `pip install pynput` to install pynput a error is occurring saying "Tunnel connection failed: 407 Proxy Authorization Required" What can i do to fix this.
2020/07/01
[ "https://Stackoverflow.com/questions/62675110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13712666/" ]
If our computer is connected to a proxy server, we will get this error. The solution is we need our proxy username and password. When we want to install the package we will solve the problem. python get-pip.py --proxy="http://username:password@proxy.com:port" pip install packageName --proxy="http://username:password@proxy.com:port" Please fill in the username and password as related to you.
try using: python -m pip install pynput or pip3 install pynput
62,675,110
So I'm using Visual studio code's cmd terminal because my pc has cmd blocked and when i go do the install command `pip install pynput` to install pynput a error is occurring saying "Tunnel connection failed: 407 Proxy Authorization Required" What can i do to fix this.
2020/07/01
[ "https://Stackoverflow.com/questions/62675110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13712666/" ]
If our computer is connected to a proxy server, we will get this error. The solution is we need our proxy username and password. When we want to install the package we will solve the problem. python get-pip.py --proxy="http://username:password@proxy.com:port" pip install packageName --proxy="http://username:password@proxy.com:port" Please fill in the username and password as related to you.
error 407 means authentication for your proxy is either missing or wrong, to fix this use this command and fill in the blank as it relates to you ``` pip install --proxy https://username:pwd@proxy:host ```
62,675,119
Here is my code: ``` with open('exr.txt','r+') as exr: while True: exr.write((input('enter your name ')+'\n')) b=exr.readlines() if 'q' in b: break print('names entered:') for c in b: print('-',c) ``` It never gets past the write() method and keeps prompting me for names even after entering 'q', any help is appreciated
2020/07/01
[ "https://Stackoverflow.com/questions/62675119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10791329/" ]
There are (at least) three problems with your approach: 1. it seems like `exr.readlines()` does not work as you expected here, with `r+`, so a `"q"` entered in the current "session" is not read 2. in contrast to that, a `"q"` entered in a *previous* session *is* read, as they remain in the names file, i.e. the loop breaks immediately in any later execution 3. you are testing whether `"q"` is in `b`, but you append a `\n` to each input, and `readlines` includes those line-end characters, so `b` can only ever contain `"q\n"` It seems like both reading and writing are using the same position in the file. You can get the position with `exr.tell()` and set it with `exr.seek(x)`. This way, you can see that: * at the beginning of the loop, `exr.tell()`, i.e. the position is at `0`, meaning your first `write` will overwrite whatever data is at the beginning of the file * after `write`, the position is at `k+1` for a name with `k` letters and the additional `\n` * now `readlines` reads all data from *that position* (i.e. *after* the name you just entered) up to the end of the file * now, the file position is at the end, and all subsequent `write` calls will append names to the end of the file, advancing the file position further to the new end, and `readlines` will read nothing, as the pointer is already at the end of the file You *could* use `exr.seek(0)` to reset the position in the file to the beginning (or any other position before the last line), but while this (together with 3.) fixes the immediate problem, you still should not do it. Instead, just store the input in a variable and check the value of that variable before adding it to the file or breaking from the loop. ``` with open('exr.txt', 'a') as exr: while True: name = input('enter your name ') if name == "q": break else: exr.write(name + '\n') ```
the .readlines() method returns a list and not a string so when youre looking for q in a list of names ["jasper, "qar"] python sorta thinks this: is the element "q" in this list? is "q" equal to "jasper" or "qar"? nope. so you have to iterate through each element in b to go through each letter in each name in the list. i would do something like this: ``` with open('exr.txt','r+') as exr: while True: exr.write((input('enter your name ')+'\n')) b=exr.readlines() for name in b: for letter in name: if 'q' in b: break print('names entered:') for c in b: print('-',c) ``` hope this is the answer youre looking for :)
62,675,130
I have a model class: ``` public class UserProfile { public string UserID { get; set; } public string Name{ get; set; } public ICollection<AddressMaster> AddressMaster { get; set; } } ``` The above class have a 1 to many relationship with AddressMaster model class given below: ``` public class AddressMaster { public string AddrID{ get; set; } public string AddressLine1{ get; set; } public UserProfile UserProfile { get; set; } public TheatreLocation TheatreLocation { get; set; } } ``` The problem is, there is one other model also that has a 1 to many relationship with addressmaster, which is: ``` public class TheatreLocation { public string LocationID { get; set; } public string Name{ get; set; } public ICollection<AddressMaster> AddressMaster { get; set; } } ``` So instead of having foreign key at the addressmaster, how can we have a intermediate table between addressmaster and the userprofile & another such table b/w addressmaster and theatre? Or am i getting the whole concept wrong? Thanks.
2020/07/01
[ "https://Stackoverflow.com/questions/62675130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7235946/" ]
There are (at least) three problems with your approach: 1. it seems like `exr.readlines()` does not work as you expected here, with `r+`, so a `"q"` entered in the current "session" is not read 2. in contrast to that, a `"q"` entered in a *previous* session *is* read, as they remain in the names file, i.e. the loop breaks immediately in any later execution 3. you are testing whether `"q"` is in `b`, but you append a `\n` to each input, and `readlines` includes those line-end characters, so `b` can only ever contain `"q\n"` It seems like both reading and writing are using the same position in the file. You can get the position with `exr.tell()` and set it with `exr.seek(x)`. This way, you can see that: * at the beginning of the loop, `exr.tell()`, i.e. the position is at `0`, meaning your first `write` will overwrite whatever data is at the beginning of the file * after `write`, the position is at `k+1` for a name with `k` letters and the additional `\n` * now `readlines` reads all data from *that position* (i.e. *after* the name you just entered) up to the end of the file * now, the file position is at the end, and all subsequent `write` calls will append names to the end of the file, advancing the file position further to the new end, and `readlines` will read nothing, as the pointer is already at the end of the file You *could* use `exr.seek(0)` to reset the position in the file to the beginning (or any other position before the last line), but while this (together with 3.) fixes the immediate problem, you still should not do it. Instead, just store the input in a variable and check the value of that variable before adding it to the file or breaking from the loop. ``` with open('exr.txt', 'a') as exr: while True: name = input('enter your name ') if name == "q": break else: exr.write(name + '\n') ```
the .readlines() method returns a list and not a string so when youre looking for q in a list of names ["jasper, "qar"] python sorta thinks this: is the element "q" in this list? is "q" equal to "jasper" or "qar"? nope. so you have to iterate through each element in b to go through each letter in each name in the list. i would do something like this: ``` with open('exr.txt','r+') as exr: while True: exr.write((input('enter your name ')+'\n')) b=exr.readlines() for name in b: for letter in name: if 'q' in b: break print('names entered:') for c in b: print('-',c) ``` hope this is the answer youre looking for :)
62,675,133
I want to create a table analysis in AWS Quicksight that shows the number of new user per day and also the total number of user that has registered up until that day for the specified month. The following sample table is what I want to achieve in Quicksight. It shows the daily register count for March: ``` +-----------+----------------------+----------------------+ | | Daily Register Count | Total Register Count | +-----------+----------------------+----------------------+ | March 1st | 2 | 42 | +-----------+----------------------+----------------------+ | March 2nd | 5 | 47 | +-----------+----------------------+----------------------+ | March 3rd | 3 | 50 | +-----------+----------------------+----------------------+ | March 4th | 8 | 58 | +-----------+----------------------+----------------------+ | March 5th | 2 | 60 | +-----------+----------------------+----------------------+ ``` The "Total Register Count" column above should show the total count of users registered from the beginning up until March 1st, and then for each row it should be incremented with the value from "Daily Register Count" I'm absolutely scratching my head trying to implement the "Total Register Count". I have found some form of success using `runningSum` function however I need to be able to filter my dataset by month, and the `runningSum` function won't count the number outside of the filtered date. My dataset is very simple, it looks like this: ``` +----+-------------+---------------+ | id | email | registered_at | +----+-------------+---------------+ | 1 | aaa@aaa.com | 2020-01-01 | +----+-------------+---------------+ | 2 | bbb@aaa.com | 2020-01-01 | +----+-------------+---------------+ | 3 | ccc@aaa.com | 2020-01-03 | +----+-------------+---------------+ | 4 | abc@aaa.com | 2020-01-04 | +----+-------------+---------------+ | 5 | def@bbb.com | 2020-02-01 | +----+-------------+---------------+ ``` I hope someone can help me with this. Thank you!
2020/07/01
[ "https://Stackoverflow.com/questions/62675133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2117734/" ]
There are (at least) three problems with your approach: 1. it seems like `exr.readlines()` does not work as you expected here, with `r+`, so a `"q"` entered in the current "session" is not read 2. in contrast to that, a `"q"` entered in a *previous* session *is* read, as they remain in the names file, i.e. the loop breaks immediately in any later execution 3. you are testing whether `"q"` is in `b`, but you append a `\n` to each input, and `readlines` includes those line-end characters, so `b` can only ever contain `"q\n"` It seems like both reading and writing are using the same position in the file. You can get the position with `exr.tell()` and set it with `exr.seek(x)`. This way, you can see that: * at the beginning of the loop, `exr.tell()`, i.e. the position is at `0`, meaning your first `write` will overwrite whatever data is at the beginning of the file * after `write`, the position is at `k+1` for a name with `k` letters and the additional `\n` * now `readlines` reads all data from *that position* (i.e. *after* the name you just entered) up to the end of the file * now, the file position is at the end, and all subsequent `write` calls will append names to the end of the file, advancing the file position further to the new end, and `readlines` will read nothing, as the pointer is already at the end of the file You *could* use `exr.seek(0)` to reset the position in the file to the beginning (or any other position before the last line), but while this (together with 3.) fixes the immediate problem, you still should not do it. Instead, just store the input in a variable and check the value of that variable before adding it to the file or breaking from the loop. ``` with open('exr.txt', 'a') as exr: while True: name = input('enter your name ') if name == "q": break else: exr.write(name + '\n') ```
the .readlines() method returns a list and not a string so when youre looking for q in a list of names ["jasper, "qar"] python sorta thinks this: is the element "q" in this list? is "q" equal to "jasper" or "qar"? nope. so you have to iterate through each element in b to go through each letter in each name in the list. i would do something like this: ``` with open('exr.txt','r+') as exr: while True: exr.write((input('enter your name ')+'\n')) b=exr.readlines() for name in b: for letter in name: if 'q' in b: break print('names entered:') for c in b: print('-',c) ``` hope this is the answer youre looking for :)
62,675,143
I have an issue when trying to edit specific data into csv file. input csv(inputfile.csv) : ``` username,password,status uname1,pwd1,todo uname2,pwd2,todo uname3,pwd2,pass ``` required output in same csv(inputfile.csv) : ``` username,password,status uname1,pwd1,pass uname2,pwd2,pass uname3,pwd2,pass ``` I tried to do this using apache poi for csv operation as well as OpenCSV. but I cold append the new result like : ``` username,password,status uname1,pwd1,todo uname2,pwd2,todo uname3,pwd2,pass uname1,pwd1,pass ``` Unable to replace the existing record. can someone please suggest any help?
2020/07/01
[ "https://Stackoverflow.com/questions/62675143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6855734/" ]
There are (at least) three problems with your approach: 1. it seems like `exr.readlines()` does not work as you expected here, with `r+`, so a `"q"` entered in the current "session" is not read 2. in contrast to that, a `"q"` entered in a *previous* session *is* read, as they remain in the names file, i.e. the loop breaks immediately in any later execution 3. you are testing whether `"q"` is in `b`, but you append a `\n` to each input, and `readlines` includes those line-end characters, so `b` can only ever contain `"q\n"` It seems like both reading and writing are using the same position in the file. You can get the position with `exr.tell()` and set it with `exr.seek(x)`. This way, you can see that: * at the beginning of the loop, `exr.tell()`, i.e. the position is at `0`, meaning your first `write` will overwrite whatever data is at the beginning of the file * after `write`, the position is at `k+1` for a name with `k` letters and the additional `\n` * now `readlines` reads all data from *that position* (i.e. *after* the name you just entered) up to the end of the file * now, the file position is at the end, and all subsequent `write` calls will append names to the end of the file, advancing the file position further to the new end, and `readlines` will read nothing, as the pointer is already at the end of the file You *could* use `exr.seek(0)` to reset the position in the file to the beginning (or any other position before the last line), but while this (together with 3.) fixes the immediate problem, you still should not do it. Instead, just store the input in a variable and check the value of that variable before adding it to the file or breaking from the loop. ``` with open('exr.txt', 'a') as exr: while True: name = input('enter your name ') if name == "q": break else: exr.write(name + '\n') ```
the .readlines() method returns a list and not a string so when youre looking for q in a list of names ["jasper, "qar"] python sorta thinks this: is the element "q" in this list? is "q" equal to "jasper" or "qar"? nope. so you have to iterate through each element in b to go through each letter in each name in the list. i would do something like this: ``` with open('exr.txt','r+') as exr: while True: exr.write((input('enter your name ')+'\n')) b=exr.readlines() for name in b: for letter in name: if 'q' in b: break print('names entered:') for c in b: print('-',c) ``` hope this is the answer youre looking for :)
62,675,161
I have the string as an input ``` The user with id '2156' helped the user '2156' to acquire an item with the id '1' with the quantity of '1'. ``` I want to get the `user id` and `item id` from the string. Can I match the input string with the `const string` and get the id from the input? ``` public const string StashAcquired = @"The user with id '{0}' helped the user '{1}' to acquire an item with the id '{2}' with the quantity of '{3}'."; here: {0} is a `user id` {2} is a `item id` ``` I don't want the other number but only two id. ``` @"The user with id '{userid}' helped the user '2156' to acquire an item with the id '{itemid}' with the quantity of '1'."; ``` rest id are irrelevant for me: I tried by getting the number from the input string and assign it into a variable like: ``` const string input = @"The user with id '2156' helped the user '2156' to acquire an item with the id '1' with the quantity of '1'."; var number = GetNumbersFromString(input); ``` **GetNumbersFromString** ``` public int[] GetNumbersFromString(string str) { List<int> result = new List<int>(); string[] numbers = Regex.Split(str, @"\D+"); int i; foreach (string value in numbers) { if (int.TryParse(value, out i)) { result.Add(i); } } return result.ToArray(); } ``` **Edit** I am gradually noticing that the inputs are more complex than what I have mentioned before, input are coming as: ``` [{ "Component": "Stash", "EventName": "An Item Acquired", "Description": "The user with id '2156' helped the user '2156' to acquire an item with the id '1' with the quantity of '1'" }, { "Component": "H5P", "EventName": "Course module viewed", "Description": "The user with id '2253' viewed the 'hvp' activity with course module id '277'." }, { "Component": "System", "EventName": "Course module completion updated", "Description": "The user with id '2254' updated the completion state for the course module with id '347' for the user with id '2254'." }, { "Component": "H5P", "EventName": "Course module viewed", "Description": "The user with id '2253' viewed the 'hvp' activity with course module id '278'." }, { "Component": "System", "EventName": "Course viewed", "Description": "The user with id '2253' viewed the course with id '13'." },{ "Component": "Quiz", "EventName": "Quiz attempt viewed", "Description": "The user with id '2184' has viewed the attempt with id '1900' belonging to the user with id '2184' for the quiz with course module id '228'." }] ```
2020/07/01
[ "https://Stackoverflow.com/questions/62675161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12012109/" ]
It seems that the keywords are "user" along with "id" and "item" also with "id". The regex should reflect that, e.g. ``` user.*id.*'(?<userid>.*)'.*item.*id.*'(?<itemid>.*)' ``` Then, I see that sometimes you need "item", but sometimes "course" or "module". Let's add a choice `(...|...|...)` to that Regex: ``` user.*id.*'(?<userid>.*)'.*(item|module|course).*id.*'(?<itemid>.*)' ``` Unfortunately, that will add a new group, which you likely don't want. Let's make it non-capturing with `?:`: ``` user.*id.*'(?<userid>.*)'.*(?:item|module|course).*id.*'(?<itemid>.*)' ``` Now, this still fails for the text ``` "The user with id '2253' viewed the 'hvp' activity with course module id '278'" ``` because it has two apostrophes after "user" and "id. You want the `.*` to be less greedy, so change it to `.*?`: ``` user.*id.*?'(?<userid>.*?)'.*(?:item|module|course).*id.*'(?<itemid>.*)' ``` See also [all tests on Regex101](https://regex101.com/r/XLXHa4/1). The code: ``` var s = "The user with id '2156' helped the user '2156' to acquire an item with the id '1' with the quantity of '1'"; var pattern = "user.*id.*?'(?<userid>.*?)'.*(?:item|module|course).*id.*'(?<itemid>.*)'"; var rex = new Regex(pattern); var m = rex.Matches(s); Console.WriteLine(m[0].Groups["userid"].Value + " " + m[0].Groups["itemid"].Value); ``` Pro tip when working with Regex: use [Linqpad](https://www.linqpad.net/). It has a very powerful output replacement for `Console.WriteLine()`. It can do stuff like: [![Regex in Linqpad](https://i.stack.imgur.com/Y9gb0.png)](https://i.stack.imgur.com/Y9gb0.png) That way, you don't need to code everything yourself. Instead you can just have a look at an object as a table.
This approach might work: Split the string with `'` as delimeter. Then your user id is the 2nd part of the string, the item id 6th part of your string. This will result in the following code: ``` string input = "The user with id '2156' helped the user '2156' to acquire an item with the id '1' with the quantity of '1'."; string[] parts = input.Split('\''); string rawUserId = parts[1]; string rawItemId = parts[5]; int userId = int.Parse(rawUserId); int itemId = int.Parse(rawItemId); ``` Online demo: <https://dotnetfiddle.net/wnDyWL>
62,675,161
I have the string as an input ``` The user with id '2156' helped the user '2156' to acquire an item with the id '1' with the quantity of '1'. ``` I want to get the `user id` and `item id` from the string. Can I match the input string with the `const string` and get the id from the input? ``` public const string StashAcquired = @"The user with id '{0}' helped the user '{1}' to acquire an item with the id '{2}' with the quantity of '{3}'."; here: {0} is a `user id` {2} is a `item id` ``` I don't want the other number but only two id. ``` @"The user with id '{userid}' helped the user '2156' to acquire an item with the id '{itemid}' with the quantity of '1'."; ``` rest id are irrelevant for me: I tried by getting the number from the input string and assign it into a variable like: ``` const string input = @"The user with id '2156' helped the user '2156' to acquire an item with the id '1' with the quantity of '1'."; var number = GetNumbersFromString(input); ``` **GetNumbersFromString** ``` public int[] GetNumbersFromString(string str) { List<int> result = new List<int>(); string[] numbers = Regex.Split(str, @"\D+"); int i; foreach (string value in numbers) { if (int.TryParse(value, out i)) { result.Add(i); } } return result.ToArray(); } ``` **Edit** I am gradually noticing that the inputs are more complex than what I have mentioned before, input are coming as: ``` [{ "Component": "Stash", "EventName": "An Item Acquired", "Description": "The user with id '2156' helped the user '2156' to acquire an item with the id '1' with the quantity of '1'" }, { "Component": "H5P", "EventName": "Course module viewed", "Description": "The user with id '2253' viewed the 'hvp' activity with course module id '277'." }, { "Component": "System", "EventName": "Course module completion updated", "Description": "The user with id '2254' updated the completion state for the course module with id '347' for the user with id '2254'." }, { "Component": "H5P", "EventName": "Course module viewed", "Description": "The user with id '2253' viewed the 'hvp' activity with course module id '278'." }, { "Component": "System", "EventName": "Course viewed", "Description": "The user with id '2253' viewed the course with id '13'." },{ "Component": "Quiz", "EventName": "Quiz attempt viewed", "Description": "The user with id '2184' has viewed the attempt with id '1900' belonging to the user with id '2184' for the quiz with course module id '228'." }] ```
2020/07/01
[ "https://Stackoverflow.com/questions/62675161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12012109/" ]
It seems that the keywords are "user" along with "id" and "item" also with "id". The regex should reflect that, e.g. ``` user.*id.*'(?<userid>.*)'.*item.*id.*'(?<itemid>.*)' ``` Then, I see that sometimes you need "item", but sometimes "course" or "module". Let's add a choice `(...|...|...)` to that Regex: ``` user.*id.*'(?<userid>.*)'.*(item|module|course).*id.*'(?<itemid>.*)' ``` Unfortunately, that will add a new group, which you likely don't want. Let's make it non-capturing with `?:`: ``` user.*id.*'(?<userid>.*)'.*(?:item|module|course).*id.*'(?<itemid>.*)' ``` Now, this still fails for the text ``` "The user with id '2253' viewed the 'hvp' activity with course module id '278'" ``` because it has two apostrophes after "user" and "id. You want the `.*` to be less greedy, so change it to `.*?`: ``` user.*id.*?'(?<userid>.*?)'.*(?:item|module|course).*id.*'(?<itemid>.*)' ``` See also [all tests on Regex101](https://regex101.com/r/XLXHa4/1). The code: ``` var s = "The user with id '2156' helped the user '2156' to acquire an item with the id '1' with the quantity of '1'"; var pattern = "user.*id.*?'(?<userid>.*?)'.*(?:item|module|course).*id.*'(?<itemid>.*)'"; var rex = new Regex(pattern); var m = rex.Matches(s); Console.WriteLine(m[0].Groups["userid"].Value + " " + m[0].Groups["itemid"].Value); ``` Pro tip when working with Regex: use [Linqpad](https://www.linqpad.net/). It has a very powerful output replacement for `Console.WriteLine()`. It can do stuff like: [![Regex in Linqpad](https://i.stack.imgur.com/Y9gb0.png)](https://i.stack.imgur.com/Y9gb0.png) That way, you don't need to code everything yourself. Instead you can just have a look at an object as a table.
Hope this helps you, using **Regex**, : ``` public static int GetIDFromString(string text, string partName) { var matchUserPart = Regex.Match(text, @$"{partName}(.*?)id(.*?)\d+", RegexOptions.IgnoreCase).Value; return matchUserPart.Length > 0 ? int.Parse(Regex.Replace(matchUserPart, @"\D", "")) : 0; } ``` You can just use it in this way: ``` int userID = GetIDFromString(text, "user"); int itemID = GetIDFromString(text, "item"); ``` Note that **Regex** class is in **System.Text.RegularExpressions** namespace. In **Regex**, **\d** (lower case) is used for every digits and vice versa **\D** (upper case) stands for every **not** digits in **Pattern** of Regex and **?** mark in **(.\*?)** cause **Regex** to match first occurrence (turn off greedy in regex).
62,675,182
I have a class I want to test if it uses the right Beans when a certain profile is active. Therefore I have written a test class, with the profile active, for the DomesticService (which in turn uses the GardeningService and CleaningService, all of it is autowired). ```java @Component public class HumanDomesticService implements DomesticService { private CleaningService cleaningService; private GardeningService gardeningService; private Logger logger; HumanDomesticService() { } @Autowired public HumanDomesticService(CleaningService cleaningService, GardeningService gardeningService, Logger logger) { setCleaningService(cleaningService); setGardeningService(gardeningService); setLogger(logger); } ``` I made a test configuration class, which should scan the whole project for Beans, since the SpringBootApplication annotation includes the ComponentScan annotation. ```java @SpringBootApplication public class ActiveProfileConfig { } ``` Yet my test class can't seem to find the right Beans to complete the test. ``` org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'be.mycompany.springlessons.housekeeping.domestic.service.ActiveProfileSmallHouseTest': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'be.mycompany.springlessons.housekeeping.domestic.service.DomesticService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} ``` After that I tried to make Beans inside my configuration class, which makes my tests succeed, but then Maven complains about finding 2 Beans which could be injected there. Maven seems to be able to see all the beans through the ComponentScan. Finally I ended importing the necessary classes, which works for both my tests and Maven, but it just doesn't seem to be the right and best solution. ``` @SpringBootTest(classes = ActiveProfileConfig.class) @ActiveProfiles(profiles = "smallHouse") @Import({HumanDomesticService.class, HumanCleaningService.class, RobotCleaningService.class, HumanGardeningService.class, HedgeTrimmerFactory.class, Broom.class, VacuumCleaner.class, Sponge.class, DisposableDuster.class, LawnMower.class, LoggerFactory.class}) public class ActiveProfileSmallHouseTest { @Autowired private DomesticService service; ``` I have tried to search on the internet for another solution and saw I wasn't the only one with the problem, but no other solution seemed yet to have worked. What is the reason ComponentScan doesn't seem to work in a test class and how best to solve this?
2020/07/01
[ "https://Stackoverflow.com/questions/62675182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13846148/" ]
It seems that the keywords are "user" along with "id" and "item" also with "id". The regex should reflect that, e.g. ``` user.*id.*'(?<userid>.*)'.*item.*id.*'(?<itemid>.*)' ``` Then, I see that sometimes you need "item", but sometimes "course" or "module". Let's add a choice `(...|...|...)` to that Regex: ``` user.*id.*'(?<userid>.*)'.*(item|module|course).*id.*'(?<itemid>.*)' ``` Unfortunately, that will add a new group, which you likely don't want. Let's make it non-capturing with `?:`: ``` user.*id.*'(?<userid>.*)'.*(?:item|module|course).*id.*'(?<itemid>.*)' ``` Now, this still fails for the text ``` "The user with id '2253' viewed the 'hvp' activity with course module id '278'" ``` because it has two apostrophes after "user" and "id. You want the `.*` to be less greedy, so change it to `.*?`: ``` user.*id.*?'(?<userid>.*?)'.*(?:item|module|course).*id.*'(?<itemid>.*)' ``` See also [all tests on Regex101](https://regex101.com/r/XLXHa4/1). The code: ``` var s = "The user with id '2156' helped the user '2156' to acquire an item with the id '1' with the quantity of '1'"; var pattern = "user.*id.*?'(?<userid>.*?)'.*(?:item|module|course).*id.*'(?<itemid>.*)'"; var rex = new Regex(pattern); var m = rex.Matches(s); Console.WriteLine(m[0].Groups["userid"].Value + " " + m[0].Groups["itemid"].Value); ``` Pro tip when working with Regex: use [Linqpad](https://www.linqpad.net/). It has a very powerful output replacement for `Console.WriteLine()`. It can do stuff like: [![Regex in Linqpad](https://i.stack.imgur.com/Y9gb0.png)](https://i.stack.imgur.com/Y9gb0.png) That way, you don't need to code everything yourself. Instead you can just have a look at an object as a table.
This approach might work: Split the string with `'` as delimeter. Then your user id is the 2nd part of the string, the item id 6th part of your string. This will result in the following code: ``` string input = "The user with id '2156' helped the user '2156' to acquire an item with the id '1' with the quantity of '1'."; string[] parts = input.Split('\''); string rawUserId = parts[1]; string rawItemId = parts[5]; int userId = int.Parse(rawUserId); int itemId = int.Parse(rawItemId); ``` Online demo: <https://dotnetfiddle.net/wnDyWL>
62,675,182
I have a class I want to test if it uses the right Beans when a certain profile is active. Therefore I have written a test class, with the profile active, for the DomesticService (which in turn uses the GardeningService and CleaningService, all of it is autowired). ```java @Component public class HumanDomesticService implements DomesticService { private CleaningService cleaningService; private GardeningService gardeningService; private Logger logger; HumanDomesticService() { } @Autowired public HumanDomesticService(CleaningService cleaningService, GardeningService gardeningService, Logger logger) { setCleaningService(cleaningService); setGardeningService(gardeningService); setLogger(logger); } ``` I made a test configuration class, which should scan the whole project for Beans, since the SpringBootApplication annotation includes the ComponentScan annotation. ```java @SpringBootApplication public class ActiveProfileConfig { } ``` Yet my test class can't seem to find the right Beans to complete the test. ``` org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'be.mycompany.springlessons.housekeeping.domestic.service.ActiveProfileSmallHouseTest': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'be.mycompany.springlessons.housekeeping.domestic.service.DomesticService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} ``` After that I tried to make Beans inside my configuration class, which makes my tests succeed, but then Maven complains about finding 2 Beans which could be injected there. Maven seems to be able to see all the beans through the ComponentScan. Finally I ended importing the necessary classes, which works for both my tests and Maven, but it just doesn't seem to be the right and best solution. ``` @SpringBootTest(classes = ActiveProfileConfig.class) @ActiveProfiles(profiles = "smallHouse") @Import({HumanDomesticService.class, HumanCleaningService.class, RobotCleaningService.class, HumanGardeningService.class, HedgeTrimmerFactory.class, Broom.class, VacuumCleaner.class, Sponge.class, DisposableDuster.class, LawnMower.class, LoggerFactory.class}) public class ActiveProfileSmallHouseTest { @Autowired private DomesticService service; ``` I have tried to search on the internet for another solution and saw I wasn't the only one with the problem, but no other solution seemed yet to have worked. What is the reason ComponentScan doesn't seem to work in a test class and how best to solve this?
2020/07/01
[ "https://Stackoverflow.com/questions/62675182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13846148/" ]
It seems that the keywords are "user" along with "id" and "item" also with "id". The regex should reflect that, e.g. ``` user.*id.*'(?<userid>.*)'.*item.*id.*'(?<itemid>.*)' ``` Then, I see that sometimes you need "item", but sometimes "course" or "module". Let's add a choice `(...|...|...)` to that Regex: ``` user.*id.*'(?<userid>.*)'.*(item|module|course).*id.*'(?<itemid>.*)' ``` Unfortunately, that will add a new group, which you likely don't want. Let's make it non-capturing with `?:`: ``` user.*id.*'(?<userid>.*)'.*(?:item|module|course).*id.*'(?<itemid>.*)' ``` Now, this still fails for the text ``` "The user with id '2253' viewed the 'hvp' activity with course module id '278'" ``` because it has two apostrophes after "user" and "id. You want the `.*` to be less greedy, so change it to `.*?`: ``` user.*id.*?'(?<userid>.*?)'.*(?:item|module|course).*id.*'(?<itemid>.*)' ``` See also [all tests on Regex101](https://regex101.com/r/XLXHa4/1). The code: ``` var s = "The user with id '2156' helped the user '2156' to acquire an item with the id '1' with the quantity of '1'"; var pattern = "user.*id.*?'(?<userid>.*?)'.*(?:item|module|course).*id.*'(?<itemid>.*)'"; var rex = new Regex(pattern); var m = rex.Matches(s); Console.WriteLine(m[0].Groups["userid"].Value + " " + m[0].Groups["itemid"].Value); ``` Pro tip when working with Regex: use [Linqpad](https://www.linqpad.net/). It has a very powerful output replacement for `Console.WriteLine()`. It can do stuff like: [![Regex in Linqpad](https://i.stack.imgur.com/Y9gb0.png)](https://i.stack.imgur.com/Y9gb0.png) That way, you don't need to code everything yourself. Instead you can just have a look at an object as a table.
Hope this helps you, using **Regex**, : ``` public static int GetIDFromString(string text, string partName) { var matchUserPart = Regex.Match(text, @$"{partName}(.*?)id(.*?)\d+", RegexOptions.IgnoreCase).Value; return matchUserPart.Length > 0 ? int.Parse(Regex.Replace(matchUserPart, @"\D", "")) : 0; } ``` You can just use it in this way: ``` int userID = GetIDFromString(text, "user"); int itemID = GetIDFromString(text, "item"); ``` Note that **Regex** class is in **System.Text.RegularExpressions** namespace. In **Regex**, **\d** (lower case) is used for every digits and vice versa **\D** (upper case) stands for every **not** digits in **Pattern** of Regex and **?** mark in **(.\*?)** cause **Regex** to match first occurrence (turn off greedy in regex).
62,675,194
The int type in Dart has default value of null. null is an object of type Null class. (as per Dart documentation). Also, in Dart, int derives from class Object. Hence, ``` int i = 10; print(i.runtimeType is Object); // returns true ``` This makes me believe that int is not a value type like in other languages (such as C#) but a reference type. If I am correct, then- `int i = 10;` means i is a reference variable holding the reference to an int object 10. Is this correct? If not, I would appreciate if a link to the description in the documentation is shared. Till now, I've been unable to find any proper explanation and hence have come to this conclusion myself. Thanks.
2020/07/01
[ "https://Stackoverflow.com/questions/62675194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2549980/" ]
`int` is a value type in the sense that if you pass `int` value into a function and change the value of a parameter inside function, it won't affect outer scope. ```dart void add(int inner) { inner += 1; } int outer = 0; add(outer); print(outer); // 0, unchanged ``` But `int` is still a class even though its name starts from lowercase letter. There was a [huge discussion](https://github.com/dart-lang/sdk/issues/1410) about its naming and lots of people consider it an inconsistency.
Everything in Dart is an object, int, double or num may look like keywords but they are built-in abstract classes. Since they are abstract classes which means they can not be instantiated, they do not start with an uppercase letter. try this line, `print('2 is instance of "int" class :\t${ 2 is int}');` this will result in true. And regarding your concern about 'null' : In Dart, like JavaScript and Python, everything that a variable can hold is an object including null. Every object including null is an instance of some class and all these classes inherit from Object class. your can refer [this link](https://medium.com/run-dart/dart-dartlang-introduction-variables-and-data-types-d269ea7d1f8f) for more info. Hope this helps.
62,675,194
The int type in Dart has default value of null. null is an object of type Null class. (as per Dart documentation). Also, in Dart, int derives from class Object. Hence, ``` int i = 10; print(i.runtimeType is Object); // returns true ``` This makes me believe that int is not a value type like in other languages (such as C#) but a reference type. If I am correct, then- `int i = 10;` means i is a reference variable holding the reference to an int object 10. Is this correct? If not, I would appreciate if a link to the description in the documentation is shared. Till now, I've been unable to find any proper explanation and hence have come to this conclusion myself. Thanks.
2020/07/01
[ "https://Stackoverflow.com/questions/62675194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2549980/" ]
Yes, Dart's `int` type is a "reference type". Dart does not have value types at all, all values are instances of a class, including integers. (At least technically, function values makes their classes very hard to see.) Integers are *immutable* and pretends to be *canonicalized*. If `a` and `b` are `int` values and `a == b`, then `identical(a, b)` is guaranteed to be true, so `a` and `b` looks like they are the same object, but it's unspecified whether that's because they really are the same object, or because `identical` just cheats and does `==` for integers. That means that you can largely treat `int` as a "value type". Whether it is copied on assignment or parameter passing, or you are passing a reference to the same object, is impossible to tell apart. The language ensures that, because it allows the implementations to do whatever is more efficient. In practice, some integers are unboxed inside functions, some integers are stored as a value in the reference itself, and some are real objects. (That's also one of the reasons you can't use an `Expando` with an `int`). (In the current Dart language, all types annotations are nullable, meaning that you can assign `null` to `int x;`. With the upcoming Null Safety feature, that changes. Types will only be nullable if you write them as such, so `int x = 1;` would not accept a `null` value, but `int? x;` would. And `null` is an object too, the only instance of the class `Null`.)
Everything in Dart is an object, int, double or num may look like keywords but they are built-in abstract classes. Since they are abstract classes which means they can not be instantiated, they do not start with an uppercase letter. try this line, `print('2 is instance of "int" class :\t${ 2 is int}');` this will result in true. And regarding your concern about 'null' : In Dart, like JavaScript and Python, everything that a variable can hold is an object including null. Every object including null is an instance of some class and all these classes inherit from Object class. your can refer [this link](https://medium.com/run-dart/dart-dartlang-introduction-variables-and-data-types-d269ea7d1f8f) for more info. Hope this helps.
62,675,194
The int type in Dart has default value of null. null is an object of type Null class. (as per Dart documentation). Also, in Dart, int derives from class Object. Hence, ``` int i = 10; print(i.runtimeType is Object); // returns true ``` This makes me believe that int is not a value type like in other languages (such as C#) but a reference type. If I am correct, then- `int i = 10;` means i is a reference variable holding the reference to an int object 10. Is this correct? If not, I would appreciate if a link to the description in the documentation is shared. Till now, I've been unable to find any proper explanation and hence have come to this conclusion myself. Thanks.
2020/07/01
[ "https://Stackoverflow.com/questions/62675194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2549980/" ]
`int` is a value type in the sense that if you pass `int` value into a function and change the value of a parameter inside function, it won't affect outer scope. ```dart void add(int inner) { inner += 1; } int outer = 0; add(outer); print(outer); // 0, unchanged ``` But `int` is still a class even though its name starts from lowercase letter. There was a [huge discussion](https://github.com/dart-lang/sdk/issues/1410) about its naming and lots of people consider it an inconsistency.
Yes `int` is a class (it even extends `num`) and therefor has common methods to use on. But one the other side it is different than "normal" classes since you don't have to use a constructor like ```dart int i = int(3); ``` See int's class documenation <https://api.dart.dev/stable/2.8.4/dart-core/int-class.html>
62,675,194
The int type in Dart has default value of null. null is an object of type Null class. (as per Dart documentation). Also, in Dart, int derives from class Object. Hence, ``` int i = 10; print(i.runtimeType is Object); // returns true ``` This makes me believe that int is not a value type like in other languages (such as C#) but a reference type. If I am correct, then- `int i = 10;` means i is a reference variable holding the reference to an int object 10. Is this correct? If not, I would appreciate if a link to the description in the documentation is shared. Till now, I've been unable to find any proper explanation and hence have come to this conclusion myself. Thanks.
2020/07/01
[ "https://Stackoverflow.com/questions/62675194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2549980/" ]
Yes, Dart's `int` type is a "reference type". Dart does not have value types at all, all values are instances of a class, including integers. (At least technically, function values makes their classes very hard to see.) Integers are *immutable* and pretends to be *canonicalized*. If `a` and `b` are `int` values and `a == b`, then `identical(a, b)` is guaranteed to be true, so `a` and `b` looks like they are the same object, but it's unspecified whether that's because they really are the same object, or because `identical` just cheats and does `==` for integers. That means that you can largely treat `int` as a "value type". Whether it is copied on assignment or parameter passing, or you are passing a reference to the same object, is impossible to tell apart. The language ensures that, because it allows the implementations to do whatever is more efficient. In practice, some integers are unboxed inside functions, some integers are stored as a value in the reference itself, and some are real objects. (That's also one of the reasons you can't use an `Expando` with an `int`). (In the current Dart language, all types annotations are nullable, meaning that you can assign `null` to `int x;`. With the upcoming Null Safety feature, that changes. Types will only be nullable if you write them as such, so `int x = 1;` would not accept a `null` value, but `int? x;` would. And `null` is an object too, the only instance of the class `Null`.)
Yes `int` is a class (it even extends `num`) and therefor has common methods to use on. But one the other side it is different than "normal" classes since you don't have to use a constructor like ```dart int i = int(3); ``` See int's class documenation <https://api.dart.dev/stable/2.8.4/dart-core/int-class.html>
62,675,194
The int type in Dart has default value of null. null is an object of type Null class. (as per Dart documentation). Also, in Dart, int derives from class Object. Hence, ``` int i = 10; print(i.runtimeType is Object); // returns true ``` This makes me believe that int is not a value type like in other languages (such as C#) but a reference type. If I am correct, then- `int i = 10;` means i is a reference variable holding the reference to an int object 10. Is this correct? If not, I would appreciate if a link to the description in the documentation is shared. Till now, I've been unable to find any proper explanation and hence have come to this conclusion myself. Thanks.
2020/07/01
[ "https://Stackoverflow.com/questions/62675194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2549980/" ]
Yes, Dart's `int` type is a "reference type". Dart does not have value types at all, all values are instances of a class, including integers. (At least technically, function values makes their classes very hard to see.) Integers are *immutable* and pretends to be *canonicalized*. If `a` and `b` are `int` values and `a == b`, then `identical(a, b)` is guaranteed to be true, so `a` and `b` looks like they are the same object, but it's unspecified whether that's because they really are the same object, or because `identical` just cheats and does `==` for integers. That means that you can largely treat `int` as a "value type". Whether it is copied on assignment or parameter passing, or you are passing a reference to the same object, is impossible to tell apart. The language ensures that, because it allows the implementations to do whatever is more efficient. In practice, some integers are unboxed inside functions, some integers are stored as a value in the reference itself, and some are real objects. (That's also one of the reasons you can't use an `Expando` with an `int`). (In the current Dart language, all types annotations are nullable, meaning that you can assign `null` to `int x;`. With the upcoming Null Safety feature, that changes. Types will only be nullable if you write them as such, so `int x = 1;` would not accept a `null` value, but `int? x;` would. And `null` is an object too, the only instance of the class `Null`.)
`int` is a value type in the sense that if you pass `int` value into a function and change the value of a parameter inside function, it won't affect outer scope. ```dart void add(int inner) { inner += 1; } int outer = 0; add(outer); print(outer); // 0, unchanged ``` But `int` is still a class even though its name starts from lowercase letter. There was a [huge discussion](https://github.com/dart-lang/sdk/issues/1410) about its naming and lots of people consider it an inconsistency.
62,675,211
I am developing a laravel application in which real-time data is to be extracted using laravel-WebSockets package.I have seen people having issues at production side but this is on development side. I am accessing web-app using host-entry All initial steps completed( downloading laravel-WebSocket package, pusher-js, php-pusher-server) And executed `php artisan websockets:serve`. When I refreshed browser I am getting error in console `app.js:40145 WebSocket connection to 'wss://erweb.in.linuxense.com:6001/app/erkey?protocol=7&client=js&version=6.0.3&flash=false' failed: WebSocket is closed before the connection is established. app.js:42637 WebSocket connection to 'wss://erweb.in.linuxense.com:6001/app/erkey?protocol=7&client=js&version=6.0.3&flash=false' failed: WebSocket opening handshake timed out` **Things checked** 1. Port 6001 is open & listening. Verified using netstat -tulpn 2. Echo config - `window.Echo = new Echo({ broadcaster: 'pusher', key: process.env.MIX_PUSHER_APP_KEY, forceTLS: true, wsHost: window.location.hostname, encrypted: false, wsPort: 6001, wssPort: 6001, disableStats: true, enabledTransports: ['ws', 'wss'] });` 3. In broadcasting.php ` 'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER\_APP\_KEY'), 'secret' => env('PUSHER\_APP\_SECRET'), 'app\_id' => env('PUSHER\_APP\_ID'), 'options' => [ 'cluster' => env('PUSHER\_APP\_CLUSTER'), 'useTLS' => true, 'host' => '127.0.0.1', 'port' => 6001, 'scheme' => 'http', 'encrypted' => false, ], ], ` 4. No changes made to SSL part of websocket config file
2020/07/01
[ "https://Stackoverflow.com/questions/62675211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10612423/" ]
`int` is a value type in the sense that if you pass `int` value into a function and change the value of a parameter inside function, it won't affect outer scope. ```dart void add(int inner) { inner += 1; } int outer = 0; add(outer); print(outer); // 0, unchanged ``` But `int` is still a class even though its name starts from lowercase letter. There was a [huge discussion](https://github.com/dart-lang/sdk/issues/1410) about its naming and lots of people consider it an inconsistency.
Everything in Dart is an object, int, double or num may look like keywords but they are built-in abstract classes. Since they are abstract classes which means they can not be instantiated, they do not start with an uppercase letter. try this line, `print('2 is instance of "int" class :\t${ 2 is int}');` this will result in true. And regarding your concern about 'null' : In Dart, like JavaScript and Python, everything that a variable can hold is an object including null. Every object including null is an instance of some class and all these classes inherit from Object class. your can refer [this link](https://medium.com/run-dart/dart-dartlang-introduction-variables-and-data-types-d269ea7d1f8f) for more info. Hope this helps.
62,675,211
I am developing a laravel application in which real-time data is to be extracted using laravel-WebSockets package.I have seen people having issues at production side but this is on development side. I am accessing web-app using host-entry All initial steps completed( downloading laravel-WebSocket package, pusher-js, php-pusher-server) And executed `php artisan websockets:serve`. When I refreshed browser I am getting error in console `app.js:40145 WebSocket connection to 'wss://erweb.in.linuxense.com:6001/app/erkey?protocol=7&client=js&version=6.0.3&flash=false' failed: WebSocket is closed before the connection is established. app.js:42637 WebSocket connection to 'wss://erweb.in.linuxense.com:6001/app/erkey?protocol=7&client=js&version=6.0.3&flash=false' failed: WebSocket opening handshake timed out` **Things checked** 1. Port 6001 is open & listening. Verified using netstat -tulpn 2. Echo config - `window.Echo = new Echo({ broadcaster: 'pusher', key: process.env.MIX_PUSHER_APP_KEY, forceTLS: true, wsHost: window.location.hostname, encrypted: false, wsPort: 6001, wssPort: 6001, disableStats: true, enabledTransports: ['ws', 'wss'] });` 3. In broadcasting.php ` 'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER\_APP\_KEY'), 'secret' => env('PUSHER\_APP\_SECRET'), 'app\_id' => env('PUSHER\_APP\_ID'), 'options' => [ 'cluster' => env('PUSHER\_APP\_CLUSTER'), 'useTLS' => true, 'host' => '127.0.0.1', 'port' => 6001, 'scheme' => 'http', 'encrypted' => false, ], ], ` 4. No changes made to SSL part of websocket config file
2020/07/01
[ "https://Stackoverflow.com/questions/62675211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10612423/" ]
Yes, Dart's `int` type is a "reference type". Dart does not have value types at all, all values are instances of a class, including integers. (At least technically, function values makes their classes very hard to see.) Integers are *immutable* and pretends to be *canonicalized*. If `a` and `b` are `int` values and `a == b`, then `identical(a, b)` is guaranteed to be true, so `a` and `b` looks like they are the same object, but it's unspecified whether that's because they really are the same object, or because `identical` just cheats and does `==` for integers. That means that you can largely treat `int` as a "value type". Whether it is copied on assignment or parameter passing, or you are passing a reference to the same object, is impossible to tell apart. The language ensures that, because it allows the implementations to do whatever is more efficient. In practice, some integers are unboxed inside functions, some integers are stored as a value in the reference itself, and some are real objects. (That's also one of the reasons you can't use an `Expando` with an `int`). (In the current Dart language, all types annotations are nullable, meaning that you can assign `null` to `int x;`. With the upcoming Null Safety feature, that changes. Types will only be nullable if you write them as such, so `int x = 1;` would not accept a `null` value, but `int? x;` would. And `null` is an object too, the only instance of the class `Null`.)
Everything in Dart is an object, int, double or num may look like keywords but they are built-in abstract classes. Since they are abstract classes which means they can not be instantiated, they do not start with an uppercase letter. try this line, `print('2 is instance of "int" class :\t${ 2 is int}');` this will result in true. And regarding your concern about 'null' : In Dart, like JavaScript and Python, everything that a variable can hold is an object including null. Every object including null is an instance of some class and all these classes inherit from Object class. your can refer [this link](https://medium.com/run-dart/dart-dartlang-introduction-variables-and-data-types-d269ea7d1f8f) for more info. Hope this helps.
62,675,211
I am developing a laravel application in which real-time data is to be extracted using laravel-WebSockets package.I have seen people having issues at production side but this is on development side. I am accessing web-app using host-entry All initial steps completed( downloading laravel-WebSocket package, pusher-js, php-pusher-server) And executed `php artisan websockets:serve`. When I refreshed browser I am getting error in console `app.js:40145 WebSocket connection to 'wss://erweb.in.linuxense.com:6001/app/erkey?protocol=7&client=js&version=6.0.3&flash=false' failed: WebSocket is closed before the connection is established. app.js:42637 WebSocket connection to 'wss://erweb.in.linuxense.com:6001/app/erkey?protocol=7&client=js&version=6.0.3&flash=false' failed: WebSocket opening handshake timed out` **Things checked** 1. Port 6001 is open & listening. Verified using netstat -tulpn 2. Echo config - `window.Echo = new Echo({ broadcaster: 'pusher', key: process.env.MIX_PUSHER_APP_KEY, forceTLS: true, wsHost: window.location.hostname, encrypted: false, wsPort: 6001, wssPort: 6001, disableStats: true, enabledTransports: ['ws', 'wss'] });` 3. In broadcasting.php ` 'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER\_APP\_KEY'), 'secret' => env('PUSHER\_APP\_SECRET'), 'app\_id' => env('PUSHER\_APP\_ID'), 'options' => [ 'cluster' => env('PUSHER\_APP\_CLUSTER'), 'useTLS' => true, 'host' => '127.0.0.1', 'port' => 6001, 'scheme' => 'http', 'encrypted' => false, ], ], ` 4. No changes made to SSL part of websocket config file
2020/07/01
[ "https://Stackoverflow.com/questions/62675211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10612423/" ]
`int` is a value type in the sense that if you pass `int` value into a function and change the value of a parameter inside function, it won't affect outer scope. ```dart void add(int inner) { inner += 1; } int outer = 0; add(outer); print(outer); // 0, unchanged ``` But `int` is still a class even though its name starts from lowercase letter. There was a [huge discussion](https://github.com/dart-lang/sdk/issues/1410) about its naming and lots of people consider it an inconsistency.
Yes `int` is a class (it even extends `num`) and therefor has common methods to use on. But one the other side it is different than "normal" classes since you don't have to use a constructor like ```dart int i = int(3); ``` See int's class documenation <https://api.dart.dev/stable/2.8.4/dart-core/int-class.html>
62,675,211
I am developing a laravel application in which real-time data is to be extracted using laravel-WebSockets package.I have seen people having issues at production side but this is on development side. I am accessing web-app using host-entry All initial steps completed( downloading laravel-WebSocket package, pusher-js, php-pusher-server) And executed `php artisan websockets:serve`. When I refreshed browser I am getting error in console `app.js:40145 WebSocket connection to 'wss://erweb.in.linuxense.com:6001/app/erkey?protocol=7&client=js&version=6.0.3&flash=false' failed: WebSocket is closed before the connection is established. app.js:42637 WebSocket connection to 'wss://erweb.in.linuxense.com:6001/app/erkey?protocol=7&client=js&version=6.0.3&flash=false' failed: WebSocket opening handshake timed out` **Things checked** 1. Port 6001 is open & listening. Verified using netstat -tulpn 2. Echo config - `window.Echo = new Echo({ broadcaster: 'pusher', key: process.env.MIX_PUSHER_APP_KEY, forceTLS: true, wsHost: window.location.hostname, encrypted: false, wsPort: 6001, wssPort: 6001, disableStats: true, enabledTransports: ['ws', 'wss'] });` 3. In broadcasting.php ` 'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER\_APP\_KEY'), 'secret' => env('PUSHER\_APP\_SECRET'), 'app\_id' => env('PUSHER\_APP\_ID'), 'options' => [ 'cluster' => env('PUSHER\_APP\_CLUSTER'), 'useTLS' => true, 'host' => '127.0.0.1', 'port' => 6001, 'scheme' => 'http', 'encrypted' => false, ], ], ` 4. No changes made to SSL part of websocket config file
2020/07/01
[ "https://Stackoverflow.com/questions/62675211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10612423/" ]
Yes, Dart's `int` type is a "reference type". Dart does not have value types at all, all values are instances of a class, including integers. (At least technically, function values makes their classes very hard to see.) Integers are *immutable* and pretends to be *canonicalized*. If `a` and `b` are `int` values and `a == b`, then `identical(a, b)` is guaranteed to be true, so `a` and `b` looks like they are the same object, but it's unspecified whether that's because they really are the same object, or because `identical` just cheats and does `==` for integers. That means that you can largely treat `int` as a "value type". Whether it is copied on assignment or parameter passing, or you are passing a reference to the same object, is impossible to tell apart. The language ensures that, because it allows the implementations to do whatever is more efficient. In practice, some integers are unboxed inside functions, some integers are stored as a value in the reference itself, and some are real objects. (That's also one of the reasons you can't use an `Expando` with an `int`). (In the current Dart language, all types annotations are nullable, meaning that you can assign `null` to `int x;`. With the upcoming Null Safety feature, that changes. Types will only be nullable if you write them as such, so `int x = 1;` would not accept a `null` value, but `int? x;` would. And `null` is an object too, the only instance of the class `Null`.)
Yes `int` is a class (it even extends `num`) and therefor has common methods to use on. But one the other side it is different than "normal" classes since you don't have to use a constructor like ```dart int i = int(3); ``` See int's class documenation <https://api.dart.dev/stable/2.8.4/dart-core/int-class.html>
62,675,211
I am developing a laravel application in which real-time data is to be extracted using laravel-WebSockets package.I have seen people having issues at production side but this is on development side. I am accessing web-app using host-entry All initial steps completed( downloading laravel-WebSocket package, pusher-js, php-pusher-server) And executed `php artisan websockets:serve`. When I refreshed browser I am getting error in console `app.js:40145 WebSocket connection to 'wss://erweb.in.linuxense.com:6001/app/erkey?protocol=7&client=js&version=6.0.3&flash=false' failed: WebSocket is closed before the connection is established. app.js:42637 WebSocket connection to 'wss://erweb.in.linuxense.com:6001/app/erkey?protocol=7&client=js&version=6.0.3&flash=false' failed: WebSocket opening handshake timed out` **Things checked** 1. Port 6001 is open & listening. Verified using netstat -tulpn 2. Echo config - `window.Echo = new Echo({ broadcaster: 'pusher', key: process.env.MIX_PUSHER_APP_KEY, forceTLS: true, wsHost: window.location.hostname, encrypted: false, wsPort: 6001, wssPort: 6001, disableStats: true, enabledTransports: ['ws', 'wss'] });` 3. In broadcasting.php ` 'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER\_APP\_KEY'), 'secret' => env('PUSHER\_APP\_SECRET'), 'app\_id' => env('PUSHER\_APP\_ID'), 'options' => [ 'cluster' => env('PUSHER\_APP\_CLUSTER'), 'useTLS' => true, 'host' => '127.0.0.1', 'port' => 6001, 'scheme' => 'http', 'encrypted' => false, ], ], ` 4. No changes made to SSL part of websocket config file
2020/07/01
[ "https://Stackoverflow.com/questions/62675211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10612423/" ]
Yes, Dart's `int` type is a "reference type". Dart does not have value types at all, all values are instances of a class, including integers. (At least technically, function values makes their classes very hard to see.) Integers are *immutable* and pretends to be *canonicalized*. If `a` and `b` are `int` values and `a == b`, then `identical(a, b)` is guaranteed to be true, so `a` and `b` looks like they are the same object, but it's unspecified whether that's because they really are the same object, or because `identical` just cheats and does `==` for integers. That means that you can largely treat `int` as a "value type". Whether it is copied on assignment or parameter passing, or you are passing a reference to the same object, is impossible to tell apart. The language ensures that, because it allows the implementations to do whatever is more efficient. In practice, some integers are unboxed inside functions, some integers are stored as a value in the reference itself, and some are real objects. (That's also one of the reasons you can't use an `Expando` with an `int`). (In the current Dart language, all types annotations are nullable, meaning that you can assign `null` to `int x;`. With the upcoming Null Safety feature, that changes. Types will only be nullable if you write them as such, so `int x = 1;` would not accept a `null` value, but `int? x;` would. And `null` is an object too, the only instance of the class `Null`.)
`int` is a value type in the sense that if you pass `int` value into a function and change the value of a parameter inside function, it won't affect outer scope. ```dart void add(int inner) { inner += 1; } int outer = 0; add(outer); print(outer); // 0, unchanged ``` But `int` is still a class even though its name starts from lowercase letter. There was a [huge discussion](https://github.com/dart-lang/sdk/issues/1410) about its naming and lots of people consider it an inconsistency.
62,675,212
I am creating function in which I will pass String and Specific text.The specific text should be bold in whole string. I want to achieve this but unable do that. Input string:-"Hi Hello boy Hello Shyam Hello" Text :- Hello. Output:- Hello word should looks bold in String.
2020/07/01
[ "https://Stackoverflow.com/questions/62675212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10316591/" ]
I'd do it like this: ```js function escapeRegExp(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'); } function boldMe(input, text){ const regExString = escapeRegExp(text) const regex = new RegExp(regExString, 'g'); let output = input.replace(regex, `<b>${text}</b>`); console.log(output); return output; } var myDev = document.getElementById('myDiv'); myDev.innerHTML = boldMe(myDev.innerHTML,'Hello'); ``` ```html <div id="myDiv">Hi Hello boy Hello Shyam Hello</div> ``` --- Edit: As [@Peter Seliger](https://stackoverflow.com/users/2627243/peter-seliger) pointed out in the comments, since working with regex, the search string has to be escaped before being used. I used [this approach](https://stackoverflow.com/a/9310752/3125277), but feel free to use any other escaping implementation
``` <span id="boldit">Bold me</span> <script> function boldme() { document.getElementById('boldit').style.fontWeight = 'bold'; } boldme(); </script> ```
62,675,212
I am creating function in which I will pass String and Specific text.The specific text should be bold in whole string. I want to achieve this but unable do that. Input string:-"Hi Hello boy Hello Shyam Hello" Text :- Hello. Output:- Hello word should looks bold in String.
2020/07/01
[ "https://Stackoverflow.com/questions/62675212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10316591/" ]
I'd do it like this: ```js function escapeRegExp(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'); } function boldMe(input, text){ const regExString = escapeRegExp(text) const regex = new RegExp(regExString, 'g'); let output = input.replace(regex, `<b>${text}</b>`); console.log(output); return output; } var myDev = document.getElementById('myDiv'); myDev.innerHTML = boldMe(myDev.innerHTML,'Hello'); ``` ```html <div id="myDiv">Hi Hello boy Hello Shyam Hello</div> ``` --- Edit: As [@Peter Seliger](https://stackoverflow.com/users/2627243/peter-seliger) pointed out in the comments, since working with regex, the search string has to be escaped before being used. I used [this approach](https://stackoverflow.com/a/9310752/3125277), but feel free to use any other escaping implementation
```js function boldString (fString, bString) { let regex = new RegExp(bString, 'g'); return fString.replace(regex, `<b>${bString}</b>`); } let output = boldString("Hi Hello boy Hello Shyam Hello", "Hello"); console.log(output); document.body.innerHTML = output; ```
62,675,248
Hello I'd like handle Xml-Files which have encoded node names like for example: ```xml <CST_x002F_SOMETHING> .... </CST_x002F_SOMETHING> ``` This node name should be decoded to `CST/SOMETHING`. These node names were encoded for example via [EncodeName](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlconvert.encodename?view=netcore-3.1). Is there any built-in XQuery-function to decode these names? Or do you have an encoding / decoding function? XML Files produced by Oracle-DB use the same escaping mechanism.
2020/07/01
[ "https://Stackoverflow.com/questions/62675248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9099261/" ]
Use `fn:analyze-string()` to split the string and match the `_XXXX_` parts. When you encounter one of these parts, use `bin:hex()` to convert hex to binary, then `bin:unpack-unsigned-integer()` to convert the binary to an integer, then `fn:codepoints-to-string()` to convert the integer codepoint to a string. The binary functions are documented at <https://www.saxonica.com/documentation/index.html#!functions/expath-binary> Requires Saxon-PE or higher. You could also use the new saxon:replace-with() function: ``` declare namespace bin = 'http://expath.org/ns/binary'; saxon:replace-with('CST_x002F_SOMETHING', '_x[0-9A-F]{4}_', function($s) {$s => substring(3, 4) => bin:hex() => bin:unpack-unsigned-integer(0,2) => codepoints-to-string()} ``` outputs `CST/SOMETHING`
You can try the following. > > XQuery > > > ``` for $x in doc('input.xml')//CST_x002F_SOMETHING return rename node $x as "whateveryouneed" ```
62,675,256
This fails to compile with clang++, can anybody explain why ? (this compiles fine with g++) ``` struct X { template <typename T> X() {} }; template X::X<int>(); int main() { return 1; } instantiate.cc:7:13: error: qualified reference to 'X' is a constructor name rather than a type in this context template X::X<int>(); ^ instantiate.cc:7:14: error: expected unqualified-id template X::X<int>(); ^ 2 errors generated. ```
2020/07/01
[ "https://Stackoverflow.com/questions/62675256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/759349/" ]
Constructors don't have names. As much is said in [[class.ctor]/1](https://timsong-cpp.github.io/cppwp/n4659/class.ctor#1). They are special members that get defined by using the name of the class. But they themselves are nameless. While C++ allows us to reference c'tors in certain contexts by using the class name, those are limited. In general, we cannot name a c'tor. And that is where the issue lies. To explicitly specify template arguments we must use the name of the templated entity. Constructors don't have names, and so we cannot specify their arguments explicitly. This is the subject of a note in [temp.arg.explicit] that summarizes the intent of the normative text. > > [7](https://timsong-cpp.github.io/cppwp/n4659/temp.arg.explicit#7) [ Note: Because the explicit template argument list follows the > function template name, and because conversion member function > templates and constructor member function templates are called without > using a function name, there is no way to provide an explicit template > argument list for these function templates.  — end note ] > > > We can still instantiate or specialize constructors, but only if the template arguments don't have to be explicitly specified (if they are deducible, or come from a default template argument). E.g ``` struct X { template <typename T> X(T) {} }; template X::X(int); // This will work ``` So Clang is not wrong to reject your code. And it's possible GCC is offering an extension. But ultimately, the standard doesn't offer a way to provide template arguments explicitly to constructor templates. --- And upon further digging, there's [CWG581](https://wg21.link/cwg581), further confirming Clang's behavior is the intended one. It also seems to have made its way into the latest standard revision with some changes to the normative text.
I think Clang is correct. Even Gcc allows it, the templated constructor can't be used at all. The template parameter can't be deduced and we can't specify template argument explicitly for constructor template. [[temp.arg.explicit]/2](https://timsong-cpp.github.io/cppwp/temp.arg.explicit#2) > > Template arguments shall not be specified when referring to a specialization of a constructor template ([class.ctor], [class.qual]). > > > [[temp.arg.explicit]/8](https://timsong-cpp.github.io/cppwp/temp.arg.explicit#8) > > [ Note: Because the explicit template argument list follows the function template name, and because constructor templates ([class.ctor]) are named without using a function name ([class.qual]), there is no way to provide an explicit template argument list for these function templates. — end note ] > > >
62,675,269
I'm using PySide2 and not clearly about *Signal* and *Event* If we have two people are doing two View. **Person A** is doing **ListView** **Person B** is doing **ParameterView** while **ListItem** be selected, update **ParameterView** How should I Connect them? use *Signal* or *Event*? Maybe I would have another **View**, it needs to be update also, while **ListItem** *selectChanged* --- *Signal* ``` class ListView(QListView): # do something class ParameterView(QWidget): def update(self): # do something list_view = ListView() parameter_view = ParameterView() list_view.selectChanged.connect(parameter_view.update) ``` *Event* ``` class ListView(QListView): def selectChanged(self): QApplication.sendEvent(self, SelectChangedEvent) class SelectChangedEvent(QEvent): # initialize ... class ParameterView(QWidget): def update(self): # do something def event(self, event): if event.type() == SelectChangedEvent: self.update() ``` [![enter image description here](https://i.stack.imgur.com/99VMt.png)](https://i.stack.imgur.com/99VMt.png)
2020/07/01
[ "https://Stackoverflow.com/questions/62675269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8932323/" ]
Constructors don't have names. As much is said in [[class.ctor]/1](https://timsong-cpp.github.io/cppwp/n4659/class.ctor#1). They are special members that get defined by using the name of the class. But they themselves are nameless. While C++ allows us to reference c'tors in certain contexts by using the class name, those are limited. In general, we cannot name a c'tor. And that is where the issue lies. To explicitly specify template arguments we must use the name of the templated entity. Constructors don't have names, and so we cannot specify their arguments explicitly. This is the subject of a note in [temp.arg.explicit] that summarizes the intent of the normative text. > > [7](https://timsong-cpp.github.io/cppwp/n4659/temp.arg.explicit#7) [ Note: Because the explicit template argument list follows the > function template name, and because conversion member function > templates and constructor member function templates are called without > using a function name, there is no way to provide an explicit template > argument list for these function templates.  — end note ] > > > We can still instantiate or specialize constructors, but only if the template arguments don't have to be explicitly specified (if they are deducible, or come from a default template argument). E.g ``` struct X { template <typename T> X(T) {} }; template X::X(int); // This will work ``` So Clang is not wrong to reject your code. And it's possible GCC is offering an extension. But ultimately, the standard doesn't offer a way to provide template arguments explicitly to constructor templates. --- And upon further digging, there's [CWG581](https://wg21.link/cwg581), further confirming Clang's behavior is the intended one. It also seems to have made its way into the latest standard revision with some changes to the normative text.
I think Clang is correct. Even Gcc allows it, the templated constructor can't be used at all. The template parameter can't be deduced and we can't specify template argument explicitly for constructor template. [[temp.arg.explicit]/2](https://timsong-cpp.github.io/cppwp/temp.arg.explicit#2) > > Template arguments shall not be specified when referring to a specialization of a constructor template ([class.ctor], [class.qual]). > > > [[temp.arg.explicit]/8](https://timsong-cpp.github.io/cppwp/temp.arg.explicit#8) > > [ Note: Because the explicit template argument list follows the function template name, and because constructor templates ([class.ctor]) are named without using a function name ([class.qual]), there is no way to provide an explicit template argument list for these function templates. — end note ] > > >
62,675,273
Simple problem, i have a members list where i iterate through it with a v-for. How can i limit the results and only show the first 2 ? ``` members = [ {id : 1, name: 'Franck'}, {id : 2, name: 'Sophie'}, {id : 3, name: 'Bob'}] <div v-for="member in members" :key="member.id"> <p>{{ name }}</p> </div> ``` Just want to know if it's feasible from template ? Otherwise i know that i can use a computed properties that filtered it and i just have to loop through the results of my filtered array
2020/07/01
[ "https://Stackoverflow.com/questions/62675273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5794331/" ]
You can use `slice()` in the template if you prefer to not use a computed property. I would though choose to have a computed property, if for nothing else, I like to handle all logic in script instead of template. But as said, you can use slice: ``` v-for="(member, index) in members.slice(0, 2)" ``` A forked **[fiddle](https://jsfiddle.net/7vje6tc3/)** that was provided by @Raffobaffo in a comment.
After some discussions here, lets divide the answer in two: A fast, not super correct way but still referred [inside vue docs](https://v2.vuejs.org/v2/guide/list.html#v-for-with-v-if) Use a v-if and set and index in the v-for. ``` <div v-for="(member, index) in members" :key="member.id" v-if="index < 3"> <p>{{ name }}</p> </div> ``` else, the most correct way is to create a computed property returning just the elements you need: ``` <template> <div v-for="member in justTwoElements" :key="member.id"> <p>{{ name }}</p> </div> <template> .... computed: { justTwoElements: function(){ return this.members.slice(0,2); } } ``` This latest solution is more indicated when your data entry is huge, the benefits of using it instead of the first solution are well explained [here.](https://v2.vuejs.org/v2/style-guide/#Avoid-v-if-with-v-for-essential) I hope this helps to give you the correct path to follow
62,675,278
How to find out BigQuery cost for a project programmatically. Is there an API to do that? Also, is it possible to know the user level cost details for queries made?
2020/07/01
[ "https://Stackoverflow.com/questions/62675278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6278953/" ]
To track individual costs for a BigQuery project, you can redirect all logs back to BigQuery - and then you can run queries over these logs. * <https://cloud.google.com/bigquery/docs/reference/auditlogs> These logs include who ran the query, and how much data was scanned. --- Another way is using the `INFORMATION_SCHEMA` table, check this post: * <https://www.pascallandau.com/bigquery-snippets/monitor-query-costs/>
You can use [Cloud Billing API](https://cloud.google.com/billing/reference/rest) For example ``` [GET] https://cloudbilling.googleapis.com/v1/projects/{projectsId}/billingInfo ```
62,675,286
I have a spring boot application that connects to an oracle database. The project contains a service class (userService) that calls the function `VALIDATEUSER(USERNAME IN VARCHAR2,PASSWD IN VARCHAR2)` in oracle and return 1 if user is valid and 0 invalid. I need to create the same function in h2 db that always return true for my integration test. Basically I wanted to created the function in sql script and load it during integration test as follows: ``` @Test @Sql(scripts={"classpath:/sql/createFunction.sql"}) public void testUserInfo() throws Exception { // userService calls VALIDATEUSER function userService.isUserValid("testdb", "testdb"); } ``` How to create the function VALIDATEUSER in h2? Thanks in advance.
2020/07/01
[ "https://Stackoverflow.com/questions/62675286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999453/" ]
To track individual costs for a BigQuery project, you can redirect all logs back to BigQuery - and then you can run queries over these logs. * <https://cloud.google.com/bigquery/docs/reference/auditlogs> These logs include who ran the query, and how much data was scanned. --- Another way is using the `INFORMATION_SCHEMA` table, check this post: * <https://www.pascallandau.com/bigquery-snippets/monitor-query-costs/>
You can use [Cloud Billing API](https://cloud.google.com/billing/reference/rest) For example ``` [GET] https://cloudbilling.googleapis.com/v1/projects/{projectsId}/billingInfo ```
62,675,318
I am trying to figure out how to understand a question in Python. The aim is to use this for an information retrieval chatbot - i.e. the user will ask for information about something, and then the chatbot will access a knowledge base to return information about that something. Example user inputs may be: "Show me information about WW1." - where [WW1] should be extracted "I want to know the symptoms of the common flu." - where [the symptoms of the common flu] should be extracted I have started of by looking at spacy and nltk, specifically nltk trees, which end up looking like these: ``` Show ___|________ | | information | | | | | about | | | me . WW1 want _______|________ | | know | | ________|______ | | | symptoms | | | __________|______ | | | | of | | | | | | | | | flu | | | | ______|____ I . to the the common ``` From here, I'm not sure how to extract the correct subtree as shown above, and I don't want to have to assume it will always be the right hand most tree. I also don't know if this is the best way of tackling this problem? Once I have the string value of which the user wants information about I can use this to find the information, I just need to get this value first.
2020/07/01
[ "https://Stackoverflow.com/questions/62675318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13846598/" ]
To track individual costs for a BigQuery project, you can redirect all logs back to BigQuery - and then you can run queries over these logs. * <https://cloud.google.com/bigquery/docs/reference/auditlogs> These logs include who ran the query, and how much data was scanned. --- Another way is using the `INFORMATION_SCHEMA` table, check this post: * <https://www.pascallandau.com/bigquery-snippets/monitor-query-costs/>
You can use [Cloud Billing API](https://cloud.google.com/billing/reference/rest) For example ``` [GET] https://cloudbilling.googleapis.com/v1/projects/{projectsId}/billingInfo ```
62,675,323
Cannot rerun **JPackage** installer if already installed, second time just **seems to exit** without warning, is this correct behaviour on Windows ? You may ask why I want to do this anyway? Well in my case I am trying to build a JPackage installer for my Java application, so I am building it installing it, then tweaking the settings, rebuilding it and try to reinstall. It took me some time to work out that I couldn't not reinstall it unless i uninstall the first installation (using Control Panel, Program and Features) My case may not be the usual usecase, but it doesn't feel correct that it just exits without giving any reason. It also means that if I deploy a new version to customers, and I later need to amend the installer than I would have to modify the version number to let the user reinstall, this may generally be best practise but is something I would not particulary want to do if the application itself had not changed. **Update:Since found out by looking at TaskManager it is still running but doesnt seem to be doing anything and gives no indication to user !**
2020/07/01
[ "https://Stackoverflow.com/questions/62675323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1480018/" ]
No idea if this helps on Mac or Linux but the Windows installer automatically removes older versions of the application when you run it so you just need to set up a scheme which changes the version number on each build to avoid having to ununstall old version each time. To do this simply you could set the version number as "YY.MM.DDHH" so version number changes each hour and cuts down on uninstalls. Ant steps: ``` <tstamp> <format property="appver" pattern="yy.MM.ddHH" /> </tstamp> <exec executable="jpackage"> <arg line="--app-version ${appver}"/> ... </exec> ``` The CMD version of this: ``` set appver=%date:~6,2%.%date:~3,2%.%date:~0,2%%time:~0,2% jpackage --app-version %appver% ... ```
This may fix the reinstall. In my case, I create the jpackage installer, install it, creates a new installer (based on Inno Setup) and uninstall the jpackage automatically. I think what may work in your case is to uninstall the first installation as the installer may detect that it's already installed with the same version. In my case I do the uninstall automatically with an Ant task ``` <target name="uninstall" depends="init"> <exec executable="wmic.exe"> <arg value="product" /> <arg value="where" /> <arg value="description='${full.name}'" /> <arg value="uninstall" /> </exec> </target> ```
62,675,324
I am new to PHP and sessions so go easy on me. This is my code ``` if(isset($_POST["username"]) || isset($_SESSION["username"])){ $_SESSION["username"] = $_POST["username"]; echo $_SESSION["username"]; } else { exit(); } ``` I'm getting an undefined index in the line that is supposed to define $SESSION["username"]. What am I doing wrong?
2020/07/01
[ "https://Stackoverflow.com/questions/62675324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13842924/" ]
I figured it out. The problem occurs if isset($\_POST["username"]) is false. Then when $\_POST["username"] doesn't exist so it returns an error
try it ``` if(isset($_POST["username"])){ $_SESSION["username"] = $_POST["username"]; echo $_SESSION["username"]; } else if (isset($_SESSION["username"])) { echo $_SESSION["username"]; } else { exit(); } ``` you're checking if your `$_POST` variable is set or `$_SESSION` variable is set, so what's happening here is your `if` statement is returning true because your `$_SESSION` variable is already set. And don't forget to start your session using `session_start()`
62,675,325
I need to replace values containing only spaces in a dataframe. I tried to use the following code but it replaces all the values from the column: ``` books['original_title'] = books.apply(lambda row: row['title'] if (str(row['original_title']).isspace() == True) else row['title'], axis=1) ``` For example, for this df: ``` books = pd.DataFrame({'title': ['If You Take a Mouse to School', 'Sea of Swords', 'SHOULD NOT CHANGE'], 'original_title': [' ', ' ', 'NOT CHANGING']}) ``` The expected answer corresponds to the following dataframe: ``` expected_answer = pd.DataFrame({'title': ['If You Take a Mouse to School', 'Sea of Swords', 'SHOULD NOT CHANGE'], 'original_title': ['If You Take a Mouse to School', 'Sea of Swords', 'NOT CHANGING']}) ``` But I'm only getting this: ``` answer = pd.DataFrame({'title': ['If You Take a Mouse to School', 'Sea of Swords', 'SHOULD NOT CHANGE'], 'original_title': ['If You Take a Mouse to School', 'Sea of Swords', 'SHOULD NOT CHANGE']}) ``` I'd be grateful if anyone could help me.
2020/07/01
[ "https://Stackoverflow.com/questions/62675325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5590048/" ]
I figured it out. The problem occurs if isset($\_POST["username"]) is false. Then when $\_POST["username"] doesn't exist so it returns an error
try it ``` if(isset($_POST["username"])){ $_SESSION["username"] = $_POST["username"]; echo $_SESSION["username"]; } else if (isset($_SESSION["username"])) { echo $_SESSION["username"]; } else { exit(); } ``` you're checking if your `$_POST` variable is set or `$_SESSION` variable is set, so what's happening here is your `if` statement is returning true because your `$_SESSION` variable is already set. And don't forget to start your session using `session_start()`
62,675,329
I have been trying to enable timed tests on Open EdX, but nothing worked so far. Here is what I did: * I started the server successfully based on the instructions here: <https://github.com/edx/devstack#getting-started> * I started a course and add components. Nothing bad yet. * Then I followed these instructions to config timed tests for the site: <https://edx.readthedocs.io/projects/edx-installing-configuring-and-running/en/latest/configuration/enable_timed_exams.html#enable-timed-exams> * In detail, I run `make lms-shell`, then `cd ..` to move 1 level above edx-platform, then change the `ENABLE_SPECIAL_EXAMS` in lms.env.json and cms.env.json to true. The I saved, quitted. Then I did the same with studio: run `make studio-shell`, then `cd ..` to move 1 level above edx-platform, then change the `ENABLE_SPECIAL_EXAMS` in lms.env.json and cms.env.json to true. * Then I restart lms and studio with `make lms-restart` and `make studio-restart` However, when I refresh the Studio/CMS, nothing changed and I still couldn't see the Advanced tab to set timing for assignments, although I have change the Enable Timed Exams and Enable Proctored Exams in Advanced Settings to true. Can someone tell we what I did wrong? Thanks
2020/07/01
[ "https://Stackoverflow.com/questions/62675329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13509959/" ]
Got the same problem. It should be added inside "FEATURES" which I think is not specified in the documentation. [![enter image description here](https://i.stack.imgur.com/5kyoe.png)](https://i.stack.imgur.com/5kyoe.png)
More information can be found here also <https://edx.readthedocs.io/projects/open-edx-ca/en/latest/course_features/timed_exams.html> If you enabled flags in env files, then you just have to enable timed exams in advanced settings. > > Studio -> settings -> Advacned settings > > > Then set > > "Enable Timed Exams" to true. > > > Then go to "advanced" in the course sub-module level, and select "**Timed**" as below. [![enter image description here](https://i.stack.imgur.com/aVKML.png)](https://i.stack.imgur.com/aVKML.png)
62,675,357
I'm trying to add a list of image locations into a list for each parent folder for image comparison. However when I pull the list of images from the folders with OS and then check them from the list with os.path.exists, some of the paths apparently do not exist, even though the files do exist when i manually check. How do I fix this or work out why it is now saying the file paths do not exist? I have already tried to strip out white spaces ```py import os directory = '$$$' listFiles = os.listdir(directory) tester = [] for entry in listFiles: fullpath = os.path.join(directory, entry) test = fullpath listFiles = os.listdir(fullpath) print(listFiles) for n in listFiles: fullpath = os.path.join(test,n) fullpath = fullpath.strip() tester.append(fullpath) for n in range (len(tester)): print(tester[n].strip()) print(os.path.exists(tester[n])) break ```
2020/07/01
[ "https://Stackoverflow.com/questions/62675357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13846644/" ]
Got the same problem. It should be added inside "FEATURES" which I think is not specified in the documentation. [![enter image description here](https://i.stack.imgur.com/5kyoe.png)](https://i.stack.imgur.com/5kyoe.png)
More information can be found here also <https://edx.readthedocs.io/projects/open-edx-ca/en/latest/course_features/timed_exams.html> If you enabled flags in env files, then you just have to enable timed exams in advanced settings. > > Studio -> settings -> Advacned settings > > > Then set > > "Enable Timed Exams" to true. > > > Then go to "advanced" in the course sub-module level, and select "**Timed**" as below. [![enter image description here](https://i.stack.imgur.com/aVKML.png)](https://i.stack.imgur.com/aVKML.png)
62,675,365
**I have next code:** ```js var users = [ { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England', val: true }, { name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' }]; let res = users.find( user => (user.name === 'John' || user.name === 'Tom' || user.val === true), ); console.log(res); ``` How I can make search by `'name'` as top priority, because now I am getting object with name `Mark` as result, but I need object with name `John` if it exists or `Tom` and if no names found search by `val`.
2020/07/01
[ "https://Stackoverflow.com/questions/62675365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1879838/" ]
Try ``` let res = users.find( user => (user.name === 'John' || user.name === 'Tom' || (!user.name && user.val === true)), ); ```
try this, it will return by val if no name is in the record ```js var users = [ { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England', val: true }, { name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' }]; function srch(name,val){ return users.filter(x=> x.name==name? x:(x.val==val?x:null)) } console.log(srch("Mark",true)) ```
62,675,365
**I have next code:** ```js var users = [ { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England', val: true }, { name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' }]; let res = users.find( user => (user.name === 'John' || user.name === 'Tom' || user.val === true), ); console.log(res); ``` How I can make search by `'name'` as top priority, because now I am getting object with name `Mark` as result, but I need object with name `John` if it exists or `Tom` and if no names found search by `val`.
2020/07/01
[ "https://Stackoverflow.com/questions/62675365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1879838/" ]
You shouldn't use `Array.find` method. It'd return only 1 value. You can use a `for...of` loop and have two arrays returned from it as below: ``` let prio1= [], prio2 = []; for (const user of users) { if (user.name === 'John' || user.name === 'Tom') prio1.push(user); if (user.val) prio2.push(user); } let res = prio1.length ? prio1 : prio2; ```
try this, it will return by val if no name is in the record ```js var users = [ { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England', val: true }, { name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' }]; function srch(name,val){ return users.filter(x=> x.name==name? x:(x.val==val?x:null)) } console.log(srch("Mark",true)) ```
62,675,365
**I have next code:** ```js var users = [ { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England', val: true }, { name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' }]; let res = users.find( user => (user.name === 'John' || user.name === 'Tom' || user.val === true), ); console.log(res); ``` How I can make search by `'name'` as top priority, because now I am getting object with name `Mark` as result, but I need object with name `John` if it exists or `Tom` and if no names found search by `val`.
2020/07/01
[ "https://Stackoverflow.com/questions/62675365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1879838/" ]
I think what you're looking for is something like the following: ```js var users = [ { name: "Mark", email: "mark@mail.com", age: 28, address: "England", val: true }, { name: "John", email: "johnson@mail.com", age: 25, address: "USA" }, { name: "Tom", email: "tom@mail.com", age: 35, address: "England" } ]; function findUser(names) { // use `Array.reduce` to loop through all names // and find the first name in the array of `users` var user = names.reduce((result, name) => { if (result) { return result; } return users.find(user => user.name === name) || null; }, null); // if user was not found, find a user based on the value of `val` return user ? user : users.find(user => user.val); } var res1 = findUser(["John", "Tom"]); var res2 = findUser(["Tom", "John"]); var res3 = findUser(["Jeff"]); console.log(res1); console.log(res2); console.log(res3); ``` References: * [Array.reduce - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
try this, it will return by val if no name is in the record ```js var users = [ { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England', val: true }, { name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' }]; function srch(name,val){ return users.filter(x=> x.name==name? x:(x.val==val?x:null)) } console.log(srch("Mark",true)) ```
62,675,365
**I have next code:** ```js var users = [ { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England', val: true }, { name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' }]; let res = users.find( user => (user.name === 'John' || user.name === 'Tom' || user.val === true), ); console.log(res); ``` How I can make search by `'name'` as top priority, because now I am getting object with name `Mark` as result, but I need object with name `John` if it exists or `Tom` and if no names found search by `val`.
2020/07/01
[ "https://Stackoverflow.com/questions/62675365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1879838/" ]
``` let userbyName = users.find(user => (user.name === 'xyz')); //Search by name if(userbyName == null) { let userbyVal = users.find(user => ( user.val=== 'true')); //Search by Value } ``` This will work for both cases , put `true/false` as per you need
try this, it will return by val if no name is in the record ```js var users = [ { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England', val: true }, { name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' }]; function srch(name,val){ return users.filter(x=> x.name==name? x:(x.val==val?x:null)) } console.log(srch("Mark",true)) ```
62,675,365
**I have next code:** ```js var users = [ { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England', val: true }, { name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' }]; let res = users.find( user => (user.name === 'John' || user.name === 'Tom' || user.val === true), ); console.log(res); ``` How I can make search by `'name'` as top priority, because now I am getting object with name `Mark` as result, but I need object with name `John` if it exists or `Tom` and if no names found search by `val`.
2020/07/01
[ "https://Stackoverflow.com/questions/62675365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1879838/" ]
You are close, change `.find()` to `.filter()` and it outputs you all users that match that criteria. I made a typo `Johnk` so it dont find `John` because of the wrong name and because he doesnt have `val` ```js var users = [ { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England', val: true }, { name: 'Johnk', email: 'johnson@mail.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' }]; let res = users.filter( user => (user.name === 'John' || user.name === 'Tom' || user.val === true), ); console.log(res); ```
try this, it will return by val if no name is in the record ```js var users = [ { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England', val: true }, { name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' }]; function srch(name,val){ return users.filter(x=> x.name==name? x:(x.val==val?x:null)) } console.log(srch("Mark",true)) ```
62,675,376
Here's the code I'm using: ``` <div class="container-fluid"> <div class="row"> <div class="col-md-2 text-center align-self-center mh-100" style="background-color:red;"> 30% Off </div> <div class="col-md-8"> <span class="badge badge-default">Promo Code</span> <h3 style="font-size:20px;font-weight:700;">Lorem ipsum dolor sit amet.</h3> <p style="font-size:12px;">Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor.</p> </div> <div class="col-md-2 text-center align-self-center"> <button class="btn blue-gradient btn-rounded btn-md">Get Code</button> </div> </div> </div> ``` It output following screen: [![enter image description here](https://i.stack.imgur.com/pR1Vg.png)](https://i.stack.imgur.com/pR1Vg.png) Issue: The col height doesn't stretch to the parent div. I've set the background to red and it's not stretched upto the parent div height. I can use the padding property but is there any other way to do that!
2020/07/01
[ "https://Stackoverflow.com/questions/62675376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13713264/" ]
All You Have To Do is, Set the Parent Row Height (Eg:- 300px) and Set the Child Height to 100%. It will work!! Reply If it Doesn't Work! Eg:- ``` <div class="container-fluid"> <div class="row" style="height: 300px"> <div class="col-md-2 text-center align-self-center mh-100" style="background-color:red; height: 100%;"> 30% Off </div> <div class="col-md-8"> <span class="badge badge-default">Promo Code</span> <h3 style="font-size:20px;font-weight:700;">Lorem ipsum dolor sit amet.</h3> <p style="font-size:12px;">Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor.</p> </div> <div class="col-md-2 text-center align-self-center"> <button class="btn blue-gradient btn-rounded btn-md">Get Code</button> </div> </div> </div> ```
```html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <title>Hello, world!</title> <style> .height-auto { background-color: red; display: flex; align-items: center; justify-content: center; color: #FFF; } </style> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-2 height-auto"> 30% Off </div> <div class="col-md-8"> <span class="badge badge-default">Promo Code</span> <h3 style="font-size:20px;font-weight:700;">Lorem ipsum dolor sit amet.</h3> <p style="font-size:12px;"> Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor. Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor. Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor. Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor. Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor. Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor. </p> </div> <div class="col-md-2 text-center align-self-center"> <button class="btn blue-gradient btn-rounded btn-md">Get Code</button> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> </body> </html> ```
62,675,381
**Backround information** Using Laravel I'm building an application where I want to link a Company profile to a Station. **Company.php** ``` namespace App; use Illuminate\Database\Eloquent\Model; class Company extends Model { protected $guarded = []; protected $table = 'companies'; public function user() { return $this->hasMany('App\User'); } public function station() { return $this->belongsToMany('App\Station')->withPivot('company_stations'); } public function line() { return $this->belongsToMany('App\Line'); } } ``` **Station.php** ``` namespace App; use Illuminate\Database\Eloquent\Model; class Station extends Model { protected $guarded = []; protected $table = 'stations'; public function lines() { return $this->belongsToMany('App\Line'); } public function company() { return $this->belongsToMany('App\Company')->withPivot('company_stations'); } } ``` ***company\_stations migration*** ``` use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCompanyStationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('company_stations', function (Blueprint $table) { $table->id(); $table->integer('company_id')->unsigned(); $table->integer('station_id')->unsigned(); $table->boolean('following')->default(false); $table->boolean('completed')->default(false); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('company_stations'); } } ``` I also have a migration company\_stations, but no Model for it. **The question** I want to create a checkbox on the station view where the currently logged in Company ID is linked to the Station ID in the pivot table to keep track of which stations the company is following and wether the company has completed that station or not. What would be the easiest and most clean approach to this? Do I make a new Model `CompanyStation` + controller or can this be filled in from the Company or Station controller?
2020/07/01
[ "https://Stackoverflow.com/questions/62675381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13803968/" ]
All You Have To Do is, Set the Parent Row Height (Eg:- 300px) and Set the Child Height to 100%. It will work!! Reply If it Doesn't Work! Eg:- ``` <div class="container-fluid"> <div class="row" style="height: 300px"> <div class="col-md-2 text-center align-self-center mh-100" style="background-color:red; height: 100%;"> 30% Off </div> <div class="col-md-8"> <span class="badge badge-default">Promo Code</span> <h3 style="font-size:20px;font-weight:700;">Lorem ipsum dolor sit amet.</h3> <p style="font-size:12px;">Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor.</p> </div> <div class="col-md-2 text-center align-self-center"> <button class="btn blue-gradient btn-rounded btn-md">Get Code</button> </div> </div> </div> ```
```html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <title>Hello, world!</title> <style> .height-auto { background-color: red; display: flex; align-items: center; justify-content: center; color: #FFF; } </style> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-2 height-auto"> 30% Off </div> <div class="col-md-8"> <span class="badge badge-default">Promo Code</span> <h3 style="font-size:20px;font-weight:700;">Lorem ipsum dolor sit amet.</h3> <p style="font-size:12px;"> Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor. Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor. Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor. Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor. Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor. Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit</strong>. Aliquam eget sapien sapien. Curabitur in metus urna. In hac habitasse platea dictumst. Phasellus eu sem sapien, sed vestibulum velit. Nam purus nibh, lacinia non faucibus et, pharetra in dolor. </p> </div> <div class="col-md-2 text-center align-self-center"> <button class="btn blue-gradient btn-rounded btn-md">Get Code</button> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> </body> </html> ```
62,675,384
I am trying to add a dynamic label to my `ion-fab-button` element but I can't seem to get it to work because I need to be able to supply the value from a variable but I am unable to bind to the property. I've tried the following but see the error: > > Error: Template parse errors: Can't bind to 'desc' since it isn't a known property of 'ion-fab-button'. > > > ``` <ion-fab-button color="success" [disabled]="true" desc="Already Sent Scale: {{ variable }}" class="labelOnRight" > <i class="fa fa-presentation fs-24"></i> </ion-fab-button> ``` In my css I use the `desc` to create a label: ``` ion-fab-button.labelOnRight[desc]::after { position: absolute; content: attr(desc); z-index: 1; left: 55px; bottom: 6px; background-color: var(--ion-color-primary); padding: 5px 9px; border-radius: 15px; color: white; box-shadow: 0 3px 5px -1px rgba(0,0,0,0.2), 0 6px 10px 0 rgba(0,0,0,0.14), 0 1px 18px 0 rgba(0,0,0,0.12); } ``` Is there any way to accomplish this? Everything works when the `desc` attribute is hard coded, but not when it's dynamic.
2020/07/01
[ "https://Stackoverflow.com/questions/62675384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3914509/" ]
Use data attributes : `<ion-fab-button [attr.data-desc]></ion-fab-button>`
I think you need to set the attribute. I am on the phone so cant test but let me know if it works. Try [attr.desc]=" 'Already sent scale' + variable"
62,675,424
I'm using polymer on the client-side and as the image upload button: ```html <vaadin-upload form-data-name="file" max-files="1" id="fileUploadImage" method="POST" headers='{"Authorization": "bearer {{auth}}", "Content-Type": "multipart/form-data; boundary=XXXX"}' target="{{config_endpoint}}/rest/upload_file/uploadFile" nodrop > </vaadin-upload> ``` on server side I'm using multer for uploading the image: ```js const express = require("express"); const multer = require("multer"); var cors = require("cors"); const config = require("../../config"); const router = express.Router(); var corsOptions = { origin: config.origin, // '*' optionsSuccessStatus: 200 }; router.use(cors(corsOptions)); var storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, "../../uploads"); }, filename: function(req, file, cb) { const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9); cb(null, file.fieldname + "-" + uniqueSuffix); } }); var uploads = multer({ storage: storage }); router.post("/uploadFile", uploads.single("file"), (req, res) => { console.log(req.files); console.log(req.body); }); module.exports = router; ``` for both req.files and req.body I got undefined values, see logs: ``` 13:54:44 0|eod | OPTIONS /rest/upload_file/uploadFile 200 0 - 0.553 ms 13:54:44 0|eod | undefined 13:54:44 0|eod | {} ``` I'm using the following versions: "multer": "^1.4.2", nodejs v8.9.3 Here are my headers" [click here](https://i.stack.imgur.com/5S7b6.png) what's wrong ? what I missed? btw, even using Postman I got the same issue
2020/07/01
[ "https://Stackoverflow.com/questions/62675424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4763411/" ]
Try console.log(req.file) instead of (req.files), since you're using uploads.single('file'). The request is stored on files (with an "s") only when you're using more than one. It should be on "file" otherwise (when it's a single upload). I think that might be what's happening here.
OK, I found the issue.. After removing the header (except the auth) it works! ("Content-Type" can't be setting manually - because we using boundary, and on the server-side it looking for the auto-generated boundary). looks like it's Vaadin-upload bug
62,675,424
I'm using polymer on the client-side and as the image upload button: ```html <vaadin-upload form-data-name="file" max-files="1" id="fileUploadImage" method="POST" headers='{"Authorization": "bearer {{auth}}", "Content-Type": "multipart/form-data; boundary=XXXX"}' target="{{config_endpoint}}/rest/upload_file/uploadFile" nodrop > </vaadin-upload> ``` on server side I'm using multer for uploading the image: ```js const express = require("express"); const multer = require("multer"); var cors = require("cors"); const config = require("../../config"); const router = express.Router(); var corsOptions = { origin: config.origin, // '*' optionsSuccessStatus: 200 }; router.use(cors(corsOptions)); var storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, "../../uploads"); }, filename: function(req, file, cb) { const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9); cb(null, file.fieldname + "-" + uniqueSuffix); } }); var uploads = multer({ storage: storage }); router.post("/uploadFile", uploads.single("file"), (req, res) => { console.log(req.files); console.log(req.body); }); module.exports = router; ``` for both req.files and req.body I got undefined values, see logs: ``` 13:54:44 0|eod | OPTIONS /rest/upload_file/uploadFile 200 0 - 0.553 ms 13:54:44 0|eod | undefined 13:54:44 0|eod | {} ``` I'm using the following versions: "multer": "^1.4.2", nodejs v8.9.3 Here are my headers" [click here](https://i.stack.imgur.com/5S7b6.png) what's wrong ? what I missed? btw, even using Postman I got the same issue
2020/07/01
[ "https://Stackoverflow.com/questions/62675424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4763411/" ]
try ``` router.use(express.json());//this is required if you are sending data as json router.use(express.urlencoded({extended:false})); ```
OK, I found the issue.. After removing the header (except the auth) it works! ("Content-Type" can't be setting manually - because we using boundary, and on the server-side it looking for the auto-generated boundary). looks like it's Vaadin-upload bug