id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
5a4a70b38a3d98c7762834b162fd62c6e89ddde5
Stackoverflow Stackexchange Q: How to sort by length and then alphabetically Assume I had the following Javascript array. How do you sort by length, then alphabetically? Assume the following array: var array = ["a", "aaa", "bb", "bbb", "c"]; When sorted it should produce: a, c, bb, aaa, bbb. Thank you in advance! A: Sort by length first then alphabetically using the || operator for more than one criteria. However, in your case, a simple sort will do. var array = ["a", "aaa", "bb", "bbb", "c"]; array.sort(function(a, b) { return a.length - b.length || a.localeCompare(b); }); console.log(array); Or var array =["c", "aa", "bb", "bbb", "b", "aaa", "a"].sort(); array.sort(function(a, b) { return a.length - b.length || 0; }); console.log(array);
Q: How to sort by length and then alphabetically Assume I had the following Javascript array. How do you sort by length, then alphabetically? Assume the following array: var array = ["a", "aaa", "bb", "bbb", "c"]; When sorted it should produce: a, c, bb, aaa, bbb. Thank you in advance! A: Sort by length first then alphabetically using the || operator for more than one criteria. However, in your case, a simple sort will do. var array = ["a", "aaa", "bb", "bbb", "c"]; array.sort(function(a, b) { return a.length - b.length || a.localeCompare(b); }); console.log(array); Or var array =["c", "aa", "bb", "bbb", "b", "aaa", "a"].sort(); array.sort(function(a, b) { return a.length - b.length || 0; }); console.log(array); A: You can first sort by length and then use localeCompare() to sort alphabetically. var array = ["a", "aaa", "bb", "bbb", "c"]; array.sort(function(a, b) { return a.length - b.length || a.localeCompare(b) }) console.log(array)
stackoverflow
{ "language": "en", "length": 148, "provenance": "stackexchange_0000F.jsonl.gz:868750", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44554122" }
5e132b302d9847b66fecc39609edb6071ac22450
Stackoverflow Stackexchange Q: node app instance name when running via pm2 cluster I have backend node app, that is run by pm2 in cluster mode. I'm running fixed 2 instances. Is there a way to identify instance name or number from within executed app? App name is "test", I would like to get from within the app "test 1" and "test 2" for given instance. Thanks! A: You'll need to use two environment variables set by pm2: * *process.env.pm_id is automatically set to the instance id (0, 1, ...). *process.env.name is set to the app name (in your case test).
Q: node app instance name when running via pm2 cluster I have backend node app, that is run by pm2 in cluster mode. I'm running fixed 2 instances. Is there a way to identify instance name or number from within executed app? App name is "test", I would like to get from within the app "test 1" and "test 2" for given instance. Thanks! A: You'll need to use two environment variables set by pm2: * *process.env.pm_id is automatically set to the instance id (0, 1, ...). *process.env.name is set to the app name (in your case test). A: While starting the pm2 set the name as: pm2 start app.js --name test
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:868819", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44554336" }
2aa9d522a631048389839f02aafe71366bcfc5eb
Stackoverflow Stackexchange Q: How to find the UID of a client connected to AF_INET socket? Is there some way or something similar like ucred for AF_UNIX in the case of AF_INET sockets (TCP in my case) for finding out the UID of the client connected to my socket? There's also /proc/net/tcp but it shows the UID of the creator of the socket and not of the connected client. Thank you.
Q: How to find the UID of a client connected to AF_INET socket? Is there some way or something similar like ucred for AF_UNIX in the case of AF_INET sockets (TCP in my case) for finding out the UID of the client connected to my socket? There's also /proc/net/tcp but it shows the UID of the creator of the socket and not of the connected client. Thank you.
stackoverflow
{ "language": "en", "length": 68, "provenance": "stackexchange_0000F.jsonl.gz:868825", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44554362" }
4dea8e581b81e44cc3fd015a29f7291f0a239c3b
Stackoverflow Stackexchange Q: Iterating over command-line argument pairs I have a more than 400 coordinates that I want to pass as an argument into a string, but i don't know how to pass the first argument as "lat" and second argument as "lng" and so on for the rest. Say I was passing in this ./test 1 2 3 4 I want my output to be coordinate: {lat: 1, lng: 2} coordinate: {lat: 3, lng: 4} This is what I have so far, but obviously this isn't how it's done. for i in $@ do echo "coordinate: {lat: $i, lng: $i}" done A: #!/usr/bin/env bash while (( "$#" >= 2 )); do echo "coordinate: {lat: $1, lng: $2}" shift 2 done Note that shift; shift is in many circles preferred over shift 2, as it works even there's only one argument left; shift 2 is safe above only because we're comparing $# to ensure that there will always be two or more arguments.
Q: Iterating over command-line argument pairs I have a more than 400 coordinates that I want to pass as an argument into a string, but i don't know how to pass the first argument as "lat" and second argument as "lng" and so on for the rest. Say I was passing in this ./test 1 2 3 4 I want my output to be coordinate: {lat: 1, lng: 2} coordinate: {lat: 3, lng: 4} This is what I have so far, but obviously this isn't how it's done. for i in $@ do echo "coordinate: {lat: $i, lng: $i}" done A: #!/usr/bin/env bash while (( "$#" >= 2 )); do echo "coordinate: {lat: $1, lng: $2}" shift 2 done Note that shift; shift is in many circles preferred over shift 2, as it works even there's only one argument left; shift 2 is safe above only because we're comparing $# to ensure that there will always be two or more arguments. A: You do not need a loop: printf "coordinate: {lat: %s, lng: %s}\n" "$@" And rename your script before putting in your path (something like /usr/local/bin), since test is a builtin function. A: You could use shift (but don't do it like this - see comments below): while [ -n "$1" ] do echo "{coordinate: {lat: $1, lng $2}" shift 2 done
stackoverflow
{ "language": "en", "length": 223, "provenance": "stackexchange_0000F.jsonl.gz:868838", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44554393" }
ae583141d352b5c27c558810da4c41e5c3bbac2e
Stackoverflow Stackexchange Q: JSDoc "Requires" appears twice? Is it normal for "Requires" to appears twice in the output documentation? If not, what is the correct way to document required modules so they appear only once? //Imports import * as C from "../support/constants.js"; import Dispatcher from "../support/Dispatcher.js"; /** * @description The <strong>TextField</strong> class creates instances of either clickable and animatable text or static text accessible via the <strong>"element"</strong> property. * @class * @requires constants * @requires Dispatcher * */ class TextField extends Dispatcher { /** * @param {string} label - Textual content set as the <strong>"textContent"</strong> property of the TextField's HTMLElement. * @param {string} id - DOMString representing the <strong>"id"</strong> property of the TextField's HTMLElement. * @param {string} href - The URL assigned to the <strong>"href"</strong> property of the TextField's HTMLElement. * */ constructor(label, id, href) { super(); this._label = label; this._id = id; this._href = href; this._init(); } ...
Q: JSDoc "Requires" appears twice? Is it normal for "Requires" to appears twice in the output documentation? If not, what is the correct way to document required modules so they appear only once? //Imports import * as C from "../support/constants.js"; import Dispatcher from "../support/Dispatcher.js"; /** * @description The <strong>TextField</strong> class creates instances of either clickable and animatable text or static text accessible via the <strong>"element"</strong> property. * @class * @requires constants * @requires Dispatcher * */ class TextField extends Dispatcher { /** * @param {string} label - Textual content set as the <strong>"textContent"</strong> property of the TextField's HTMLElement. * @param {string} id - DOMString representing the <strong>"id"</strong> property of the TextField's HTMLElement. * @param {string} href - The URL assigned to the <strong>"href"</strong> property of the TextField's HTMLElement. * */ constructor(label, id, href) { super(); this._label = label; this._id = id; this._href = href; this._init(); } ...
stackoverflow
{ "language": "en", "length": 147, "provenance": "stackexchange_0000F.jsonl.gz:868857", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44554445" }
720d4944f1ea2bb0a5b369d0a9c81ce3798a61fe
Stackoverflow Stackexchange Q: Roundtripping 3d objects with Unity and Clara.io? I've been looking at Clara.io for some collaborative 3D editing of game objects for a Unity game. From what I can see FBX is about the best format to use, but I'm having some trouble retaining textures to and from Clara.io and Unity. Anyone have any experience roundtripping between the two in such a way so as to preserve as much detail as possible like the textures aside from just the model itself?
Q: Roundtripping 3d objects with Unity and Clara.io? I've been looking at Clara.io for some collaborative 3D editing of game objects for a Unity game. From what I can see FBX is about the best format to use, but I'm having some trouble retaining textures to and from Clara.io and Unity. Anyone have any experience roundtripping between the two in such a way so as to preserve as much detail as possible like the textures aside from just the model itself?
stackoverflow
{ "language": "en", "length": 81, "provenance": "stackexchange_0000F.jsonl.gz:868868", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44554469" }
3be48c27b819c34b6441ad516d563bb7c39c7208
Stackoverflow Stackexchange Q: Style a Mapbox Popup's Pointer/Indicator I am styling some popups for a map displayed through Mapbox using Mapbox's GL JS. However, I cannot find in their documentation regarding the classes that are automatically assigned to the popups. Thus far, my CSS looks like this: .mapboxgl-Popup-content { color: #F3F3DD; background-color: #91785D; border-color: #91785D; max-width: 250px; box-shadow: 3px 3px 2px #8B5D33; font-family: 'Oswald'; } This yields these pretty little boxes: My issue is the white triangle at the very bottom that points to the marker. I want to change its color. I have tried a number of CSS classes to fix this. Including, but not limited to, .mapboxgl-popup, .mapboxgl-popup-anchor, .mapboxgl-popup-pointer, etc. I am not sure where to acquire the documentation I need to know what CSS class I should be using to change the color of this pesky triangle. A: The CSS class that you need to update is ".mapboxgl-popup-tip". If there is no any class like that in your CSS file, just create it and give the color what you want to "border-top-color: " attribute.
Q: Style a Mapbox Popup's Pointer/Indicator I am styling some popups for a map displayed through Mapbox using Mapbox's GL JS. However, I cannot find in their documentation regarding the classes that are automatically assigned to the popups. Thus far, my CSS looks like this: .mapboxgl-Popup-content { color: #F3F3DD; background-color: #91785D; border-color: #91785D; max-width: 250px; box-shadow: 3px 3px 2px #8B5D33; font-family: 'Oswald'; } This yields these pretty little boxes: My issue is the white triangle at the very bottom that points to the marker. I want to change its color. I have tried a number of CSS classes to fix this. Including, but not limited to, .mapboxgl-popup, .mapboxgl-popup-anchor, .mapboxgl-popup-pointer, etc. I am not sure where to acquire the documentation I need to know what CSS class I should be using to change the color of this pesky triangle. A: The CSS class that you need to update is ".mapboxgl-popup-tip". If there is no any class like that in your CSS file, just create it and give the color what you want to "border-top-color: " attribute. A: Here's what you need. It's not just one class because the tip can change position: .mapboxgl-popup-anchor-top .mapboxgl-popup-tip, .mapboxgl-popup-anchor-top-left .mapboxgl-popup-tip, .mapboxgl-popup-anchor-top-right .mapboxgl-popup-tip { border-bottom-color: #fff; } .mapboxgl-popup-anchor-bottom .mapboxgl-popup-tip, .mapboxgl-popup-anchor-bottom-left .mapboxgl-popup-tip, .mapboxgl-popup-anchor-bottom-right .mapboxgl-popup-tip { border-top-color: #fff; } .mapboxgl-popup-anchor-left .mapboxgl-popup-tip { border-right-color: #fff; } .mapboxgl-popup-anchor-right .mapboxgl-popup-tip { border-left-color: #fff; } A: I figured out why applying CSS doesn't affect the element (in this case, the tip). I did some debugging in Chrome with Inspect Element. It turns out my CSS was indeed being applied; however, it was being overridden from the MapBox stylesheet I applied in my index.html. At first, I thought that maybe if I reordered my stylesheets I could have my stylesheet be invoked after the MapBox stylesheet, then I'd be fine. This was not true. Inspect element still showed my CSS was being overridden. The solution was to add !important: border-top-color: black !important; This would override any previous styling done by MapBox. For more info see: * *What do the crossed style properties in Google Chrome devtools mean? *https://www.w3schools.com/css/css_important.asp A: .mapboxgl-popup-anchor-bottom > .mapboxgl-popup-tip { border-top-color: #f15b28; } i finally got it how this works. <Popup archor={'bottom'}, use .mapboxgl-popup-anchor-bottom plus .mapboxgl-popup-tip changing border color (top, bottom, left, right).
stackoverflow
{ "language": "en", "length": 373, "provenance": "stackexchange_0000F.jsonl.gz:868936", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44554692" }
a42c209d4b1598fd67829c3eec18e8dd8ac6172e
Stackoverflow Stackexchange Q: How to embed for loops in Kotlin string templates We can easily nest expression operators like if and when in Kotlin string templates: "List ${if (list.isEmpty()) "is empty" else "has ${list.size} items"}." But for or while are not expressions and can't be nested in template like this: "<ol>${for (item in list) "<li>$item"}</ol>" So I was looking for convinient ways to use loops inside large templates. A: The easiest out-of-the-box way I found so far is to replace loops with equivalent joinToString calls: "<ol>${list.joinToString("") { "<li>$it" }}</ol>" or """ <ol>${list.indices.joinToString("") { """ <li id="item${it + 1}">${list[it]}""" }} </ol>""".trimIndent() In the matter of preference, it's also possible to simulate loops with helper functions: inline fun <T> forEach(iterable: Iterable<T>, crossinline out: (v: T) -> String) = iterable.joinToString("") { out(it) } fun <T> forEachIndexed1(iterable: Iterable<T>, out: (i: Int, v: T) -> String): String { val sb = StringBuilder() iterable.forEachIndexed { i, it -> sb.append(out(i + 1, it)) } return sb.toString() } and use them like this: "<ol>${forEach(list) { "<li>$it" }}</ol>" or """ <ol>${forEachIndexed1(list) { i, item -> """ <li id="item$i">$item""" }} </ol>""".trimIndent()
Q: How to embed for loops in Kotlin string templates We can easily nest expression operators like if and when in Kotlin string templates: "List ${if (list.isEmpty()) "is empty" else "has ${list.size} items"}." But for or while are not expressions and can't be nested in template like this: "<ol>${for (item in list) "<li>$item"}</ol>" So I was looking for convinient ways to use loops inside large templates. A: The easiest out-of-the-box way I found so far is to replace loops with equivalent joinToString calls: "<ol>${list.joinToString("") { "<li>$it" }}</ol>" or """ <ol>${list.indices.joinToString("") { """ <li id="item${it + 1}">${list[it]}""" }} </ol>""".trimIndent() In the matter of preference, it's also possible to simulate loops with helper functions: inline fun <T> forEach(iterable: Iterable<T>, crossinline out: (v: T) -> String) = iterable.joinToString("") { out(it) } fun <T> forEachIndexed1(iterable: Iterable<T>, out: (i: Int, v: T) -> String): String { val sb = StringBuilder() iterable.forEachIndexed { i, it -> sb.append(out(i + 1, it)) } return sb.toString() } and use them like this: "<ol>${forEach(list) { "<li>$it" }}</ol>" or """ <ol>${forEachIndexed1(list) { i, item -> """ <li id="item$i">$item""" }} </ol>""".trimIndent() A: you can simply using joinToString instead. val s = """<ol> ${list.joinToString { "<li>$it</li>" }} </ol>"""; Output <ol> <li>one</li> <li>two</li> ... </ol>
stackoverflow
{ "language": "en", "length": 201, "provenance": "stackexchange_0000F.jsonl.gz:868966", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44554781" }
5aa0e72c06449cc647df0cb2dc9fbf4b00962969
Stackoverflow Stackexchange Q: Could not import cufflinks Problem I am trying to install both plotly and cufflinks. However I had a problem. The installation of both plotly and cufflinks were successful. Although, I can't import cufflinks. Below is a picture of the problem. It seems to be a dependency error: I tried manually downloading and installing "talib" but I keep getting failures. (Shown below). talib\common.c(240): fatal error C1083: Cannot open include file: 'ta_libc.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2 Any Ideas? I tried re-installing both modules and Anaconda. Nothing So far. Other infos: * *Cufflinks version: 0.11.0 *Plotly version: 2.0.10 *Anaconda version: 3-4.4.0 (But I don't think it have anything to do with it) *Python version: 3.6.1 A: try installing this version of cufflinks, it eliminated the error for me. pip install cufflinks==0.8.2
Q: Could not import cufflinks Problem I am trying to install both plotly and cufflinks. However I had a problem. The installation of both plotly and cufflinks were successful. Although, I can't import cufflinks. Below is a picture of the problem. It seems to be a dependency error: I tried manually downloading and installing "talib" but I keep getting failures. (Shown below). talib\common.c(240): fatal error C1083: Cannot open include file: 'ta_libc.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2 Any Ideas? I tried re-installing both modules and Anaconda. Nothing So far. Other infos: * *Cufflinks version: 0.11.0 *Plotly version: 2.0.10 *Anaconda version: 3-4.4.0 (But I don't think it have anything to do with it) *Python version: 3.6.1 A: try installing this version of cufflinks, it eliminated the error for me. pip install cufflinks==0.8.2 A: From this link: github.com/mrjbq7/ta-lib#troubleshooting Troubleshooting Sometimes installation will produce build errors like this: func.c:256:28: fatal error: ta-lib/ta_libc.h: No such file or directory compilation terminated. This typically means that it can't find the underlying TA-Lib library, a dependency which needs to be installed. On Windows, this could be caused by installing the 32-bit binary distribution of the underlying TA-Lib library, but trying to use it with 64-bit Python. Windows Download ta-lib-0.4.0-msvc.zip and unzip to C:\ta-lib This is a 32-bit release. If you want to use 64-bit Python, you will need to build a 64-bit version of the library. My Fix So, for windows, we need a 64-bit version of the library? Luckly I found a lot of modules built for 32 and 64 bits python: http://www.lfd.uci.edu/~gohlke/pythonlibs/ search for "ta-lib" and click on the module you need (In my case cp36 64 bits). Then, open the command prompt. Change to where you downloaded the file: cd path/to/file Type: pip install NameOfFile (in my case pip install TA_Lib‑0.4.10‑cp36‑cp36m‑win_amd64.whl ) Now the 64-bits Ta-Lib module should be installed in your machine. I tested the previous line of codes and it worked! Thanks for the help :) A: I have now removed all dependencies on talib. All studies are pure python based now and you should not face any of this errors.
stackoverflow
{ "language": "en", "length": 361, "provenance": "stackexchange_0000F.jsonl.gz:868984", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44554830" }
b6d37d422e07715a4f4efc4244708e0e5abd3158
Stackoverflow Stackexchange Q: Python pandas: flag duplicate rows I am using the following code to denote duplicate rows df['duplicate']=df.Column_A.duplicated() However, when I look at the df, I see the following: Column_A | duplicate AAA False ABC False ABC True I need row 2 to also be True, so that I can filter the row "duplicate" easily. How can I accomplish that? A: I imagine myself lost in the wilderness and all I have to survive is pd.factorize and np.bincount Please, don't accept this answer f, u = pd.factorize(df.Column_A.values) df.assign(duplicate=np.bincount(f)[f] > 1) Column_A duplicate 0 AAA False 1 ABC True 2 ABC True
Q: Python pandas: flag duplicate rows I am using the following code to denote duplicate rows df['duplicate']=df.Column_A.duplicated() However, when I look at the df, I see the following: Column_A | duplicate AAA False ABC False ABC True I need row 2 to also be True, so that I can filter the row "duplicate" easily. How can I accomplish that? A: I imagine myself lost in the wilderness and all I have to survive is pd.factorize and np.bincount Please, don't accept this answer f, u = pd.factorize(df.Column_A.values) df.assign(duplicate=np.bincount(f)[f] > 1) Column_A duplicate 0 AAA False 1 ABC True 2 ABC True A: As per the docs use the keep argument and set as False. As you can see it defaults to first. import pandas as pd df = pd.DataFrame({'Column_A': ['AAA', 'AAB', 'AAB', 'AAC']}) df['duplicate'] = df.duplicated(keep=False) print(df) Column_A duplicate 0 'AAA' False 1 'AAB' True 2 'AAB' True 3 'AAC' False
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:868991", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44554848" }
9c5a075c64f6565b33d8e7b784f8c9fed5b29c6e
Stackoverflow Stackexchange Q: In a setup.py involving Cython, if install_requires, then how can from library import something? This doesn't make sense to me. How can I use the setup.py to install Cython and then also use the setup.py to compile a library proxy? import sys, imp, os, glob from setuptools import setup from Cython.Build import cythonize # this isn't installed yet setup( name='mylib', version='1.0', package_dir={'mylib': 'mylib', 'mylib.tests': 'tests'}, packages=['mylib', 'mylib.tests'], ext_modules = cythonize("mylib_proxy.pyx"), #how can we call cythonize here? install_requires=['cython'], test_suite='tests', ) Later: python setup.py build Traceback (most recent call last): File "setup.py", line 3, in <module> from Cython.Build import cythonize ImportError: No module named Cython.Build It's because cython isn't installed yet. What's odd is that a great many projects are written this way. A quick github search reveals as much: https://github.com/search?utf8=%E2%9C%93&q=install_requires+cython&type=Code A: One solution to this is to not make Cython a build requirement, and instead distribute the Cython generated C files with your package. I'm sure there is a simpler example somewhere, but this is what pandas does - it conditionally imports Cython, and if not present can be built from the c files. https://github.com/pandas-dev/pandas/blob/3ff845b4e81d4dde403c29908f5a9bbfe4a87788/setup.py#L433 Edit: The doc link from @danny has an easier to follow example. http://docs.cython.org/en/latest/src/reference/compilation.html#distributing-cython-modules
Q: In a setup.py involving Cython, if install_requires, then how can from library import something? This doesn't make sense to me. How can I use the setup.py to install Cython and then also use the setup.py to compile a library proxy? import sys, imp, os, glob from setuptools import setup from Cython.Build import cythonize # this isn't installed yet setup( name='mylib', version='1.0', package_dir={'mylib': 'mylib', 'mylib.tests': 'tests'}, packages=['mylib', 'mylib.tests'], ext_modules = cythonize("mylib_proxy.pyx"), #how can we call cythonize here? install_requires=['cython'], test_suite='tests', ) Later: python setup.py build Traceback (most recent call last): File "setup.py", line 3, in <module> from Cython.Build import cythonize ImportError: No module named Cython.Build It's because cython isn't installed yet. What's odd is that a great many projects are written this way. A quick github search reveals as much: https://github.com/search?utf8=%E2%9C%93&q=install_requires+cython&type=Code A: One solution to this is to not make Cython a build requirement, and instead distribute the Cython generated C files with your package. I'm sure there is a simpler example somewhere, but this is what pandas does - it conditionally imports Cython, and if not present can be built from the c files. https://github.com/pandas-dev/pandas/blob/3ff845b4e81d4dde403c29908f5a9bbfe4a87788/setup.py#L433 Edit: The doc link from @danny has an easier to follow example. http://docs.cython.org/en/latest/src/reference/compilation.html#distributing-cython-modules A: When you use setuptool, you should add cython to setup_requires (and also to install_requires if cython is used by installation), i.e. # don't import cython, it isn't yet there from setuptools import setup, Extension # use Extension, rather than cythonize (it is not yet available) cy_extension = Extension(name="mylib_proxy", sources=["mylib_proxy.pyx"]) setup( name='mylib', ... ext_modules = [cy_extension], setup_requires=["cython"], ... ) Cython isn't imported (it is not yet available when setup.pystarts), but setuptools.Extension is used instead of cythonize to add cython-extension to the setup. It should work now. The reason: setuptools will try to import cython, after setup_requires are fulfilled: ... try: # Attempt to use Cython for building extensions, if available from Cython.Distutils.build_ext import build_ext as _build_ext # Additionally, assert that the compiler module will load # also. Ref #1229. __import__('Cython.Compiler.Main') except ImportError: _build_ext = _du_build_ext ... It becomes more complicated, if your Cython-extension uses numpy, but also this is possible - see this SO post. A: As I understand it, this is where PEP 518 comes in - also see some clarifications by one of its authors. The idea is that you add yet another file to your Python project / package: pyproject.toml. It is supposed to contain information on build environment dependencies (among other stuff, long term). pip (or just any other package manager) could look into this file and before running setup.py (or any other build script) install the required build environment. A pyproject.toml could therefore look like this: [build-system] requires = ["setuptools", "wheel", "Cython"] It is a fairly recent development and, as of yet (January 2019), it is not finalized / approved by the Python community, though (limited) support was added to pip in May 2017 / the 10.0 release. A: It doesn't make sense in general. It is, as you suspect, an attempt to use something that (possibly) has yet to be installed. If tested on a system that already has the dependency installed, you might not notice this defect. But run it on a system where your dependency is absent, and you will certainly notice. There is another setup() keyword argument, setup_requires, that can appear to be parallel in form and use to install_requires, but this is an illusion. Whereas install_requires triggers a lovely ballet of automatic installation in environments that lack the dependencies it names, setup_requires is more documentation than automation. It won't auto-install, and certainly not magically jump back in time to auto-install modules that have already been called for in import statements. There's more on this at the setuptools docs, but the quick answer is that you're right to be confused by a module that is trying to auto-install its own setup pre-requisites. For a practical workaround, try installing cython separately, and then run this setup. While it won't fix the metaphysical illusions of this setup script, it will resolve the requirements and let you move on.
stackoverflow
{ "language": "en", "length": 673, "provenance": "stackexchange_0000F.jsonl.gz:869009", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44554882" }
281367281897b340ba574a66d925de54bbd4b8cf
Stackoverflow Stackexchange Q: Is there a way to stop Google Chrome from showing most visited sites on a blank tab? Whenever I open a new tab in Google Chrome I see the Google search bar plus 8 thumbnails of recently visited (or most visited) sites. I never click on the thumbnails and find them to be annoying. Is there anyway to disable this in Chrome? I can think of a hacky workaround like creating a blank page someplace and setting that to be the new tab page, but there must be a better way. Any ideas? A: Since nobody answered I thought I would post and answer to my question: Use the Empty New Tab Page extension for a new blank tab instead of the default new tab. There are also some redirect extensions such as Momentum, which loads a different full screen image each day.
Q: Is there a way to stop Google Chrome from showing most visited sites on a blank tab? Whenever I open a new tab in Google Chrome I see the Google search bar plus 8 thumbnails of recently visited (or most visited) sites. I never click on the thumbnails and find them to be annoying. Is there anyway to disable this in Chrome? I can think of a hacky workaround like creating a blank page someplace and setting that to be the new tab page, but there must be a better way. Any ideas? A: Since nobody answered I thought I would post and answer to my question: Use the Empty New Tab Page extension for a new blank tab instead of the default new tab. There are also some redirect extensions such as Momentum, which loads a different full screen image each day. A: type chrome://flags then Disable "Top Sites from Site Engagement" A: Chrome allows extensions to run on chrome:// urls so one such possible future solution is if AdBlock explicitly requests the permission to run on chrome://newtab then you can just block the div with id most-visited. But currently AdBlock does not request this permission. You could edit the manifest of AdBlock manually to include this permission or suggest it as a future feature. A: The default new tap page's url is chrome-search://local-ntp/local-ntp.html. You can press F12 to check it. It's a local resource located in C:\Program Files (x86)\Google\Chrome\Application\{Version}\resources.pak or C:\Users\%username%\AppData\Local\Google\Chrome\Application\{Version}\resources.pak Open it with a HEX editor, search text cur.style.opacity = 1.0 , and replace it with cur.style.opacity = 0.0 Tested on Chrome 77.0.3865.90 .
stackoverflow
{ "language": "en", "length": 268, "provenance": "stackexchange_0000F.jsonl.gz:869045", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44554977" }
a32e272c50868b871848d39e2d2701608844e406
Stackoverflow Stackexchange Q: asp-validation-summary not showing, field validation working Im using dotnet core MVC and am having issues with asp-validation-summary. Validation is working at a field level using asp-validation-for however I am not getting anything showing up in the asp-validation-summary. <div asp-validation-summary="ModelOnly" class="text-danger"></div> I have also tried <div asp-validation-summary="All" class="text-danger"></div> Any ideas what I am missing. Done loads of searching and cant see solution to my problem Thanks A: Also you can include jquery script for validation tag-helper <form asp-controller="home" asp-action="CreatePoll" method="post" class="mt-3"> <div class="validation" asp-validation-summary="All"></div> <div class="form-group"> <label asp-for="Name">Name of the Poll:</label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <button type="submit" class="btn btn-primary">Create</button> </form> @section scripts{ <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script> <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script> }
Q: asp-validation-summary not showing, field validation working Im using dotnet core MVC and am having issues with asp-validation-summary. Validation is working at a field level using asp-validation-for however I am not getting anything showing up in the asp-validation-summary. <div asp-validation-summary="ModelOnly" class="text-danger"></div> I have also tried <div asp-validation-summary="All" class="text-danger"></div> Any ideas what I am missing. Done loads of searching and cant see solution to my problem Thanks A: Also you can include jquery script for validation tag-helper <form asp-controller="home" asp-action="CreatePoll" method="post" class="mt-3"> <div class="validation" asp-validation-summary="All"></div> <div class="form-group"> <label asp-for="Name">Name of the Poll:</label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <button type="submit" class="btn btn-primary">Create</button> </form> @section scripts{ <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script> <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script> } A: You should add this for each your model field with asp-validation-summary="ModelOnly" and set @Html.ValidationSummary() before html form //Validation Summary Parameters public static MvcHtmlString ValidationSummary( this HtmlHelper htmlHelper, bool excludePropertyErrors, // to include or exclude your field validation errors string message, object htmlAttributes, string headingTag ) @Html.ValidationSummary() // use this with your desired parameters <form> ...... // your inputs <input asp-for="YourField" class="form-control" /> <span asp-validation-for="YourField" class="text-danger"></span> </form> A: Display field level error messages using ValidationSummary: By default, ValidationSummary filters out field level error messages. If you want to display field level error messages as a summary then specify excludePropertyErrors = false. Example: ValidationSummary to display field errors @Html.ValidationSummary(false, "", new { @class = "text-danger" }) So now, in the view will display error messages as a summary at the top. Please make sure that you don't have a ValidationMessageFor method for each of the fields. official doc:https://msdn.microsoft.com/en-us/library/system.web.mvc.html.validationextensions.validationsummary(v=vs.118).aspx Hope it will be helpful Thanks Karthik A: I had the same issue, field validation worked well, can display xx is required below the input window. But the validation-summary didn't show up. At first, I have code below in my cshtml file, <div class="row"> <div asp-validation-summary="ModelOnly"></div> @Html.ValidationSummary(false, "", new { @class = "text-danger" }) </div> and I had code below in my controller, ModelState.AddModelError("key", "validation summary error"); return View(rdl); then only @Html.ValidationSummary() worked, and asp-validation-summary didn't show up(if it displayed message, it should have black font) Then I tried asp-validation-summary="All", it worked. The difference between ALL and ModelOnly is ModelOnly will only display the invalid message for the model. So I use ModelState.AddModelError("", "validation summary error."); in my Controller to make the <div asp-validation-summary="ModelOnly"></div> display error message. I only know it can make it display correctly, but I don't know why...
stackoverflow
{ "language": "en", "length": 399, "provenance": "stackexchange_0000F.jsonl.gz:869078", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555080" }
ee765a1d73b2ff2d9871a6903fe358db84b1e4ee
Stackoverflow Stackexchange Q: Subquery support in datomic Does datomic support subqueries or can those be simulated within a query? That would essentially be a :find within another :find. I'm trying to perform analytical transformations of data in the query/DB itself rather than in the application. A: Yes, you can issue a 'subquery' in Datomic. An example is provided here. It's also worth noting that because the work of query happens in your peer (assuming you're using the Peer API), there is not the same "n+1 problem" penalty for issuing two separate queries as you would have with a traditional RDB. So in addition to the sub-query approach, you could also issue the 'inner' query first, then pass the results from it as parameters to the 'outer' query. -Marshall
Q: Subquery support in datomic Does datomic support subqueries or can those be simulated within a query? That would essentially be a :find within another :find. I'm trying to perform analytical transformations of data in the query/DB itself rather than in the application. A: Yes, you can issue a 'subquery' in Datomic. An example is provided here. It's also worth noting that because the work of query happens in your peer (assuming you're using the Peer API), there is not the same "n+1 problem" penalty for issuing two separate queries as you would have with a traditional RDB. So in addition to the sub-query approach, you could also issue the 'inner' query first, then pass the results from it as parameters to the 'outer' query. -Marshall
stackoverflow
{ "language": "en", "length": 126, "provenance": "stackexchange_0000F.jsonl.gz:869156", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555326" }
f5f99352b89bc75b3adb764aff4da63dc7a6fe36
Stackoverflow Stackexchange Q: Text truncated on start when longer than TextInput size Trying to use the Android TextInput component, but the text gets cut off in start when text is longer than the component size. Required state Actual state Is there way I can get the text rendered from start or set the cursor at beginning. And only set the cursor to end when this component is focussed or selected ?
Q: Text truncated on start when longer than TextInput size Trying to use the Android TextInput component, but the text gets cut off in start when text is longer than the component size. Required state Actual state Is there way I can get the text rendered from start or set the cursor at beginning. And only set the cursor to end when this component is focussed or selected ?
stackoverflow
{ "language": "en", "length": 69, "provenance": "stackexchange_0000F.jsonl.gz:869162", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555342" }
bbe63572be23be15996cbc6b5498f6c82c42efd5
Stackoverflow Stackexchange Q: How to return a dynamic struct array from a function in SystemVerilog I am having issues figuring out the syntax for returning a dynamic struct array from a function. I have the following small example: `timescale 1ns/10ps typedef struct{ string Name; int Age; } PersonType; function PersonType A [] getPeopleInfo(); automatic string Name [50];//Max of 50 people automatic int Age [50]; PersonType A []; /*Turns out we only have 3 people->this may change at runtime*/ Name[0]="Jon";Age[0]=25; Name[1]="Ana";Age[1]=32; Name[2]="Ali";Age[2]=19; A=new[3];/*This size may change at runtime*/ for(int idx=0;idx<3;idx++) begin A[idx].Name=Name[idx]; A[idx].Age=Age[idx]; end return A; endfunction // getPeopleInfo module Test(); PersonType A []; initial begin A=getPeopleInfo(); for(int idx=0;idx<A.size();idx++) begin $display(A[idx].Name); $display(A[idx].Age); end end endmodule // Test When I modify the function so that it passes the dynamic struct array as argument ie: void getPeopleInfo(output PersonType A []); Then it works fine. Is it possible to return a dynamic struct array from a function?, if so what is the correct syntax?. A: You need a typedef when you want a function to return an unpacked type. typedef PersonType PersonType_da_t[]; function automatic PersonType_da_t getPeopleInfo();
Q: How to return a dynamic struct array from a function in SystemVerilog I am having issues figuring out the syntax for returning a dynamic struct array from a function. I have the following small example: `timescale 1ns/10ps typedef struct{ string Name; int Age; } PersonType; function PersonType A [] getPeopleInfo(); automatic string Name [50];//Max of 50 people automatic int Age [50]; PersonType A []; /*Turns out we only have 3 people->this may change at runtime*/ Name[0]="Jon";Age[0]=25; Name[1]="Ana";Age[1]=32; Name[2]="Ali";Age[2]=19; A=new[3];/*This size may change at runtime*/ for(int idx=0;idx<3;idx++) begin A[idx].Name=Name[idx]; A[idx].Age=Age[idx]; end return A; endfunction // getPeopleInfo module Test(); PersonType A []; initial begin A=getPeopleInfo(); for(int idx=0;idx<A.size();idx++) begin $display(A[idx].Name); $display(A[idx].Age); end end endmodule // Test When I modify the function so that it passes the dynamic struct array as argument ie: void getPeopleInfo(output PersonType A []); Then it works fine. Is it possible to return a dynamic struct array from a function?, if so what is the correct syntax?. A: You need a typedef when you want a function to return an unpacked type. typedef PersonType PersonType_da_t[]; function automatic PersonType_da_t getPeopleInfo();
stackoverflow
{ "language": "en", "length": 180, "provenance": "stackexchange_0000F.jsonl.gz:869163", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555343" }
49c129d4d1ae2622cad677ff251792270003ca0b
Stackoverflow Stackexchange Q: How Can I Change an ItemsPanelTemplate in Code Behind? <ItemsControl> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Grid /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> If I want to change the ItemsPanelTemplate from the default (StackPanel) to a Grid, I do the above in XAML. How could I achieve the same thing in code? I read this here but couldn't figure it out. A: I'd prefer to do this in the default style of the custom control inside Generic.xaml, but if you want a pure C# way, here is how it can be done - private void ApplyGridAsItemsPanel() { MyItemsControl.ItemsPanel = ParseItemsPanelTemplate(typeof(Grid)); ItemsPanelTemplate ParseItemsPanelTemplate(Type panelType) { var itemsPanelTemplateXaml = $@"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'> <{panelType.Name} /> </ItemsPanelTemplate>"; return (ItemsPanelTemplate)XamlReader.Load(itemsPanelTemplateXaml); } }
Q: How Can I Change an ItemsPanelTemplate in Code Behind? <ItemsControl> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Grid /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> If I want to change the ItemsPanelTemplate from the default (StackPanel) to a Grid, I do the above in XAML. How could I achieve the same thing in code? I read this here but couldn't figure it out. A: I'd prefer to do this in the default style of the custom control inside Generic.xaml, but if you want a pure C# way, here is how it can be done - private void ApplyGridAsItemsPanel() { MyItemsControl.ItemsPanel = ParseItemsPanelTemplate(typeof(Grid)); ItemsPanelTemplate ParseItemsPanelTemplate(Type panelType) { var itemsPanelTemplateXaml = $@"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'> <{panelType.Name} /> </ItemsPanelTemplate>"; return (ItemsPanelTemplate)XamlReader.Load(itemsPanelTemplateXaml); } }
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:869194", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555462" }
7d0693720eeb2efef1fd3f3af7a2293a28ab849d
Stackoverflow Stackexchange Q: Python multiprocessing tool vs Py(Spark) A newbie question, as I get increasingly confused with pyspark. I want to scale an existing python data preprocessing and data analysis pipeline. I realize if I partition my data with pyspark, I can't treat each partition as a standalone pandas data frame anymore, and need to learn to manipulate with pyspark.sql row/column functions, and change a lot of existing code, plus I am bound to spark mllib libraries and can't take full advantage of more mature scikit-learn package. Then why would I ever need to use Spark if I can use multiprocessing tools for cluster computing and parallelize tasks on existing dataframe? A: True, Spark does have the limitations you have mentioned, that is you are bounded in the functional spark world (spark mllib, dataframes etc). However, what it provides vs other multiprocessing tools/libraries is the automatic distribution, partition and rescaling of parallel tasks. Scaling and scheduling spark code becomes an easier task than having to program your custom multiprocessing code to respond to larger amounts of data + computations.
Q: Python multiprocessing tool vs Py(Spark) A newbie question, as I get increasingly confused with pyspark. I want to scale an existing python data preprocessing and data analysis pipeline. I realize if I partition my data with pyspark, I can't treat each partition as a standalone pandas data frame anymore, and need to learn to manipulate with pyspark.sql row/column functions, and change a lot of existing code, plus I am bound to spark mllib libraries and can't take full advantage of more mature scikit-learn package. Then why would I ever need to use Spark if I can use multiprocessing tools for cluster computing and parallelize tasks on existing dataframe? A: True, Spark does have the limitations you have mentioned, that is you are bounded in the functional spark world (spark mllib, dataframes etc). However, what it provides vs other multiprocessing tools/libraries is the automatic distribution, partition and rescaling of parallel tasks. Scaling and scheduling spark code becomes an easier task than having to program your custom multiprocessing code to respond to larger amounts of data + computations.
stackoverflow
{ "language": "en", "length": 177, "provenance": "stackexchange_0000F.jsonl.gz:869202", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555485" }
1079fc54f9c0220bd9867173f284b1c3e291abdf
Stackoverflow Stackexchange Q: Flutter - The screen is not scrolling I inserted 6 cards, however it is not possible to scroll the screen. According to the image below, a red stripe appears in the footer, and the screen does not scroll. What is missing to be able to scroll the screen? main.dart import 'package:flutter/material.dart'; void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: "Myapp", home: new HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) => new Scaffold( appBar: new AppBar( backgroundColor: new Color(0xFF26C6DA), ), body: new Column( children: <Widget>[ new Card( child: new Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const ListTile( leading: const Icon(Icons.album), title: const Text('The Enchanted Nightingale'), subtitle: const Text('Music by Julie Gable. Lyrics by Sidney Stein.'), ), ], ), ), ... ... ... ], ) ); } A: you have to put it on ListView.builder ListView.builder( itemBuilder: (BuildContext context, int index){ final item = yourItemLists[index]; new Card( child: new Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const ListTile( leading: const Icon(Icons.album), title: const Text('The Enchanted Nightingale'), subtitle: const Text('Music by Julie Gable. Lyrics by Sidney Stein.'), ), ], ), ); }, itemCount: yourItemLists.length, );
Q: Flutter - The screen is not scrolling I inserted 6 cards, however it is not possible to scroll the screen. According to the image below, a red stripe appears in the footer, and the screen does not scroll. What is missing to be able to scroll the screen? main.dart import 'package:flutter/material.dart'; void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: "Myapp", home: new HomePage(), ); } } class HomePage extends StatelessWidget { @override Widget build(BuildContext context) => new Scaffold( appBar: new AppBar( backgroundColor: new Color(0xFF26C6DA), ), body: new Column( children: <Widget>[ new Card( child: new Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const ListTile( leading: const Icon(Icons.album), title: const Text('The Enchanted Nightingale'), subtitle: const Text('Music by Julie Gable. Lyrics by Sidney Stein.'), ), ], ), ), ... ... ... ], ) ); } A: you have to put it on ListView.builder ListView.builder( itemBuilder: (BuildContext context, int index){ final item = yourItemLists[index]; new Card( child: new Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const ListTile( leading: const Icon(Icons.album), title: const Text('The Enchanted Nightingale'), subtitle: const Text('Music by Julie Gable. Lyrics by Sidney Stein.'), ), ], ), ); }, itemCount: yourItemLists.length, ); A: Columns don't scroll. Try replacing your outer Column with a ListView. You may need to put shrinkWrap: true on it. A: A column in a column make the layout impossible to calculate without setting height. The second column is useless since it contains only one element, try to put the ListTile directly as the body of the Card. A: This might do the trick, worked like charm for me: shrinkWrap: true, physics: ClampingScrollPhysics(), A: To make a column scrollable, simply wrap it in a SingleChildScrollView. A: You should use ListView.builder in place of the inner column (as I suggested above that columns are not scrollable). Set shrinkWrap: true, and physics: ClampingScrollPhysics() inside ListView.builder. Just using shrinkWrap: true didn't solve my problem. But setting physics to ClampingScrollPhysics() started to make it scroll. A: There are generally two ways to make a screen scrollable. One is by using Column, and the other is by using ListView. Use Column (wrapped in SingleChildScrollView): SingleChildScrollView( // Don't forget this. child: Column( children: [ Text('First'), //... other children Text('Last'), ], ), ) Use ListView: ListView( children: [ Text('First'), //... other children Text('Last'), ], ) This approach is simpler to use, but you lose features like crossAxisAlignment. For this case, you can wrap your children widget inside Align and set alignment property. A: I needed placing SingleChildScrollView inside Column. The SingleChildScrollView also needed Column as a child, but the scroll wasn't working for me in that case. The solution was to wrap the SingleChildScrollView with Expanded. So here's how it looked: Column( children: <Widget>[ MyFirstWidget(), Expanded( child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ // Scrollable content. ], ), ), ), ], ), A: You can also Wrap the parent Column in a Container and then wrap the Container with the SingleChildscrollView widget. (This solved my issue). A: Just Add physics: ClampingScrollPhysics(),
stackoverflow
{ "language": "en", "length": 504, "provenance": "stackexchange_0000F.jsonl.gz:869251", "question_score": "39", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555629" }
6bbc0770b69f01db48f740020eaf43acbf38bce6
Stackoverflow Stackexchange Q: Abstract methods in typescript mixins I want a Typescript Mixin to have an abstract method that's implemented by the mixed-into class. Something like this. class MyBase { } type Constructor<T = {}> = new (...args: any[]) => T; function Mixin<TBase extends Constructor<MyBase>>(Base: TBase) { return class extends Base { baseFunc(s: string) {}; doA() { this.baseFunc("A"); } } }; class Foo extends Mixin(MyBase) { constructor() { super(); } baseFunc(s: string) { document.write("Foo "+ s +"... ") } }; Now, this works, but I'd really like to make baseFunc in the mixin be abstract to ensure that it's implemented in Foo. Is there any way of doing this, as abstract baseFunc(s:string); says I must have an abstract class, which isn't allowed for mixins... A: Anonymous class can not be abstract, but you still can declare local mixin class which is abstract like this: class MyBase { } type Constructor<T = {}> = new (...args: any[]) => T; function Mixin(Base: Constructor<MyBase>) { abstract class AbstractBase extends Base { abstract baseFunc(s: string); doA() { this.baseFunc("A"); } } return AbstractBase; }; class Foo extends Mixin(MyBase) { constructor() { super(); } baseFunc(s: string) { document.write("Foo "+ s +"... ") } };
Q: Abstract methods in typescript mixins I want a Typescript Mixin to have an abstract method that's implemented by the mixed-into class. Something like this. class MyBase { } type Constructor<T = {}> = new (...args: any[]) => T; function Mixin<TBase extends Constructor<MyBase>>(Base: TBase) { return class extends Base { baseFunc(s: string) {}; doA() { this.baseFunc("A"); } } }; class Foo extends Mixin(MyBase) { constructor() { super(); } baseFunc(s: string) { document.write("Foo "+ s +"... ") } }; Now, this works, but I'd really like to make baseFunc in the mixin be abstract to ensure that it's implemented in Foo. Is there any way of doing this, as abstract baseFunc(s:string); says I must have an abstract class, which isn't allowed for mixins... A: Anonymous class can not be abstract, but you still can declare local mixin class which is abstract like this: class MyBase { } type Constructor<T = {}> = new (...args: any[]) => T; function Mixin(Base: Constructor<MyBase>) { abstract class AbstractBase extends Base { abstract baseFunc(s: string); doA() { this.baseFunc("A"); } } return AbstractBase; }; class Foo extends Mixin(MyBase) { constructor() { super(); } baseFunc(s: string) { document.write("Foo "+ s +"... ") } };
stackoverflow
{ "language": "en", "length": 196, "provenance": "stackexchange_0000F.jsonl.gz:869254", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555639" }
179e1d509ebb28ebded6f198105a568c8d807b12
Stackoverflow Stackexchange Q: C# using statement inside #if DEBUG but not ship assembly I have a feature that I only want to happen on Debug, but do not want to ship the dll's that this feature requires. Is that possible to do? I have: #if DEBUG using MyAssembly; #endif Of course MyAssembly is being referenced by the project. I would like MyAssembly.dll to not be shipped on a release mode. Can that be achieved? Will using Conditional("DEBUG") help in this regard? A: References that aren't required are usually removed automatically by the compiler, however: you can be more explicit by changing the csproj to include a Condition on the PropertyGroup. Something like: <PropertyGroup Condition="'$(Configuration)' == 'Debug'"> <Reference Include="YourReference" /> </PropertyGroup> (it could also be a <PackageReference> etc)
Q: C# using statement inside #if DEBUG but not ship assembly I have a feature that I only want to happen on Debug, but do not want to ship the dll's that this feature requires. Is that possible to do? I have: #if DEBUG using MyAssembly; #endif Of course MyAssembly is being referenced by the project. I would like MyAssembly.dll to not be shipped on a release mode. Can that be achieved? Will using Conditional("DEBUG") help in this regard? A: References that aren't required are usually removed automatically by the compiler, however: you can be more explicit by changing the csproj to include a Condition on the PropertyGroup. Something like: <PropertyGroup Condition="'$(Configuration)' == 'Debug'"> <Reference Include="YourReference" /> </PropertyGroup> (it could also be a <PackageReference> etc) A: It's perfectly fine to put a using directive in an #if DEBUG section, and it will remove that directive when compiled for debug. However, that's only part of the story; it won't accomplish your objective by itself. The Solution Explorer in Visual Studio also has a References section. You would need to remove the reference for the assembly, as well, or it will still be included when you build. I don't recall anything in the Visual Studio user interface that will let you do this, but I expect it should be possible somehow if you manually edit the Project file (it's just an MSBuild file). Personally, I try very hard to avoid doing things that require manual edits to the project files. Visual Studio wants to be able to own these files, and you can end up creating conflicts, where you and Visual Studio overwrite each other's changes.
stackoverflow
{ "language": "en", "length": 274, "provenance": "stackexchange_0000F.jsonl.gz:869258", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555646" }
39d02b9dbd8cdb8bd25a92085756f9b87516b2ac
Stackoverflow Stackexchange Q: mdInput messages show animation called on invalid messages element: Not sure why I'm getting the following message. Has anyone else encountered this in AngularJS/Angular Material? What am I doing wrong? The message itself seems a little vague. mdInput messages show animation called on invalid messages element: md-input-container.md-block.md-icon-right.md-default-theme.md-input-has-value A: Old question, but just in case anyone bumps into this, you need to supply an error message for the input field. The error is saying that it can't animate the error message into view because the messages element is missing. In your md-input-container include the ng-messages element to handle the error. For example, if you have a form called myFrm with a required email address input named email, your code would be something like this: <form name="myFrm"> <md-input-container> <label>Email Address</label> <input type="email" ng-model="myFrm.email" name="email" required/> <div ng-messages="myFrm.email.$error"> <div ng-message="required">Email address is required</div> </div> </md-input-container> <!-- Other form elements.... --> </form>
Q: mdInput messages show animation called on invalid messages element: Not sure why I'm getting the following message. Has anyone else encountered this in AngularJS/Angular Material? What am I doing wrong? The message itself seems a little vague. mdInput messages show animation called on invalid messages element: md-input-container.md-block.md-icon-right.md-default-theme.md-input-has-value A: Old question, but just in case anyone bumps into this, you need to supply an error message for the input field. The error is saying that it can't animate the error message into view because the messages element is missing. In your md-input-container include the ng-messages element to handle the error. For example, if you have a form called myFrm with a required email address input named email, your code would be something like this: <form name="myFrm"> <md-input-container> <label>Email Address</label> <input type="email" ng-model="myFrm.email" name="email" required/> <div ng-messages="myFrm.email.$error"> <div ng-message="required">Email address is required</div> </div> </md-input-container> <!-- Other form elements.... --> </form>
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:869303", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555801" }
a7642daf4cc1dfbf17dea1489a7bec9d00493b12
Stackoverflow Stackexchange Q: How to print out the minibatchData's value? minibatch_size = 5 data = reader.next_minibatch(minibatch_size, input_map={ # fetch minibatch x: reader.streams.query, y: reader.streams.slot_labels }) evaluator = C.eval.Evaluator(loss, progress_printer) evaluator.test_minibatch(data) print("labels=", data[y].as_sequences()) I got an error for data[y].as_sequences() saying: raise ValueError('cannot convert sparse value to sequences ' ValueError: cannot convert sparse value to sequences without the corresponding variable How do I fix this? What is a variable? What should I put? A: data[y].as_sequences(variable=y) should do the trick, but I wouldn't recommend it. On larger datasets as_sequences and asarray quickly cause out of memory exception to be thrown. I ended up using this: true_labels = cntk.ops.argmax(labels_input).eval(minibatch[labels_input]).astype(int)
Q: How to print out the minibatchData's value? minibatch_size = 5 data = reader.next_minibatch(minibatch_size, input_map={ # fetch minibatch x: reader.streams.query, y: reader.streams.slot_labels }) evaluator = C.eval.Evaluator(loss, progress_printer) evaluator.test_minibatch(data) print("labels=", data[y].as_sequences()) I got an error for data[y].as_sequences() saying: raise ValueError('cannot convert sparse value to sequences ' ValueError: cannot convert sparse value to sequences without the corresponding variable How do I fix this? What is a variable? What should I put? A: data[y].as_sequences(variable=y) should do the trick, but I wouldn't recommend it. On larger datasets as_sequences and asarray quickly cause out of memory exception to be thrown. I ended up using this: true_labels = cntk.ops.argmax(labels_input).eval(minibatch[labels_input]).astype(int)
stackoverflow
{ "language": "en", "length": 103, "provenance": "stackexchange_0000F.jsonl.gz:869307", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555805" }
60657d18c7722437561d1bef416e3f56bb6ca89f
Stackoverflow Stackexchange Q: Get the request body in custom filter java Play framework I've read https://www.playframework.com/documentation/2.5.x/ScalaHttpFilters#more-powerful-filters, but I still don't understand how to access the request body inside the filter chain. I'm trying to make an accumulator but I'm not sure how to access the nextFilter in the apply method of EssentialAction. If anyone knows how to actually access the request body inside the filter chain let me know! I'm working in java A: In order to parse the body of the request, you can use Action composition in your filters. You must actually stream / parse the body in the filter manually, and then let the framework parse it again as it passes to your controller. Here is a good article on how this can be achieved. https://www.javacodegeeks.com/2013/02/understanding-the-play-filter-api.html
Q: Get the request body in custom filter java Play framework I've read https://www.playframework.com/documentation/2.5.x/ScalaHttpFilters#more-powerful-filters, but I still don't understand how to access the request body inside the filter chain. I'm trying to make an accumulator but I'm not sure how to access the nextFilter in the apply method of EssentialAction. If anyone knows how to actually access the request body inside the filter chain let me know! I'm working in java A: In order to parse the body of the request, you can use Action composition in your filters. You must actually stream / parse the body in the filter manually, and then let the framework parse it again as it passes to your controller. Here is a good article on how this can be achieved. https://www.javacodegeeks.com/2013/02/understanding-the-play-filter-api.html
stackoverflow
{ "language": "en", "length": 127, "provenance": "stackexchange_0000F.jsonl.gz:869310", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555816" }
3fef4694718950a4f12db4891148c5351f548f02
Stackoverflow Stackexchange Q: How to replace text at bookmark in a Word document I am trying to programmatically replace text at a bookmark in a Word document. I can find the text at the bookmark (I am using a test document with only one bookmark), and print it out to debug - but can't seem to set the value of the text. How do I replace the text at the bookmark? WordprocessingDocument wordprocessingDocument=WordprocessingDocument.Open(filepath, true); foreach (BookmarkStart bookmark in wordprocessingDocument.MainDocumentPart.Document.Body.Descendants<BookmarkStart>()) { System.Diagnostics.Debug.WriteLine(bookmark.Name + " - " + bookmark.Parent.InnerText); /* Below line does not work */ bookmark.Parent.InnerText = "My Replacement Text" } A: Get all bookmark start public List<WP.BookmarkStart> GetAllBookmarks () { var bmk = _workspace.MainDocumentPart.RootElement.Descendants<WP.BookmarkStart>().ToList(); return bmk; } Iterate through all bookmarks foreach (var bookmark in bookmarks) { string modifiedString = GetModifiedString(); ReplaceBookmarkText(bookmark, modifiedString); } Replace Bookmark Text public void ReplaceBookmarkText(WP.BookmarkStart bookmark, string newText) { try { var bmkText = bookmark.NextSibling<WP.Run>(); if (bmkText != null) { bmkText.GetFirstChild<WP.Text>().Text = newText; wordprocessingDocument.MainDocumentPart.Document.Save(); } } catch(Exception ex) { Debug.WriteLine(ex.Message); throw; } } Where WP is using WP = DocumentFormat.OpenXml.Wordprocessing;
Q: How to replace text at bookmark in a Word document I am trying to programmatically replace text at a bookmark in a Word document. I can find the text at the bookmark (I am using a test document with only one bookmark), and print it out to debug - but can't seem to set the value of the text. How do I replace the text at the bookmark? WordprocessingDocument wordprocessingDocument=WordprocessingDocument.Open(filepath, true); foreach (BookmarkStart bookmark in wordprocessingDocument.MainDocumentPart.Document.Body.Descendants<BookmarkStart>()) { System.Diagnostics.Debug.WriteLine(bookmark.Name + " - " + bookmark.Parent.InnerText); /* Below line does not work */ bookmark.Parent.InnerText = "My Replacement Text" } A: Get all bookmark start public List<WP.BookmarkStart> GetAllBookmarks () { var bmk = _workspace.MainDocumentPart.RootElement.Descendants<WP.BookmarkStart>().ToList(); return bmk; } Iterate through all bookmarks foreach (var bookmark in bookmarks) { string modifiedString = GetModifiedString(); ReplaceBookmarkText(bookmark, modifiedString); } Replace Bookmark Text public void ReplaceBookmarkText(WP.BookmarkStart bookmark, string newText) { try { var bmkText = bookmark.NextSibling<WP.Run>(); if (bmkText != null) { bmkText.GetFirstChild<WP.Text>().Text = newText; wordprocessingDocument.MainDocumentPart.Document.Save(); } } catch(Exception ex) { Debug.WriteLine(ex.Message); throw; } } Where WP is using WP = DocumentFormat.OpenXml.Wordprocessing;
stackoverflow
{ "language": "en", "length": 173, "provenance": "stackexchange_0000F.jsonl.gz:869349", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555916" }
e04b40a7dbb686da1b6683f7c5c81b5a0d20a3e3
Stackoverflow Stackexchange Q: Logstash for windows .netcore application I am a newbie to Logstash. I found it very interesting. But currently I am dealing with logging related to .NET core application. Am I right in using Logstash for my logging needs? I am confused after seeing that logstash is used only for server-side logging. Thanks in advance for the help. A: You can use a typical logging library like NLog and have the LogStash Filebeat properly configured so that logs are pushed to LogStash. To make the most out of LogStash, it is highly preferable to log machine readable log entries over human readable logs. (ex: structured json over string messages, read more here.)
Q: Logstash for windows .netcore application I am a newbie to Logstash. I found it very interesting. But currently I am dealing with logging related to .NET core application. Am I right in using Logstash for my logging needs? I am confused after seeing that logstash is used only for server-side logging. Thanks in advance for the help. A: You can use a typical logging library like NLog and have the LogStash Filebeat properly configured so that logs are pushed to LogStash. To make the most out of LogStash, it is highly preferable to log machine readable log entries over human readable logs. (ex: structured json over string messages, read more here.)
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:869373", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555979" }
d2ec5696047a651a576e5eb19f889a4f988a990a
Stackoverflow Stackexchange Q: Where to load script tags in Vue? I am new to Vue.js and I am simply trying to load script tags to the page, like jQuery for example. I tried adding the scripts to the end of the body in the index.html file, but they come back as 404s. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>title</title> </head> <body> <div id="app"></div> <!-- JQUERY --> <script src="assets/js/jquery-2.1.4.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.matchHeight/0.7.0/jquery.matchHeight-min.js"></script> <script src="assets/js/bootstrap.min.js"></script> <script src="assets/js/tipr.min.js"></script> </body> </html> A: Try moving them to the /static/ folder &/or prefixing the paths with ./ or /
Q: Where to load script tags in Vue? I am new to Vue.js and I am simply trying to load script tags to the page, like jQuery for example. I tried adding the scripts to the end of the body in the index.html file, but they come back as 404s. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>title</title> </head> <body> <div id="app"></div> <!-- JQUERY --> <script src="assets/js/jquery-2.1.4.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.matchHeight/0.7.0/jquery.matchHeight-min.js"></script> <script src="assets/js/bootstrap.min.js"></script> <script src="assets/js/tipr.min.js"></script> </body> </html> A: Try moving them to the /static/ folder &/or prefixing the paths with ./ or /
stackoverflow
{ "language": "en", "length": 90, "provenance": "stackexchange_0000F.jsonl.gz:869374", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555981" }
59f05de39147aba4c2f5cafcebab34edda8dbd89
Stackoverflow Stackexchange Q: Subdomains Laravel Routing and Vue.js I'm using Laravel 5.4, vue.js 2.3 and vue-router. Current situation When example.com is hit, Laravel returns the app view which starts the Vue.app web.php Route::get('/', function () { return view('app'); }); app.js const routes = [ { path: '/', component: App }, ]; const app = new Vue({ el: '#app', router, data () { return {} }, }); App.vue export default { ... } What I'm trying to do If usa.example.com is typed, I would like the alert() in my App.vue to show usa. If italy.example.com is typed, I would like the alert() in my App.vue to show italy. I read the documentation of vue-router but I'm not sure wether it is a Laravel issue, a Vue issue or both. App.vue export default { .... created() { alert('subdomain is ' + $route.params.subdomain) } } A: VueRouter doesn't keep track of the subdomain. But, you can get the subdomain from the location and use that in your component's created method: created() { let subdomain = location.hostname.split('.').shift(); alert('subdomain is ' + subdomain); } The above code is based off of this answer.
Q: Subdomains Laravel Routing and Vue.js I'm using Laravel 5.4, vue.js 2.3 and vue-router. Current situation When example.com is hit, Laravel returns the app view which starts the Vue.app web.php Route::get('/', function () { return view('app'); }); app.js const routes = [ { path: '/', component: App }, ]; const app = new Vue({ el: '#app', router, data () { return {} }, }); App.vue export default { ... } What I'm trying to do If usa.example.com is typed, I would like the alert() in my App.vue to show usa. If italy.example.com is typed, I would like the alert() in my App.vue to show italy. I read the documentation of vue-router but I'm not sure wether it is a Laravel issue, a Vue issue or both. App.vue export default { .... created() { alert('subdomain is ' + $route.params.subdomain) } } A: VueRouter doesn't keep track of the subdomain. But, you can get the subdomain from the location and use that in your component's created method: created() { let subdomain = location.hostname.split('.').shift(); alert('subdomain is ' + subdomain); } The above code is based off of this answer.
stackoverflow
{ "language": "en", "length": 186, "provenance": "stackexchange_0000F.jsonl.gz:869376", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44555986" }
79eb380771a4ea2bf09abdc4382150a65d101d42
Stackoverflow Stackexchange Q: How to add logo in firebase ui authentication in android? I'm not able to set custom logo of my app at the signIn activity, while using firebase auth UI? A: You can set the logo using .setLogo() property of AuthUI.getInstance(). Github firebase authUI Doc. AuthUI.getInstance() .createSignInIntentBuilder() .setTheme(R.style.FirebaseLoginTheme) .setLogo(R.drawable.logo) .setIsSmartLockEnabled(!BuildConfig.DEBUG) .setProviders(providers) .build(), RC_SIGN_IN);
Q: How to add logo in firebase ui authentication in android? I'm not able to set custom logo of my app at the signIn activity, while using firebase auth UI? A: You can set the logo using .setLogo() property of AuthUI.getInstance(). Github firebase authUI Doc. AuthUI.getInstance() .createSignInIntentBuilder() .setTheme(R.style.FirebaseLoginTheme) .setLogo(R.drawable.logo) .setIsSmartLockEnabled(!BuildConfig.DEBUG) .setProviders(providers) .build(), RC_SIGN_IN);
stackoverflow
{ "language": "en", "length": 53, "provenance": "stackexchange_0000F.jsonl.gz:869397", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556046" }
a6e43476b4e863b6eadb7e74d0bdab9f620f5bbd
Stackoverflow Stackexchange Q: Docker: readonly filesystem error I am required to a create container (docker run), run an application like gams and then destroy the container. for a load test I repeat this a 1000 times. by the end of this test, RHEL7 complains about a 'readonly filesystem' or 'segmentation fault' on ls. the only solution thus far is a disk reset. tried increasing the ulimit. tried resetting $LD_LIBRARY_PATH.none worked. what could be a good diagnosis? Solutions so far: upgraded from docker 1.12.6 to 17.x set the interval to 5min between runs no disk reset has been experienced so far after implementing the above two solutions, waiting for the next test to complete to confirm Update Issue cropped again when copying files from the master node to compute node through java code: "bash: cannot create temp file for here-document: Read-only file system"
Q: Docker: readonly filesystem error I am required to a create container (docker run), run an application like gams and then destroy the container. for a load test I repeat this a 1000 times. by the end of this test, RHEL7 complains about a 'readonly filesystem' or 'segmentation fault' on ls. the only solution thus far is a disk reset. tried increasing the ulimit. tried resetting $LD_LIBRARY_PATH.none worked. what could be a good diagnosis? Solutions so far: upgraded from docker 1.12.6 to 17.x set the interval to 5min between runs no disk reset has been experienced so far after implementing the above two solutions, waiting for the next test to complete to confirm Update Issue cropped again when copying files from the master node to compute node through java code: "bash: cannot create temp file for here-document: Read-only file system"
stackoverflow
{ "language": "en", "length": 140, "provenance": "stackexchange_0000F.jsonl.gz:869431", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556149" }
d59ed3de6c1cd6877471bd3780db74de22d64bea
Stackoverflow Stackexchange Q: d3 setting multiple attributes from the same function? Is there any way to set multiple attributes from the same function? d3.selectAll('.myshape') .attr('y',function(d,i) { ... calculates something ... }) .attr('height',function(d,i) { ... calculates something very similar... }) I would like to calculate y1 and y2 at the same time and then set y = y1 and height = y2-y1. But the standard way of doing this in d3 seems to be having separate functions per attribute. Is there a better way? A: If I understand your question correctly, you have an intensive calculation that you would like to compute only once per element, regardless the number of attributes you're setting. That being the case, you can use an each to pass the current element (this), along with the datum, the index and the group, if you need them: d3.selectAll(".myShape").each(function(d,i,n){ //Here you put the complex calculation //which will assign the values of y1 and y2. //This calculation runs only once per element d3.select(this).attr("y", y1).attr("height", y2 - y1) });
Q: d3 setting multiple attributes from the same function? Is there any way to set multiple attributes from the same function? d3.selectAll('.myshape') .attr('y',function(d,i) { ... calculates something ... }) .attr('height',function(d,i) { ... calculates something very similar... }) I would like to calculate y1 and y2 at the same time and then set y = y1 and height = y2-y1. But the standard way of doing this in d3 seems to be having separate functions per attribute. Is there a better way? A: If I understand your question correctly, you have an intensive calculation that you would like to compute only once per element, regardless the number of attributes you're setting. That being the case, you can use an each to pass the current element (this), along with the datum, the index and the group, if you need them: d3.selectAll(".myShape").each(function(d,i,n){ //Here you put the complex calculation //which will assign the values of y1 and y2. //This calculation runs only once per element d3.select(this).attr("y", y1).attr("height", y2 - y1) }); A: Not exactly. But you could solve the issue in a indirect way. This adds slightly more overhead but worth it imo. JS doesn't have nice "compile-time" (as far as the js engine is concerned) macros like C family, that give you nice expansions without runtime cost. like this (you may already know): let myshape = d3.selectAll('.myshape') ['y', 'height', ...].forEach(attr => myshape.attr(attr, calcAttr)); function calcAttr(a, i) { // shared code switch (a) { case 'y': //attr specific break; } }
stackoverflow
{ "language": "en", "length": 247, "provenance": "stackexchange_0000F.jsonl.gz:869437", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556167" }
b18ea83b2d64d99155e221e77e4f0246a6b38f52
Stackoverflow Stackexchange Q: How to upload file (pdf) using raw in Postman? I am trying to automate attaching a form data pdf file in Postman. Can it be done using raw in Postman? Please assist. Thank you! A: You can choose the form-data upload. When adding a new form field, you can change the type of the field to "File". In Postman's current version (7.8) you have to leave the entry line and then move the mouse over the newly created entry to see this option.
Q: How to upload file (pdf) using raw in Postman? I am trying to automate attaching a form data pdf file in Postman. Can it be done using raw in Postman? Please assist. Thank you! A: You can choose the form-data upload. When adding a new form field, you can change the type of the field to "File". In Postman's current version (7.8) you have to leave the entry line and then move the mouse over the newly created entry to see this option. A: Files can only be uploaded using the 'binary' and 'form-data' option. Postman considers raw data as a string. Have a look at the documentation for a complete list of options Postman provides: https://www.getpostman.com/docs/postman/sending_api_requests/requests
stackoverflow
{ "language": "en", "length": 118, "provenance": "stackexchange_0000F.jsonl.gz:869445", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556185" }
42e86b6154027b84e41ca99230c00d64802634e2
Stackoverflow Stackexchange Q: How to change resharpers default access modifier to public instead of internal for generated classes? when you auto generate a class, by default resharper seems to go with internal class Blah, but I'd like it to default to public class Blah I can understand why, because at that moment of generation, it is only internally scoped, but very quickly I will use it publicly scoped. Which requires an auto fixup, which is just annoying. I'd like to be able specify the default access modifier I have 2017.1.2 The way I generate the class is as following :- var x = new Blah() ALT+ENTER -> Create Type /Generate Class A: You have to modify the templates. Resharper => Tools => Template Explorer choose Live/File Templates for the c#. Now you can edit to whatever you like. Templates Explorer Window edit: Seems that you are invoking through "quick fixes" suggestions. Probably related to the "search/replace patterns". Didnt see the default exposed though.
Q: How to change resharpers default access modifier to public instead of internal for generated classes? when you auto generate a class, by default resharper seems to go with internal class Blah, but I'd like it to default to public class Blah I can understand why, because at that moment of generation, it is only internally scoped, but very quickly I will use it publicly scoped. Which requires an auto fixup, which is just annoying. I'd like to be able specify the default access modifier I have 2017.1.2 The way I generate the class is as following :- var x = new Blah() ALT+ENTER -> Create Type /Generate Class A: You have to modify the templates. Resharper => Tools => Template Explorer choose Live/File Templates for the c#. Now you can edit to whatever you like. Templates Explorer Window edit: Seems that you are invoking through "quick fixes" suggestions. Probably related to the "search/replace patterns". Didnt see the default exposed though.
stackoverflow
{ "language": "en", "length": 161, "provenance": "stackexchange_0000F.jsonl.gz:869452", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556203" }
b753bf5fafeea9f83287d08fc99d57d16a2c1cb7
Stackoverflow Stackexchange Q: What is the source of the index in a ColumnDataSource created from a pandas DataFrame? Dataframes naturally come with an index, i.e. those set of row headers we can think of them as. When I construct a ColumnDataSource in bokeh to capture the information in that dataframe for plotting and annotating in a HoverTool I see that the hover tool has a built in ( "index" , "$index" ) tooltip available. Will this index be identical to my dataframe's index or is it simply the row index in the ColumnDataSource A: The special variable $index simply displays the row index of the column data source (it can't be a pandas index in general, because although CDS may be created from data frames, they do not have to). If you want to include the pandas dataframe index you can add it: In [5]: d = pd.DataFrame(dict(a=[1,2,3], b=[2,3,4])) In [6]: d.index Out[6]: RangeIndex(start=0, stop=3, step=1) In [7]: source = ColumnDataSource(d) In [8]: source.add(d.index, 'index') This field can be accessed in a hover tool with the standard and general @colname syntax for any standard CDS column (so in this specific case: @index)
Q: What is the source of the index in a ColumnDataSource created from a pandas DataFrame? Dataframes naturally come with an index, i.e. those set of row headers we can think of them as. When I construct a ColumnDataSource in bokeh to capture the information in that dataframe for plotting and annotating in a HoverTool I see that the hover tool has a built in ( "index" , "$index" ) tooltip available. Will this index be identical to my dataframe's index or is it simply the row index in the ColumnDataSource A: The special variable $index simply displays the row index of the column data source (it can't be a pandas index in general, because although CDS may be created from data frames, they do not have to). If you want to include the pandas dataframe index you can add it: In [5]: d = pd.DataFrame(dict(a=[1,2,3], b=[2,3,4])) In [6]: d.index Out[6]: RangeIndex(start=0, stop=3, step=1) In [7]: source = ColumnDataSource(d) In [8]: source.add(d.index, 'index') This field can be accessed in a hover tool with the standard and general @colname syntax for any standard CDS column (so in this specific case: @index)
stackoverflow
{ "language": "en", "length": 190, "provenance": "stackexchange_0000F.jsonl.gz:869455", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556208" }
66c3ad8d521b4463af4c54f0e28479e5e67c190e
Stackoverflow Stackexchange Q: Are web publishing tools available for VS2017 in MSBuild directory? I have the web developer tools installed on my VS2017 IDE and the Microsoft.Web.Publishing.Tasks.dll is found in: C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\VisualStudio\v15.0\Web\ This is fine when running my build inside VS2017. However, when I run my build from the command line, MSBuild searches for the web.publishing tasks in the following location: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0\Web\Microsoft.Web.Publishing.Tasks.dll And in this location it is missing. For Visual Studio 2015 I don't remember installing anything special to make this work and for v14.0, the dll is in both locations. Does anyone know what I am missing?
Q: Are web publishing tools available for VS2017 in MSBuild directory? I have the web developer tools installed on my VS2017 IDE and the Microsoft.Web.Publishing.Tasks.dll is found in: C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\VisualStudio\v15.0\Web\ This is fine when running my build inside VS2017. However, when I run my build from the command line, MSBuild searches for the web.publishing tasks in the following location: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0\Web\Microsoft.Web.Publishing.Tasks.dll And in this location it is missing. For Visual Studio 2015 I don't remember installing anything special to make this work and for v14.0, the dll is in both locations. Does anyone know what I am missing?
stackoverflow
{ "language": "en", "length": 102, "provenance": "stackexchange_0000F.jsonl.gz:869476", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556272" }
fc31ceb113b908c0b4f216e3003d39e15b017963
Stackoverflow Stackexchange Q: Microsoft Graph API - find message by internetmessageid I need to find conversationId for email exchange between two user - John and Harry. In my scenario: * *John sends message to Harry. *I have email metadata from email that John has sent, e.g. converstationId, internetMessageId, messageId (m$ graph user specific). *Now I would like to reply from Harry. Unfortunately the converstionId of Harry is different then John, so I can't use it. What I would like to do is to find email message object in Harry's inbox and use his conversationId. *With valid converstationId, I would be able to call replyAll on Harry behalf. Can I make call like: GET /me/messages?$filter=internetMessageId eq abcd A: Yes, you can make a GET call in the form you suggest - have you tried it? The graph API supports standard ODATA query parameters. On the graph API explorer, the following call works for me: https://graph.microsoft.com/v1.0/me/messages?$filter=internetMessageId eq '<1430948481468.34600@THCIE7Dev2.onmicrosoft.com>'
Q: Microsoft Graph API - find message by internetmessageid I need to find conversationId for email exchange between two user - John and Harry. In my scenario: * *John sends message to Harry. *I have email metadata from email that John has sent, e.g. converstationId, internetMessageId, messageId (m$ graph user specific). *Now I would like to reply from Harry. Unfortunately the converstionId of Harry is different then John, so I can't use it. What I would like to do is to find email message object in Harry's inbox and use his conversationId. *With valid converstationId, I would be able to call replyAll on Harry behalf. Can I make call like: GET /me/messages?$filter=internetMessageId eq abcd A: Yes, you can make a GET call in the form you suggest - have you tried it? The graph API supports standard ODATA query parameters. On the graph API explorer, the following call works for me: https://graph.microsoft.com/v1.0/me/messages?$filter=internetMessageId eq '<1430948481468.34600@THCIE7Dev2.onmicrosoft.com>' A: This works https://graph.microsoft.com/v1.0/me/messages?$filter=internetMessageId eq '<1430948481468.34600@THCIE7Dev2.onmicrosoft.com>' BUT One must URL encode the internetMessageId Thus https://graph.microsoft.com/v1.0/me/messages?$filter=internetMessageId eq '%3C1430948481468.34600%40THCIE7Dev2.onmicrosoft.com%3E'
stackoverflow
{ "language": "en", "length": 171, "provenance": "stackexchange_0000F.jsonl.gz:869490", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556311" }
0b4271df71ed910b18f52247bb5da0dfc7e19dfb
Stackoverflow Stackexchange Q: Site direction base on language in laravel I'm working with laravel 5.4 and my application supports both LTR and RTL languages, my question is how can I redirect my content when user choose RTL language and reverse of it obviously? A: I had same question and after some investigations i did following process: * *added following code to my language file: 'page_direction' => 'rtl', you can learn more about this subject on Laravel Localization documentations. *After this added following code to my master template: class="{{ __('global.page_direction') }}" *At this time i can define special CSS code when body element have rtl class like this: body.rtl .element{float:right}
Q: Site direction base on language in laravel I'm working with laravel 5.4 and my application supports both LTR and RTL languages, my question is how can I redirect my content when user choose RTL language and reverse of it obviously? A: I had same question and after some investigations i did following process: * *added following code to my language file: 'page_direction' => 'rtl', you can learn more about this subject on Laravel Localization documentations. *After this added following code to my master template: class="{{ __('global.page_direction') }}" *At this time i can define special CSS code when body element have rtl class like this: body.rtl .element{float:right} A: You'll want look in to incorporating Laravel's localization features for this. https://laravel.com/docs/5.4/localization Each language has it's translated phrases stored in the resources/lang directory. Then based on the user's browser settings the application will display the correct translated text. A: You may try writing an JS function for onchange event of RTL or LTR $(document).on('change', '#language_selector' , function() { var locale = $(this).val(); $.ajax({ url: "{{ url('change_language') }}", type: "POST", data: { locale: locale }, success: function() { window.location.reload(); } }); }); and attach a route to set the locale Route::post('change_language', function() { $locale = Input::get('locale'); App::setLocale($locale); }); and in your view based on the locale you could set the style css @if(App::getLocale() == 'en') <link href="ltr.css" type="stylesheet" /> @else <link href="rtl.css" type="stylesheet" /> @endif
stackoverflow
{ "language": "en", "length": 232, "provenance": "stackexchange_0000F.jsonl.gz:869502", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556355" }
80247e9ee9e462e7a4fac4869bd2f44d9c47b4a4
Stackoverflow Stackexchange Q: Bot Framework does not notify about Telegram messages that begin with a mention I’m testing with the following setup: I have a bot with privacy mode disabled, so it listens to all messages in a channel. I have a webhook set in the Bot Framework that prints all incoming messages. I noticed the issue first on Telegram web and later discovered that it also affects Android, where you don’t get notifications only if you type a mention manually—if you select a mention from the drop-down, a notification gets sent. Here are the screenshots of the channel where I was sending messages: And here are the messages I got from the webhook: new message: this message sent from web will be relayed even if it contains the mention @jlarky new message: @JLarkyTestBot you can mention the bot though new message: ^^ last message from web new message: Now message from Android new message: Yarosla mentions work new message: Yarosla it has to be from mention dropdown, otherwise it's not sent either As you can see, only a part of them was delivered.
Q: Bot Framework does not notify about Telegram messages that begin with a mention I’m testing with the following setup: I have a bot with privacy mode disabled, so it listens to all messages in a channel. I have a webhook set in the Bot Framework that prints all incoming messages. I noticed the issue first on Telegram web and later discovered that it also affects Android, where you don’t get notifications only if you type a mention manually—if you select a mention from the drop-down, a notification gets sent. Here are the screenshots of the channel where I was sending messages: And here are the messages I got from the webhook: new message: this message sent from web will be relayed even if it contains the mention @jlarky new message: @JLarkyTestBot you can mention the bot though new message: ^^ last message from web new message: Now message from Android new message: Yarosla mentions work new message: Yarosla it has to be from mention dropdown, otherwise it's not sent either As you can see, only a part of them was delivered.
stackoverflow
{ "language": "en", "length": 182, "provenance": "stackexchange_0000F.jsonl.gz:869516", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556396" }
09f85afe53b2b9c33a8801d4d3b4fb8d39b122dc
Stackoverflow Stackexchange Q: React componentWillRecieveProps not called after mapStateToProps I have an isomorphic react app using react router 4 and redux. I have a situation where I have multiple routes that use the same component (SectionFront). This component is connected to the redux store. I'm expecting the component's componentWillRecieveProps() to be called whenever the store's location is updated, however it is never called. class SectionFront extends React.Component{ componentWillReceiveProps( nextprops ){ console.log('next props... does not fire on location change'); } render(){ console.log('Render was called', this.props); return( <div>this is the section front</div> ) } } const mapDispatchToProps = { loadSectionFront } const mapStateToProps = (state) =>{ console.log('This is called properly every time after the state changes', state); return { sectionFront : state.sectionFront.payload, isLoading: state.sectionFront.loading, pathname: state.location.pathname } } export default connect(mapStateToProps, mapDispatchToProps)(SectionFront) Any thoughts as to why componentWillReceiveProps() does not get triggered even though the props are being updated and the render function is still called ?
Q: React componentWillRecieveProps not called after mapStateToProps I have an isomorphic react app using react router 4 and redux. I have a situation where I have multiple routes that use the same component (SectionFront). This component is connected to the redux store. I'm expecting the component's componentWillRecieveProps() to be called whenever the store's location is updated, however it is never called. class SectionFront extends React.Component{ componentWillReceiveProps( nextprops ){ console.log('next props... does not fire on location change'); } render(){ console.log('Render was called', this.props); return( <div>this is the section front</div> ) } } const mapDispatchToProps = { loadSectionFront } const mapStateToProps = (state) =>{ console.log('This is called properly every time after the state changes', state); return { sectionFront : state.sectionFront.payload, isLoading: state.sectionFront.loading, pathname: state.location.pathname } } export default connect(mapStateToProps, mapDispatchToProps)(SectionFront) Any thoughts as to why componentWillReceiveProps() does not get triggered even though the props are being updated and the render function is still called ?
stackoverflow
{ "language": "en", "length": 153, "provenance": "stackexchange_0000F.jsonl.gz:869540", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556482" }
5bd4fa4ba394a0afb74985ab2165d7106d299fd9
Stackoverflow Stackexchange Q: Django forms with slider Is it possible to use a slider with Django Forms with Crispy Forms? I am using Foundation and the example code is below. <div class="slider" data-slider data-initial-start="50" data-end="100"> <span class="slider-handle" data-slider-handle role="slider" tabindex="1"></span> <span class="slider-fill" data-slider-fill></span> <input type="hidden" name="amount"> </div> A: After burning a couple days playing with this, I am convinced that the jquery approach is not the best way to tackle this. I would recommend just going with the Crispy-form template approach Field('slider', template="custom-slider.html") good luck.
Q: Django forms with slider Is it possible to use a slider with Django Forms with Crispy Forms? I am using Foundation and the example code is below. <div class="slider" data-slider data-initial-start="50" data-end="100"> <span class="slider-handle" data-slider-handle role="slider" tabindex="1"></span> <span class="slider-fill" data-slider-fill></span> <input type="hidden" name="amount"> </div> A: After burning a couple days playing with this, I am convinced that the jquery approach is not the best way to tackle this. I would recommend just going with the Crispy-form template approach Field('slider', template="custom-slider.html") good luck.
stackoverflow
{ "language": "en", "length": 83, "provenance": "stackexchange_0000F.jsonl.gz:869553", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556519" }
39ae5d704d0fa91efdfb4808ac7156643408ef3a
Stackoverflow Stackexchange Q: How to merge two array objects in ruby? If I start with two arrays such as: array1 = [{"ID":"1","name":"Dog"}] array2 = [{"ID":"2","name":"Cat"}] How to merge this array into one array like this? arraymerge = [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}] A: Other answer for your question is to use Array#concat: array1 = [{"ID":"1","name":"Dog"}] array2 = [{"ID":"2","name":"Cat"}] array1.concat(array2) # [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}]
Q: How to merge two array objects in ruby? If I start with two arrays such as: array1 = [{"ID":"1","name":"Dog"}] array2 = [{"ID":"2","name":"Cat"}] How to merge this array into one array like this? arraymerge = [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}] A: Other answer for your question is to use Array#concat: array1 = [{"ID":"1","name":"Dog"}] array2 = [{"ID":"2","name":"Cat"}] array1.concat(array2) # [{"ID":"1","name":"Dog"}, {"ID":"2","name":"Cat"}] A: Just add them together: puts array1+array2 {:ID=>"1", :name=>"Dog"} {:ID=>"2", :name=>"Cat"} Or: p array1+array2 [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}] See also: Merge arrays in Ruby/Rails A: array1 = [{ID:"1",name:"Dog"}] array2 = [{ID:"2",name:"Cat"}] p array1 + array2 # => [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}] Or maybe this is superfluous: array1 = [{ID:"1",name:"Dog"}] array2 = [{ID:"2",name:"Cat"}] array3 = [{ID:"3",name:"Duck"}] p [array1, array2, array3].map(&:first) # => [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}, {:ID=>"3", :name=>"Duck"}] A: You can just use + operator to do that array1 = [{"ID":"1","name":"Dog"}] array2 = [{"ID":"2","name":"Cat"}] arraymerge = array1 + array2 #=> [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]
stackoverflow
{ "language": "en", "length": 150, "provenance": "stackexchange_0000F.jsonl.gz:869595", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556630" }
41269beb7045d33664f9e89bf5e74d25c00e3b1f
Stackoverflow Stackexchange Q: Get the View of UIBarButtonItem in Swift Hopefully, this is an easy question. I am trying to obtain the UIView of a UIBarButtonItem. Looking at the following StackOverflow question I came up with the following code: let notificationButton = UIBarButtonItem(image: UIImage(named: "icon_notification.png"), style: .plain, target: self, action: nil) let notificationView = notificationButton.value(forKey: "view") as? UIView However, notificationView is nil. So, thoughts on what I failed to interpret from the linked StackOverflow question? A: Starting from iOS 11 this code will not work cause line of code below will not cast UIView. Also it's counting as private API and seems to be will not pass AppStore review. guard let view = self.value(forKey: "view") as? UIView else { return } Thread on: forums.developer.apple
Q: Get the View of UIBarButtonItem in Swift Hopefully, this is an easy question. I am trying to obtain the UIView of a UIBarButtonItem. Looking at the following StackOverflow question I came up with the following code: let notificationButton = UIBarButtonItem(image: UIImage(named: "icon_notification.png"), style: .plain, target: self, action: nil) let notificationView = notificationButton.value(forKey: "view") as? UIView However, notificationView is nil. So, thoughts on what I failed to interpret from the linked StackOverflow question? A: Starting from iOS 11 this code will not work cause line of code below will not cast UIView. Also it's counting as private API and seems to be will not pass AppStore review. guard let view = self.value(forKey: "view") as? UIView else { return } Thread on: forums.developer.apple A: So, DS Dharma gave me a idea which ended up working. The "view" value is only available after it is assigned to the toolbar navigation item like this: self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_notification.png"), style: .plain, target: self, action: nil) self.navigationItem.rightBarButtonItem?.addBadge(number: 0, withOffset: CGPoint(x: 7.0, y: 0.0) , andColor: UIColor.black, andFilled: true) where the addBadge() function needs the UIView. BTW, if anyone is wondering, the addBadge function was taken from this post: http://www.stefanovettor.com/2016/04/30/adding-badge-uibarbuttonitem Highly recommended if you need this piece of functionality.
stackoverflow
{ "language": "en", "length": 204, "provenance": "stackexchange_0000F.jsonl.gz:869610", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556686" }
0e509483ed8a222fd9e745c1510838a804c923d7
Stackoverflow Stackexchange Q: How can I break from an *ngFor loop in Angular 4? How can I break from an *ngFor loop in Angular 4? I just want this loop to break after it executes once. <div *ngFor="let thing of things"> <div *ngIf="thing == otherThing"> <h4>Sub Title</h4> ***BREAK HERE*** </div> </div> A: You can't break *ngFor. But you can build a custom pipe to filter the data. But as Jus10's said, the better way is to do it in ts-file.
Q: How can I break from an *ngFor loop in Angular 4? How can I break from an *ngFor loop in Angular 4? I just want this loop to break after it executes once. <div *ngFor="let thing of things"> <div *ngIf="thing == otherThing"> <h4>Sub Title</h4> ***BREAK HERE*** </div> </div> A: You can't break *ngFor. But you can build a custom pipe to filter the data. But as Jus10's said, the better way is to do it in ts-file. A: I had to break the loop so i followed the following approach. I don't know whether its helpful or not still sharing that piece of code. As ausutine mentioned: You can't break *ngFor. It's just an alternate way to do so. <ng-container *ngFor="let product of products; let i = index"> <div *ngIf="i < 10"> <span> product.name </span> </div> </ng-container> A: Please try this slice, scenario (you want to run loop for n elements) <div *ngFor="let thing of things.slice(0,1)"> <div *ngIf="thing == otherThing"> <h4>Sub Title</h4> </div>
stackoverflow
{ "language": "en", "length": 164, "provenance": "stackexchange_0000F.jsonl.gz:869619", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556721" }
e52c9508a87fb6eb1854504b0140e8c792d26aeb
Stackoverflow Stackexchange Q: How can I show two activities at a time in android I have 2 activities, In first activity I have a button and I want when user clicks or move up that button the second activity come from bottom and stop when it goes to the half of the screen. I don't understand how can I achieve this. I also searched google but they show some type of dialog boxes :(. This is what I want. When app start 1st activity is shown on the screen but when user click ^ this button both 2 activities show 50% on the screen. Can anybody tell me how can I achieve this. Is it possible??? A: You would achieve this using Fragments. I would suggest you start with the offical documentation - https://developer.android.com/training/basics/fragments/index.html
Q: How can I show two activities at a time in android I have 2 activities, In first activity I have a button and I want when user clicks or move up that button the second activity come from bottom and stop when it goes to the half of the screen. I don't understand how can I achieve this. I also searched google but they show some type of dialog boxes :(. This is what I want. When app start 1st activity is shown on the screen but when user click ^ this button both 2 activities show 50% on the screen. Can anybody tell me how can I achieve this. Is it possible??? A: You would achieve this using Fragments. I would suggest you start with the offical documentation - https://developer.android.com/training/basics/fragments/index.html A: You should read about fragments. They can be used for the UI you described. You can make it so that a second fragment is GONE, and when the user presses a button, it becomes visible. You should probably use a relative layout for the two fragments. A: In order to create the interface above you could use fragments instead of activity. In your case you need to have an activity with two fragments (you can use coordinatorlayout). If you don't have enough knowledge about fragments I recommend to read those articles: * *Codepath fragments guide *Vogella fragments guide A: Convert Activity to Fragment and use <FrameLayout> on page to display/remove fragments from page. Fragments are reusable components Refer to convert Activity to Fragment This might help you understand how to work with Fragments link
stackoverflow
{ "language": "en", "length": 267, "provenance": "stackexchange_0000F.jsonl.gz:869623", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556729" }
478b5387f7074c0bdcfb22aadb15c681b61dac90
Stackoverflow Stackexchange Q: 'CREATE CREDENTIAL' is not supported in this version of SQL Server - Azure SQL Database I am looking to set up my Azure SQL databases to back up to my Azure Blob Storage. When trying to create the SQL credential with this code: CREATE CREDENTIAL mycredential WITH IDENTITY= 'storageaccountname' , SECRET = 'DefaultEndpointsProtocol=https;AccountName=storageaccountname;AccountKey=8L ==;EndpointSuffix=core.windows.net' I get this error: Msg 40514, Level 16, State 1, Line 4 'CREATE CREDENTIAL' is not supported in this version of SQL Server. The version of SQL is: SELECT @@VERSION AS 'SQL Server Version' Microsoft SQL Azure (RTM) - 12.0.2000.8 Jun 11 2017 11:55:10 Copyright (C) 2017 Microsoft Corporation. All rights reserved. A: Stop right there. As far as i can tell, you don't have backup/restore in Azure SQL database, you'd have to use import/export instead. Is that what you are talking about? Back to the question, CREATE(server-scoped)CREDENTIAL is not supported in Azure SQL database, if you still wish to use credential in Azure SQL database, use CREATE DATABASE SCOPED CREDENTIAL instead.
Q: 'CREATE CREDENTIAL' is not supported in this version of SQL Server - Azure SQL Database I am looking to set up my Azure SQL databases to back up to my Azure Blob Storage. When trying to create the SQL credential with this code: CREATE CREDENTIAL mycredential WITH IDENTITY= 'storageaccountname' , SECRET = 'DefaultEndpointsProtocol=https;AccountName=storageaccountname;AccountKey=8L ==;EndpointSuffix=core.windows.net' I get this error: Msg 40514, Level 16, State 1, Line 4 'CREATE CREDENTIAL' is not supported in this version of SQL Server. The version of SQL is: SELECT @@VERSION AS 'SQL Server Version' Microsoft SQL Azure (RTM) - 12.0.2000.8 Jun 11 2017 11:55:10 Copyright (C) 2017 Microsoft Corporation. All rights reserved. A: Stop right there. As far as i can tell, you don't have backup/restore in Azure SQL database, you'd have to use import/export instead. Is that what you are talking about? Back to the question, CREATE(server-scoped)CREDENTIAL is not supported in Azure SQL database, if you still wish to use credential in Azure SQL database, use CREATE DATABASE SCOPED CREDENTIAL instead. A: It seems you are using incorrect key (secret key) in this case. You need to review your Azure container. https://learn.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string A: Was running into same issue trying to create a credential. Following actions helped me resolve * *On the container, create an access policy first and used it in Shared access token creation. *Use SA user on the database to run the command. I think the SA user might be the issue in my case. But one of my colleague used the access policy method and created the credential successfully
stackoverflow
{ "language": "en", "length": 258, "provenance": "stackexchange_0000F.jsonl.gz:869641", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556794" }
1f4064c70989f3a7a9526b88d21323b18e4cadd1
Stackoverflow Stackexchange Q: Google OAuth 2.0 invalid_request, Missing Scheme I cannot authorize Google OAuth on ios, safari always say 400 That's an error. Invalid parameter value for redirect_uri: Missing scheme: com.googleusercontent.apps.984813079630-3lmlrubo9345ng4qhtf62ud1i02m6ta8 I have checked API Key, Client_ID, client_secret on Google Console page many times and also create url scheme in the xcode. Here are my Swift code: oauthswift = OAuth2Swift( consumerKey: "xxxxx-3lmlrubo9345ng4qhtf62ud1i02m6ta8.apps.googleusercontent.com", consumerSecret: "xxxtg6qslUOC2np1sBg0hnWgBcpZb4", authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth", responseType: "token" ) let handle = oauthswift.authorize( withCallbackURL: URL(string: "com.googleusercontent.apps.984813079630-3lmlrubo9345ng4qhtf62ud1i02m6ta8")!, scope: "profile", state:"GOOGLE", success: { credential, response, parameters in print(credential.oauthToken) // Do your request }, failure: { error in print(error.localizedDescription) } ) Could you help me ? A: It is pretty simple fix for this issue: just set prefix before your schema. Example: your schema parameter: com.googleusercontent.apps.984813079630-3lmlrubo9345ng4qhtf62ud1i02m6ta8 the identifier of your iOS application: net.the-red-queen.www so, value for your redirect URI parameter is: net.the-red-queen.www:com.googleusercontent.apps.984813079630-3lmlrubo9345ng4qhtf62ud1i02m6ta8
Q: Google OAuth 2.0 invalid_request, Missing Scheme I cannot authorize Google OAuth on ios, safari always say 400 That's an error. Invalid parameter value for redirect_uri: Missing scheme: com.googleusercontent.apps.984813079630-3lmlrubo9345ng4qhtf62ud1i02m6ta8 I have checked API Key, Client_ID, client_secret on Google Console page many times and also create url scheme in the xcode. Here are my Swift code: oauthswift = OAuth2Swift( consumerKey: "xxxxx-3lmlrubo9345ng4qhtf62ud1i02m6ta8.apps.googleusercontent.com", consumerSecret: "xxxtg6qslUOC2np1sBg0hnWgBcpZb4", authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth", responseType: "token" ) let handle = oauthswift.authorize( withCallbackURL: URL(string: "com.googleusercontent.apps.984813079630-3lmlrubo9345ng4qhtf62ud1i02m6ta8")!, scope: "profile", state:"GOOGLE", success: { credential, response, parameters in print(credential.oauthToken) // Do your request }, failure: { error in print(error.localizedDescription) } ) Could you help me ? A: It is pretty simple fix for this issue: just set prefix before your schema. Example: your schema parameter: com.googleusercontent.apps.984813079630-3lmlrubo9345ng4qhtf62ud1i02m6ta8 the identifier of your iOS application: net.the-red-queen.www so, value for your redirect URI parameter is: net.the-red-queen.www:com.googleusercontent.apps.984813079630-3lmlrubo9345ng4qhtf62ud1i02m6ta8 A: I think the actual issue is that you didn't specify a full URI. (The schema doesn't have a colon and then a path.) Try making your redirect_uri look something like the following (properly encoded, of course): com.googleusercontent.apps.984813079630-3lmlrubo9345ng4qhtf62ud1i02m6ta8:/oauth A: You should probably recheck the Google Dev Console. Your clientID might be wrongly registered for Javascript Web Apps rather than Mobile Apps A: I'm writing an Android client, and this information helped, but wasn't quite what I needed. I found that I had to make the redirect uri a little differently. Take the uri that you're using as a target on the phone (usually the package name, but it can be different if re-defined in the applicationId in the app's build.gradle file). Append this at the end of the target: :/oauth2callback So my package is com.fooboy.testapp3. Add the above bit and the redirect uri becomes: com.foobly.testapp3:/oauth2callback. There are a lot of other things that need to be just right (especially in the google api console), but this was the final trick for me. Good luck (you'll need it)!
stackoverflow
{ "language": "en", "length": 314, "provenance": "stackexchange_0000F.jsonl.gz:869642", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556797" }
c4a9f855e93370684cb898ed7bcbd07fcfa44c37
Stackoverflow Stackexchange Q: logd shortcut doesn't work in Intellij with Kotlin Logging Java in Intellij is easy with shortcuts such as 'logt', 'logd', 'loge'... and so on. But I moved to Kotlin, I noticed that those shortcuts doesn't work anymore. I don't know if it has something to do with my configuration, but if not, how can I fix this? A: These are provided in IntelliJ as a Live Template configuration for AndroidLog (found in Preferences -> Editor -> Live Templates), and are applicable specifically to Java code: There isn't anything broken in your configuration, but if you want to make these Live Templates available for Kotlin you will need to add new Live Template for AndroidLog and make them applicable to Kotlin code. https://www.jetbrains.com/help/idea/2017.1/creating-and-editing-live-templates.html There's an open feature request to have them added as defaults here: https://youtrack.jetbrains.com/issue/KT-10464
Q: logd shortcut doesn't work in Intellij with Kotlin Logging Java in Intellij is easy with shortcuts such as 'logt', 'logd', 'loge'... and so on. But I moved to Kotlin, I noticed that those shortcuts doesn't work anymore. I don't know if it has something to do with my configuration, but if not, how can I fix this? A: These are provided in IntelliJ as a Live Template configuration for AndroidLog (found in Preferences -> Editor -> Live Templates), and are applicable specifically to Java code: There isn't anything broken in your configuration, but if you want to make these Live Templates available for Kotlin you will need to add new Live Template for AndroidLog and make them applicable to Kotlin code. https://www.jetbrains.com/help/idea/2017.1/creating-and-editing-live-templates.html There's an open feature request to have them added as defaults here: https://youtrack.jetbrains.com/issue/KT-10464 A: You should create separate templates to make them work correctly. Here is the step-by-step guide: Firstly, Copy and paste AndroidLog templates to Kotlin (Just select them and use CMD+C, CMD+V (or Ctrl+C, Ctrl+V) Secondly, You have to adjust them manually: 1. logd (and others) Select the logd item and press "Edit variables" Change expression to: kotlinFunctionName() Also, remove ; from the end of the template, as you don't need it in Kotlin. Now your method name will be shown correctly *logt This one is a bit trickier. Solution 1 TAG = class name. * *Template text : private val TAG = "$className$" * *Edit variables -> Expression: groovyScript("_1.take(Math.min(23, _1.length()));", kotlinClassName()) Solution 2 TAG = file name (can be used inside Companion) * *Template text : private const val TAG = "$className$ or: companion object { private const val TAG = "$className$" } * *Edit variables -> Expression: groovyScript("_1.take(Math.min(23, _1.length()));", fileNameWithoutExtension()) Edit 19.02.19 Also, it might be useful for someone. In order to avoid creating the TAG variable, you can use the class name as a variable, for instance: Log.d("BaseActivity", "onCreate: ") Where BaseActivity is the class name. The template will look now as: android.util.Log.d("$CLASS_NAME$", "$METHOD_NAME$: $content$") Where CLASS_NAME variable is: groovyScript("_1.take(Math.min(23, _1.length()));", fileNameWithoutExtension()) A: Change the scope of the template in the applicable option. A: In Android Studio 4.0 there's new AndroidLogKotlin block. You can implement @LeoDroidcoder's solution there.
stackoverflow
{ "language": "en", "length": 366, "provenance": "stackexchange_0000F.jsonl.gz:869653", "question_score": "27", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44556828" }
f40b8fec4053dd721e543f4c942267a2f380b500
Stackoverflow Stackexchange Q: Adding properties to an existing type with TypeScript So I have a library written in TypeScript, which uses the NPM depenedency 'ldapjs'. I also have @types/ldapjs installed into my project. So in my project, I have this: import {Client} from '@types/ldapjs'; import * as ldap from 'ldapjs'; Now here is my question - how can I add properties to a client with type Client? I have this: export interface IClient extends Client{ __inactiveTimeout: Timer, returnToPool: Function, ldapPoolRemoved?: boolean } where IClient is my version of an ldapjs Client with a few extra properties. let client = ldap.createClient(this.connOpts); // => Client client.cdtClientId = this.clientId++; but the problem is, if I try to add properties to client, I get this error: 'cdtClientId' property does not exist on type Client. Is there some way I can cast Client to IClient? How can I do this? I have this same problem in many different projects. A: While what you have added as answer might solve your problem, you can directly augment the Client interface and add the properties. You don't even need IClient. You can use module augmentation: declare module "ldapjs" { interface Client { // Your additional properties here } }
Q: Adding properties to an existing type with TypeScript So I have a library written in TypeScript, which uses the NPM depenedency 'ldapjs'. I also have @types/ldapjs installed into my project. So in my project, I have this: import {Client} from '@types/ldapjs'; import * as ldap from 'ldapjs'; Now here is my question - how can I add properties to a client with type Client? I have this: export interface IClient extends Client{ __inactiveTimeout: Timer, returnToPool: Function, ldapPoolRemoved?: boolean } where IClient is my version of an ldapjs Client with a few extra properties. let client = ldap.createClient(this.connOpts); // => Client client.cdtClientId = this.clientId++; but the problem is, if I try to add properties to client, I get this error: 'cdtClientId' property does not exist on type Client. Is there some way I can cast Client to IClient? How can I do this? I have this same problem in many different projects. A: While what you have added as answer might solve your problem, you can directly augment the Client interface and add the properties. You don't even need IClient. You can use module augmentation: declare module "ldapjs" { interface Client { // Your additional properties here } } A: Wow, that wasn't so hard, I have been wondering how to do this for months. let client = ldap.createClient(this.connOpts) as IClient; we use the as notation to cast a generic type to a more specific type (I think that's the right way to put it). I figure this out via this article: http://acdcjunior.github.io/typescript-cast-object-to-other-type-or-instanceof.html
stackoverflow
{ "language": "en", "length": 253, "provenance": "stackexchange_0000F.jsonl.gz:869801", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44557308" }
c52faf55a0deaebbc37b3201f2346b3cd59b9a80
Stackoverflow Stackexchange Q: Reverse checkbox value in angular2 Having some troubles reversing the checkbox value in Angular 2. In Angular 1.x we could make a directive like below. .directive('invertValue', function() { return { require: 'ngModel', link: function(scope, element, attrs, ngModel) { ngModel.$parsers.unshift(function(val) { return !val; }); ngModel.$formatters.unshift(function(val) { return !val; }); } }; }) A: why you need directive for this simple thing you can achieve like this <input type="checkbox" [checked]="!value" (change)="value= !value" />
Q: Reverse checkbox value in angular2 Having some troubles reversing the checkbox value in Angular 2. In Angular 1.x we could make a directive like below. .directive('invertValue', function() { return { require: 'ngModel', link: function(scope, element, attrs, ngModel) { ngModel.$parsers.unshift(function(val) { return !val; }); ngModel.$formatters.unshift(function(val) { return !val; }); } }; }) A: why you need directive for this simple thing you can achieve like this <input type="checkbox" [checked]="!value" (change)="value= !value" />
stackoverflow
{ "language": "en", "length": 72, "provenance": "stackexchange_0000F.jsonl.gz:869817", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44557359" }
716185dd81c2af6a01abe334525a45848eebbdad
Stackoverflow Stackexchange Q: Odoo 9 How to sort order for a field in form view I've been trying to modify project issue object. and When I click Assign to field, It shows a list of users with dropdown. But I'd like to change its order to DESC. Is there any thing I can do in View? here is my code below <record id="project_issue_custom_form" model="ir.ui.view"> <field name="inherit_id" ref="project_issue.project_issue_form_view"/> <field name="model">project.issue</field> <field name="arch" type="xml"> <field name="user_id" position="attributes"> <attribute name="default_order">sequence desc</attribute> </field> </field> </record> Also I tried in controller class Project_issue(models.Model): _inherit = "project.issue" _order = "user_id desc" But It still doesn't affected. A: The tag default_order can only be used for lists and kanban views. But you want to change the order of the content of a many2one field (user_id on project.issue). Your second approach has potential. But it is the wrong model: class ResUsers(models.Model): _inherit = "res.users" _order = "name desc" # or id
Q: Odoo 9 How to sort order for a field in form view I've been trying to modify project issue object. and When I click Assign to field, It shows a list of users with dropdown. But I'd like to change its order to DESC. Is there any thing I can do in View? here is my code below <record id="project_issue_custom_form" model="ir.ui.view"> <field name="inherit_id" ref="project_issue.project_issue_form_view"/> <field name="model">project.issue</field> <field name="arch" type="xml"> <field name="user_id" position="attributes"> <attribute name="default_order">sequence desc</attribute> </field> </field> </record> Also I tried in controller class Project_issue(models.Model): _inherit = "project.issue" _order = "user_id desc" But It still doesn't affected. A: The tag default_order can only be used for lists and kanban views. But you want to change the order of the content of a many2one field (user_id on project.issue). Your second approach has potential. But it is the wrong model: class ResUsers(models.Model): _inherit = "res.users" _order = "name desc" # or id
stackoverflow
{ "language": "en", "length": 151, "provenance": "stackexchange_0000F.jsonl.gz:869823", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44557376" }
5b12aa64187d528b2d7c1ad84c3a47b57daf55fd
Stackoverflow Stackexchange Q: Ionic native File plugin's getFile() method I'm using native file plugin on Ionic 3 app.Can you please tell me how to use getFile() method on it? I can't find a proper implementation of that method.Its signature is like below.But I don't know how to give the directoryEntry parameter. getFile(directoryEntry, fileName, flags) A: constructor(private file: File, private platform: Platform) { platform.ready() .then(() => { return this.file.resolveDirectoryUrl(this.file.dataDirectory) }) .then((rootDir) => { return this.file.getFile(rootDir, 'main.jpeg', { create: false }) }) .then((fileEntry) => { fileEntry.file(file => { console.log(file) }) }) }
Q: Ionic native File plugin's getFile() method I'm using native file plugin on Ionic 3 app.Can you please tell me how to use getFile() method on it? I can't find a proper implementation of that method.Its signature is like below.But I don't know how to give the directoryEntry parameter. getFile(directoryEntry, fileName, flags) A: constructor(private file: File, private platform: Platform) { platform.ready() .then(() => { return this.file.resolveDirectoryUrl(this.file.dataDirectory) }) .then((rootDir) => { return this.file.getFile(rootDir, 'main.jpeg', { create: false }) }) .then((fileEntry) => { fileEntry.file(file => { console.log(file) }) }) }
stackoverflow
{ "language": "en", "length": 88, "provenance": "stackexchange_0000F.jsonl.gz:869853", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44557461" }
0399f0bf9c8d990b763fbc75b7dde66f80aa5d32
Stackoverflow Stackexchange Q: Angular 2 Reactive Forms vs Template Forms We are starting a new Angular 2 project and are considering whether to use Reactive Forms or Template Forms. Background reading here: https://angular.io/guide/reactive-forms As far as I can tell, the biggest advantage of Reactive Forms is that they're synchronous, but we have simple forms and I don't think asynchronicity will cause us issues. There seems to be much more overhead with Reactive, on the surface more code to do the same things. Can someone provide a solid use case where I would use Reactive over the simpler Template Forms? A: This is a slide from my course on Forms in Pluralsight. Some of these points may be arguable, but I worked with the person from the Angular team that developed Forms to put together this list.
Q: Angular 2 Reactive Forms vs Template Forms We are starting a new Angular 2 project and are considering whether to use Reactive Forms or Template Forms. Background reading here: https://angular.io/guide/reactive-forms As far as I can tell, the biggest advantage of Reactive Forms is that they're synchronous, but we have simple forms and I don't think asynchronicity will cause us issues. There seems to be much more overhead with Reactive, on the surface more code to do the same things. Can someone provide a solid use case where I would use Reactive over the simpler Template Forms? A: This is a slide from my course on Forms in Pluralsight. Some of these points may be arguable, but I worked with the person from the Angular team that developed Forms to put together this list. A: The advantage of template driven design is its simplicity. There will be not much code in the controller. Most logic happens in the template. This is suitable for simple forms which do not need much logic behind the html-code. But each form has a state that can be updated by many different interactions and it's up to the application developer to manage that state and prevent it from getting corrupted. This can get hard to do for very large forms and can introduce bugs. On the other hand, if more logic is needed, there is often also a need for testing. Then the reactive model driven design offers more. We can unit-test the form validation logic. We can do that by instantiating the class, setting some values in the form controls and perform tests. For complex software this is absolutely needed for design and maintainability. The disadvantage of reactive model driven design is its complexity. There is also a way of mixing both design-types, but that would be having the disadvantages of both types. You can find this explained with simple example code for both ways here: Introduction to Angular Forms - Template Driven vs Model Driven or Reactive Forms A: behind the scene they are same. In reactive form, this is what u import in app.module.ts: import { ReactiveFormsModule } from '@angular/forms'; imports: [BrowserModule, ReactiveFormsModule], then in your parent.component.ts import { FormGroup, FormControl, Validators } from '@angular/forms'; cardForm = new FormGroup({ name: new FormControl('', [ Validators.required, Validators.minLength(3), Validators.maxLength(5), ]), }); cardForm is an instance of FormGroup. We need to connect it to the form itself. <form [formGroup]="cardForm" (ngSubmit)="onSubmit()"></form> This tells that this form will be handled by "cardForm". inside each input element of the form, we will add controller to listen for all the changes and pass those changes to the "cardForm". <form [formGroup]="cardForm" (ngSubmit)="onSubmit()"> <app-input label="Name" [control]="cardForm.get('name')"> </app-input> </form> cardForm.get('name')= new FormControl('initValue', [ Validators.required, Validators.minLength(3), Validators.maxLength(5), ]), in a nutshell, FormControl instances are placed in the input elements, they listen for all change and report them to FormGroup instance. We are setting up FormGroup and FormControl in the class component explciitly. if you work with template forms, you do not set up anything in the parent.component.ts. you write your code inside the parent.component.html. BUT at this moment, angular behind the scene will still create FormGroup and will handle the form through FormGroup. in app.module.ts import { FormsModule } from '@angular/forms'; imports: [BrowserModule, FormsModule], we are not writing any code for the FormGroup and FormControl. we go to the template file: <form (ngSubmit)="onSubmit()" #emailForm="ngForm"> #emailForm creates a ref to the "FormGroup" that created behind the scene. with this we can access to all of the properties of FormGroup like "touched", "valid" etc. then we place input element inside the form: <input type="email" required name="email" [(ngModel)]="email" #emailControl="ngModel" /> * *ngModel is directive. tells Angular, we want to keep track of the value in this input. It will attach alot of event handler to the input element. *[(ngModel)] is two way binding. property binding and event handling syntax put together. if the value "email" in the class changes, update the input value, likewise if the input value changes, update the "email" in the class. we already defined "email" in the class component export class AppComponent { email: string; // [(ngModel)] communicates with this onSubmit() { console.log(this.email); } } *#emailControl is the reference to the input control. name could be anything. emailControl===emailForm.controls.email So in this template form, #emailForm represents the FormGroup, #emailControl represents the FormControl. * *in reactive forms, we write our validation logic inside the FormControl explicitly. But with template, if you check the input element we added "required". when angular sees this, it will automatically assign it to Validator.required
stackoverflow
{ "language": "en", "length": 754, "provenance": "stackexchange_0000F.jsonl.gz:869860", "question_score": "19", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44557477" }
d0f2dc0c7e841e721f6e03a018334d2495ef89c1
Stackoverflow Stackexchange Q: How do I set the value of a nested formBuilder group My nested form is currently formatted in this way: ngOnInit() { this.user = this.fb.group({ name: ['', [Validators.required, Validators.minLength(2)]], quest1: ['', Validators.required], account: this.fb.group({ email: ['', Validators.required], confirm: ['', Validators.required] }), questions: this.fb.group({ quest2: ['', Validators.required], }), }); } I would usually set the value like this: this.user.controls['quest1'].setValue('false'); But because the formGroups are nested, I'm not sure how to set the nested values. How do I set a value for "quest2"? What's the correct syntax for set a form control value in a nested formGroup? A: You can do it using the syntax below: this.user.get('questions.quest2').setValue(false); Note that setValue method throws an error if some control is missing. So, if you don't want to update all controls, you can use patchValue: this.user.get('questions.quest2').patchValue(false); or this.user.get(['questions', 'quest2']).patchValue(false); or this.user.patchValue({questions: {quest2: false}});
Q: How do I set the value of a nested formBuilder group My nested form is currently formatted in this way: ngOnInit() { this.user = this.fb.group({ name: ['', [Validators.required, Validators.minLength(2)]], quest1: ['', Validators.required], account: this.fb.group({ email: ['', Validators.required], confirm: ['', Validators.required] }), questions: this.fb.group({ quest2: ['', Validators.required], }), }); } I would usually set the value like this: this.user.controls['quest1'].setValue('false'); But because the formGroups are nested, I'm not sure how to set the nested values. How do I set a value for "quest2"? What's the correct syntax for set a form control value in a nested formGroup? A: You can do it using the syntax below: this.user.get('questions.quest2').setValue(false); Note that setValue method throws an error if some control is missing. So, if you don't want to update all controls, you can use patchValue: this.user.get('questions.quest2').patchValue(false); or this.user.get(['questions', 'quest2']).patchValue(false); or this.user.patchValue({questions: {quest2: false}});
stackoverflow
{ "language": "en", "length": 139, "provenance": "stackexchange_0000F.jsonl.gz:869959", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44557772" }
8a18603ae0649b573f684461ed891e437f98fa4d
Stackoverflow Stackexchange Q: Backpressure in storm In our storm 1.0.2 application we are facing out of memory exceptions.Upon debugging we saw that the Kafka spout was emitting too many messages to the bolts . The bolts were running at a capacity of almost 4.0. So is there a way to enable backpressure in storm so that the spout emits depending on the capacity in bolts. Tried enabling the topology.backpressure.enable to true but ran to this issue https://issues.apache.org/jira/browse/STORM-1949. We are using the out of the box implementation of KafkaSpout and extending the BaseRichBolt for our bolts .Our DAG is linear. A: You can handle the back pressure of the KafkaSpout by setting the maxSpoutPending value in the topology configuration, Config config = new Config(); config.setMaxSpoutPending(200); config.setMessageTimeoutSecs(100); StormSubmitter.submitTopology("testtopology", config, builder.createTopology()); maxSpoutPending is the number of tuples that can be pending acknowledgement in your topology at a given time. Setting this property, will intimate the KafkaSpout not to consume any more data from Kafka unless the unacknowledged tuple count is less than maxSpoutPending value.
Q: Backpressure in storm In our storm 1.0.2 application we are facing out of memory exceptions.Upon debugging we saw that the Kafka spout was emitting too many messages to the bolts . The bolts were running at a capacity of almost 4.0. So is there a way to enable backpressure in storm so that the spout emits depending on the capacity in bolts. Tried enabling the topology.backpressure.enable to true but ran to this issue https://issues.apache.org/jira/browse/STORM-1949. We are using the out of the box implementation of KafkaSpout and extending the BaseRichBolt for our bolts .Our DAG is linear. A: You can handle the back pressure of the KafkaSpout by setting the maxSpoutPending value in the topology configuration, Config config = new Config(); config.setMaxSpoutPending(200); config.setMessageTimeoutSecs(100); StormSubmitter.submitTopology("testtopology", config, builder.createTopology()); maxSpoutPending is the number of tuples that can be pending acknowledgement in your topology at a given time. Setting this property, will intimate the KafkaSpout not to consume any more data from Kafka unless the unacknowledged tuple count is less than maxSpoutPending value.
stackoverflow
{ "language": "en", "length": 169, "provenance": "stackexchange_0000F.jsonl.gz:870005", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44557915" }
5fa72afd07167d28966768dec2c011e97f6edc17
Stackoverflow Stackexchange Q: "Unexpected indentation" with restructuredtext list I did not succeed to get a simple 3 levels indented list with Restructuredtext: $ cat test.rst Title ====== - aaaa - aaaa2 - aaaa2 - aaaa3 - aaaa - aaaa Ok $ rst2html test.rst > /tmp/a.html test.rst:7: (ERROR/3) Unexpected indentation. $ I've try different combination of spaces in front of aaaa3 but I get in all cases (ERROR/3) Unexpected indentation. A: Nested lists are tricky because different levels require blank lines between those levels. Nested lists are possible, but be aware that they must be separated from the parent list items by blank lines This should work: - aaaa - aaaa2 - aaaa2 - aaaa3 - aaaa - aaaa
Q: "Unexpected indentation" with restructuredtext list I did not succeed to get a simple 3 levels indented list with Restructuredtext: $ cat test.rst Title ====== - aaaa - aaaa2 - aaaa2 - aaaa3 - aaaa - aaaa Ok $ rst2html test.rst > /tmp/a.html test.rst:7: (ERROR/3) Unexpected indentation. $ I've try different combination of spaces in front of aaaa3 but I get in all cases (ERROR/3) Unexpected indentation. A: Nested lists are tricky because different levels require blank lines between those levels. Nested lists are possible, but be aware that they must be separated from the parent list items by blank lines This should work: - aaaa - aaaa2 - aaaa2 - aaaa3 - aaaa - aaaa
stackoverflow
{ "language": "en", "length": 116, "provenance": "stackexchange_0000F.jsonl.gz:870016", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44557957" }
671bf769030312cc536ef9dfced5692eb440842d
Stackoverflow Stackexchange Q: Your repository has no remotes configured to push to I am using Visual Studio Code and running into the message below while trying to check in. Your repository has no remotes configured to push to. This is right after I upgrade from the April version on the Macintosh to the May version. I upgraded since I was getting an infinite progress bar during a git update. Does anybody have any ideas how to fix this? I have used the command line to verify that I do indeed have remotes configured. Can't post them here since it will show inter company info :(. Please help. A: Check the Github adding a remote article official doc which have better code highlighting and infos but if you are an experienced user, just check out below commands and note that only the first command is required and second one is just for verifying and will return related repo details. git remote add origin https://github.com/user/repo.git git remote -v Git Remote add Command dissection * *params: * *remote name: origin (a default name for a remote Repo in Git ) *remote url: https://github.com/user/repo.git (in this example)
Q: Your repository has no remotes configured to push to I am using Visual Studio Code and running into the message below while trying to check in. Your repository has no remotes configured to push to. This is right after I upgrade from the April version on the Macintosh to the May version. I upgraded since I was getting an infinite progress bar during a git update. Does anybody have any ideas how to fix this? I have used the command line to verify that I do indeed have remotes configured. Can't post them here since it will show inter company info :(. Please help. A: Check the Github adding a remote article official doc which have better code highlighting and infos but if you are an experienced user, just check out below commands and note that only the first command is required and second one is just for verifying and will return related repo details. git remote add origin https://github.com/user/repo.git git remote -v Git Remote add Command dissection * *params: * *remote name: origin (a default name for a remote Repo in Git ) *remote url: https://github.com/user/repo.git (in this example) A: Restart VS Code editor use below commands on vscode: command1: on vscode terminal change directory to project folder to push your vscode on github: command2: git push -u origin master github signin popup will appear signed it goto GitHub account repository and refresh it example-->> https://github.com/username/projectfoldername it worked for me and I hope it will solve your problem now your VS Code file will be available on GitHub. A: Working with Remotes To be able to collaborate on any Git project, you need to know how to manage your remote repositories. Remote repositories are versions of your project that are hosted on the Internet or network somewhere. You can have several of them, each of which generally is either read-only or read/write for you. Collaborating with others involves managing these remote repositories and pushing and pulling data to and from them when you need to share work. Managing remote repositories includes knowing how to add remote repositories, remove remotes that are no longer valid, manage various remote branches and define them as being tracked or not, and more. In this section, we’ll cover some of these remote-management skills. Showing Your Remotes To see which remote servers you have configured, you can run the git remote command. It lists the shortnames of each remote handle you’ve specified. If you’ve cloned your repository, you should at least see origin – that is the default name Git gives to the server you cloned from: $ git clone https://github.com/schacon/ticgit Cloning into 'ticgit'... remote: Reusing existing pack: 1857, done. remote: Total 1857 (delta 0), reused 0 (delta 0) Receiving objects: 100% (1857/1857), 374.35 KiB | 268.00 KiB/s, done. Resolving deltas: 100% (772/772), done. Checking connectivity... done. $ cd ticgit $ git remote origin You can also specify -v, which shows you the URLs that Git has stored for the shortname to be used when reading and writing to that remote: $ git remote -v origin https://github.com/schacon/ticgit (fetch) origin https://github.com/schacon/ticgit (push) A: enter git remote -v if see like this result origin https://github.com/xxx/yyy Close Vs Code And Open Again A: If you are using VS Code. 1.Go to View->Command pallete->git:add remote (This will create a remote) 2.Give a name(Usually the same as the project name) 3.It will now ask you to give a repository url, Create one and paste the link. 4. You can commit and push accordingly.
stackoverflow
{ "language": "en", "length": 584, "provenance": "stackexchange_0000F.jsonl.gz:870017", "question_score": "53", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44557960" }
d45ca71cf2d7499e32f593ef0f976da73c90c0dc
Stackoverflow Stackexchange Q: Display html element from JSON object on ionic App I have been trying to embed html element from JSON object, and It is currently displaying the html as raw code instead. Can someone please help me ? detail.ts this.questionsData[i].question_type.title = "<ion-input type=\"text\" placeholder=\"Short answer\"></ion-input>"; detail.html <ion-item *ngFor="let question of questionsData"> {{question.title}} <br> Text : {{question.question_type.title}} <br> <div [innerHTML]="question.question_type.title"> </div> </ion-item> Isn't it should be input box under the text : , anyone know why it's not rendered ? Thanks A: InnerHtml will only help to render pure html code on run time, you can't use ionic components to render dynamically using innerhtml. I think you need to use dynamic component loader feature in angular here. You can refer this link on use cases of this feature https://medium.com/@DenysVuika/dynamic-content-in-angular-2-3c85023d9c36
Q: Display html element from JSON object on ionic App I have been trying to embed html element from JSON object, and It is currently displaying the html as raw code instead. Can someone please help me ? detail.ts this.questionsData[i].question_type.title = "<ion-input type=\"text\" placeholder=\"Short answer\"></ion-input>"; detail.html <ion-item *ngFor="let question of questionsData"> {{question.title}} <br> Text : {{question.question_type.title}} <br> <div [innerHTML]="question.question_type.title"> </div> </ion-item> Isn't it should be input box under the text : , anyone know why it's not rendered ? Thanks A: InnerHtml will only help to render pure html code on run time, you can't use ionic components to render dynamically using innerhtml. I think you need to use dynamic component loader feature in angular here. You can refer this link on use cases of this feature https://medium.com/@DenysVuika/dynamic-content-in-angular-2-3c85023d9c36 A: Your approach needs to change, do not include html tags in component block, instead add parameters as json data and set it at component. Then you can interpolate the tags in the template view. Ex: at the component: this.inputDataArray = [{"title":"What cartoon do you like to watch?", "name":"inp1","placeholder":"short answer"},{"title":"What movie do you like to watch?", "name":"inp2","placeholder":"short answer"}]; at the view: <ion-item *ngFor="let question of inputDataArray"> {{question.title}} <br> Text : <input name={{question.name}} placeholder={{question.placeholder}} /> <br> </ion-item> Its just a reference, Hope it helps A: This worked for me. <div [innerHTML]="data.text"></div>
stackoverflow
{ "language": "en", "length": 218, "provenance": "stackexchange_0000F.jsonl.gz:870038", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558028" }
d83809c5528d81dcab77659f2fd34422b32cd908
Stackoverflow Stackexchange Q: What are double colons :: in a shell script? What is double colon :: in shell scripts? like this piece of script: function guess_built_binary_path { local hyperkube_path=$(kube::util::find-binary "hyperkube") if [[ -z "${hyperkube_path}" ]]; then return fi echo -n "$(dirname "${hyperkube_path}")" } I found it in here: https://github.com/kubernetes/kubernetes/blob/master/hack/local-up-cluster.sh A: Although it seems like Bash allows putting colons in function names, this behaviour is not standardized by POSIX. Function names should consist of underscores, digits, and letters from the portable set.
Q: What are double colons :: in a shell script? What is double colon :: in shell scripts? like this piece of script: function guess_built_binary_path { local hyperkube_path=$(kube::util::find-binary "hyperkube") if [[ -z "${hyperkube_path}" ]]; then return fi echo -n "$(dirname "${hyperkube_path}")" } I found it in here: https://github.com/kubernetes/kubernetes/blob/master/hack/local-up-cluster.sh A: Although it seems like Bash allows putting colons in function names, this behaviour is not standardized by POSIX. Function names should consist of underscores, digits, and letters from the portable set. A: The :: is just a Naming Convention for function names. Is a coding-style such as snake_case or CamelCase The convention for Function names in shell style commonly is: Lower-case, with underscores to separate words. Separate libraries with ::. Parentheses are required after the function name. The keyword function is optional, but must be used consistently throughout a project. You can check here. A: It's nothing, these colons are part of the command names apparently. You can verify yourself by creating and running a command with : in the name. The shell by default will autoescape them and its all perfectly legal.
stackoverflow
{ "language": "en", "length": 182, "provenance": "stackexchange_0000F.jsonl.gz:870053", "question_score": "30", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558080" }
d955a88a449e88b20a3dd52052658a027a82678f
Stackoverflow Stackexchange Q: How to read csv without header and name them with names while reading in pyspark? 100000,20160214,93374987 100000,20160214,1925301 100000,20160216,1896542 100000,20160216,84167419 100000,20160216,77273616 100000,20160507,1303015 I want to read the csv file which has no column names in first row. How to read it and name the columns with my specified names in the same time ? for now, I just renamed the original columns with my specified names like this: df = spark.read.csv("user_click_seq.csv",header=False) df = df.withColumnRenamed("_c0", "member_srl") df = df.withColumnRenamed("_c1", "click_day") df = df.withColumnRenamed("_c2", "productid") Any better way ? A: You can import the csv file into a dataframe with a predefined schema. The way you define a schema is by using the StructType and StructField objects. Assuming your data is all IntegerType data: from pyspark.sql.types import StructType, StructField, IntegerType schema = StructType([ StructField("member_srl", IntegerType(), True), StructField("click_day", IntegerType(), True), StructField("productid", IntegerType(), True)]) df = spark.read.csv("user_click_seq.csv",header=False,schema=schema) should work.
Q: How to read csv without header and name them with names while reading in pyspark? 100000,20160214,93374987 100000,20160214,1925301 100000,20160216,1896542 100000,20160216,84167419 100000,20160216,77273616 100000,20160507,1303015 I want to read the csv file which has no column names in first row. How to read it and name the columns with my specified names in the same time ? for now, I just renamed the original columns with my specified names like this: df = spark.read.csv("user_click_seq.csv",header=False) df = df.withColumnRenamed("_c0", "member_srl") df = df.withColumnRenamed("_c1", "click_day") df = df.withColumnRenamed("_c2", "productid") Any better way ? A: You can import the csv file into a dataframe with a predefined schema. The way you define a schema is by using the StructType and StructField objects. Assuming your data is all IntegerType data: from pyspark.sql.types import StructType, StructField, IntegerType schema = StructType([ StructField("member_srl", IntegerType(), True), StructField("click_day", IntegerType(), True), StructField("productid", IntegerType(), True)]) df = spark.read.csv("user_click_seq.csv",header=False,schema=schema) should work. A: You can read the data with header=False and then pass the column names with toDF as bellow: data = spark.read.csv('data.csv', header=False) data = data.toDF('name1', 'name2', 'name3') A: For those who would like to do this in scala and may not want to add types: val df = spark.read.format("csv") .option("header","false") .load("hdfs_filepath") .toDF("var0","var1","var2","var3") A: In my case, it handled many columns and creating a schema was very tedious when, in addition, spark inferred the schema well. So I opted to rename it using a select. First I create a list with the new names: val listNameColumns: List[String] = List("name1", "name2" , "name3") Then I combine the column names of the original dataframe with the above list and create a list of Column elements: import org.apache.spark.sql.Column import org.apache.spark.sql.functions.col val selectStament: Array[Column] = df.columns zip listNameColumns map { case(a, b) => col(a).as(b)} Finally I make the select: val dfRenamed = df.select(selectStament:_*)
stackoverflow
{ "language": "en", "length": 293, "provenance": "stackexchange_0000F.jsonl.gz:870077", "question_score": "38", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558139" }
687e987d3419cd44db239a839e0697900c39060d
Stackoverflow Stackexchange Q: Nuclide debugger with node and babel? I've been trying to use Nuclide/Atom to launch and debug a unit test that uses Babel and ES6+ code. The launch config looks like this: Node runs the unit test as if I had run it from the command-line, and does not stop at my breakpoints. If I use the same invocation at the command-line with --inspect-brk I can debug correctly (with sourcemaps) from the chrome-devtools url in Chrome. Is there a way to make this work? I can't really "attach" since the unit tests are, and should be, a straight-shot script execution. A: Nuclide currently does not support the new v8 Inspector protocol for debugging. You will need to use --debug flag to debug with Nuclide. Note, however, that the old debugger protocol has been removed from Node.js starting with Node.js 8.0. PS. You can attach to a running Node.js process with Nuclide debugger just fine - just start your tests with node --debug --debug-brk ... and then attach the debugger from Nuclide. The test process will be stopped at first line, allowing you to resume execution at your own convenience.
Q: Nuclide debugger with node and babel? I've been trying to use Nuclide/Atom to launch and debug a unit test that uses Babel and ES6+ code. The launch config looks like this: Node runs the unit test as if I had run it from the command-line, and does not stop at my breakpoints. If I use the same invocation at the command-line with --inspect-brk I can debug correctly (with sourcemaps) from the chrome-devtools url in Chrome. Is there a way to make this work? I can't really "attach" since the unit tests are, and should be, a straight-shot script execution. A: Nuclide currently does not support the new v8 Inspector protocol for debugging. You will need to use --debug flag to debug with Nuclide. Note, however, that the old debugger protocol has been removed from Node.js starting with Node.js 8.0. PS. You can attach to a running Node.js process with Nuclide debugger just fine - just start your tests with node --debug --debug-brk ... and then attach the debugger from Nuclide. The test process will be stopped at first line, allowing you to resume execution at your own convenience.
stackoverflow
{ "language": "en", "length": 189, "provenance": "stackexchange_0000F.jsonl.gz:870082", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558149" }
585cae6bcb077513591cbce029170880a57dfd48
Stackoverflow Stackexchange Q: Why can I import animation components from both @angular/animations and @angular/core? I recently updated to angular 4 and checking the animations docs I see I should import trigger, animate and transition from @angular/animations. import { Component, Input } from '@angular/core'; import { trigger, state, style, animate, transition } from '@angular/animations'; In my project however I have been importing from @angular/core so far and everything works fine, even after animations were separated from core. import { ... trigger, state, style, animate, transition } from '@angular/core'; Why does angular core still hold these animation components ? Backwards compatability maybe ? Why not just remove it completely from core? A: Imports from @angular/core were deprecated. https://angular.io/api/core/animate This symbol has moved. Please Import from @angular/animations instead! I think they will remove them from core one day.
Q: Why can I import animation components from both @angular/animations and @angular/core? I recently updated to angular 4 and checking the animations docs I see I should import trigger, animate and transition from @angular/animations. import { Component, Input } from '@angular/core'; import { trigger, state, style, animate, transition } from '@angular/animations'; In my project however I have been importing from @angular/core so far and everything works fine, even after animations were separated from core. import { ... trigger, state, style, animate, transition } from '@angular/core'; Why does angular core still hold these animation components ? Backwards compatability maybe ? Why not just remove it completely from core? A: Imports from @angular/core were deprecated. https://angular.io/api/core/animate This symbol has moved. Please Import from @angular/animations instead! I think they will remove them from core one day. A: Taken from the changelog. It is deprecated but you can still use it in your app. Not all programmers have the luxury to update their apps on every new release. It is just a warning that you should update your code, so that when the major release happens, your migration will be smooth. Hope this helps.
stackoverflow
{ "language": "en", "length": 190, "provenance": "stackexchange_0000F.jsonl.gz:870099", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558184" }
97fc9e4fe76df7589da3402a2bfc6b683299e393
Stackoverflow Stackexchange Q: Unrecognised font family ‘Ionicons’ error - Native Base I am trying to use native base icons in my app but every time i am getting Unrecognized font family ‘Ionicons’ error. I searched it on google and tried everything. like rm -rf node_modules && npm install react-native link react-native-vector-icons react-native start --reset-cache can anybody tell me some basic setups like where should I create my resource folder and all for this fix? Thanks A: I think you have to create folder call "Resources" in your Xcode project and place Ionicons.ttf file inside that folder. Try setup iOS Manually here (https://github.com/oblador/react-native-vector-icons) * *Browse to node_modules/react-native-vector-icons and drag the folder Fonts (or just the ones you want) to your project in Xcode. Make sure your app is checked under "Add to targets" and that "Create groups" is checked if you add the whole folder. *Edit Info.plist and add a property called Fonts provided by application.
Q: Unrecognised font family ‘Ionicons’ error - Native Base I am trying to use native base icons in my app but every time i am getting Unrecognized font family ‘Ionicons’ error. I searched it on google and tried everything. like rm -rf node_modules && npm install react-native link react-native-vector-icons react-native start --reset-cache can anybody tell me some basic setups like where should I create my resource folder and all for this fix? Thanks A: I think you have to create folder call "Resources" in your Xcode project and place Ionicons.ttf file inside that folder. Try setup iOS Manually here (https://github.com/oblador/react-native-vector-icons) * *Browse to node_modules/react-native-vector-icons and drag the folder Fonts (or just the ones you want) to your project in Xcode. Make sure your app is checked under "Add to targets" and that "Create groups" is checked if you add the whole folder. *Edit Info.plist and add a property called Fonts provided by application. A: for anyone facing similar issue while using the following combination "native-base": "^2.8.1", "react": "16.6.1", "react-native": "0.57.7", "react-native-gesture-handler": "^1.0.10", "react-native-vector-icons": "^6.1.0", "react-navigation": "^3.0.8", first clean the node_modules folder, then reinstall and also link rm -rf node_modules npm i react-native link then from xcode clean and then build for the ios project and run it in the simulator from xcode itself. A: I faced same issue. Following steps helped me out: * *Install react-native-vector-icons npm *Install pod And you are good to go.
stackoverflow
{ "language": "en", "length": 235, "provenance": "stackexchange_0000F.jsonl.gz:870149", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558326" }
7459a6e25c6a04f71740d2edc0c2bef07b5be327
Stackoverflow Stackexchange Q: Finding string index of a tag in BeautifulSoup Does BeautifulSoup provide a method to get the string index of a tag or its text within the HTML string it comes from? For example: from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> </body> </html> """ soup = BeautifulSoup(html_doc, 'lxml') Is there a way to know the string index inside html_doc where soup.p (<p class="title"><b>The Dormouse's Story</b></p>) starts? Or where its text (The Dormouse's story) starts? EDIT: The expected index for soup.p would be 63, i.e. html_doc.index('''<p class="title"><b>The Dormouse's story</b></p>'''). The expected index for its text would be 83. I am not using str.index() since the returned index might not correspond to the tag in question. A: It appears that you are doing some web scraping. I suggest you check out XPath - Google around for XPath libraries in the language you are coding in. Using XPath selectors, you can find text elements like: ("//text()[contains(.,"The Dormouse's story")]") From here on, it is only a matter of selecting its parent class if you need the paragraph element.
Q: Finding string index of a tag in BeautifulSoup Does BeautifulSoup provide a method to get the string index of a tag or its text within the HTML string it comes from? For example: from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> </body> </html> """ soup = BeautifulSoup(html_doc, 'lxml') Is there a way to know the string index inside html_doc where soup.p (<p class="title"><b>The Dormouse's Story</b></p>) starts? Or where its text (The Dormouse's story) starts? EDIT: The expected index for soup.p would be 63, i.e. html_doc.index('''<p class="title"><b>The Dormouse's story</b></p>'''). The expected index for its text would be 83. I am not using str.index() since the returned index might not correspond to the tag in question. A: It appears that you are doing some web scraping. I suggest you check out XPath - Google around for XPath libraries in the language you are coding in. Using XPath selectors, you can find text elements like: ("//text()[contains(.,"The Dormouse's story")]") From here on, it is only a matter of selecting its parent class if you need the paragraph element. A: from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="title"><b>The Dormouse's story</b></p> </body> </html> """ def findall(patt, s): '''Yields all the positions of the pattern patt in the string s.''' i = s.find(patt) while i != -1: yield i i = s.find(patt, i+1) soup = BeautifulSoup(html_doc, 'html.parser') x = str(soup) y = str(soup.find("p", {'class':'title'})) print([(i, x[i:i+len(y)]) for i in findall(y, x)]) A: You can do like this. print(soup.find("p").text) The output is, The Dormouse's story Can change the html_doc content for verify the code logic. Change the html_doc like this. html_doc = """ <html><head><title>The EEEE's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> </body> </html> """ The code had the same output with above.
stackoverflow
{ "language": "en", "length": 301, "provenance": "stackexchange_0000F.jsonl.gz:870162", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558375" }
4efe8faf90e55e08c1b58c8aebc21d4c9b64b46b
Stackoverflow Stackexchange Q: How do you set the PHP error log location in the Apache configuration file? We have an out-of-the-box PHP application running on a subdomain, and it's logging errors in its DocumentRoot: /var/www/appname/path/to/document/root/php-errors.log ...instead of where we want the error logs to go: /var/www/appname/logs/php-errors.log Since I don't want to change the code in the out-of-the-box application, and I don't want to change the error log location for all the subdomains (read: file php.ini), how can I do this in just the Apache configuration file that relates to the subdomain? A: From error_log per Virtual Host?: <VirtualHost *:80> ServerName example.com DocumentRoot /var/www/domains/example.com/html ErrorLog /var/www/domains/example.com/apache.error.log CustomLog /var/www/domains/example.com/apache.access.log common php_flag log_errors on php_flag display_errors on php_value error_reporting 2147483647 php_value error_log /var/www/domains/example.com/php.error.log </VirtualHost>
Q: How do you set the PHP error log location in the Apache configuration file? We have an out-of-the-box PHP application running on a subdomain, and it's logging errors in its DocumentRoot: /var/www/appname/path/to/document/root/php-errors.log ...instead of where we want the error logs to go: /var/www/appname/logs/php-errors.log Since I don't want to change the code in the out-of-the-box application, and I don't want to change the error log location for all the subdomains (read: file php.ini), how can I do this in just the Apache configuration file that relates to the subdomain? A: From error_log per Virtual Host?: <VirtualHost *:80> ServerName example.com DocumentRoot /var/www/domains/example.com/html ErrorLog /var/www/domains/example.com/apache.error.log CustomLog /var/www/domains/example.com/apache.access.log common php_flag log_errors on php_flag display_errors on php_value error_reporting 2147483647 php_value error_log /var/www/domains/example.com/php.error.log </VirtualHost> A: For those wishing to do this using php-fpm (which I meant to originally post about), here's how you do it: Ensure you're logged in as root, or using sudo for all your commands. Go into your php-fpm directory*, using the command below: cd /etc/php/fpm/ In that directory, edit your php.ini file and add the following to the end: If you want to set error log by host [HOST=www.example.com] error_log=/var/www/myapplication/path/to/my/error.log [HOST=sub.example.com] error_log=/var/www/mysubapplication/path/to/my/error.log If you want to set error log by path (handy if you're working on a server with an IP address but no domain) [PATH=/var/www/myapplication] error_log=/var/www/myapplication/path/to/my/error.log [PATH=/var/www/mysubapplication] error_log=/var/www/mysubapplication/path/to/my/error.log You now need to go into the pool directory*, using the command below: cd /etc/php/fpm/pool.d/ In that directory, edit the file www.conf. Note the values for user and group in that file, whose out-of-the-box setting is www-data for both. Look for the term catch_workers_output and make sure it is uncommented and set to yes, like so: catch_workers_output = yes Now you need to create the error log file(s) and ensure that php-fpm has access to it. This is why you needed to note the values for user and group from the previous file edit. Create an error log file for each HOST/PATH you set when editing php.ini and give them the appropriate permissions and ownership, for example: touch /var/www/myapplication/path/to/my/error.log chmod 0660 /var/www/myapplication/path/to/my/error.log chown www-data:www-data /var/www/myapplication/path/to/my/error.log Finally, restart your php-fpm service using the command** below: service php-fpm restart * Note: If, like me, you install declared versions of php-fpm, the directory paths will change to (for example) the following: /etc/php/5.6/fpm/ /etc/php/5.6/fpm/pool.d/ /etc/php/7.1/fpm/ /etc/php/7.1/fpm/pool.d/ ** The service takes a specific versioned name if you installed declared versions, and you will need use (for example) the following: service php5.6-fpm restart service php7.1-fpm restart A: I configure it like this: File /etc/apache2/envvars # For supporting multiple Apache 2 instances if [ "${APACHE_CONFDIR##/etc/apache2-}" != "${APACHE_CONFDIR}" ] ; then SUFFIX="-${APACHE_CONFDIR##/etc/apache2-}" else SUFFIX= fi export APACHE_LOG_DIR=/var/log/apache2$SUFFIX File /etc/apache2/sites-available/000-default.conf ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined
stackoverflow
{ "language": "en", "length": 444, "provenance": "stackexchange_0000F.jsonl.gz:870163", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558380" }
06b1b0d9de21ecb6bf51d686de554f9fd5409ec3
Stackoverflow Stackexchange Q: MATLAB Fill area between two contour plots I have two contour plots and I want to be able to fill from one contour in one image to the same height contour in the other. In the plot you can see two lines of each color - these are the lines I want to fill between, with the same color as the lines (though preferably translucent). The code for these are as follows test = repmat(repelem(0:6,2),10,1); test1 = test(:,2:end-1); test2 = test(:,1:end-2); contour(test1,1:5); hold on; contour(test2,1:5); I did think that maybe I could create another image that has the desired height at each bin and do some kind of contourf, but that could be a problem if in future the lines cross over, which they may well do. In that case, I'd like the area they cross to be a combination of the colors that are crossing over. A: Have you try using ```fill``? % test values col = 'g'; x1=[6 6 6];y1=[1 5 10]; x2= [7 7 7]; x2 = [x1, fliplr(x2)]; inBetween = [y1, fliplr(y1)]; fill(x2, inBetween, col);
Q: MATLAB Fill area between two contour plots I have two contour plots and I want to be able to fill from one contour in one image to the same height contour in the other. In the plot you can see two lines of each color - these are the lines I want to fill between, with the same color as the lines (though preferably translucent). The code for these are as follows test = repmat(repelem(0:6,2),10,1); test1 = test(:,2:end-1); test2 = test(:,1:end-2); contour(test1,1:5); hold on; contour(test2,1:5); I did think that maybe I could create another image that has the desired height at each bin and do some kind of contourf, but that could be a problem if in future the lines cross over, which they may well do. In that case, I'd like the area they cross to be a combination of the colors that are crossing over. A: Have you try using ```fill``? % test values col = 'g'; x1=[6 6 6];y1=[1 5 10]; x2= [7 7 7]; x2 = [x1, fliplr(x2)]; inBetween = [y1, fliplr(y1)]; fill(x2, inBetween, col);
stackoverflow
{ "language": "en", "length": 180, "provenance": "stackexchange_0000F.jsonl.gz:870165", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558393" }
ded5a84f6bb9e42ef06d391bee9acf1d7630fe46
Stackoverflow Stackexchange Q: "contains" in Bigquery standard SQL I wish to migrate from Legacy SQL to Standard SQL I had the following code in Legacy SQL SELECT hits.page.pageTitle FROM [mytable] WHERE hits.page.pageTitle contains '%' And I tried this in Standard SQL: SELECT hits.page.pageTitle FROM `mytable` WHERE STRPOS(hits.page.pageTitle, "%") But it gives me this error: Error: Cannot access field page on a value with type ARRAY> at [4:21] A: Try this one: SELECT hits.page.pageTitle FROM `table`, UNNEST(hits) hits WHERE REGEXP_CONTAINS(hits.page.pageTitle, r'%') LIMIT 1000 In ga_sessions schema, "hits" is an ARRAY (that is, REPEATED mode). You need to apply the UNNEST operation in order to work with arrays in BigQuery.
Q: "contains" in Bigquery standard SQL I wish to migrate from Legacy SQL to Standard SQL I had the following code in Legacy SQL SELECT hits.page.pageTitle FROM [mytable] WHERE hits.page.pageTitle contains '%' And I tried this in Standard SQL: SELECT hits.page.pageTitle FROM `mytable` WHERE STRPOS(hits.page.pageTitle, "%") But it gives me this error: Error: Cannot access field page on a value with type ARRAY> at [4:21] A: Try this one: SELECT hits.page.pageTitle FROM `table`, UNNEST(hits) hits WHERE REGEXP_CONTAINS(hits.page.pageTitle, r'%') LIMIT 1000 In ga_sessions schema, "hits" is an ARRAY (that is, REPEATED mode). You need to apply the UNNEST operation in order to work with arrays in BigQuery.
stackoverflow
{ "language": "en", "length": 106, "provenance": "stackexchange_0000F.jsonl.gz:870186", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558448" }
7511b28113bf0fb58de4995894c0c76f1adf5dc1
Stackoverflow Stackexchange Q: Compare two Animated Interpolations objects together in react native I need to compare the values of two AnimatedInterpolation objects in react-native. I want to know which AnimatedInterpolation has the smallest decimal value. Interpolation documentation Unfortunately, Math.min(value1, value2) doesn't work. How can I get the float value of an AnimatedInterpolation object ? I have tried the following : interpolateOpacity = () => { let xOpacity = this.state.pan.x.interpolate({ inputRange: this.props.inputOpacityRangeX, outputRange: this.props.outputOpacityRangeX }); let yOpacity = this.state.pan.y.interpolate({ inputRange: this.props.inputOpacityRangeY, outputRange: this.props.outputOpacityRangeY }); return Math.min(xOpacity, yOpacity) // NOT WORKING }; Debugger: A: The way I would do this would be to compare the input values. If your mapping for the output range isn't significantly complicated, you should be able to compare the input ranges like this by accessing this.state.pan.x._value and this.state.pan.y._value, or better practice would be to set up a listener as described here. I don't think there is a way to compare the interpolated values in real-time.
Q: Compare two Animated Interpolations objects together in react native I need to compare the values of two AnimatedInterpolation objects in react-native. I want to know which AnimatedInterpolation has the smallest decimal value. Interpolation documentation Unfortunately, Math.min(value1, value2) doesn't work. How can I get the float value of an AnimatedInterpolation object ? I have tried the following : interpolateOpacity = () => { let xOpacity = this.state.pan.x.interpolate({ inputRange: this.props.inputOpacityRangeX, outputRange: this.props.outputOpacityRangeX }); let yOpacity = this.state.pan.y.interpolate({ inputRange: this.props.inputOpacityRangeY, outputRange: this.props.outputOpacityRangeY }); return Math.min(xOpacity, yOpacity) // NOT WORKING }; Debugger: A: The way I would do this would be to compare the input values. If your mapping for the output range isn't significantly complicated, you should be able to compare the input ranges like this by accessing this.state.pan.x._value and this.state.pan.y._value, or better practice would be to set up a listener as described here. I don't think there is a way to compare the interpolated values in real-time. A: You could probably using something like this.state.pan.y.__getValue(). If that isn't effective, I'd recommend adding a listener to the animated value and using that value instead like so: this.state.pan = new Animated.Value({ x: 0, y: 0 }); this.panValue = { x: 0, y: 0 }; this.state.pan.addListener((value) => this.panValue = value); // value is an object with x and y props Also, don't forget to set and reset the values and offsets like so: onPanResponderGrant: () => { this.state.pan.setOffset({ x: this.panValue.x, y: this.panValue.y }); this.state.pan.setValue(0); }, onPanResponderMove: (evt, { dx, dy }) => { this.state.pan.setValue({ x: dx, y: dy}); }
stackoverflow
{ "language": "en", "length": 255, "provenance": "stackexchange_0000F.jsonl.gz:870197", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558466" }
995d5294902f608fb7ec8d89d2327d1eeba798a7
Stackoverflow Stackexchange Q: Notification action icon didn't show I try to show a notification in Android, and use the code from this Link. In some source people said that the icon should be totally white and some source said I should use .png instead of vector. I try all of this ways but no one didn't help me. I try this code: Notification newMessageNotification = new Notification.Builder(mContext) .setSmallIcon(R.drawable.ic_message) .setContentTitle(getString(R.string.title)) .setContentText(getString(R.string.content)) .addAction(action)) .build(); A: after search about 1 hour in all the question with this topic finally I find out it's because of my android version! look at the image below. In Api level 24 an above, there is no icon in design!!
Q: Notification action icon didn't show I try to show a notification in Android, and use the code from this Link. In some source people said that the icon should be totally white and some source said I should use .png instead of vector. I try all of this ways but no one didn't help me. I try this code: Notification newMessageNotification = new Notification.Builder(mContext) .setSmallIcon(R.drawable.ic_message) .setContentTitle(getString(R.string.title)) .setContentText(getString(R.string.content)) .addAction(action)) .build(); A: after search about 1 hour in all the question with this topic finally I find out it's because of my android version! look at the image below. In Api level 24 an above, there is no icon in design!! A: With Nougat they have changed design of Notification icons https://android-developers.googleblog.com/2016/06/notifications-in-android-n.html You’ll note that the icons are not present in the new notifications; instead more room is provided for the labels themselves in the constrained space of the notification shade. However, the notification action icons are still required and continue to be used on older versions of Android and on devices such as Android Wear. A: Notification icons must be entirely white If you want to support Lollipop Material Icons then make transparent icons for Lollipop and above version. Please refer following https://design.google.com/icons/
stackoverflow
{ "language": "en", "length": 203, "provenance": "stackexchange_0000F.jsonl.gz:870213", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558501" }
2a284963963ddd60ca85e8048577a7c0ea7a70a8
Stackoverflow Stackexchange Q: Remove specific migration in laravel As per laravel doc, To rollback the latest migration operation, you may use the rollback command. This command rolls back the last "batch" of migrations, which may include multiple migration files: php artisan migrate:rollback You may rollback a limited number of migrations by providing the step option to the rollback command. For example, the following command will rollback the last five migrations: php artisan migrate:rollback --step=5 The migrate:reset command will roll back all of your application's migrations: php artisan migrate:reset You can check here. But i need to remove the specific migration file. As per my project having 30-40 migration file. I want to remove one of the migration file and its model. Is there any way to do this or have to do it manually. A: Don’t. Migrations are version control for your database. “Removing” a particular migration is like removing a random commit from your Git repository’s history: it can have terrible consequences. Instead, if you no longer need a table, then create a new migration that drops that table in the up method, and recreates it in the down method so the migration can be rolled back.
Q: Remove specific migration in laravel As per laravel doc, To rollback the latest migration operation, you may use the rollback command. This command rolls back the last "batch" of migrations, which may include multiple migration files: php artisan migrate:rollback You may rollback a limited number of migrations by providing the step option to the rollback command. For example, the following command will rollback the last five migrations: php artisan migrate:rollback --step=5 The migrate:reset command will roll back all of your application's migrations: php artisan migrate:reset You can check here. But i need to remove the specific migration file. As per my project having 30-40 migration file. I want to remove one of the migration file and its model. Is there any way to do this or have to do it manually. A: Don’t. Migrations are version control for your database. “Removing” a particular migration is like removing a random commit from your Git repository’s history: it can have terrible consequences. Instead, if you no longer need a table, then create a new migration that drops that table in the up method, and recreates it in the down method so the migration can be rolled back. A: Delete the migration file, remove the table from the database, and also remove that file name from migrations table in the database. Sometimes, doing things manually is the best way. A: Just do it manually and save yourself the stress of further issues * *Delete the model first (if you don't) need the model any longer *Delete the migration from ...database/migrations folder *If you have already migrated i.e if you have already run php artisan migrate, log into your phpmyadmin or SQL(whichever the case is) and in your database, delete the table created by the migration *Still within your database, in the migrations folder, locate the row with that migration file name and delete the row. Works for me, hope it helps! A: If you simply remove (delete) the migration file and re-run the migrations (migrate:refresh), the database tables will be rebuilt (without the table that's defined in the migration file you deleted). A: you can increment the batch number of that particular migration to make it latest batch and run rollback command. Rollback one specific migration in Laravel
stackoverflow
{ "language": "en", "length": 376, "provenance": "stackexchange_0000F.jsonl.gz:870219", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558543" }
9dfcf134f51f0157b03cd0d9ea47aa9f28b8ee8e
Stackoverflow Stackexchange Q: Is there any way to adjust Netbeans to show history line by line aside programming area? I am using Git. For looking into history we need to click history tab and another window opens show dif to previous and current. Like Intellij, where history of Line is shown in left gadget, which show date and author who checked in code. Is there any way or plugin to get similar screens in netbeans? A: Right click on the editor's tab, then ghoose "Git -> Show Annotations" The last commit and the committer are shown in the left area of the editor then. If you hover the mouse over that is also shows you the commit message:
Q: Is there any way to adjust Netbeans to show history line by line aside programming area? I am using Git. For looking into history we need to click history tab and another window opens show dif to previous and current. Like Intellij, where history of Line is shown in left gadget, which show date and author who checked in code. Is there any way or plugin to get similar screens in netbeans? A: Right click on the editor's tab, then ghoose "Git -> Show Annotations" The last commit and the committer are shown in the left area of the editor then. If you hover the mouse over that is also shows you the commit message:
stackoverflow
{ "language": "en", "length": 116, "provenance": "stackexchange_0000F.jsonl.gz:870228", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558582" }
4f8074a296e5c0e7475d7f40b000cc98d91ebab7
Stackoverflow Stackexchange Q: How to check accuracy of Ellipsoid Fitting? I calibrated magnetometer HMC5883L for my IMU using Ellipsoid Fitting as done in this tip: http://www.st.com/content/ccc/resource/technical/document/design_tip/group0/a2/98/f5/d4/9c/48/4a/d1/DM00286302/files/DM00286302.pdf/jcr:content/translations/en.DM00286302.pdf . I get the offsets and the inverse transformation matrix to correct the hard iron and soft iron errors respectively. How can I check for the accuracy of the obtained offsets and transformation matrix? I tried searching for the same and found out two ways. There is the MotionCal GUI by Adafruit and the other one is a python program called PIEFACE. However, both of them use minimum volume enclosing ellipsoid fitting, which is an altogether different method from the one that I am using. Hence comparing my method with either of the two wouldn't be the correct way. Is there a way I can find out the correctness of my results?
Q: How to check accuracy of Ellipsoid Fitting? I calibrated magnetometer HMC5883L for my IMU using Ellipsoid Fitting as done in this tip: http://www.st.com/content/ccc/resource/technical/document/design_tip/group0/a2/98/f5/d4/9c/48/4a/d1/DM00286302/files/DM00286302.pdf/jcr:content/translations/en.DM00286302.pdf . I get the offsets and the inverse transformation matrix to correct the hard iron and soft iron errors respectively. How can I check for the accuracy of the obtained offsets and transformation matrix? I tried searching for the same and found out two ways. There is the MotionCal GUI by Adafruit and the other one is a python program called PIEFACE. However, both of them use minimum volume enclosing ellipsoid fitting, which is an altogether different method from the one that I am using. Hence comparing my method with either of the two wouldn't be the correct way. Is there a way I can find out the correctness of my results?
stackoverflow
{ "language": "en", "length": 136, "provenance": "stackexchange_0000F.jsonl.gz:870236", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558605" }
9f68afc0940b4897a787d761561e1af1138b300e
Stackoverflow Stackexchange Q: Fish alias pass multiple arguments, access specific argument I would like to create an alias in script for creating pull-requests using hub. I'm planning on creating a function like this. # PR function pr --description 'hub pr' hub pull-request -b $argv[0] -m $argv[1]; end The -m part can be optional though. So I can all it like this pr 'branch here' 'message here' But I get an error saying Array index out of bounds. A: function pr -d 'git pull-request' -a branch message set -q message[1] and set message -m $message hub pull-request -b $branch $message end
Q: Fish alias pass multiple arguments, access specific argument I would like to create an alias in script for creating pull-requests using hub. I'm planning on creating a function like this. # PR function pr --description 'hub pr' hub pull-request -b $argv[0] -m $argv[1]; end The -m part can be optional though. So I can all it like this pr 'branch here' 'message here' But I get an error saying Array index out of bounds. A: function pr -d 'git pull-request' -a branch message set -q message[1] and set message -m $message hub pull-request -b $branch $message end A: Fish arrays start at index 1, so your $argv[0] is wrong here. Use $argv[1] instead of that, and $argv[2] instead of the $argv[1] you currently have. However, currently any element except 1 will result in an array-index-out-of-bounds error if you try to access it and it isn't set, so you need to check if it is with set -q argv[2]. # PR function pr --description 'hub pr' set -l message if set -q argv[2] set message -m $argv[2] end hub pull-request -b $argv[1] $message; end (Also, https://github.com/fish-shell/fish-shell/issues/826 discusses removing index-out-of-bounds errors) A: Got it. But -m is not optional in this case. # PR function pr --description 'git pr' --argument-names message branch hub pull-request -m $message -b $branch; end And then you can type pr 'message' 'branch' A: There is another way to check your input using the test method in combination with count. Here is an example checking for greater than (gt) 1. if test (count $argv) -gt 1; set r_args $argv[2..-1];
stackoverflow
{ "language": "en", "length": 262, "provenance": "stackexchange_0000F.jsonl.gz:870250", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558668" }
cb77443f331793ac02ed10a4601a2822eaf1f026
Stackoverflow Stackexchange Q: Suitable replacement for HTA in Windows 10 I'm working in an office that uses something similar to Message of the Day here -> http://www.jhouseconsulting.com/2007/12/28/creating-a-message-of-the-day-banner-using-a-hta-4 But as we're upgrading to Windows 10 and it doesn't support HTA (ignoring IE9 compatibility) this will need replacing. Question is what can do the same thing, the provisos are: * *Not before Login (so not using Login Banner) *Only after Login Window *Should not be close-able except by using the "Agree to this MSG" button *Text will vary so need easy method to keep text from control(html file?) *will be distributed by DC (logon script) This application is used for Acknowledgement of Compliance and security information dissemination. Thanks for your thoughts, A: AFAIK Windows 10 can still run HTAs. If you want to force IE9 mode you can stick a meta tag in the head: <head> <meta http-equiv="X-UA-Compatible" content="IE=9" /> </head>
Q: Suitable replacement for HTA in Windows 10 I'm working in an office that uses something similar to Message of the Day here -> http://www.jhouseconsulting.com/2007/12/28/creating-a-message-of-the-day-banner-using-a-hta-4 But as we're upgrading to Windows 10 and it doesn't support HTA (ignoring IE9 compatibility) this will need replacing. Question is what can do the same thing, the provisos are: * *Not before Login (so not using Login Banner) *Only after Login Window *Should not be close-able except by using the "Agree to this MSG" button *Text will vary so need easy method to keep text from control(html file?) *will be distributed by DC (logon script) This application is used for Acknowledgement of Compliance and security information dissemination. Thanks for your thoughts, A: AFAIK Windows 10 can still run HTAs. If you want to force IE9 mode you can stick a meta tag in the head: <head> <meta http-equiv="X-UA-Compatible" content="IE=9" /> </head> A: Just give a try with this HTA : Tested only on Windows 7 (64 bits) <html> <!-- MOTD.hta (Message of the Day) Written by Jeremy.Saunders@au1.ibm.com on 12/11/06. --> <head> <meta http-equiv="X-UA-Compatible" content="IE=8" /> <title>Message of the Day</title> <hta:application id="objHTAInfo" applicationname="Message of the Day" version="1.0" border="thin" borderstyle="raised" caption="yes" contextmenu="yes" innerborder="no" maximizebutton="no" minimizebutton="no" selection="yes" scroll="yes" scrollflat="yes" showintaskbar="no" SysMenu="no" SINGLEINSTANCE="yes" > <style type="text/css"> body { font: 13pt arial; color: white; filter: progid:DXImageTransform.Microsoft.Gradient (GradientType=0, StartColorStr='#000000', EndColorStr='#0000FF') } p { margin: 0 0 0 0; } </style> </head> <SCRIPT LANGUAGE="VBScript"> Option Explicit Const ForReading = 1 Sub Window_Onload Dim strMOTDFile, arrCommands, strLogonServer, strCommonPath, strPath, strcurrentPath, strLine, strContents Dim i, WshShell, oFSO, objFile strMOTDFile = "motd.txt" arrCommands = Split(objHTAInfo.commandLine, chr(34)) ' Uncomment the next three lines for testing only. ' For i = 3 to (Ubound(arrCommands) - 1) Step 2 ' Msgbox arrCommands(i) ' Next If Ubound(arrCommands) = 2 Then strcurrentPath = Replace(Left(document.location.pathname,InStrRev(document.location.pathname,"\")),"%20"," ") strPath = strcurrentPath Else Set WshShell = CreateObject("WScript.Shell") strLogonServer = WshShell.ExpandEnvironmentStrings("%LogonServer%") strPath = strLogonServer & "\" & arrCommands(3) & "\" End If ' Uncomment the next line for testing only. ' Msgbox strPath Set oFSO = CreateObject("Scripting.Filesystemobject") If oFSO.fileexists(strPath & strMOTDFile) Then Set objFile = oFSO.OpenTextFile(strPath & strMOTDFile, ForReading) Do Until objFile.AtEndOfStream strLine = objFile.ReadLine strContents = strContents & strLine & "<BR>" Loop objFile.Close document.getelementbyid("textarea").innerHTML = strContents Else ExitProgram End If posBtn document.body.onresize = GetRef("posBtn") Set WshShell = Nothing Set oFSO = Nothing Set objFile = Nothing End Sub Sub posBtn Dim btn, bod, leftLoc Set btn=document.getelementbyid("runbutton") Set bod=document.getelementbyid("mainbody") leftLoc = (bod.offsetWidth/2) - (btn.offsetWidth/2) btn.style.position="absolute" btn.style.posLeft = leftLoc End Sub Sub ExitProgram window.close() End Sub </SCRIPT> <body id="mainbody"> <center><h1>Message of the Day</h1></center> <h3>Important notice:</h3> <p id="textarea"></p> <BR> <BR> <input id=runbutton type="button" value="I have read and understood this message." onClick="ExitProgram"> </body> </html>
stackoverflow
{ "language": "en", "length": 437, "provenance": "stackexchange_0000F.jsonl.gz:870254", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558679" }
710d49c0bdf4c488d6f123cc7f05d702ccc18a22
Stackoverflow Stackexchange Q: VSCode: normal word completion I understand that VSCode has intelisense. But sometimes one only needs a simple completion of a variable name that has appeared somewhere in the same file or in the already opened files. Like what Vim has for Ctrl+o Ctrl+p. Is it possible to do it in VSCode? A: Edit: from vscode 1.51 it should be possible: "editor.wordBasedSuggestionsMode": "currentDocument" | "matchingDocuments" | "allDocuments" It is possible now with the extension: All Autocomplete. It auto-completes based on words in all opened files. Related issue https://github.com/Microsoft/vscode/issues/5312
Q: VSCode: normal word completion I understand that VSCode has intelisense. But sometimes one only needs a simple completion of a variable name that has appeared somewhere in the same file or in the already opened files. Like what Vim has for Ctrl+o Ctrl+p. Is it possible to do it in VSCode? A: Edit: from vscode 1.51 it should be possible: "editor.wordBasedSuggestionsMode": "currentDocument" | "matchingDocuments" | "allDocuments" It is possible now with the extension: All Autocomplete. It auto-completes based on words in all opened files. Related issue https://github.com/Microsoft/vscode/issues/5312 A: It has been years, I believe now VSCode (1.52.1) has supported Ctrl+p / Ctrl+n for word autocompletion if you have Vim extenstion installed and enabled. However, it still requires Ctrl+space to trigger the autocompltion popup then you can use Ctrl+p / Ctrl+n to go next or prev If you dislike to press Ctrl+space, I found adding following in the keybindings.json could help and behave the same as Vim. { "key": "ctrl+p", "command": "editor.action.triggerSuggest", "when": "editorHasCompletionItemProvider && !suggestWidgetVisible && textInputFocus && !editorReadonly" }, { "key": "ctrl+n", "command": "editor.action.triggerSuggest", "when": "editorHasCompletionItemProvider && !suggestWidgetVisible && textInputFocus && !editorReadonly" }, Hope you like this.
stackoverflow
{ "language": "en", "length": 189, "provenance": "stackexchange_0000F.jsonl.gz:870346", "question_score": "17", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558955" }
ace362b7cd74d346545c6b1faaa6abbf1abc0a4d
Stackoverflow Stackexchange Q: Laravel: What is the proper response of a controller to an ajax request? I am having a problem returning a proper response to an ajax request I made. Basically, I have a checkbox which when changed() fires an ajax with csrf-token to be accepted in POST method, the changes reflected on the database is successful but the error starts on returning the "status" of the process to the ajax. Heres my controller method: public function update(Request $request, $id) { $result = ItemPrice::toggleRestockable($id); return $result; } $result is the output of DB::update() method The ajax goes to error: block with Internal Server Error 500 regardless whether the query was a success or not. The responseText of data variable in ajax was mainly: (1/1) UnexpectedValueException The Response content must be a string or object implementing __toString(), "boolean" given. Now I know I am returning boolean or technically an integer because it was a result of DB::update() which returns the number of rows affected by the update. Now how could I properly return a response that an ajax can understand? A: Try This public function update(Request $request, $id) { $result = ItemPrice::toggleRestockable($id); return Response::json(['success' => $result], 200); }
Q: Laravel: What is the proper response of a controller to an ajax request? I am having a problem returning a proper response to an ajax request I made. Basically, I have a checkbox which when changed() fires an ajax with csrf-token to be accepted in POST method, the changes reflected on the database is successful but the error starts on returning the "status" of the process to the ajax. Heres my controller method: public function update(Request $request, $id) { $result = ItemPrice::toggleRestockable($id); return $result; } $result is the output of DB::update() method The ajax goes to error: block with Internal Server Error 500 regardless whether the query was a success or not. The responseText of data variable in ajax was mainly: (1/1) UnexpectedValueException The Response content must be a string or object implementing __toString(), "boolean" given. Now I know I am returning boolean or technically an integer because it was a result of DB::update() which returns the number of rows affected by the update. Now how could I properly return a response that an ajax can understand? A: Try This public function update(Request $request, $id) { $result = ItemPrice::toggleRestockable($id); return Response::json(['success' => $result], 200); } A: Create one base ApiController abstract class and extend it in your any controller. so you no need to prepare response obj for success and error in every function and every controller. you just call function. example given here. // Base ApiController abstract class ApiController extends Controller { /** * Make standard response with some data * * @param object|array $data Data to be send as JSON * @param int $code optional HTTP response code, default to 200 * @return \Illuminate\Http\JsonResponse */ protected function respondWithData($data, $code = 200) { return Response::json([ 'success' => true, 'data' => $data ], $code); } /** * Make standard successful response ['success' => true, 'message' => $message] * * @param string $message Success message * @param int $code HTTP response code, default to 200 * @return \Illuminate\Http\JsonResponse */ protected function respondSuccess($message = 'Done!', $code = 200) { return Response::json([ 'success' => true, 'message' => $message ], $code); } /** * Make standard response with error ['success' => false, 'message' => $message] * * @param string $message Error message * @param int $code HTTP response code, default to 500 * @return \Illuminate\Http\JsonResponse */ protected function respondWithError($message = 'Server error', $code = 500) { return Response::json([ 'success' => false, 'message' => $message ], $code); } How to use functions of base class. see example here public function update(Request $request, $id) { try{ $result = ItemPrice::toggleRestockable($id); return $this->respondWithData($result); }catch(Exception $e){ return $this->respondWithError($e->getMessage()); } } how to extend base controller into your controller class TestController extends ApiController {} A: JsonResponse is the class you need. return response()->json($result); using helpers. Use ->toArray() on $result if dealing with collections. A: return $result; will return the object of data, there are multiple ways to handle this depending on the return type of your toggle function. The Typical way to handle an AJAX request is to save data and return the status and message. in your scenario, I could use a response to JSON public function update(Request $request, $id) { $status = 500; $message = 'An Un expected error Occured'; try { $result = ItemPrice::toggleRestockable($id); //assuming toggleRestockable function will return bool if ($result) { $status = 200; $message = 'Successfully Updated'; } return response()->json(['status' => $status, 'message' => $message]); } catch (Exception $e) { return response()->json(['status' => 500, 'message' => $e->getMessage()]); } } This way of doing works fine for me A: public function update(Request $request, $id) { $this->validate($request, [ //some of your data =>'required|min:4'; <-your rules ]); $result = ItemPrice::findOrFail($id); //something request; $result->save(); return response()->json(['result'=>$result]); } and you can call your error by using this @if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif i hope it will helps you a lot :)
stackoverflow
{ "language": "en", "length": 647, "provenance": "stackexchange_0000F.jsonl.gz:870362", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44558998" }
8bf6e92f9b2b26e4cbd703299edced807867c9d1
Stackoverflow Stackexchange Q: sequelize.js orm :Unique email validation for mysql not working Here is my model validation for check email-id exists or not email:{ type:Sequelize.STRING, validate:{ notEmpty:{ args:true, msg:"Email-id required" }, isEmail:{ args:true, msg:'Valid email-id required' } }, unique: { args:true, msg: 'Email address already in use!' } } All other validations are working fine except unique email validion A: I had the same issue, to solve this i first added to index to the model's table: queryInterface.addIndex('users', ['email'], { indexName: 'email', indicesType: 'UNIQUE' }) And sets its name equal to the field, because if you dont, it will create one by default and the model will not work with it. email: { type: Sequelize.STRING(191), allowNull: false, unique: { msg: 'your-message-here' } }, I dont know if it is a bug on sequelize or a problem with version that i'm using, but it only worked after i set the index name as the same of the field.
Q: sequelize.js orm :Unique email validation for mysql not working Here is my model validation for check email-id exists or not email:{ type:Sequelize.STRING, validate:{ notEmpty:{ args:true, msg:"Email-id required" }, isEmail:{ args:true, msg:'Valid email-id required' } }, unique: { args:true, msg: 'Email address already in use!' } } All other validations are working fine except unique email validion A: I had the same issue, to solve this i first added to index to the model's table: queryInterface.addIndex('users', ['email'], { indexName: 'email', indicesType: 'UNIQUE' }) And sets its name equal to the field, because if you dont, it will create one by default and the model will not work with it. email: { type: Sequelize.STRING(191), allowNull: false, unique: { msg: 'your-message-here' } }, I dont know if it is a bug on sequelize or a problem with version that i'm using, but it only worked after i set the index name as the same of the field. A: email: { type : DataTypes.STRING, validate : { isEmail: { msg: "wrong format email" }, notEmpty: { msg: 'Email not null' }, isUnique: function(value, next){ 'table'.find({ where : { email:value, id:{[Op.ne]: this.id} } }).then(function(result){ if(result === null){ return next() }else{ return next(' Email already use') } }).catch(err =>{ return next() }) } } } A: Try this email:{ type:Sequelize.STRING, validate:{ notEmpty:{ args:true, msg:"Email-id required" }, isEmail:{ args:true, msg:'Valid email-id required' } }, unique: { msg: 'Email address already in use!' } } A: email:{ type:Sequelize.STRING, validate:{ notEmpty:{ args:true, msg:"Email-id required" }, isEmail:{ args:true, msg:'Valid email-id required' } }, unique: { args:true, msg: 'Email address already in use!' } } This will work. For that you only need to do is drop db and restart the server once after you add the unique constraint to your model. Or you can add db.sequelize.sync({force: true}).then(() => { console.log("Drop and re-sync db."); }); to your app.js. In this the {force: true} will drop and rebuilt db each time automatically. * *So you can add {force: true} to your **db.sequelize.sync** . *Restart the server. *Check that the unique constraint is working. *Remove {force: true} from your **db.sequelize.sync** .
stackoverflow
{ "language": "en", "length": 349, "provenance": "stackexchange_0000F.jsonl.gz:870392", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559079" }
09130b6d1e2e20ce8d0bef59445e37f9800b0e33
Stackoverflow Stackexchange Q: Invalid or unsupported video capability (PJMEDIA_EVID_INVCAP) Invalid or unsupported video capability (PJMEDIA_EVID_INVCAP) In Pjsip in android while setting preview size MediaSize size=new MediaSize(); size.setH(200); size.setW(200); SipService.currentCall.vidPrev.start(vidPrevParam); SipService.currentCall. vidPrev.getVideoWindow().setSize(size); A: This occurs due to unsupported properties. You can not modify Windows size directly so you should be using codec 264 for encoding video To resize the window preview you should be enable codec H264.check this ticket for How to enable codec. You should rebuild *.so file with added below line config_site.h. define PJMEDIA_HAS_OPENH264_CODEC 1 After that, you can resize preview windows I refer this doc Modifying video codec parameters for video call Now in Android, you resize like below VidCodecParam param = JacquesApp.ep.getVideoCodecParam("H264/97"); MediaFormatVideo formatVideo = param.getEncFmt(); formatVideo.setHeight(352); formatVideo.setWidth(288); param.setEncFmt(formatVideo); endPoint.setVideoCodecParam("H264/97", param);
Q: Invalid or unsupported video capability (PJMEDIA_EVID_INVCAP) Invalid or unsupported video capability (PJMEDIA_EVID_INVCAP) In Pjsip in android while setting preview size MediaSize size=new MediaSize(); size.setH(200); size.setW(200); SipService.currentCall.vidPrev.start(vidPrevParam); SipService.currentCall. vidPrev.getVideoWindow().setSize(size); A: This occurs due to unsupported properties. You can not modify Windows size directly so you should be using codec 264 for encoding video To resize the window preview you should be enable codec H264.check this ticket for How to enable codec. You should rebuild *.so file with added below line config_site.h. define PJMEDIA_HAS_OPENH264_CODEC 1 After that, you can resize preview windows I refer this doc Modifying video codec parameters for video call Now in Android, you resize like below VidCodecParam param = JacquesApp.ep.getVideoCodecParam("H264/97"); MediaFormatVideo formatVideo = param.getEncFmt(); formatVideo.setHeight(352); formatVideo.setWidth(288); param.setEncFmt(formatVideo); endPoint.setVideoCodecParam("H264/97", param);
stackoverflow
{ "language": "en", "length": 122, "provenance": "stackexchange_0000F.jsonl.gz:870407", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559126" }
4400add054d86ebe5d6c5582625357bdfefded66
Stackoverflow Stackexchange Q: Is it possible to open files with a new window? Is it possible to open files with a new window (Not splitting them into two tab in the same window)? Otherwise my second monitor will become useless. A: VSCode: Open file In a new Window: * *File->New Window to open a second window, *Drag the file you want to view to the second window Source: https://social.msdn.microsoft.com/Forums/en-US/3560f10e-cfdb-4a76-aeb3-52783d34db91/can-vscode-open-file-in-a-new-window?forum=vsarch
Q: Is it possible to open files with a new window? Is it possible to open files with a new window (Not splitting them into two tab in the same window)? Otherwise my second monitor will become useless. A: VSCode: Open file In a new Window: * *File->New Window to open a second window, *Drag the file you want to view to the second window Source: https://social.msdn.microsoft.com/Forums/en-US/3560f10e-cfdb-4a76-aeb3-52783d34db91/can-vscode-open-file-in-a-new-window?forum=vsarch A: I don't know when it was added but see: "window.openFilesInNewWindow": "on", "window.openFoldersInNewWindow": "on", and open recent files in a new window A: If you have the file open you can use ctl+k O to open file in new window.
stackoverflow
{ "language": "en", "length": 107, "provenance": "stackexchange_0000F.jsonl.gz:870428", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559192" }
e7d9e388eafc4fdd0727ffd250152e557ebfe7a9
Stackoverflow Stackexchange Q: DB::update laravel 5 raw query I intend to use laravel db update which equivalent to sql. update users set username = "admin", status = "active" where user_id = 1 This is the query I test to run. Any wrong? $username = "admin"; $status = "active"; DB::update('update users set username = ' .$username. ', status = '.$status.' where user_id = ?' ,['1']); A: The better way to do that with laravel query builder is: DB::table('users') ->where('user_id', 1) ->update(['username' => $username, 'status' => $status]);
Q: DB::update laravel 5 raw query I intend to use laravel db update which equivalent to sql. update users set username = "admin", status = "active" where user_id = 1 This is the query I test to run. Any wrong? $username = "admin"; $status = "active"; DB::update('update users set username = ' .$username. ', status = '.$status.' where user_id = ?' ,['1']); A: The better way to do that with laravel query builder is: DB::table('users') ->where('user_id', 1) ->update(['username' => $username, 'status' => $status]); A: You are using raw query , it can be done as update users set username = "admin", status = "active" where user_id = 1 DB::table('users') ->where('user_id',1) ->update(['username'=>'admin','status'=>'active']); OR $username = "admin"; $status = "active"; DB::update(DB::RAW('update users set username = ' .$username. ', status = '.$status.' where user_id = ?' ,['1'])); A: You should update your query like : Eloquent Query: User::where('user_id',1)->update(array( 'username'=>$username, )); Fluent Query: DB::table('users')->where('user_id',1)->update(array( 'username'=>$username, )); Hope this helps you A: The correct query would be DB::update('update users set username = ? , status = ? where user_id = ?', ["admin" , "active" , 1]); OR User::where('user_id', 1)->update( array('username'=>'admin', 'status'=>'active') ); Where "User" is the model name of "users" table. A: The correct ways to Call DB::update you need something like this $username = "admin"; $status = "active"; DB::update('update users set username = ? , status = ? where user_id = ?', [$username , $status , 1]); This should return number of rows affected
stackoverflow
{ "language": "en", "length": 240, "provenance": "stackexchange_0000F.jsonl.gz:870444", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559252" }
87f1e174a83574f4aae61ee76ee1b0f1d1287c98
Stackoverflow Stackexchange Q: Get storage metadata in Cloud Functions for Firebase is it possible to get custom storage metadata in Cloud Functions for Firebase? for example in android code: StorageMetadata metadata = new StorageMetadata.Builder().setContentType("image/jpg") .setCustomMetadata("latitude",String.valueOf(image.latitude)) .setCustomMetadata("longitude",String.valueOf(image.longitude)) .setCustomMetadata("deviceID",image.deviceID) .setCustomMetadata("userID",image.userID) .setCustomMetadata("deviceFilePath",image.filename) .setCustomMetadata("timestamp",String.valueOf(image.timestamp)) .setCustomMetadata("caption",image.caption) .setCustomMetadata("location",image.location) .setCustomMetadata("imageID",key) .build(); i want to retrieved the custom metadata value in cloud function A: Use this. }).then(() => { return file.getMetadata(); }).then((meta) => { console.log(meta[0]); value1 = meta[0]["metadata"]["key1"]; value2 = meta[0]["metadata"]["key2"];
Q: Get storage metadata in Cloud Functions for Firebase is it possible to get custom storage metadata in Cloud Functions for Firebase? for example in android code: StorageMetadata metadata = new StorageMetadata.Builder().setContentType("image/jpg") .setCustomMetadata("latitude",String.valueOf(image.latitude)) .setCustomMetadata("longitude",String.valueOf(image.longitude)) .setCustomMetadata("deviceID",image.deviceID) .setCustomMetadata("userID",image.userID) .setCustomMetadata("deviceFilePath",image.filename) .setCustomMetadata("timestamp",String.valueOf(image.timestamp)) .setCustomMetadata("caption",image.caption) .setCustomMetadata("location",image.location) .setCustomMetadata("imageID",key) .build(); i want to retrieved the custom metadata value in cloud function A: Use this. }).then(() => { return file.getMetadata(); }).then((meta) => { console.log(meta[0]); value1 = meta[0]["metadata"]["key1"]; value2 = meta[0]["metadata"]["key2"]; A: You can get custom metadata in cloud functions as shown below using event.data.metadata. If you want to see complete example, here is the link http://www.zoftino.com/android-firebase-cloud-functions-cloud-storage-trigger-example exports.metadata = functions.storage.object().onChange(event => { //metada const fileInfo = event.data; //custom metadata const customMetadata = fileInfo.metadata; //get each custom metadata value using its key like.. const customMetadataDeviceID = customMetadata['deviceID']; ....... A: Sure, you can use the Google Cloud Storage Node SDK to work with files in your storage bucket. Use it to get a File object that points to the file of interest. Then call its getMetadata() method to get the metadata.
stackoverflow
{ "language": "en", "length": 169, "provenance": "stackexchange_0000F.jsonl.gz:870456", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559283" }
da4abfc14f7ba083cee08a5e5d9cece4d52ba00b
Stackoverflow Stackexchange Q: Is there any computational limitation (CPU usage) for Windows Subsystem for Linux? I am running a heavy program on Bash in Windows, However, the task manager shows the CPU usage is only 14% (Intel i7-7700). Is Windows Subsystem for Linux allowed to use the full potential of CPU? A: Yes, if your process was single threaded 14% CPU usage on a quad core CPU seems reasonable. It would be using about 55% of the single core. If you wanted to test, whether there are limitations to the linux subsystem, you could write a process, that should uses 100% (or at least very close) - execute it and watch your CPU usage. If the CPU usage isn't around 20-25% it would seem, that the subsystem is limited in some way.
Q: Is there any computational limitation (CPU usage) for Windows Subsystem for Linux? I am running a heavy program on Bash in Windows, However, the task manager shows the CPU usage is only 14% (Intel i7-7700). Is Windows Subsystem for Linux allowed to use the full potential of CPU? A: Yes, if your process was single threaded 14% CPU usage on a quad core CPU seems reasonable. It would be using about 55% of the single core. If you wanted to test, whether there are limitations to the linux subsystem, you could write a process, that should uses 100% (or at least very close) - execute it and watch your CPU usage. If the CPU usage isn't around 20-25% it would seem, that the subsystem is limited in some way. A: Yes, 14 % CPU usage on an i7-7700 for a single threaded program is expected. You have 4 physical cores and 8 logical cores. Using a single logical core without boosting would put you at 100 % / 8 = 12 % usage. An i7-7700 can boost from 3.6 GHz to 4.2 GHz. That gives a theoretical max limit of (4.2 / 3.6) * (100 % / 8) = 14.0 %. Congratulations, your CPU is running at the maximum of 4.2 GHz! If you want better performance, you need to thread your application. Your actual turbo boost speedup will depend on your CPU. I'm on a mobile i7-6820HQ. On CPU intensive tasks, I'm seeing about 16 % utilization, which is consistent with my speedup from turbo boost ( (3.6 GHz / 2.7 GHz) * (100 % / 8) = 16.0 ).
stackoverflow
{ "language": "en", "length": 272, "provenance": "stackexchange_0000F.jsonl.gz:870468", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559314" }
b106df13d5679894656522ddb3735f8bfdebac5b
Stackoverflow Stackexchange Q: Create a template and replace placeholders dynamically in Ruby On Rails I have a set template in which there is address informations and other set of user information. I have created a html file in the public folder and load the file at runtime and use template = File.read("public/filename.html") template % {key:value} to replace the tokens with actual value and process as required. Can anyone please let me know if its the correct way to do this, or are there any better ways like placing the template in other folders like views, bin etc? A: I would use wicked_pdf. After you've installed it, create a new route and controller that will take your user/address info as params and pass them as an instance variable into your template. From there, you can can template the pdf just like a regular view.
Q: Create a template and replace placeholders dynamically in Ruby On Rails I have a set template in which there is address informations and other set of user information. I have created a html file in the public folder and load the file at runtime and use template = File.read("public/filename.html") template % {key:value} to replace the tokens with actual value and process as required. Can anyone please let me know if its the correct way to do this, or are there any better ways like placing the template in other folders like views, bin etc? A: I would use wicked_pdf. After you've installed it, create a new route and controller that will take your user/address info as params and pass them as an instance variable into your template. From there, you can can template the pdf just like a regular view. A: vim app/view/filename.html.erb you can create template(view) and set the root to config/routes
stackoverflow
{ "language": "en", "length": 154, "provenance": "stackexchange_0000F.jsonl.gz:870470", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559317" }
3fd89ec7985510c80eee33932452eec71eaa9270
Stackoverflow Stackexchange Q: How can I import LambdaContext? I'm making AWS Lambda Function. Now I want to isinstance(context,LambdaContext) , I'm expecting It works in AWS Lambda. But I'm running unit test in local. So How can I import LambdaContext. Best A: You could try using LocalStack: LocalStack provides an easy-to-use test/mocking framework for developing Cloud applications. Currently, the focus is primarily on supporting the AWS cloud stack. LocalStack spins up the following core Cloud APIs on your local machine: API Gateway at http://localhost:4567 Kinesis at http://localhost:4568 DynamoDB at http://localhost:4569 DynamoDB Streams at http://localhost:4570 Elasticsearch at http://localhost:4571 S3 at http://localhost:4572 Firehose at http://localhost:4573 Lambda at http://localhost:4574 SNS at http://localhost:4575 SQS at http://localhost:4576 Redshift at http://localhost:4577 ES (Elasticsearch Service) at http://localhost:4578 SES at http://localhost:4579 Route53 at http://localhost:4580 CloudFormation at http://localhost:4581 CloudWatch at http://localhost:4582
Q: How can I import LambdaContext? I'm making AWS Lambda Function. Now I want to isinstance(context,LambdaContext) , I'm expecting It works in AWS Lambda. But I'm running unit test in local. So How can I import LambdaContext. Best A: You could try using LocalStack: LocalStack provides an easy-to-use test/mocking framework for developing Cloud applications. Currently, the focus is primarily on supporting the AWS cloud stack. LocalStack spins up the following core Cloud APIs on your local machine: API Gateway at http://localhost:4567 Kinesis at http://localhost:4568 DynamoDB at http://localhost:4569 DynamoDB Streams at http://localhost:4570 Elasticsearch at http://localhost:4571 S3 at http://localhost:4572 Firehose at http://localhost:4573 Lambda at http://localhost:4574 SNS at http://localhost:4575 SQS at http://localhost:4576 Redshift at http://localhost:4577 ES (Elasticsearch Service) at http://localhost:4578 SES at http://localhost:4579 Route53 at http://localhost:4580 CloudFormation at http://localhost:4581 CloudWatch at http://localhost:4582 A: class LambdaContext defined in /var/runtime/awslambda/bootstrap.py which is used to launch users functions and has the following structure: class LambdaContext(object): def __init__(self, invokeid, context_objs, client_context, invoked_function_arn=None): self.aws_request_id = invokeid self.log_group_name = os.environ['AWS_LAMBDA_LOG_GROUP_NAME'] self.log_stream_name = os.environ['AWS_LAMBDA_LOG_STREAM_NAME'] self.function_name = os.environ["AWS_LAMBDA_FUNCTION_NAME"] self.memory_limit_in_mb = os.environ['AWS_LAMBDA_FUNCTION_MEMORY_SIZE'] self.function_version = os.environ['AWS_LAMBDA_FUNCTION_VERSION'] self.invoked_function_arn = invoked_function_arn self.client_context = make_obj_from_dict(ClientContext, client_context) if self.client_context is not None: self.client_context.client = make_obj_from_dict(Client, self.client_context.client) self.identity = make_obj_from_dict(CognitoIdentity, context_objs) def get_remaining_time_in_millis(self): return lambda_runtime.get_remaining_time() def log(self, msg): str_msg = str(msg) lambda_runtime.send_console_message(str_msg, byte_len(str_msg)) If you want to emulate it on your local environment, just add it into your script: class ClientContext(object): __slots__ = ['custom', 'env', 'client'] def make_obj_from_dict(_class, _dict, fields=None): if _dict is None: return None obj = _class() set_obj_from_dict(obj, _dict) return obj def set_obj_from_dict(obj, _dict, fields=None): if fields is None: fields = obj.__class__.__slots__ for field in fields: setattr(obj, field, _dict.get(field, None)) class LambdaContext(object): def __init__(self, invokeid, context_objs, client_context, invoked_function_arn=None): self.aws_request_id = invokeid self.log_group_name = os.environ['AWS_LAMBDA_LOG_GROUP_NAME'] self.log_stream_name = os.environ['AWS_LAMBDA_LOG_STREAM_NAME'] self.function_name = os.environ["AWS_LAMBDA_FUNCTION_NAME"] self.memory_limit_in_mb = os.environ['AWS_LAMBDA_FUNCTION_MEMORY_SIZE'] self.function_version = os.environ['AWS_LAMBDA_FUNCTION_VERSION'] self.invoked_function_arn = invoked_function_arn self.client_context = make_obj_from_dict(ClientContext, client_context) if self.client_context is not None: self.client_context.client = None self.identity = None def get_remaining_time_in_millis(self): return None def log(self, msg): str_msg = str(msg) print(str_msg) # lambda_runtime.send_console_message(str_msg, byte_len(str_msg)) A: Just found this package, it seems that someone made a pip package using the concepts from the other answers in this question. Had the same issue, hope it helps whoever comes across this question in the future. A: This is not in the strictest sense an answer, please remove if unsuitable. I have experimented with @Dmitry-Masanov 's answer, and have bodged a python fixture for pytest, which can be used either in the test script itself, or as I am doing, in the conftest.py file. @pytest.fixture def mock_lambda_context(): class ClientContext: """ Class for mocking Context Has `custom`, `env`, and `client` `__slots__` """ __slots__ = ["custom", "env", "client"] def make_obj_from_dict(_class, _dict, fields=None): """ Makes an object of `_class` from a `dict` :param _class: A class representing the context :type _class: `ContextClass` :param _dict: A dictionary of data :type _dict: `dict` :param fields: [description], defaults to None :type fields: [type], optional :return: An object :rtype: `ClientContext` class """ if _dict is None: return None obj = _class() set_obj_from_dict(obj, _dict) return obj def set_obj_from_dict(obj, _dict, fields=None): if fields is None: fields = obj.__class__.__slots__ for field in fields: setattr(obj, field, _dict.get(field, None)) class LambdaContext(object): """ Create a Lambda Context Class object """ def __init__(self, invokeid, client_context, invoked_function_arn=None): self.aws_request_id = invokeid self.log_group_name = "AWS_LAMBDA_LOG_GROUP_NAME" self.log_stream_name = "AWS_LAMBDA_LOG_STREAM_NAME" self.function_name = "AWS_LAMBDA_FUNCTION_NAME" self.memory_limit_in_mb = "AWS_LAMBDA_FUNCTION_MEMORY_SIZE" self.function_version = "AWS_LAMBDA_FUNCTION_VERSION" self.invoked_function_arn = invoked_function_arn self.client_context = make_obj_from_dict(ClientContext, client_context) if self.client_context is not None: self.client_context.client = None self.identity = None def get_remaining_time_in_millis(self): return None def log(self, msg): str_msg = str(msg) print(str_msg) lambda_context = LambdaContext("AWS_ID", {}) return lambda_context I'm nearly certain my implementation can be improved (OO python isn't a strong skill of mine), but this serves my purpose of: * *mocking a lambda context object *integrating with pytest This can be used in a way similar to this: @pytest.mark.smoke def test_lambda_handler(apigw_event, mock_lambda_context): ret = app.lambda_handler(apigw_event, mock_lambda_context) assert "log_stream_name" in ret["body"] Thanks again Dmitry, your answer saved me a bunch of hassle.
stackoverflow
{ "language": "en", "length": 643, "provenance": "stackexchange_0000F.jsonl.gz:870474", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559331" }
9c1a61321bb542f6c5ea3375693929c6605aa0d5
Stackoverflow Stackexchange Q: How to include relationship object in response composer-rest-server? We have defined Asset as: asset PurchaseOrder identified by orderId { o String orderId --> SupplierChainParticipant createdBy --> SupplierChainParticipant assignedTo o String description o String status o Integer quantity o String assetId } and Participant as : participant SupplierChainParticipant identified by participantId { o String participantId o String identity o String type } Now When I am fetching Asset details using REST API of composer-rest-server, I receive response as: { "orderId": "o5", "createdBy": "resource:com.supplychain-network.SupplierChainParticipant#p1", "assignedTo": "resource:com.supplychain-network.SupplierChainParticipant#p2", "description": "New Engine", "status": "created", "quantity": 1, "assetId": "a1" } As currently its only returning participantId only while fetching Asset details, Is there a way to fetch details of participant along with Asset as JSON response? A: If you specify a filter key called include and set the value to resolve then relationships will be resolved and the related assets will also be returned.
Q: How to include relationship object in response composer-rest-server? We have defined Asset as: asset PurchaseOrder identified by orderId { o String orderId --> SupplierChainParticipant createdBy --> SupplierChainParticipant assignedTo o String description o String status o Integer quantity o String assetId } and Participant as : participant SupplierChainParticipant identified by participantId { o String participantId o String identity o String type } Now When I am fetching Asset details using REST API of composer-rest-server, I receive response as: { "orderId": "o5", "createdBy": "resource:com.supplychain-network.SupplierChainParticipant#p1", "assignedTo": "resource:com.supplychain-network.SupplierChainParticipant#p2", "description": "New Engine", "status": "created", "quantity": 1, "assetId": "a1" } As currently its only returning participantId only while fetching Asset details, Is there a way to fetch details of participant along with Asset as JSON response? A: If you specify a filter key called include and set the value to resolve then relationships will be resolved and the related assets will also be returned. A: To improve upon the accepted answer with example - 1. 'http://localhost:3000/api/PurchaseOrder?filter={"where":{"orderId":"A01"},"include":"resolve"}' 2. 'http://localhost:3000/api/PurchaseOrder?filter={"include":"resolve"}'
stackoverflow
{ "language": "en", "length": 163, "provenance": "stackexchange_0000F.jsonl.gz:870501", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559413" }
2fe34d5a0b5473030a61d153a4b27567b3aeb9f5
Stackoverflow Stackexchange Q: Download XLSX getting corrupted I'm trying to convert a HTML table to XLSX uisng AngularJS or even plain JavaScript. When I'm converting to XLS using below its downloading fine and a XLS file is opening. var blob = new Blob([template], {type: "data:application/vnd.ms-excel"}); window.navigator.msSaveOrOpenBlob(blob, "myExcel.xls"); But, my requirement wants the file in XLSX, so I changed the MIME type and extension of file in the same code like below, var blob = new Blob([template], {type: "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}); window.navigator.msSaveOrOpenBlob(blob, "myExcel.xlsx"); But when I'm opening the downloaded xlsx file its corrupted and MS office is trowing error popup. What I'm doing wrong and how I can convert a HTML table to XLSX? Even alternate ideas also accepted. PS: The table is quite complicated, rows within columns and all, so plugins like ALASQL, JS-XLSX is not helping. A: The problem may lie in the type XLSX. This post states that it is a zipped set of XLS files. Have a read through. I cannot comment, because my score isn't over 50 yet, so I'm posting as an answer. https://stackoverflow.com/a/37516332/1425168
Q: Download XLSX getting corrupted I'm trying to convert a HTML table to XLSX uisng AngularJS or even plain JavaScript. When I'm converting to XLS using below its downloading fine and a XLS file is opening. var blob = new Blob([template], {type: "data:application/vnd.ms-excel"}); window.navigator.msSaveOrOpenBlob(blob, "myExcel.xls"); But, my requirement wants the file in XLSX, so I changed the MIME type and extension of file in the same code like below, var blob = new Blob([template], {type: "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}); window.navigator.msSaveOrOpenBlob(blob, "myExcel.xlsx"); But when I'm opening the downloaded xlsx file its corrupted and MS office is trowing error popup. What I'm doing wrong and how I can convert a HTML table to XLSX? Even alternate ideas also accepted. PS: The table is quite complicated, rows within columns and all, so plugins like ALASQL, JS-XLSX is not helping. A: The problem may lie in the type XLSX. This post states that it is a zipped set of XLS files. Have a read through. I cannot comment, because my score isn't over 50 yet, so I'm posting as an answer. https://stackoverflow.com/a/37516332/1425168 A: just try to change mime-type change it to application/vnd.ms-excel it works fine with XLSX also. var blob = new Blob([template], {type: "application/vnd.ms-excel"}); window.navigator.msSaveOrOpenBlob(blob, "myExcel.xlsx"); Try this code.
stackoverflow
{ "language": "en", "length": 203, "provenance": "stackexchange_0000F.jsonl.gz:870518", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559457" }
d8bf7f1e3b56b8503ed641fdc8398bd107828f10
Stackoverflow Stackexchange Q: How to reset the number inside "In [ ]" from Jupyter Notebook cell? I am a newbie to Jupyter and trying to learn it. I ran a cell four times and now there's In[4] and Out[4] and if I execute again, it increases. Now how can I reset the values? Also why are these values stored? Any help is appreciated. A: It's so that if you have a lot of cells you can have a record of what order you ran them in. To reset the counter, you reset the kernel, either via the Kernel menu or by pressing "0" twice.
Q: How to reset the number inside "In [ ]" from Jupyter Notebook cell? I am a newbie to Jupyter and trying to learn it. I ran a cell four times and now there's In[4] and Out[4] and if I execute again, it increases. Now how can I reset the values? Also why are these values stored? Any help is appreciated. A: It's so that if you have a lot of cells you can have a record of what order you ran them in. To reset the counter, you reset the kernel, either via the Kernel menu or by pressing "0" twice.
stackoverflow
{ "language": "en", "length": 102, "provenance": "stackexchange_0000F.jsonl.gz:870522", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559471" }
e26157c83d8250a78713d9274bddd18b82eb9bb4
Stackoverflow Stackexchange Q: ngrx effects gives Type 'void' is not assignable to type 'ObservableInput' @Injectable() export class ApiSearchEffects { @Effect() search$: Observable<any> = this.actions$ .ofType(query.ActionTypes.QUERYSERVER) .debounceTime(300) .map((action: query.QueryServerAction) => action.payload) .switchMap(payload => { console.log(payload); const nextSearch$ = this.actions$.ofType(query.ActionTypes.QUERYSERVER).skip(1); this.searchService.getsearchresults(payload) .takeUntil(nextSearch$) .map((response) => ({type: '[Search] Change', payload: response} )) }); above code gives me Argument of type '(payload: any) => void' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'. Type 'void' is not assignable to type 'ObservableInput'. where could be the mistake be. I have followed the ngrx effects official intro at https://github.com/ngrx/effects/blob/master/docs/intro.md . A: The problem is that your switchMap should return a value; its returning void as you have it. Try this return this.searchService.getsearchresults(payload) .takeUntil(nextSearch$)
Q: ngrx effects gives Type 'void' is not assignable to type 'ObservableInput' @Injectable() export class ApiSearchEffects { @Effect() search$: Observable<any> = this.actions$ .ofType(query.ActionTypes.QUERYSERVER) .debounceTime(300) .map((action: query.QueryServerAction) => action.payload) .switchMap(payload => { console.log(payload); const nextSearch$ = this.actions$.ofType(query.ActionTypes.QUERYSERVER).skip(1); this.searchService.getsearchresults(payload) .takeUntil(nextSearch$) .map((response) => ({type: '[Search] Change', payload: response} )) }); above code gives me Argument of type '(payload: any) => void' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'. Type 'void' is not assignable to type 'ObservableInput'. where could be the mistake be. I have followed the ngrx effects official intro at https://github.com/ngrx/effects/blob/master/docs/intro.md . A: The problem is that your switchMap should return a value; its returning void as you have it. Try this return this.searchService.getsearchresults(payload) .takeUntil(nextSearch$)
stackoverflow
{ "language": "en", "length": 119, "provenance": "stackexchange_0000F.jsonl.gz:870526", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559480" }
baefe587213111d3ec7b8cd5da49a316dba99dd8
Stackoverflow Stackexchange Q: How to export all tables in separate sql files I have to upload my database on godaddy host but it restricted to upload more than 8 MB file. So I have decided to upload my table one by one. I am looking for a query or a way to export each table one by one, is there any way available to do this job easily? That I get each table sql with the data? I am using PHPMyAdmin. A: You can import tables from phpmyadmin as follows : You also get option to include data along with table schema.
Q: How to export all tables in separate sql files I have to upload my database on godaddy host but it restricted to upload more than 8 MB file. So I have decided to upload my table one by one. I am looking for a query or a way to export each table one by one, is there any way available to do this job easily? That I get each table sql with the data? I am using PHPMyAdmin. A: You can import tables from phpmyadmin as follows : You also get option to include data along with table schema.
stackoverflow
{ "language": "en", "length": 100, "provenance": "stackexchange_0000F.jsonl.gz:870539", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559525" }
d4ddd5c7caf690423ad19ed8926a7261d93c481d
Stackoverflow Stackexchange Q: How to unlock jenkins on windows 10 I installed jenkins on my window 10 machine by using the msi I downloaded. It installed fine and has now launched the browser prompting me to unlock jenkins with the initialadminpassword. I can't find this file anywhere. I looked in the install directory C:\Program Files (x86)\Jenkins and I have checked the log files and no password was written to it. I even did a search on my whole C: for initialadminpassword and nothing came up. I do have a file called secret.key in my Jenkins install directory but the key in this file isn't working. Any ideas on how I can get around this would be very helpful Thanks A: In the Jenkins Home directory there should be a secrets subfolder. In that directory there should be a file called initialAdminPassword (no extension). This file contains the password it is referring to.
Q: How to unlock jenkins on windows 10 I installed jenkins on my window 10 machine by using the msi I downloaded. It installed fine and has now launched the browser prompting me to unlock jenkins with the initialadminpassword. I can't find this file anywhere. I looked in the install directory C:\Program Files (x86)\Jenkins and I have checked the log files and no password was written to it. I even did a search on my whole C: for initialadminpassword and nothing came up. I do have a file called secret.key in my Jenkins install directory but the key in this file isn't working. Any ideas on how I can get around this would be very helpful Thanks A: In the Jenkins Home directory there should be a secrets subfolder. In that directory there should be a file called initialAdminPassword (no extension). This file contains the password it is referring to. A: I found the long password in this path C:\Program Files\Jenkins\jinkins.err, in the jinkins.err file all the logs are recorded, so if you screw down slowly you can find the password being generated by the system. A: In addition to "How to “Unlock Jenkins”?", I use a groovy script in order to make sure an admin account was created. That means: * *I copy the groovy script in <Jenkins>/ref/init.groovy.d/security.groovy *I launch jenkins.war with -Djenkins.install.runSetupWizard=false In that script, replace the path of the files with the username/password by a Windows path one: def user = new File("/run/secrets/jenkins-adm-name").text.trim() def pass = new File("/run/secrets/jenkins-adm-pass").text.trim() That way: * *no wizard *one admin account with a username/password of my choosing. A: I was faced with the same issue in windows 10, following the below steps, it's working fine. *Unlock Jenkins * *Open Command Prompt Run as Administrator *Check and Go Junking Installed Location in Command Prompt *Opens the jenkins.err.log file *Find the password A: Jenkins do this because it want to ensure Jenkins is securely set up by the administrator , So you cannot open this file direct you must going step by step to the path it given to you . C:\WINDOWS\system32\config\systemprofile.jenkins\secrets\initialAdminPassword * *Go to : C:\WINDOWS\ . *Go to : system32 *....... *....... Continue tracking path And you will found it . A: Open command prompt with admin privilege (i.e, "Run as Admin"). And then navigate to the folder as mentioned in the Jenkins localhost web page. And then run the following command: notepad initialadminpassword this will display the password and then you can copy-paste it. A: if you use visual studio code Go to container Files -> var -> jenkins_home -> secrets -> initialadminpassword
stackoverflow
{ "language": "en", "length": 432, "provenance": "stackexchange_0000F.jsonl.gz:870548", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559565" }
bb2202140084572cd341be3328d7200ea6d22f09
Stackoverflow Stackexchange Q: RabbitMQ batching messages Does RabbitMQ support sending of a batch of messages at producer end and consuming a batch of messages at consumer end ? Like Kafka which stores the messages produced in batches till linger.limit is reached or till the batch is full ! Does RabbitMQ also support batching at producer side ? A: For the consumer side, the closest you can get is consumer prefetch For producer side, as far as I'm aware, batching is not supported.
Q: RabbitMQ batching messages Does RabbitMQ support sending of a batch of messages at producer end and consuming a batch of messages at consumer end ? Like Kafka which stores the messages produced in batches till linger.limit is reached or till the batch is full ! Does RabbitMQ also support batching at producer side ? A: For the consumer side, the closest you can get is consumer prefetch For producer side, as far as I'm aware, batching is not supported.
stackoverflow
{ "language": "en", "length": 80, "provenance": "stackexchange_0000F.jsonl.gz:870563", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559618" }
f56336c6381264219701673057816b34b1150d46
Stackoverflow Stackexchange Q: Project 'Pods' was rejected as an implicit dependency for 'Pods.framework' because its architectures didn't contain all required architectures Target 'AAA-Pods' for project 'Pods' was rejected as an implicit dependency for 'Pods_AAA.framework' because its architectures 'x86_64' didn't contain all required architectures 'i386 x86_64'. This appears as warning, then linker error appears. A: On a very new project on Xcode 9.4.1, the issue was that my Podfile's deployment target was set to platform :ios, '11.0' while my project's iOS deployment target was set to 10.3. This caused the generated Pods project to target iOS 11.0 (supported by only 64-bit devices on arm64 architecture), but since my main project targets 10.3 and includes armv7 devices, this doesn't work when archiving a Release build since a Release build also builds nonactive architectures by nature (unless you only support iOS 11 devices). The fix then is to simply change the Podfile's deployment target to match your main project's, in my case it's platform :ios, '10.3'. Afterwards, run pod update and the Pods project should be regenerated. Launch Xcode, perform a clean and you should be able to run the archive process.
Q: Project 'Pods' was rejected as an implicit dependency for 'Pods.framework' because its architectures didn't contain all required architectures Target 'AAA-Pods' for project 'Pods' was rejected as an implicit dependency for 'Pods_AAA.framework' because its architectures 'x86_64' didn't contain all required architectures 'i386 x86_64'. This appears as warning, then linker error appears. A: On a very new project on Xcode 9.4.1, the issue was that my Podfile's deployment target was set to platform :ios, '11.0' while my project's iOS deployment target was set to 10.3. This caused the generated Pods project to target iOS 11.0 (supported by only 64-bit devices on arm64 architecture), but since my main project targets 10.3 and includes armv7 devices, this doesn't work when archiving a Release build since a Release build also builds nonactive architectures by nature (unless you only support iOS 11 devices). The fix then is to simply change the Podfile's deployment target to match your main project's, in my case it's platform :ios, '10.3'. Afterwards, run pod update and the Pods project should be regenerated. Launch Xcode, perform a clean and you should be able to run the archive process. A: Possible Solution: * *Open Xcode project (cocoapods project) using .xc... file. *Select Pods project in the project navigator (blue icon on left). *Under Project, ensure Pods (blue icon) is selected. *Navigate to Build Settings. *Set Build Active Architectures Only = No (for both debug & release). *Optional: set base sdk to latest iOS (or select the preferred platform/version). Note: This solution resolved this issue (warning and linker error) for me. Suggested resources: Github Project: https://github.com/CocoaPods/CocoaPods/issues/2053 Github Pull Request: https://github.com/CocoaPods/CocoaPods/pull/1352 A: For future Googlers: Also make sure that your podfile targets the same iOS version your project targets: For example, if you're targeting iOS 10.0 in your Xcode project your podfile should include platform :ios, '10.0' at the top, too. A: I realize this question is a little old, however I spent 2 days fighting the same issue right after XCode updated to 9.4. What I found was in the info.plist under the key required device capabilities armv7 was set when it should have been blank. Hope this helps someone. A: I had the same issue recently after migrating to Xcode 10.1. Building with Debug config was working just fine, however archiving with Release config was generating this warning. And then archiving would fail, because in the main project all the module imports referring to Pods were failing. Checking the Build Settings for the Project I realised that iOS Deployment Target was showing a different value for my Release config. iOS 10.0, while my Podfile was set to platform :ios, '11.0'. A: Another solution which works for me. * *Open up .xcodeproject (not .xcodeworkspace) *Find IOS Deployment Target *Choose the latest version you have(My latest version is 11.4)
stackoverflow
{ "language": "en", "length": 465, "provenance": "stackexchange_0000F.jsonl.gz:870564", "question_score": "29", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559621" }
d0f0a61ada9f8f3a06b5e68f278abb8b9b22e88a
Stackoverflow Stackexchange Q: Create New Instance of Derived Class From Parent Class Javascript es6 Im getting the following error when doing this. Super expression must either be null or a function, not undefined What I'm trying to do in javascript which I can do in c# is have the child class be able to call the parent class and use functions that instantiate the base class again. Say for instance you have a navbar on a page and each icon takes you to a different page but the navbar is always visible. By inheriting from the parent page I would be able to keep the code dry like we do in c# but for some reason javascript is flipping out when trying to do the same thing even if I just pass null into the super. Doing this would allow me to havenew Support(browser).someMethod().cb().someMethod() import { Support } from "./community/Support"; export class NavigationController { constructor(browser){ this.browser = browser; } cb(){ this.browser.cool() return new Support(this.browser); } import { NavigationController } from "../navigation_controller"; export class Support extends NavigationController { constructor(browser){ super(browser); this.browser = browser; } someMethod(){ this.browser.blah() return this; }
Q: Create New Instance of Derived Class From Parent Class Javascript es6 Im getting the following error when doing this. Super expression must either be null or a function, not undefined What I'm trying to do in javascript which I can do in c# is have the child class be able to call the parent class and use functions that instantiate the base class again. Say for instance you have a navbar on a page and each icon takes you to a different page but the navbar is always visible. By inheriting from the parent page I would be able to keep the code dry like we do in c# but for some reason javascript is flipping out when trying to do the same thing even if I just pass null into the super. Doing this would allow me to havenew Support(browser).someMethod().cb().someMethod() import { Support } from "./community/Support"; export class NavigationController { constructor(browser){ this.browser = browser; } cb(){ this.browser.cool() return new Support(this.browser); } import { NavigationController } from "../navigation_controller"; export class Support extends NavigationController { constructor(browser){ super(browser); this.browser = browser; } someMethod(){ this.browser.blah() return this; }
stackoverflow
{ "language": "en", "length": 186, "provenance": "stackexchange_0000F.jsonl.gz:870581", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559669" }
fe5abacd76e6fed8a49359aa622bc56f45b853b1
Stackoverflow Stackexchange Q: Implicit Flow of OpenID Connect without browser and webview If I don't use browser and webview, I can't open page for user authentication, so can native applications not be able to OpenID Connect? The native application isn't an application that runs on a browser (such as Javascript) or webView. If it can realize, I would like to know the method.
Q: Implicit Flow of OpenID Connect without browser and webview If I don't use browser and webview, I can't open page for user authentication, so can native applications not be able to OpenID Connect? The native application isn't an application that runs on a browser (such as Javascript) or webView. If it can realize, I would like to know the method.
stackoverflow
{ "language": "en", "length": 61, "provenance": "stackexchange_0000F.jsonl.gz:870618", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559780" }
8e4469a38dbee63c32bf2c274d382d27b50d2a79
Stackoverflow Stackexchange Q: Why does it not shows JSON data in console log using jquery? When I code this in some file (say: test.html): <html> <head> <title>Test</title> </head> <body> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=my-api-key',function(json) { console.log(json); }); </script> </body> </html> But if I do same thing in some other file say (main.js) (function(){ $.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=my-api-key',function(json) { console.log(json); }); }); The above code doesn't show any JSON data in console, I have added main.js in HTML. A: Because on the second snippet, the function doesn't execute at all. Code below, (function(){ $.getJSON('... url ...', function(json) { console.log(json); }; }); Can be simplified into (function(){}); Which doesn't execute at all. You need to put parenthesis on the end of the function to execute, like this: (function(){}()); Or better yet, use the jquery document ready short-hand for proper execution after the page loaded. $(function(){}); Hope it's help.
Q: Why does it not shows JSON data in console log using jquery? When I code this in some file (say: test.html): <html> <head> <title>Test</title> </head> <body> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=my-api-key',function(json) { console.log(json); }); </script> </body> </html> But if I do same thing in some other file say (main.js) (function(){ $.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=my-api-key',function(json) { console.log(json); }); }); The above code doesn't show any JSON data in console, I have added main.js in HTML. A: Because on the second snippet, the function doesn't execute at all. Code below, (function(){ $.getJSON('... url ...', function(json) { console.log(json); }; }); Can be simplified into (function(){}); Which doesn't execute at all. You need to put parenthesis on the end of the function to execute, like this: (function(){}()); Or better yet, use the jquery document ready short-hand for proper execution after the page loaded. $(function(){}); Hope it's help. A: You need to evoke the function you are creating in your main.js file. If you wrap code with function() {}, you are defining what the function is, but not calling it. You need to call it as well as define it. (function(){ $.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=045089075bc74354be01b34f6335d32b',function(json) { console.log(json); }); })(); // parenthesis call the function
stackoverflow
{ "language": "en", "length": 194, "provenance": "stackexchange_0000F.jsonl.gz:870634", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559842" }
7072dcab2e3c246bc148e5354806905512915e51
Stackoverflow Stackexchange Q: ionic- Minimizing the app in ios I want to minimize the app. While pressing home button, the foreground app is going to background. While launching the app, the background operation should perform in foreground with corresponding page where i put the app in background. In my case, while launching the app after minimize, it navigates to login screen. A: Add Application does not run in background in info.plist and set its value NO
Q: ionic- Minimizing the app in ios I want to minimize the app. While pressing home button, the foreground app is going to background. While launching the app, the background operation should perform in foreground with corresponding page where i put the app in background. In my case, while launching the app after minimize, it navigates to login screen. A: Add Application does not run in background in info.plist and set its value NO
stackoverflow
{ "language": "en", "length": 74, "provenance": "stackexchange_0000F.jsonl.gz:870639", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559862" }
8950a54f3d7e9f510cd062a34d055aa8b89b3129
Stackoverflow Stackexchange Q: Table cells right align inside row I'm trying to figure out how to move a cell to the left on HTML table. I want to use less cells in the last row and it's on the right by default. I have this table for example: <table> <tr> <th>one</th> <th>two</th> <th>three</th> </tr> <tr> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <td>this</td> <td>right</td> </tr> </table> I'm trying to move the "this" and "right" cells to the opposite side. I'm looking for a way with less as possible css.. preferred HTML only. Update: I wasn't looking for answers about text/value align. colspan solves it somehow but still, won't call it a perfect solution. A: The td should span two columns by using the attribute colspan="2", and align the text to the right: .alignRight { text-align: right; } <table> <tr> <th>one</th> <th>two</th> <th>three</th> </tr> <tr> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <td>this</td> <td colspan="2" class="alignRight">right</td> </tr> </table> Another, html only, option is to use colspan="2" on the "this" cell: <table> <tr> <th>one</th> <th>two</th> <th>three</th> </tr> <tr> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <td colspan="2">this</td> <td>right</td> </tr> </table>
Q: Table cells right align inside row I'm trying to figure out how to move a cell to the left on HTML table. I want to use less cells in the last row and it's on the right by default. I have this table for example: <table> <tr> <th>one</th> <th>two</th> <th>three</th> </tr> <tr> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <td>this</td> <td>right</td> </tr> </table> I'm trying to move the "this" and "right" cells to the opposite side. I'm looking for a way with less as possible css.. preferred HTML only. Update: I wasn't looking for answers about text/value align. colspan solves it somehow but still, won't call it a perfect solution. A: The td should span two columns by using the attribute colspan="2", and align the text to the right: .alignRight { text-align: right; } <table> <tr> <th>one</th> <th>two</th> <th>three</th> </tr> <tr> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <td>this</td> <td colspan="2" class="alignRight">right</td> </tr> </table> Another, html only, option is to use colspan="2" on the "this" cell: <table> <tr> <th>one</th> <th>two</th> <th>three</th> </tr> <tr> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <td colspan="2">this</td> <td>right</td> </tr> </table> A: you can only add align="right" attribute <table> <tr> <th>one</th> <th>two</th> <th>three</th> </tr> <tr> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <td>this</td> <td colspan="2" align="right">right</td> </tr> </table> A: Or just insert an empty cell before <td>this</td> <table> <tr> <th>one</th> <th>two</th> <th>three</th> </tr> <tr> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <td></td> <td>this</td> <td>right</td> </tr> </table> A: I'm looking for a way with less as possible css.. preferred HTML only. You can try align attribute of td with colspan. <table> <tr> <th>one</th> <th>two</th> <th>three</th> </tr> <tr> <td>one</td> <td>two</td> <td>three</td> </tr> <tr> <td>this</td> <td colspan="2" align="right">right</td> </tr> </table> A: <tr> <td colspan="2">this</td> <td align="right">right</td> </tr> colspan can be used in both cells. This will merge cell into 2.
stackoverflow
{ "language": "en", "length": 292, "provenance": "stackexchange_0000F.jsonl.gz:870641", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559866" }
42cf7b9a964228b996c79e64227e7c688fd70924
Stackoverflow Stackexchange Q: Touchstart click event is not working for iPhone / iPade I've written an event to open new browser tab (window.open) by jQuery like below: $(document).on('touchstart click', '.myClass', {self: this}, function (e) { var mylink = e.data.self.validateDomValue(this, 'attr=data-affiliate') if(myLink) { window.open(mylink, '_blank'); } }); This scripts working well for windows, mac and iPad but the problem is arising for iPhone. The event is not firing for iPhone (version: 5, 6 and 7). What was my mistake? Any of your suggestion will be appreciated. A: Oh! Yes! I got the point. I need to use css cursor:pointer. That works for me. if (/iP(hone|od|ad)/.test(navigator.platform)) { $(".myClass").css({"cursor":"pointer"}); }
Q: Touchstart click event is not working for iPhone / iPade I've written an event to open new browser tab (window.open) by jQuery like below: $(document).on('touchstart click', '.myClass', {self: this}, function (e) { var mylink = e.data.self.validateDomValue(this, 'attr=data-affiliate') if(myLink) { window.open(mylink, '_blank'); } }); This scripts working well for windows, mac and iPad but the problem is arising for iPhone. The event is not firing for iPhone (version: 5, 6 and 7). What was my mistake? Any of your suggestion will be appreciated. A: Oh! Yes! I got the point. I need to use css cursor:pointer. That works for me. if (/iP(hone|od|ad)/.test(navigator.platform)) { $(".myClass").css({"cursor":"pointer"}); } A: use css cursor:pointer didn't work for me once the element I used was on 'position:fixed'. I added a 'click' event listener and it solved the case. Once I click on the element only one of the events is fired.
stackoverflow
{ "language": "en", "length": 145, "provenance": "stackexchange_0000F.jsonl.gz:870647", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559876" }
126a8f0b636fca945a041dd844affe8300f16b83
Stackoverflow Stackexchange Q: Caching ignite client node I'm writing a back-end application which is supposed to receive request from clients and perform some operations with ignite cache. The issue is I need low-latency response time and recreating Ignite client node to perform some operation with cache is totally unacceptable. Is it common to create Ignite client node once on application startup and then use it any time the back-end received request from client that requires some operations with Ignite cache. I mean something like that: public class Handler{ private static final Ignite igniteClient; static{ Ignition.setClientMode(true); igniteClient = Ignition.start(); } private final Semaphore semaphore = new Semaphore(5); private void handle(){ semaphore.acquire(); //use igniteClient semaphore.release(); } } A: Yes, it's common to create Ignite client nodes on application startup and then reuse it. Moreover, it's a not a good idea to create new client for each request, because it will lead to topology changes on each NODE_JOIN & NODE_LEFT events, which lead to creating new objects and connections for each client on a server nodes.
Q: Caching ignite client node I'm writing a back-end application which is supposed to receive request from clients and perform some operations with ignite cache. The issue is I need low-latency response time and recreating Ignite client node to perform some operation with cache is totally unacceptable. Is it common to create Ignite client node once on application startup and then use it any time the back-end received request from client that requires some operations with Ignite cache. I mean something like that: public class Handler{ private static final Ignite igniteClient; static{ Ignition.setClientMode(true); igniteClient = Ignition.start(); } private final Semaphore semaphore = new Semaphore(5); private void handle(){ semaphore.acquire(); //use igniteClient semaphore.release(); } } A: Yes, it's common to create Ignite client nodes on application startup and then reuse it. Moreover, it's a not a good idea to create new client for each request, because it will lead to topology changes on each NODE_JOIN & NODE_LEFT events, which lead to creating new objects and connections for each client on a server nodes.
stackoverflow
{ "language": "en", "length": 171, "provenance": "stackexchange_0000F.jsonl.gz:870651", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559889" }
4daec1b9ae5c325ade5cafba064b884538e9dad8
Stackoverflow Stackexchange Q: Destructuring array get second value? How to get array using destructing? const num = [1,2,3,4,5]; const [ first ] = num; //1 console.log(first) I'm able to get 1, but when I try to do const [ null, second ] = num it has expected token error. How to get 2nd item of num array? A: As alternative you can use object destructuring because arrays are objects: var {1: second} = num; But simply omitting the first element as Piotr suggests in their answer is a bit cleaner in this particular case. See also Object destructuring solution for long arrays?
Q: Destructuring array get second value? How to get array using destructing? const num = [1,2,3,4,5]; const [ first ] = num; //1 console.log(first) I'm able to get 1, but when I try to do const [ null, second ] = num it has expected token error. How to get 2nd item of num array? A: As alternative you can use object destructuring because arrays are objects: var {1: second} = num; But simply omitting the first element as Piotr suggests in their answer is a bit cleaner in this particular case. See also Object destructuring solution for long arrays? A: You can skip parametr name just by putting comma var num = [1, 2, 3, 4, 5]; var [ ,x] = num; for more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Ignoring_some_returned_values section Ignoring some returned values
stackoverflow
{ "language": "en", "length": 131, "provenance": "stackexchange_0000F.jsonl.gz:870678", "question_score": "56", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44559964" }
ebb269d0e50b168312fc5401d85b445d0dad239a
Stackoverflow Stackexchange Q: Message from debugger: unable to attach error for osx app I have been building mac app on my mac mini and it always worked well but today i faced this error, searched a lot but no luck. Message from debugger: unable to attach What i tried: * *Clear derived data *Quit Xcode *Restart machine *installation directory set to blank and also to /Applications *Tried Skip Install No / Yes *Using developer Signing certs *M using only Developer certificates and not provisioning profile to sign my cocoa app Xcode 8.2 OSX 10.12.1 Please help :) A: This is what fixed it for me, perhaps it will help others but I do realize the question was for 8.2. I had it set to Xcode 9 "New Build System" disabling this and switching to "Standard Build System" in the Project Settings under the File Menu. I had tried all the other things like killing DerivedData, clean build, restarting Xcode. I also verified that my dependent libraries were set correctly. The only thing that worked was disabling new "New Build System"
Q: Message from debugger: unable to attach error for osx app I have been building mac app on my mac mini and it always worked well but today i faced this error, searched a lot but no luck. Message from debugger: unable to attach What i tried: * *Clear derived data *Quit Xcode *Restart machine *installation directory set to blank and also to /Applications *Tried Skip Install No / Yes *Using developer Signing certs *M using only Developer certificates and not provisioning profile to sign my cocoa app Xcode 8.2 OSX 10.12.1 Please help :) A: This is what fixed it for me, perhaps it will help others but I do realize the question was for 8.2. I had it set to Xcode 9 "New Build System" disabling this and switching to "Standard Build System" in the Project Settings under the File Menu. I had tried all the other things like killing DerivedData, clean build, restarting Xcode. I also verified that my dependent libraries were set correctly. The only thing that worked was disabling new "New Build System" A: I just had this problem today. I have little demo code in a mac project(created with Xcode 9.4). This error just started to occur after I upgraded system to macOS Mojave 10.14. However, in Xcode 10 this project runs no problem(without changing anything). If you can use Xcode 10 it will probably be fixed. A: Unfortunately, the above solutions didn't work for me (although I am sure they work for some people). Here is what worked for me, in case this helps anyone else: * *Close Xcode *Open Xcode and Create a new Xcode project *In the iOS template, select Single View App then click Next * *yes, I know you are trying to get a macOS app attaching to the debugger :). *Give the iOS app any product name and organization identifier you would like and click Next *Create the new project anywhere you would like (I saved it to my desktop) *Build and run (cmd + r) the iOS app on a simulator like the iPhone 8 (starting a simulator and running the iOS app will take a little time, so have patients) *After the iOS app runs in the simulator, click to stop it from running (the stop button is next to the run button) *Open your macOS app that you are having trouble connecting a debugger to, and build and run it (cmd + r) This, for some reason, allowed me to connect to the debugger with my macOS app... Xcode version: 10.1, macOS Mojave version: 10.14.2
stackoverflow
{ "language": "en", "length": 430, "provenance": "stackexchange_0000F.jsonl.gz:870693", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44560003" }