id
stringlengths 40
40
| text
stringlengths 29
2.03k
| original_text
stringlengths 3
154k
| subdomain
stringclasses 20
values | metadata
dict |
---|---|---|---|---|
77ce41afa99d2faf4fe12313f4a0464f2a1b4bda
|
Stackoverflow Stackexchange
Q: VueJS - How can I bind multiple class from object that created by v-for? I wanted to make it like this:
<ul>
<li class="aaa active">text-aaa</li>
<li class="bbb">text-bbb</li>
<li class="ccc">text-ccc</li>
</ul>
Here's the code. https://jsfiddle.net/qwvwsgb9/
I can bind value calculated by v-for by using non-object format :class="v.name"
<div id="app">
<ul>
<li v-for="v, i in listAry" :class="{v.name:true,active:active==i}">{{ v.text }}</li>
</ul>
</div>
script:
let vm = new Vue({
el: "#app",
data: {
active:0,
listAry: [{
name: 'aaa',
text: 'text-aaa'
}, {
name: 'bbb',
text: 'text-bbb'
}, {
name: 'ccc',
text: 'text-ccc'
}]
}
})
but as long as I tried to apply it in object format, the error occurs.
How can I do it?
A: Try something like this :class="[{ active: active === i }, v.name]"
<div id="app">
<ul>
<li v-for="v, i in listAry" :class="[{ active: active === i }, v.name]">
{{ v.text }}
</li>
</ul>
</div>
|
Q: VueJS - How can I bind multiple class from object that created by v-for? I wanted to make it like this:
<ul>
<li class="aaa active">text-aaa</li>
<li class="bbb">text-bbb</li>
<li class="ccc">text-ccc</li>
</ul>
Here's the code. https://jsfiddle.net/qwvwsgb9/
I can bind value calculated by v-for by using non-object format :class="v.name"
<div id="app">
<ul>
<li v-for="v, i in listAry" :class="{v.name:true,active:active==i}">{{ v.text }}</li>
</ul>
</div>
script:
let vm = new Vue({
el: "#app",
data: {
active:0,
listAry: [{
name: 'aaa',
text: 'text-aaa'
}, {
name: 'bbb',
text: 'text-bbb'
}, {
name: 'ccc',
text: 'text-ccc'
}]
}
})
but as long as I tried to apply it in object format, the error occurs.
How can I do it?
A: Try something like this :class="[{ active: active === i }, v.name]"
<div id="app">
<ul>
<li v-for="v, i in listAry" :class="[{ active: active === i }, v.name]">
{{ v.text }}
</li>
</ul>
</div>
|
stackoverflow
|
{
"language": "en",
"length": 145,
"provenance": "stackexchange_0000F.jsonl.gz:888693",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616454"
}
|
2e49d1d02898258169b621879c2aa49124c948a9
|
Stackoverflow Stackexchange
Q: Finding the mean and standard deviation of a timedelta object in pandas df I would like to calculate the mean and standard deviation of a timedelta by bank from a dataframe with two columns shown below. When I run the code (also shown below) I get the below error:
pandas.core.base.DataError: No numeric types to aggregate
My dataframe:
bank diff
Bank of Japan 0 days 00:00:57.416000
Reserve Bank of Australia 0 days 00:00:21.452000
Reserve Bank of New Zealand 55 days 12:39:32.269000
U.S. Federal Reserve 8 days 13:27:11.387000
My code:
means = dropped.groupby('bank').mean()
std = dropped.groupby('bank').std()
A: Pandas mean() and other aggregation methods support numeric_only=False parameter.
dropped.groupby('bank').mean(numeric_only=False)
Found here: Aggregations for Timedelta values in the Python DataFrame
|
Q: Finding the mean and standard deviation of a timedelta object in pandas df I would like to calculate the mean and standard deviation of a timedelta by bank from a dataframe with two columns shown below. When I run the code (also shown below) I get the below error:
pandas.core.base.DataError: No numeric types to aggregate
My dataframe:
bank diff
Bank of Japan 0 days 00:00:57.416000
Reserve Bank of Australia 0 days 00:00:21.452000
Reserve Bank of New Zealand 55 days 12:39:32.269000
U.S. Federal Reserve 8 days 13:27:11.387000
My code:
means = dropped.groupby('bank').mean()
std = dropped.groupby('bank').std()
A: Pandas mean() and other aggregation methods support numeric_only=False parameter.
dropped.groupby('bank').mean(numeric_only=False)
Found here: Aggregations for Timedelta values in the Python DataFrame
A: You need to convert timedelta to some numeric value, e.g. int64 by values what is most accurate, because convert to ns is what is the numeric representation of timedelta:
dropped['new'] = dropped['diff'].values.astype(np.int64)
means = dropped.groupby('bank').mean()
means['new'] = pd.to_timedelta(means['new'])
std = dropped.groupby('bank').std()
std['new'] = pd.to_timedelta(std['new'])
Another solution is to convert values to seconds by total_seconds, but that is less accurate:
dropped['new'] = dropped['diff'].dt.total_seconds()
means = dropped.groupby('bank').mean()
A: No need to convert timedelta back and forth. Numpy and pandas can seamlessly do it for you with a faster run time. Using your dropped DataFrame:
import numpy as np
grouped = dropped.groupby('bank')['diff']
mean = grouped.apply(lambda x: np.mean(x))
std = grouped.apply(lambda x: np.std(x))
A: I would suggest passing the numeric_only=False argument to mean as mentioned by Alexander Usikov - this works for pandas version 0.20+.
If you have an older version, the following works:
import pandas pd
df = pd.DataFrame({
'td': pd.Series([pd.Timedelta(days=i) for i in range(5)]),
'group': ['a', 'a', 'a', 'b', 'b']
})
(
df
.astype({'td': int}) # convert timedelta to integer (nanoseconds)
.groupby('group')
.mean()
.astype({'td': 'timedelta64[ns]'})
)
|
stackoverflow
|
{
"language": "en",
"length": 291,
"provenance": "stackexchange_0000F.jsonl.gz:888725",
"question_score": "29",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616546"
}
|
b75f345c4329dd366c9bab8695a1265faba11f94
|
Stackoverflow Stackexchange
Q: Any way to use Firebase google authentication in expo (create-react-native-app) without "eject" project As the question, for Login with google in firebase need to set google-service but if you create new react-native project with create-react-native-app there will have no "android" or "ios" folder (accept used "eject") so, anyone have a suggestion for me?
However I've no idea for how to setting google-service in my project too (even I "eject" the project).
A: It isn't necessary to make any changes to the android or ios folders in order to support Google sign in with firebase on an app built with Expo.
*
*Follow the guide for configuring Google auth on the Expo docs
*Use the approach described in Expo's Using Firebase guide, where it describes how to authenticate with Facebook, and swap out Google where needed.
|
Q: Any way to use Firebase google authentication in expo (create-react-native-app) without "eject" project As the question, for Login with google in firebase need to set google-service but if you create new react-native project with create-react-native-app there will have no "android" or "ios" folder (accept used "eject") so, anyone have a suggestion for me?
However I've no idea for how to setting google-service in my project too (even I "eject" the project).
A: It isn't necessary to make any changes to the android or ios folders in order to support Google sign in with firebase on an app built with Expo.
*
*Follow the guide for configuring Google auth on the Expo docs
*Use the approach described in Expo's Using Firebase guide, where it describes how to authenticate with Facebook, and swap out Google where needed.
A: @brentvatne 's answer is a bit out of date. Here's how I got it working on Expo v27
Important bit: you can get your client ids with these instructions.
Just select your firebase app from the project dropdown on the google page.
const _loginWithGoogle = async function() {
try {
const result = await Expo.Google.logInAsync({
androidClientId:"YOUR_ANDROID_CLIENT_ID",
iosClientId:"YOUR_iOS_CLIENT_ID",
scopes: ["profile", "email"]
});
if (result.type === "success") {
const { idToken, accessToken } = result;
const credential = firebase.auth.GoogleAuthProvider.credential(idToken, accessToken);
firebase
.auth()
.signInAndRetrieveDataWithCredential(credential)
.then(res => {
// user res, create your user, do whatever you want
})
.catch(error => {
console.log("firebase cred err:", error);
});
} else {
return { cancelled: true };
}
} catch (err) {
console.log("err:", err);
}
};
|
stackoverflow
|
{
"language": "en",
"length": 257,
"provenance": "stackexchange_0000F.jsonl.gz:888746",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616596"
}
|
402c33a9c60161cd23cb0612cad5cd3205e1cad4
|
Stackoverflow Stackexchange
Q: CSR algorithm/size is incorrect.Expected RSA 2048 I am trying to integrate apple pay with braintree. I have followed up the following instructions to enable apple pay in the brain tree. In the first step, if you click on certificate signing request, it downloads a braintree_app_pay.certSigningRequest file which is used in the apple membership.
When I choose to create payment process certificate, I am getting the following error.
A: Full disclosure: I work at Braintree. If you have any further questions, feel free to contact our Support team.
Make sure you're selecting the Apple Pay Certificate option under Production (even if this is for a Sandbox; see the Braintree Apple Pay configuration docs for details) when choosing the type of certificate to add in the Apple Developer portal. Apple Pay CSRs should be generated with ECC, not RSA.
Here's what the CSR prompt screen should look like. Although you'll be uploading the CSR obtained from Braintree instead of generating one, note Apple's specifications for the key:
|
Q: CSR algorithm/size is incorrect.Expected RSA 2048 I am trying to integrate apple pay with braintree. I have followed up the following instructions to enable apple pay in the brain tree. In the first step, if you click on certificate signing request, it downloads a braintree_app_pay.certSigningRequest file which is used in the apple membership.
When I choose to create payment process certificate, I am getting the following error.
A: Full disclosure: I work at Braintree. If you have any further questions, feel free to contact our Support team.
Make sure you're selecting the Apple Pay Certificate option under Production (even if this is for a Sandbox; see the Braintree Apple Pay configuration docs for details) when choosing the type of certificate to add in the Apple Developer portal. Apple Pay CSRs should be generated with ECC, not RSA.
Here's what the CSR prompt screen should look like. Although you'll be uploading the CSR obtained from Braintree instead of generating one, note Apple's specifications for the key:
A: Please follow below steps[If use Apple Pay with stripe or any other payment gateway]:
*
*Double click on CSR (Downloaded from Stripe), [It will open Certificate Assistant]
*Click on Continue
*Select 'Request a certificate from an existing CA', and Continue
*In Certificate Information screen, Enter User Email Address, Common Name, Leave CA Email Address empty, Select 'Saved to disk & checked Let me specify key pair information' [Select your specific location and save]
*In Key Pair Information screen, select 'ECC' algorithm & select Key size : 256 bits and continue.
Now use this CSR in your payment processing certificate.
A: This issue is not specific to Apple Pay or Braintree - I ran into the same issue when trying to create a CSR for getting a Safari certificate from Apple.
What's important to know is that you need to select the iCloud keychain before using the Request Certificate from Certificate Authority command. If you don't, another keychain may be active, causing wrong keys to be used.
A: From Apple Developer Forum
Within the Keychain Access drop down menu, select Keychain Access >
Certificate Assistant > Request a Certificate from a Certificate
Authority.
*
*In the Certificate Information window, enter the following information:
*
*In the User Email Address field, enter your email address.
*In the Common Name field, create a name for your private key (e.g., John Doe Dev Key).
*The CA Email Address field should be left empty.
*In the "Request is" group, select the "Saved to disk" option.
*Select "Let me specify key pair information".
*Click Continue within Keychain Access and select the file location.
*Set the Key Pair Information to the following:
*
*Algorithm: ECC
*Key Size: 256 bits Click
*Continue within Keychain Access to complete the CSR generating process.
A: complimenting what @zepp said, you need to specify when creating CRS, and you can that by following the process below
*
*Go to Keychain Access
*Click on Certificate Assistance
*Click on Request Certificate from Certificate Authority (click for image)
*Enter all information and click on "Let me specify key pair Information"checkbox, then click on Continue
*Select KeySize to be 256 and Algorithm to be ECC (click for image)
*Then click on continue.
A: I don't get it, because it's said You must use the CSR we provide. Do not create a CSR file yourself on braintree website.
And with this CSR file, it's always failed on apple's upload page.
Edit:
I finally upload success with follow steps of @anjali-jariwala 's answer.
Just in last step, I choose RSA & 2048 as alert requirement.
A: For me I accidentally chose Yes when asked Will payments associated with this Merchant ID be processed exclusively in China?
Choosing No solved the issue for me
A: I had the same error. The mistake on my part was choosing the wrong type of certificate while creating it in the Apple developer portal. I used 'Apple Pay Merchant Identity Certificate', but I needed to use 'Apple Pay Payment Processing Certificate', which solved the issue.
|
stackoverflow
|
{
"language": "en",
"length": 669,
"provenance": "stackexchange_0000F.jsonl.gz:888840",
"question_score": "19",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616923"
}
|
ff581e8bdecb497c6bcd1e67e2f97918f764da00
|
Stackoverflow Stackexchange
Q: Is the PADDD instruction actually supported by MMX, even though it's missing from Intel's manual? I wrote this code in NASM:
PADDD mm0, mm1
And it was assembled with no errors, but this instruction, though it exists in NASM, I couldn't find it in Intel Instructions Manuals, all I found is this:
PADDD xmm1, xmm2/m128
Which takes an xmm register and not an mm register.
This is the opcode of PADDD mm0, mm1: 0FFEC1
And this is the opcode of PADDD xmm0, xmm1: 660FFEC1
So why PADDD mm0, mm1 is missing in Intel's Instructions manuals?
A: This is a simple case of a typo/omission in the current version of Intel's manuals.
On this site, which hosts a copy of the Intel docs (although not necessary the latest Intel docs), the opcode for MMX is present:
Opcode/Instruction Op/En 64/32 bit Mode Support CPUID Feature Flag Description
0F FC /r1 PADDB mm, mm/m64 RM V/V MMX Add packed byte integers from mm/m64 and mm.
You will also find it in an older Intel manual from 2005, as well as in the March 2017 version.
Nothing to see here; please move along.
|
Q: Is the PADDD instruction actually supported by MMX, even though it's missing from Intel's manual? I wrote this code in NASM:
PADDD mm0, mm1
And it was assembled with no errors, but this instruction, though it exists in NASM, I couldn't find it in Intel Instructions Manuals, all I found is this:
PADDD xmm1, xmm2/m128
Which takes an xmm register and not an mm register.
This is the opcode of PADDD mm0, mm1: 0FFEC1
And this is the opcode of PADDD xmm0, xmm1: 660FFEC1
So why PADDD mm0, mm1 is missing in Intel's Instructions manuals?
A: This is a simple case of a typo/omission in the current version of Intel's manuals.
On this site, which hosts a copy of the Intel docs (although not necessary the latest Intel docs), the opcode for MMX is present:
Opcode/Instruction Op/En 64/32 bit Mode Support CPUID Feature Flag Description
0F FC /r1 PADDB mm, mm/m64 RM V/V MMX Add packed byte integers from mm/m64 and mm.
You will also find it in an older Intel manual from 2005, as well as in the March 2017 version.
Nothing to see here; please move along.
|
stackoverflow
|
{
"language": "en",
"length": 190,
"provenance": "stackexchange_0000F.jsonl.gz:888852",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44616973"
}
|
c430cedab4a547e6374464ea695e3196534e976c
|
Stackoverflow Stackexchange
Q: Azure Web App slots, why does Source default to production on a swap Every time I'm Swapping, the dropdown for 'source' is prefilled with 'production'.
Shouldn't the destination always be prefilled with 'production'
Since destination is the one that's supposed to stay live without interruption. Source=Staging right
A: You are correct that Staging should always be the source. And the good news is that despite what the UI says, Production is always treated as the Destination during the swap, regardless of the direction you specify. In other words, this is more or less a UI bug.
Additionally, note that if instead of clicking Swap while directly on the main site, you can first go into your Staging slot, and click swap from there. In that case, the default direction is what you expect. Though again, the direction the UI shows ends up being irrelevant during the swap (as long as Production is one of the two slots).
|
Q: Azure Web App slots, why does Source default to production on a swap Every time I'm Swapping, the dropdown for 'source' is prefilled with 'production'.
Shouldn't the destination always be prefilled with 'production'
Since destination is the one that's supposed to stay live without interruption. Source=Staging right
A: You are correct that Staging should always be the source. And the good news is that despite what the UI says, Production is always treated as the Destination during the swap, regardless of the direction you specify. In other words, this is more or less a UI bug.
Additionally, note that if instead of clicking Swap while directly on the main site, you can first go into your Staging slot, and click swap from there. In that case, the default direction is what you expect. Though again, the direction the UI shows ends up being irrelevant during the swap (as long as Production is one of the two slots).
|
stackoverflow
|
{
"language": "en",
"length": 158,
"provenance": "stackexchange_0000F.jsonl.gz:888867",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617007"
}
|
2205bb88201bbb498668d0f4baa097c8909a1ec9
|
Stackoverflow Stackexchange
Q: How to install Caret package? While installing, I am getting this message library(caret)
Loading required package: ggplot2 Error: package or namespace load
failed for ‘ggplot2’ in loadNamespace(i, c(lib.loc, .libPaths()),
versionCheck = vI[[i]]): there is no package called ‘gtable’ Error:
package ‘ggplot2’ could not be loaded
A: Try this...
install.packages('caret', dependencies = TRUE)
|
Q: How to install Caret package? While installing, I am getting this message library(caret)
Loading required package: ggplot2 Error: package or namespace load
failed for ‘ggplot2’ in loadNamespace(i, c(lib.loc, .libPaths()),
versionCheck = vI[[i]]): there is no package called ‘gtable’ Error:
package ‘ggplot2’ could not be loaded
A: Try this...
install.packages('caret', dependencies = TRUE)
A: I had the same issue (R 3.5 for Windows).
Just had to keep going installing the missing dependencies until everything installed (for me there were about 10 dependencies missing)
This even required changing to a different mirror when the files could not be found!
Hope this helps someone in future...
> install.packages('caret', dependencies = TRUE)
> library('caret')
Loading required package: ggplot2 Error: package or namespace load failed for ‘ggplot2’ in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]): there is no package called ‘gtable’ Error: package ‘ggplot2’ could not be loaded
> install.packages('gtable', dependencies = TRUE)
> install.packages('ggplot2', dependencies = TRUE)
> library('caret')
Error: package or namespace load failed for ‘caret’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
there is no package called ‘gower’
> install.packages('gower', dependencies = TRUE)
...
A: In Ubuntu:
sudo apt-get update
sudo apt-get install r-cran-caret
A: So what worked for me is a bit old school: after installing the caret package and getting that error, I did a quick search on my PC for caret (In my case; I went to ThisPC > RoseAdediran), deleted the caret folder, searched for plyr and deleted the folder as well. Went back to RStudio, restarted the session and tried this code again
install.packages('caret', dependencies=T)
library(caret)
Once you load the library, other imports would be loaded as well.
A: Try this ...
install.packages('caret', repos='http://cran.rstudio.com/')
A: I had a similar issue for another package, and the easiest way to fix it was as follows(in RStudio):
*
*Close all open .rmd, .r and .rnw files.
*On the right hand lower corner I pressed on Packages and then on update. I selected all packages that needed an update and updated them. (You might also need to restart R, which can be done via Ctrl + Shift + F10).
After this I had no problems.
A: when attempting:
install.packages("caret")
I'm getting the following errors:
Warning: unable to access index for repository https://cran.mtu.edu/src/contrib:
cannot open URL 'https://cran.mtu.edu/src/contrib/PACKAGES'
Warning: unable to access index for repository https://cran.mtu.edu/bin/macosx/el-capitan/contrib/3.6:
cannot open URL 'https://cran.mtu.edu/bin/macosx/el-capitan/contrib/3.6/PACKAGES'
Warning message:
package ‘~/Downloads/caret’ is not available (for R version 3.6.1)
(yes, I should upgrade)
Solved by installing from the Rstudio CRAN repo:
install.packages('caret', repos='http://cran.rstudio.com/')
A: As Ian suggested, try installing the package mentioned in the error message. I had the same issue and the error was 'there is no package as Biobase'. So I searched on the web for Biobase, installed it, tried library(caret) and it asked for another package and I kept installing till library(caret) worked. In your case, it shows 'there is no package called ‘gtable’. So start with installing gtable and load caret and keep at it.
A: I had the same problem when updating to R 3.5, if you changed R versions using something like the updater function from the installr package, it has some problems copying the libraries between major releases (3.4 -> 3.5).
The solution that worked for me was installing manually all the previous libraries.
A: Wrote the command
install.packages("caret")
on my rmd file and had problems with the installation. It was solved just by typing the same line in the console.
A: just try this
install.packages(pkgs = "caret",
dependencies = c("Depends", "Imports"))
|
stackoverflow
|
{
"language": "en",
"length": 580,
"provenance": "stackexchange_0000F.jsonl.gz:888893",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617073"
}
|
ea8aed02c7753e57f6c40c7a4acf61488b5715ca
|
Stackoverflow Stackexchange
Q: Python 3.6 Module cannot be found: Folium I am trying to import folium into a Jupyter notebook I'm working on and I cannot seem to solve the import issues with the Folium library. Has anyone else solved this problem?
!pip install folium
import pandas as pd
import folium
Output from the above yields:
`ModuleNotFoundError Traceback (most recent call last)
<ipython-input-7-a9938c267a0c> in <module>()
1 get_ipython().system('pip install folium')
2 import pandas as pd
----> 3 import folium
ModuleNotFoundError: No module named 'folium'`
A: I solved the same problem by executing following command
python3 -m pip install folium
|
Q: Python 3.6 Module cannot be found: Folium I am trying to import folium into a Jupyter notebook I'm working on and I cannot seem to solve the import issues with the Folium library. Has anyone else solved this problem?
!pip install folium
import pandas as pd
import folium
Output from the above yields:
`ModuleNotFoundError Traceback (most recent call last)
<ipython-input-7-a9938c267a0c> in <module>()
1 get_ipython().system('pip install folium')
2 import pandas as pd
----> 3 import folium
ModuleNotFoundError: No module named 'folium'`
A: I solved the same problem by executing following command
python3 -m pip install folium
A: From the source:
*
*Choose the sandbox folder of your choice (~/sandbox for example)
$ mkdir visualization
$ cd visualization
*Clone folium from github:
$ git clone https://github.com/python-visualization/folium
*Run the installation script
$ cd folium
$ python setup.py install
A: I had similar issues as the original problem. I installed successfully from the shell but jupyter would not recognize the module.
What worked for me was (in the jupyter notebook):
!pip install folium
A: My method was:
$ cd C:\programdata\anaconda3\lib\site_packages
Then
git clone https://github.com/python-visualization/folium.git
git clone https://github.com/pallets/jinja.git
I imported Folium then it worked.
A: It is not available via default conda channel. Try using conda-forge channel to install folium as show below:
conda install -c conda-forge folium
A: I eventually git-cloned the github repositories for folium and jinja2 into a file and it worked.
Specifically, on my computer, I changed into the right directory from the command line interface with:
$ cd C:\programdata\anaconda3\lib\site_packages
And then typed:
git clone https://github.com/python-visualization/folium.git
git clone https://github.com/pallets/jinja.git
Then import folium (from within python) worked.
A: I had the same problem while installing with pip3 (macOS with python3).
Manually cloning the github repo solved it.
*
*Move to the package folder of python 3
cd /usr/local/lib/python3.6/site-packages/
*Then
git clone https://github.com/python-visualization/folium
cd folium
python setup.py install
A: So for Mac OS with Python 3.x, Anaconda doesn't have the library on its installer by default.
You need to clone and manually install 2 two libraries:
1) Navigate to /Users/<username>/anaconda3/lib/python3.6/site-packages
2)Folium
git clone https://github.com/python-visualization/folium.git
cd folium
python setup.py install
3)Branca (This library is a spinoff from folium, that would host the non-map-specific features, if importing folium without branca the kernel complains about missing module named branca)
git clone https://github.com/python-visualization/branca.git
cd branca
python setup.py install
4)Restart your kernel
5)Import
import folium
import branca
A: Running the following code in the terminal fixed it for me.
$ conda install folium -c conda-forge
A: Make sure to reinstall jupyter in new conda env. From what I was able to tell, it runs the Jupyter from preexisting environments and that jupyter does not have access to the packages of the new environment
A: I am using windows 10. I was getting same issue. This is how I fixed it.
Open Command prompt, run as administrator.
type "python" to check if python is installed, if not install python globally.
if python is installed, you will see python prompt, Ctrl+Z to exit and Run :
python -m pip install folium
A: For osx-64 v0.4.0 the following code worked for me:
Install folium using:
conda install -c conda-forge/label/cf201901 folium
Then verify if the package has been installed
import folium
print('Folium installed and imported!')
A: Nothing in this thread didn't work for me. So my solution was a little bit strange. I am using a PyCharm, and in my project dir I have a requirements.txt file. PyCharm understands that libraties in this file must be installed, and if they are not, it can install by itself. So I just wrote "folium==0.12.1" in this file and PyCharm done all the work. Maybe another IDE also can do it.
A: Below mentioned command execute in your root working environment.
Solution 1:
pip install folium
or
pip3 install folium
Solution 2:
conda install branca
conda install folium
|
stackoverflow
|
{
"language": "en",
"length": 634,
"provenance": "stackexchange_0000F.jsonl.gz:888920",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617159"
}
|
d6bf38749299b114855c3fccef749c2162b24724
|
Stackoverflow Stackexchange
Q: window.history.pushState() data, how and when they are retrieved? window.history.pushState([data], 'Title', '/url');
When I set up data in here, how can I use them and what kind of data this is meant for?
A: The data object is meant to store structured data of your choosing associated with the history item, so that when the state is revisited, the application has some data available associated with it. Maybe you can save the location of the page that the user was previously viewing, or some form options they had entered but never submitted.
Browsers will call the popstate() method when a back button is fired, which will pop the most recent state pushed to the stack. Developers should add an event listener to the window object for custom handling of the popstate event (such as using the data associated with the state).
// Below function will get fired for every app-wide popstate
window.addEventListener('popstate', function(event) {
// Can access state data using event.state.data
});
|
Q: window.history.pushState() data, how and when they are retrieved? window.history.pushState([data], 'Title', '/url');
When I set up data in here, how can I use them and what kind of data this is meant for?
A: The data object is meant to store structured data of your choosing associated with the history item, so that when the state is revisited, the application has some data available associated with it. Maybe you can save the location of the page that the user was previously viewing, or some form options they had entered but never submitted.
Browsers will call the popstate() method when a back button is fired, which will pop the most recent state pushed to the stack. Developers should add an event listener to the window object for custom handling of the popstate event (such as using the data associated with the state).
// Below function will get fired for every app-wide popstate
window.addEventListener('popstate', function(event) {
// Can access state data using event.state.data
});
A: This is like a unqiue identifier to the state that is being pushed. When the time comes when you want to replaceState for that particular state, it will be helpful.
Example:
Store the state:
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
You could do this to replace the state:
history.replaceState(stateObj, "page 3", "bar2.html");
Reference: https://developer.mozilla.org/en/docs/Web/API/History_API#The_pushState()_method
|
stackoverflow
|
{
"language": "en",
"length": 222,
"provenance": "stackexchange_0000F.jsonl.gz:888990",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617363"
}
|
eaaa0a0d7b2cee1ffd77f76eae48dd235dd81d3e
|
Stackoverflow Stackexchange
Q: Ionic 3 get index of clicked item I need to get the index of the clicked item in an ion list, so I can access the position in an array.
The html code I used is this:
<ion-list>
<ion-item *ngFor="let poi of poiList" (click)="openPage(poi, $index)">
<h2> {{ poi.name }} </h2>
</ion-item>
</ion-list>
Inside the function openPage I've printed the index in the console, but it is showed as "undefined". I couldn't find any other way to get the index correctly.
A: $index will only work for AngularJS, in Angular2 and above the way to get the clicked item index is the following :
<ion-list>
<ion-item *ngFor="let poi of poiList; let i= index" (click)="openPage(poi, i)">
<h2> {{ poi.name }} </h2>
</ion-item>
</ion-list>
|
Q: Ionic 3 get index of clicked item I need to get the index of the clicked item in an ion list, so I can access the position in an array.
The html code I used is this:
<ion-list>
<ion-item *ngFor="let poi of poiList" (click)="openPage(poi, $index)">
<h2> {{ poi.name }} </h2>
</ion-item>
</ion-list>
Inside the function openPage I've printed the index in the console, but it is showed as "undefined". I couldn't find any other way to get the index correctly.
A: $index will only work for AngularJS, in Angular2 and above the way to get the clicked item index is the following :
<ion-list>
<ion-item *ngFor="let poi of poiList; let i= index" (click)="openPage(poi, i)">
<h2> {{ poi.name }} </h2>
</ion-item>
</ion-list>
|
stackoverflow
|
{
"language": "en",
"length": 122,
"provenance": "stackexchange_0000F.jsonl.gz:889005",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617412"
}
|
4a4f1c1a87aa67631f482be6399fa9639d0820e0
|
Stackoverflow Stackexchange
Q: Update Query with JPA and Java Im trying to update my jpa repository
@Transactional
public interface UserRepository extends JpaRepository<User, Integer> {
User findByUsername(String username);
User findById(Long id);
@Query(value = "update user t set t.rule_id = NULL where t.rule_id = :id", nativeQuery = true)
List<User> setNUll(@Param("id") String id);}
This is a part of my controller:
@RequestMapping(value = "/admin/rule/{id}/edit", method = RequestMethod.GET)
public String editRule(@PathVariable Integer id, Model model)
{
userService.setNUll(Integer.toString(id));
model.addAttribute("rule", ruleCrudService.getRuleById(id));
updateUserData();
return "ruleForm";
}
And this error apears in my browser:
There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet
The server also says:
SQL Error: 0, SQLState: S1009
2017-06-18 12:51:15.778 ERROR 10388 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Can not issue data manipulation statements with executeQuery().
2017-06-18 12:51:15.844 ERROR 10388 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
A: you need to use @Modifying annotation above of @Query to exicute update query using JPA.
|
Q: Update Query with JPA and Java Im trying to update my jpa repository
@Transactional
public interface UserRepository extends JpaRepository<User, Integer> {
User findByUsername(String username);
User findById(Long id);
@Query(value = "update user t set t.rule_id = NULL where t.rule_id = :id", nativeQuery = true)
List<User> setNUll(@Param("id") String id);}
This is a part of my controller:
@RequestMapping(value = "/admin/rule/{id}/edit", method = RequestMethod.GET)
public String editRule(@PathVariable Integer id, Model model)
{
userService.setNUll(Integer.toString(id));
model.addAttribute("rule", ruleCrudService.getRuleById(id));
updateUserData();
return "ruleForm";
}
And this error apears in my browser:
There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet
The server also says:
SQL Error: 0, SQLState: S1009
2017-06-18 12:51:15.778 ERROR 10388 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Can not issue data manipulation statements with executeQuery().
2017-06-18 12:51:15.844 ERROR 10388 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
A: you need to use @Modifying annotation above of @Query to exicute update query using JPA.
A: In my case I add two annotations.
@Transactional
@Modifying
annotations above of @Query to execute update query using Jpa.
|
stackoverflow
|
{
"language": "en",
"length": 215,
"provenance": "stackexchange_0000F.jsonl.gz:889008",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617429"
}
|
a3d6354d543fdf84ca29131fba5c4d1288b1a674
|
Stackoverflow Stackexchange
Q: Vue Js - Loop via v-for X times (in a range) How can I repeat a loop via v-for X (e.g. 10) times?
<!-- want to repeat this (e.g.) 10 times -->
<ul>
<li v-for="item in shoppingItems">
{{ item.name }} - {{ item.price }}
</li>
</ul>
The documentation shows:
<ul>
<li v-for="item in 10">{{ item }}</li>
</ul>
<!-- or -->
<li v-for="n in 10">{{ n }} </li>
<!-- this doesn't work -->
<li v-for="item in 10">{{ item.price }}</li>
but from where does vue know the source of the objects?
If I render it like the doc says, I get the number of items and items, but without content.
A: I have solved it with Dov Benjamin's help like that:
<ul>
<li v-for="(n,index) in 2">{{ n }}, {{ index }}</li>
</ul>
Note that in this case, n is 1-indexed, and index is 0-indexed.
And another method, for both V1.x and 2.x of vue.js
Vue 1:
<p v-for="item in items | limitBy 10">{{ item }}</p>
Vue2:
// Via slice method in computed prop
<p v-for="item in filteredItems">{{ item }}</p>
computed: {
filteredItems: function () {
return this.items.slice(0, 10)
}
}
|
Q: Vue Js - Loop via v-for X times (in a range) How can I repeat a loop via v-for X (e.g. 10) times?
<!-- want to repeat this (e.g.) 10 times -->
<ul>
<li v-for="item in shoppingItems">
{{ item.name }} - {{ item.price }}
</li>
</ul>
The documentation shows:
<ul>
<li v-for="item in 10">{{ item }}</li>
</ul>
<!-- or -->
<li v-for="n in 10">{{ n }} </li>
<!-- this doesn't work -->
<li v-for="item in 10">{{ item.price }}</li>
but from where does vue know the source of the objects?
If I render it like the doc says, I get the number of items and items, but without content.
A: I have solved it with Dov Benjamin's help like that:
<ul>
<li v-for="(n,index) in 2">{{ n }}, {{ index }}</li>
</ul>
Note that in this case, n is 1-indexed, and index is 0-indexed.
And another method, for both V1.x and 2.x of vue.js
Vue 1:
<p v-for="item in items | limitBy 10">{{ item }}</p>
Vue2:
// Via slice method in computed prop
<p v-for="item in filteredItems">{{ item }}</p>
computed: {
filteredItems: function () {
return this.items.slice(0, 10)
}
}
A: The same goes for v-for in range:
<li v-for="n in 20 " :key="n">{{n}}</li>
A: There are two ways you can solve,
First One is,
<div v-for="(item, index) in items.slice(0,10)" :key="index">
Second one is,
<li v-for="item in 20 " :key="item">{{item}}</li>
Hope you get your answer, thank you.
A: If you want to loop x number of times you can simply use the following:
<div v-for="(item, index) in 10" :key="index">{{ item }}</div>
A: I had to add parseInt() to tell v-for it was looking at a number.
<li v-for="n in parseInt(count)" :key="n">{{n}}</li>
A: You can use an index in a range and then access the array via its index:
<ul>
<li v-for="index in 10" :key="index">
{{ shoppingItems[index].name }} - {{ shoppingItems[index].price }}
</li>
</ul>
Note that this is 1-indexed: in the first iteration, index is 1, and in the second iteration, index is 2, and so forth.
You can also check the Official Documentation for more information.
A: You can use the native JS slice method:
<div v-for="item in shoppingItems.slice(0,10)">
The slice() method returns the selected elements in an array, as a new array object.
Based on tip in the migration guide: https://v2.vuejs.org/v2/guide/migration.html#Replacing-the-limitBy-Filter
A: SOLUTION 1:
<p v-for="i in 5" :key="i">{{ i }}</p>
Remember, result will be from 1-5.
SOLUTION 2:
If you want to show limited number of elements in array. You should use slice() method of JavaScript.
<p v-for="i in usersList.slice(0,5)" :key="i">{{ i }}</p>
A: In 2.2.0+, when using v-for with a component, a key is now required.
<div v-for="item in items" :key="item.id">
Source
A: try a v-if in the v-for, so for example if you want to only show less than 3 (o r any arbitrary amount) in items, then you can do something like this.
<span v-for="(item, itemIndex) in items" :key="itemIndex">
<div v-if="itemIndex < 3">
<p>
{{ item }}
</p>
</div>
</span>
A: First Version
// I expect your data like this
shoppingItems: [
{
name: "Clothes A",
price: 1000
},
{
name: "Clothes B",
price: 5000
},
{
name: "Clothes C",
price: 20000
}
]
<ul>
// The item in here means each object in shoppingItems
<li v-for="item in shoppingItems">
{{ item.name }} - {{ item.price }}
</li>
</ul>
Example code above is for loop each item in shoppingItems
Second Version
<ul>
// The index will start form 0 until 10 - 1
<li v-for="index in 10">
{{ shoppingitems[index].name }} - {{ shoppingitems[index].price }}
</li>
</ul>
A: <ul v-for="(item, index) in items.slice(0,10)" :key="item.index">
<li>
{{item.name}}-{{item.price}}
</li>
</ul>
A: It works for me..
<li v-for="(index,key) in data.slice(0,5)" :key="key">{{ index.title }}</li>
|
stackoverflow
|
{
"language": "en",
"length": 612,
"provenance": "stackexchange_0000F.jsonl.gz:889022",
"question_score": "250",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617484"
}
|
d412cabce8d0ceac8e7ce0ffadc8c18a11dc2b06
|
Stackoverflow Stackexchange
Q: How to center placeholder text in UISearchBar iOS 11 With iOS 11, searchBars are defaulting to a left aligned text. While this looks good with the rest of the native changes to iOS, it doesn't really fit my design, and I would like it to be center, as it was before.
I can't find any such alignment attributes on UISearchBar. Am I missing something, or is it simply not possible? Do I have to create my own custom search bar e.g derived from a UITextField to achieve this?
A: I had exactly the same problem - I'm struggling to understand why the default alignment would be changed without allowing us to easily set this back to centered.
The below works for me (Swift):
let placeholderWidth = 200 // Replace with whatever value works for your placeholder text
var offset = UIOffset()
override func viewDidLoad() {
offset = UIOffset(horizontal: (searchBar.frame.width - placeholderWidth) / 2, vertical: 0)
searchBar.setPositionAdjustment(offset, for: .search)
}
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
let noOffset = UIOffset(horizontal: 0, vertical: 0)
searchBar.setPositionAdjustment(noOffset, for: .search)
return true
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.setPositionAdjustment(offset, for: .search)
return true
}
|
Q: How to center placeholder text in UISearchBar iOS 11 With iOS 11, searchBars are defaulting to a left aligned text. While this looks good with the rest of the native changes to iOS, it doesn't really fit my design, and I would like it to be center, as it was before.
I can't find any such alignment attributes on UISearchBar. Am I missing something, or is it simply not possible? Do I have to create my own custom search bar e.g derived from a UITextField to achieve this?
A: I had exactly the same problem - I'm struggling to understand why the default alignment would be changed without allowing us to easily set this back to centered.
The below works for me (Swift):
let placeholderWidth = 200 // Replace with whatever value works for your placeholder text
var offset = UIOffset()
override func viewDidLoad() {
offset = UIOffset(horizontal: (searchBar.frame.width - placeholderWidth) / 2, vertical: 0)
searchBar.setPositionAdjustment(offset, for: .search)
}
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
let noOffset = UIOffset(horizontal: 0, vertical: 0)
searchBar.setPositionAdjustment(noOffset, for: .search)
return true
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.setPositionAdjustment(offset, for: .search)
return true
}
A: This is the only one that worked for me, Swift 4.2:
extension UISearchBar {
func setCenteredPlaceHolder(){
let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
//get the sizes
let searchBarWidth = self.frame.width
let placeholderIconWidth = textFieldInsideSearchBar?.leftView?.frame.width
let placeHolderWidth = textFieldInsideSearchBar?.attributedPlaceholder?.size().width
let offsetIconToPlaceholder: CGFloat = 8
let placeHolderWithIcon = placeholderIconWidth! + offsetIconToPlaceholder
let offset = UIOffset(horizontal: ((searchBarWidth / 2) - (placeHolderWidth! / 2) - placeHolderWithIcon), vertical: 0)
self.setPositionAdjustment(offset, for: .search)
}
}
Usage:
searchBar.setCenteredPlaceHolder()
Result:
A: This is a bit of a workaround.
First of all you need to get the text field of the search bar and center the text alignment:
let textFieldOfSearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField
textFieldOfSearchBar?.textAlignment = .center
After that, you need to change the placeholder's alignment. For some reason it doesn't change with the text field's alignment. You should do that by adding a padding to the left view of the textfield only when the search controller is active, so use it's delegate methods:
func presentSearchController(_ searchController: UISearchController) {
//Is active
let width: CGFloat = 100.0 //Calcualte a suitable width based on search bar width, screen size, etc..
let textfieldOfSearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField
let paddingView = UIView(x: 0, y: 0, w: width, h: searchController.searchBar.frame.size.height)
textfieldOfSearchBar?.leftView = paddingView
textfieldOfSearchBar?.leftViewMode = .unlessEditing
}
func willDismissSearchController(_ searchController: UISearchController) {
let textfieldOfSearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField
textfieldOfSearchBar?.leftView = nil
}
Good luck
A: There's no official way to do that. Try using UISearchBarDelegate methods and your own UILabel.
extension YourViewController: UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
placeholderLabel.isHidden = true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
placeholderLabel.isHidden = false
}
}
Don't forget to hide the standard left-aligned icon (use blank image):
searchBar.setImage(UIImage.imageWithColor(.clear), for: .search, state: .normal)
A: let placeHolderOffSet = UIOffset(horizontal: 100, vertical: 0)
setPositionAdjustment(placeHolderOffSet, for: .search)
if you want a different position while the bar is active, you'll have to reset this in the corresponding delegate method
A: For swift 4.0+
Well as your question doesn't really specify only placeholder I'll give an answer to both placeholder and the text. In my project, I needed both texts to be centered at all times, not just when I was not editing the textfield. You can return it to left align with some of the answers in this post by using the delegate as they stated.
Also im not using SearchController, but a SearchBar outlet, either way it can be easily fixed for your project if you use a controller. (just replace for searchController.searchBar instead of just searchBar).
So just have to call the next function where you need it.
func searchBarCenterInit(){
if let searchBarTextField = searchBar.value(forKey: "searchField") as? UITextField {
//Center search text
searchBarTextField.textAlignment = .center
//Center placeholder
let width = searchBar.frame.width / 2 - (searchBarTextField.attributedPlaceholder?.size().width)!
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: searchBar.frame.height))
searchBarTextField.leftView = paddingView
searchBarTextField.leftViewMode = .unlessEditing
}
}
A: I did some modification in @Danny182 answer. Here is the updated version and it will work on all OS versions.
extension UISearchBar {
func setPlaceHolder(text: String?) {
self.layoutIfNeeded()
self.placeholder = text
var textFieldInsideSearchBar:UITextField?
if #available(iOS 13.0, *) {
textFieldInsideSearchBar = self.searchTextField
} else {
for view : UIView in (self.subviews[0]).subviews {
if let textField = view as? UITextField {
textFieldInsideSearchBar = textField
}
}
}
//get the sizes
let searchBarWidth = self.frame.width
let placeholderIconWidth = textFieldInsideSearchBar?.leftView?.frame.width
let placeHolderWidth = textFieldInsideSearchBar?.attributedPlaceholder?.size().width
let offsetIconToPlaceholder: CGFloat = 8
let placeHolderWithIcon = placeholderIconWidth! + offsetIconToPlaceholder
let offset = UIOffset(horizontal: ((searchBarWidth / 2) - (placeHolderWidth! / 2) - placeHolderWithIcon), vertical: 0)
self.setPositionAdjustment(offset, for: .search)
}
}
You just need to call:
searchBar.setPlaceHolder(text: "Search \(name)")
|
stackoverflow
|
{
"language": "en",
"length": 782,
"provenance": "stackexchange_0000F.jsonl.gz:889071",
"question_score": "14",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617653"
}
|
e5cfeacff6736c5ce21d9b9a6f91a63229ecf483
|
Stackoverflow Stackexchange
Q: Issue loading images with stb_image I want to load images using stb_image. I downloaded stb_image.h from https://github.com/nothings/stb. When I run the code:
string file="image.png";
int width,height,components;
unsigned char *imageData = stbi_load(file.c_str(),
&width, &height, &components, STBI_rgb_alpha);
i get the following errors:
Main.cpp:(.text+0xa14): undefined reference to `stbi_load'
Main.cpp:(.text+0xb74): undefined reference to `stbi_image_free'
A: You probably should add: #define STB_IMAGE_IMPLEMENTATION to your code before the include. This is suggested in one of the first lines of the header file.
|
Q: Issue loading images with stb_image I want to load images using stb_image. I downloaded stb_image.h from https://github.com/nothings/stb. When I run the code:
string file="image.png";
int width,height,components;
unsigned char *imageData = stbi_load(file.c_str(),
&width, &height, &components, STBI_rgb_alpha);
i get the following errors:
Main.cpp:(.text+0xa14): undefined reference to `stbi_load'
Main.cpp:(.text+0xb74): undefined reference to `stbi_image_free'
A: You probably should add: #define STB_IMAGE_IMPLEMENTATION to your code before the include. This is suggested in one of the first lines of the header file.
|
stackoverflow
|
{
"language": "en",
"length": 77,
"provenance": "stackexchange_0000F.jsonl.gz:889076",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617665"
}
|
c9433be8f13b5a8bb2775bd40a0aa63feff5d79d
|
Stackoverflow Stackexchange
Q: How to handle emojis correctly in OpenNLP? For example, for this sentence,
Hoseok yelled out Puma at the end
The tokenized emojis becomes "????". Is this an issue for openNLP or something else?
|
Q: How to handle emojis correctly in OpenNLP? For example, for this sentence,
Hoseok yelled out Puma at the end
The tokenized emojis becomes "????". Is this an issue for openNLP or something else?
|
stackoverflow
|
{
"language": "en",
"length": 34,
"provenance": "stackexchange_0000F.jsonl.gz:889103",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617776"
}
|
ee9459d14e99bd952a5e1d87642b4d599ebf6eb7
|
Stackoverflow Stackexchange
Q: Google cloud compute engine high latency I just started using google cloud, and I've been having issues with my instance. The connection is really unstable and has really high ping. Used speedtest to test it, and has over 150 ms. Is this normal? It shouldnt be. I'd appreciate anyones help.
|
Q: Google cloud compute engine high latency I just started using google cloud, and I've been having issues with my instance. The connection is really unstable and has really high ping. Used speedtest to test it, and has over 150 ms. Is this normal? It shouldnt be. I'd appreciate anyones help.
|
stackoverflow
|
{
"language": "en",
"length": 51,
"provenance": "stackexchange_0000F.jsonl.gz:889113",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617797"
}
|
210d268c1e94996f56a191c86d4675a29b9d2f06
|
Stackoverflow Stackexchange
Q: How to access store in second component in react-redux I have a single component App.js where I trying to save state using redux. In index.js where I set store for only <App /> component.
index.js
let store = createStore(scoreReducer);
ReactDOM.render(
<Provider store={store}><App /></Provider>,
document.getElementById("root")
);
registerServiceWorker();
I have this method in App.js to map state to props which is available inside App.js.
App.js
function mapStateToProps(state) {
return { score: state.score, status: state.status };
}
Everything is well so far, now I am not sure how to access { this.props.score} in another component ?
What changes I need to do in index.js and second component if I want to access {this.props.score} in another component ?
A: Provider component sets the context for all its children, providing the store in it. when you use the High Order Component(HOC) connect you can wrap any component and access the store through the provided mapStateToProps and mapStateToProps no matter how nested they are. You can also access the store using context context.store but this is not recommended. Using map functions and connect, similar to what you have with your App component, is the best approach.
|
Q: How to access store in second component in react-redux I have a single component App.js where I trying to save state using redux. In index.js where I set store for only <App /> component.
index.js
let store = createStore(scoreReducer);
ReactDOM.render(
<Provider store={store}><App /></Provider>,
document.getElementById("root")
);
registerServiceWorker();
I have this method in App.js to map state to props which is available inside App.js.
App.js
function mapStateToProps(state) {
return { score: state.score, status: state.status };
}
Everything is well so far, now I am not sure how to access { this.props.score} in another component ?
What changes I need to do in index.js and second component if I want to access {this.props.score} in another component ?
A: Provider component sets the context for all its children, providing the store in it. when you use the High Order Component(HOC) connect you can wrap any component and access the store through the provided mapStateToProps and mapStateToProps no matter how nested they are. You can also access the store using context context.store but this is not recommended. Using map functions and connect, similar to what you have with your App component, is the best approach.
A: When you are using Provider any component that is children of the Provider Higher Order Component can access the store properties though the use of connect function.
So you can add the following in any component that is a child of Provider and access the score prop
function mapStateToProps(state) {
return { score: state.score, status: state.status };
}
export default connect(mapStateToProps)(MyComponent)
However if this other component is a direct child of App component then you can also pass the score prop as a prop to this component from App like
<MyComponent score={this.props.score}/>
|
stackoverflow
|
{
"language": "en",
"length": 284,
"provenance": "stackexchange_0000F.jsonl.gz:889118",
"question_score": "13",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617808"
}
|
0e193d214b7325920fa3eb7d67cee65ebddadf30
|
Stackoverflow Stackexchange
Q: Passing headers with axios POST request I have written an Axios POST request as recommended from the npm package documentation like:
var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data)
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
And it works, but now I have modified my backend API to accept headers.
Content-Type: 'application/json'
Authorization: 'JWT fefege...'
Now, this request works fine on Postman, but when writing an axios call, I follow this link and can't quite get it to work.
I am constantly getting 400 BAD Request error.
Here is my modified request:
axios.post(Helper.getUserAPI(), {
headers: {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
},
data
})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
A:
const data = {
email: "[email protected]",
username: "me"
};
const options = {
headers: {
'Content-Type': 'application/json',
}
};
axios.post('http://path', data, options)
.then((res) => {
console.log("RESPONSE ==== : ", res);
})
.catch((err) => {
console.log("ERROR: ====", err);
})
All status codes above 400 will be caught in the Axios catch block.
Also, headers are optional for the post method in Axios
|
Q: Passing headers with axios POST request I have written an Axios POST request as recommended from the npm package documentation like:
var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data)
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
And it works, but now I have modified my backend API to accept headers.
Content-Type: 'application/json'
Authorization: 'JWT fefege...'
Now, this request works fine on Postman, but when writing an axios call, I follow this link and can't quite get it to work.
I am constantly getting 400 BAD Request error.
Here is my modified request:
axios.post(Helper.getUserAPI(), {
headers: {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
},
data
})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
A:
const data = {
email: "[email protected]",
username: "me"
};
const options = {
headers: {
'Content-Type': 'application/json',
}
};
axios.post('http://path', data, options)
.then((res) => {
console.log("RESPONSE ==== : ", res);
})
.catch((err) => {
console.log("ERROR: ====", err);
})
All status codes above 400 will be caught in the Axios catch block.
Also, headers are optional for the post method in Axios
A: Here is a full example of an axios.post request with custom headers
var postData = {
email: "[email protected]",
password: "password"
};
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
};
axios.post('http://<host>:<port>/<path>', postData, axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
A: You can also use interceptors to pass the headers
It can save you a lot of code
axios.interceptors.request.use(config => {
if (config.method === 'POST' || config.method === 'PATCH' || config.method === 'PUT')
config.headers['Content-Type'] = 'application/json;charset=utf-8';
const accessToken = AuthService.getAccessToken();
if (accessToken) config.headers.Authorization = 'Bearer ' + accessToken;
return config;
});
A: When using Axios, in order to pass custom headers, supply an object containing the headers as the last argument
Modify your Axios request like:
const headers = {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
}
axios.post(Helper.getUserAPI(), data, {
headers: headers
})
.then((response) => {
dispatch({
type: FOUND_USER,
data: response.data[0]
})
})
.catch((error) => {
dispatch({
type: ERROR_FINDING_USER
})
})
A: Shubham's answer didn't work for me.
When you are using the Axios library and to pass custom headers, you need to construct headers as an object with the key name 'headers'. The 'headers' key should contain an object, here it is Content-Type and Authorization.
The below example is working fine.
var headers = {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
}
axios.post(Helper.getUserAPI(), data, {"headers" : headers})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
A: We can pass headers as arguments,
onClickHandler = () => {
const data = new FormData();
for (var x = 0; x < this.state.selectedFile.length; x++) {
data.append("file", this.state.selectedFile[x]);
}
const options = {
headers: {
"Content-Type": "application/json",
},
};
axios
.post("http://localhost:8000/upload", data, options, {
onUploadProgress: (ProgressEvent) => {
this.setState({
loaded: (ProgressEvent.loaded / ProgressEvent.total) * 100,
});
},
})
.then((res) => {
// then print response status
console.log("upload success");
})
.catch((err) => {
// then print response status
console.log("upload fail with error: ", err);
});
};
A: To set headers in an Axios POST request, pass the third object to the axios.post() call.
const token = '..your token..'
axios.post(url, {
//...data
}, {
headers: {
'Authorization': `Basic ${token}`
}
})
To set headers in an Axios GET request, pass a second object to the axios.get() call.
const token = '..your token..'
axios.get(url, {
headers: {
'Authorization': `Basic ${token}`
}
})
A: axios.post can accept 3 arguments that the last argument can accept a config object that you can set header.
Sample code with your question:
var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data, {
headers: {Authorization: token && `Bearer ${ token }`}
})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
A: If you are using some property from vuejs prototype that can't be read on creation you can also define headers and write i.e.
storePropertyMaxSpeed(){
axios
.post(
"api/property",
{
property_name: "max_speed",
property_amount: this.newPropertyMaxSpeed,
},
{
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + this.$gate.token(),
},
}
)
.then(() => {
//this below peace of code isn't important
Event.$emit("dbPropertyChanged");
$("#addPropertyMaxSpeedModal").modal("hide");
Swal.fire({
position: "center",
type: "success",
title: "Nova brzina unešena u bazu",
showConfirmButton: false,
timer: 1500,
});
})
.catch(() => {
Swal.fire("Neuspješno!", "Nešto je pošlo do đavola", "warning");
});
};
A: Interceptors
I had the same issue and the reason was that I hadn't returned the response in the interceptor. Javascript thought, rightfully so, that I wanted to return undefined for the promise:
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
|
stackoverflow
|
{
"language": "en",
"length": 795,
"provenance": "stackexchange_0000F.jsonl.gz:889121",
"question_score": "300",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617825"
}
|
6b16cc9a5b24a5128a5afdf40b69cae3f6674acc
|
Stackoverflow Stackexchange
Q: Evaluating multiple fn:contains() conditions with JSTL I have variable x that i need to check and see does not contain variable y but does contain variable z.
How would one go about doing that with JSTL? Tried wrapping the statement within another one, but it doesn't seem to register. It only responds to the first evaluation.
<c:if test="${not fn:contains('x', 'y')}">
<c:if test="${fn:contains('x', 'z')}">
</c:if>
</c:if>
Would be great if it was possible to do something like:
<c:if test="${fn:contains('x', 'z', not 'y')}">
A: Please try this:
<c:if test="${not fn:contains(x, y) && fn:contains(x, z)}">
</c:if>
|
Q: Evaluating multiple fn:contains() conditions with JSTL I have variable x that i need to check and see does not contain variable y but does contain variable z.
How would one go about doing that with JSTL? Tried wrapping the statement within another one, but it doesn't seem to register. It only responds to the first evaluation.
<c:if test="${not fn:contains('x', 'y')}">
<c:if test="${fn:contains('x', 'z')}">
</c:if>
</c:if>
Would be great if it was possible to do something like:
<c:if test="${fn:contains('x', 'z', not 'y')}">
A: Please try this:
<c:if test="${not fn:contains(x, y) && fn:contains(x, z)}">
</c:if>
|
stackoverflow
|
{
"language": "en",
"length": 94,
"provenance": "stackexchange_0000F.jsonl.gz:889153",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617906"
}
|
5a77316a370372accad7373a63233ed0676f1fef
|
Stackoverflow Stackexchange
Q: What are the Flux equivalents of debounce, throttleFirst, and throttleLast debounce, throttleFirst, and throttleLast are most conspicuously absent from Project Reactor's Flux. Do they have any counterparts?
A: The sample operators are the once relating to the behavior you're searching for.
sampleTimeout could be used as debounce.
sampleFirst could be used as throttleFirst.
sample could be used as throttleLast.
|
Q: What are the Flux equivalents of debounce, throttleFirst, and throttleLast debounce, throttleFirst, and throttleLast are most conspicuously absent from Project Reactor's Flux. Do they have any counterparts?
A: The sample operators are the once relating to the behavior you're searching for.
sampleTimeout could be used as debounce.
sampleFirst could be used as throttleFirst.
sample could be used as throttleLast.
A: I've been struggling to understand how to use sampleTimeout to do a debounce so I though I would put it here in case someone else is looking for this:
The would be equivalent to a debounce of 200ms
myFlux.sampleTimeout(u -> Mono.empty().delaySubscription(Duration.ofMillis(200)))
|
stackoverflow
|
{
"language": "en",
"length": 102,
"provenance": "stackexchange_0000F.jsonl.gz:889155",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617913"
}
|
4b341ca39b2be3a0ed4c1433ce99fccbbaab1367
|
Stackoverflow Stackexchange
Q: Grab the value from a Dictionary in Swift 3 Here is some code:
class MapViewController: UIViewController {
var dico:Dictionary<String, Any>?
override func viewDidLoad() {
super.viewDidLoad()
let dest = "\(String(describing: self.dico?.index(forKey: "adresse"))) \(String(describing: self.dico?.index(forKey: "cp"))) \(String(describing: self.dico?.index(forKey: "ville")))"
print(dest)}}
That's 'dico' it's coming from a segue:
["cp": 1000, "id": 4, "loyer": , "ville": bruxelles, "nom": , "ref": garage2, "adresse": 50 rue de spa, "prenom": , "nouveau_loyer": ]
I want to get the value of each element of 'dico' as a string to reuse them after as a long string (it's an address for the Geocoder)
Anyone knows ?
With the previous code I am having this error:
Optional(Swift.Dictionary.Index(_value: Swift.DictionaryIndexRepresentation._native(Swift._NativeDictionaryIndex(offset: 13))))
A: Try this combination of string interpolation, optional chaining, conditional casting and the nil coalescing operator ??:
let dest = "\(dico?["adresse"] as? String ?? "") \(dico?["cp"] as? String ?? "") \(dico?["ville"] as? String ?? "")"
If the value for key "cp" is really an Int, then do this:
let dest = "\(dico?["adresse"] as? String ?? "") \(dico?["cp"] as? Int ?? 0) \(dico?["ville"] as? String ?? "")"
|
Q: Grab the value from a Dictionary in Swift 3 Here is some code:
class MapViewController: UIViewController {
var dico:Dictionary<String, Any>?
override func viewDidLoad() {
super.viewDidLoad()
let dest = "\(String(describing: self.dico?.index(forKey: "adresse"))) \(String(describing: self.dico?.index(forKey: "cp"))) \(String(describing: self.dico?.index(forKey: "ville")))"
print(dest)}}
That's 'dico' it's coming from a segue:
["cp": 1000, "id": 4, "loyer": , "ville": bruxelles, "nom": , "ref": garage2, "adresse": 50 rue de spa, "prenom": , "nouveau_loyer": ]
I want to get the value of each element of 'dico' as a string to reuse them after as a long string (it's an address for the Geocoder)
Anyone knows ?
With the previous code I am having this error:
Optional(Swift.Dictionary.Index(_value: Swift.DictionaryIndexRepresentation._native(Swift._NativeDictionaryIndex(offset: 13))))
A: Try this combination of string interpolation, optional chaining, conditional casting and the nil coalescing operator ??:
let dest = "\(dico?["adresse"] as? String ?? "") \(dico?["cp"] as? String ?? "") \(dico?["ville"] as? String ?? "")"
If the value for key "cp" is really an Int, then do this:
let dest = "\(dico?["adresse"] as? String ?? "") \(dico?["cp"] as? Int ?? 0) \(dico?["ville"] as? String ?? "")"
|
stackoverflow
|
{
"language": "en",
"length": 176,
"provenance": "stackexchange_0000F.jsonl.gz:889157",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617916"
}
|
065ae7efb8873bd546dab8c469ac46c27718dd88
|
Stackoverflow Stackexchange
Q: Trying to clear input placeholder on focus/touch This is my code:
<TextInput value={this.state.task} underlineColorAndroid={'transparent'} placeholder = {'+ הוסף משימה חדשה'}
style={styles.input}
onChangeText={(text) => {
this.setState({task: text});
} }
onEndEditing={()=> this.addTask()}
/>
Not sure how I can do this. Hope someone can help. Thanks!
A: You can use the onFocus method like this
<TextInput
value={this.state.task}
onFocus={() => this.onFocus()}
/>
onFocus() {
this.setState({
task: ''
});
}
|
Q: Trying to clear input placeholder on focus/touch This is my code:
<TextInput value={this.state.task} underlineColorAndroid={'transparent'} placeholder = {'+ הוסף משימה חדשה'}
style={styles.input}
onChangeText={(text) => {
this.setState({task: text});
} }
onEndEditing={()=> this.addTask()}
/>
Not sure how I can do this. Hope someone can help. Thanks!
A: You can use the onFocus method like this
<TextInput
value={this.state.task}
onFocus={() => this.onFocus()}
/>
onFocus() {
this.setState({
task: ''
});
}
|
stackoverflow
|
{
"language": "en",
"length": 66,
"provenance": "stackexchange_0000F.jsonl.gz:889162",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617928"
}
|
a76b4537a5793e9001ab8a900b082d33dfa8ac67
|
Stackoverflow Stackexchange
Q: How to stop event propagation in react? I have tried doing e.stopPropagation(); and e.nativeEvent.stopImmediatePropagation();
This is what my code looks like for the child component:
class S extends React.Component {
handleClick(e) {
e.preventDefault();
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
}
render() {
return (
<div class='box' onClick={this.handleClick.bind(this)}>
</div>
)
}
}
But in the parent component, the event for click still gets triggered
Any ideas??
Thanks
|
Q: How to stop event propagation in react? I have tried doing e.stopPropagation(); and e.nativeEvent.stopImmediatePropagation();
This is what my code looks like for the child component:
class S extends React.Component {
handleClick(e) {
e.preventDefault();
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
}
render() {
return (
<div class='box' onClick={this.handleClick.bind(this)}>
</div>
)
}
}
But in the parent component, the event for click still gets triggered
Any ideas??
Thanks
|
stackoverflow
|
{
"language": "en",
"length": 63,
"provenance": "stackexchange_0000F.jsonl.gz:889169",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44617964"
}
|
5f9af383b5c684786a9703777d696f2b8ac0018c
|
Stackoverflow Stackexchange
Q: How add styled-components as an external for the rollup build? I'm trying to add styled-components in my rollup.config.js as the reproduction below, but it throw an error. I had the similar issue for react-router-dom and solved it by renaming react-router-dom into react-router-dom/Link in externals of rollup.config.js.
How to do with styled-components ?
Reproduction:
// rollup.config.js
export default {
...
external: ['react', 'react-router-dom/Link', 'styled-components'],
...
globals: { react: 'React', 'react-router-dom/Link': 'Link', 'styled-
components: 'styled' },
};
Actual Behavior: Throw error when build with rollup
(babel plugin) An unexpected situation arose. Please raise an issue at
https://github.com/rollup/rollup-plugin-babel/issues. Thanks!
node_modules/styled-components/dist/styled-components.es.js
Version styled-components: 2.0.1
Version rollup-plugin-babel: 2.7.1
A: Finally I resolve my need with this in my rollup.config.js
export default {
...
external: ['styled-components'],
...
globals: { 'styled-components': 'styled' },
};
It's depend on how we import the package, in my case I import it in my files as:
import styled from 'styled-components';
|
Q: How add styled-components as an external for the rollup build? I'm trying to add styled-components in my rollup.config.js as the reproduction below, but it throw an error. I had the similar issue for react-router-dom and solved it by renaming react-router-dom into react-router-dom/Link in externals of rollup.config.js.
How to do with styled-components ?
Reproduction:
// rollup.config.js
export default {
...
external: ['react', 'react-router-dom/Link', 'styled-components'],
...
globals: { react: 'React', 'react-router-dom/Link': 'Link', 'styled-
components: 'styled' },
};
Actual Behavior: Throw error when build with rollup
(babel plugin) An unexpected situation arose. Please raise an issue at
https://github.com/rollup/rollup-plugin-babel/issues. Thanks!
node_modules/styled-components/dist/styled-components.es.js
Version styled-components: 2.0.1
Version rollup-plugin-babel: 2.7.1
A: Finally I resolve my need with this in my rollup.config.js
export default {
...
external: ['styled-components'],
...
globals: { 'styled-components': 'styled' },
};
It's depend on how we import the package, in my case I import it in my files as:
import styled from 'styled-components';
|
stackoverflow
|
{
"language": "en",
"length": 150,
"provenance": "stackexchange_0000F.jsonl.gz:889186",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618029"
}
|
7650d2beb71a53100d713858d30202b54a7ee267
|
Stackoverflow Stackexchange
Q: WebStorm error: expression statement is not assignment or call I'm using WebStorm and I'm getting an error that I can't understand. Node.js + MongoDB.
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(' mongodb://localhost:27017/TodoApp');
var Todo = mongoose.model('Todo', {
text: {
type: String
},
completed: {
type: Boolean
},
completedAt: {
type: Number
}
});
var newTodo = new Todo({
text: 'Cook dinner'
});
The problem is in this block:
newTodo.save().then((doc) => {
console.log('Saved todo', doc);
}, (e) => {
console.log('Unable to save todo')
})
P.S.: The code works fine.
A: You need to change JavaScript Language Version to ES6. Changing this setting should fix the issue:
In some scenarios, you might need to restart your IDE for the changes to reflect properly.
|
Q: WebStorm error: expression statement is not assignment or call I'm using WebStorm and I'm getting an error that I can't understand. Node.js + MongoDB.
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(' mongodb://localhost:27017/TodoApp');
var Todo = mongoose.model('Todo', {
text: {
type: String
},
completed: {
type: Boolean
},
completedAt: {
type: Number
}
});
var newTodo = new Todo({
text: 'Cook dinner'
});
The problem is in this block:
newTodo.save().then((doc) => {
console.log('Saved todo', doc);
}, (e) => {
console.log('Unable to save todo')
})
P.S.: The code works fine.
A: You need to change JavaScript Language Version to ES6. Changing this setting should fix the issue:
In some scenarios, you might need to restart your IDE for the changes to reflect properly.
A: The problem is that WebStorm will show a warning if that statement isn't doing any of the following within a function:
*
*Calling another function
*Making any sort of assignment
*Returning a value
*(There may be more, but those are the ones I know of)
In other words, WebStorm views that function as unnecessary and tries to help you catch unused code.
For example this will show the warning:
const arr = [1, 2];
const willShowWarning = arr.map(num => {
num + 1;
});
Adding a return will take the warning away:
const arr = [1, 2];
const willNotShowWarning = arr.map(num => {
return num + 1;
});
The answer is not to change WebStorm settings.
|
stackoverflow
|
{
"language": "en",
"length": 240,
"provenance": "stackexchange_0000F.jsonl.gz:889205",
"question_score": "34",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618100"
}
|
b462dc33975c2c76b9749d7fff8169b8535d67ac
|
Stackoverflow Stackexchange
Q: Currency conversion with easymoney and pandas I am trying to convert values with different currency to "USD" currency. I tried easymoney and CurrencyConvertor packages but those do not seem to work with dataframe python.
It seems working if I do conversion row by row using iloc but that is taking an awful lot of time.
from easymoney.money import EasyPeasy
ep = EasyPeasy()
ep.currency_converter(df_train['goal'], from_currency=df_train['currency'], to_currency="USD")
Error:
TypeError: invalid type comparison
A: You need apply with axis=1 for processing by rows:
from easymoney.money import EasyPeasy
ep = EasyPeasy()
df_train['converted'] = df_train.apply(lambda x: ep.currency_converter(x['goal'], from_currency=x['currency'], to_currency="USD"), axis=1)
|
Q: Currency conversion with easymoney and pandas I am trying to convert values with different currency to "USD" currency. I tried easymoney and CurrencyConvertor packages but those do not seem to work with dataframe python.
It seems working if I do conversion row by row using iloc but that is taking an awful lot of time.
from easymoney.money import EasyPeasy
ep = EasyPeasy()
ep.currency_converter(df_train['goal'], from_currency=df_train['currency'], to_currency="USD")
Error:
TypeError: invalid type comparison
A: You need apply with axis=1 for processing by rows:
from easymoney.money import EasyPeasy
ep = EasyPeasy()
df_train['converted'] = df_train.apply(lambda x: ep.currency_converter(x['goal'], from_currency=x['currency'], to_currency="USD"), axis=1)
|
stackoverflow
|
{
"language": "en",
"length": 96,
"provenance": "stackexchange_0000F.jsonl.gz:889215",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618142"
}
|
3e02b6c44e9b9806b635d61ea51a41fc212edaea
|
Stackoverflow Stackexchange
Q: Parsing U+00BE (¾) to number in python I have a string which represents a ingredient with an amount, unit, description and so on.
¾ cup fresh pineapple, cut in small chunks or canned pineapple tidbits, drained
I'd like to parse this string into an object which holds all the different characteristics of this ingredient.
The problem I'm facing is that I don't know how to convert the number (¾) from the Unicode representation to a normal number.
How can I parse this sentence to get something like 3/4 or 0.75 back as result?
A: import unicodedata
unicodedata.numeric(u'¾')
will give you 0.75 (or without u if Python 3+)
|
Q: Parsing U+00BE (¾) to number in python I have a string which represents a ingredient with an amount, unit, description and so on.
¾ cup fresh pineapple, cut in small chunks or canned pineapple tidbits, drained
I'd like to parse this string into an object which holds all the different characteristics of this ingredient.
The problem I'm facing is that I don't know how to convert the number (¾) from the Unicode representation to a normal number.
How can I parse this sentence to get something like 3/4 or 0.75 back as result?
A: import unicodedata
unicodedata.numeric(u'¾')
will give you 0.75 (or without u if Python 3+)
|
stackoverflow
|
{
"language": "en",
"length": 108,
"provenance": "stackexchange_0000F.jsonl.gz:889234",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618217"
}
|
65113483960ac15982ba2e620fb91af5ca8d4109
|
Stackoverflow Stackexchange
Q: ERROR: function addgeometrycolumn does not exist: When trying to import file into POSTGIS database by QGIS DB Manager I am trying to import a shapefile via db manager in QGIS to my POSTGIS database but I get an error, that I do not know to resolve:
ERROR: function addgeometrycolumn(unknown, unknown, unknown, integer, unknown, integer) does not exist
LINE 1: SELECT AddGeometryColumn('demoschema','Bomen',NULL,31370,'MU...
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
So what do I need to do?
A: Without postgis extension in postgresSQL, if you try to add any spatial layers to postgresSQL , you get above error.
In pgadmin right click on extensions and check whether postgis extension is saved or not.
if in extensions postgis option is absent ,you can follow these steps to
install postgis in postgres https://www.youtube.com/watch?v=afK8GWpb8RU
|
Q: ERROR: function addgeometrycolumn does not exist: When trying to import file into POSTGIS database by QGIS DB Manager I am trying to import a shapefile via db manager in QGIS to my POSTGIS database but I get an error, that I do not know to resolve:
ERROR: function addgeometrycolumn(unknown, unknown, unknown, integer, unknown, integer) does not exist
LINE 1: SELECT AddGeometryColumn('demoschema','Bomen',NULL,31370,'MU...
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
So what do I need to do?
A: Without postgis extension in postgresSQL, if you try to add any spatial layers to postgresSQL , you get above error.
In pgadmin right click on extensions and check whether postgis extension is saved or not.
if in extensions postgis option is absent ,you can follow these steps to
install postgis in postgres https://www.youtube.com/watch?v=afK8GWpb8RU
A: The 3rd parameter is the column name, which is Null in your case. Make sure you specify it in the interface
|
stackoverflow
|
{
"language": "en",
"length": 163,
"provenance": "stackexchange_0000F.jsonl.gz:889290",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618374"
}
|
74f065ffd443d9fd3691807e7b4ad371efedbc59
|
Stackoverflow Stackexchange
Q: Easiest way to plot data from JSON with matplotlib? So I have some data in json format, here's a snippet:
"sell": [
{
"Rate": 0.001425,
"Quantity": 537.27713514
},
{
"Rate": 0.00142853,
"Quantity": 6.59174681
}
]
What's the easiest way to access Rate and Quantity so that I can plot it in Matplotlib? Do I have to flatten/normalize it, or create a for loop to generate an array, or can I use pandas or some other library to convert it into matplotlib friendly data automatically?
I know matplotlib can handle inputs in a few ways
plt.plot([1,2,3,4], [1,4,9,16])
plt.plot([1,1],[2,4],[3,9],[4,16])
A: The simpliest is DataFrame constructor with DataFrame.plot:
import pandas as pd
d = {"sell": [
{
"Rate": 0.001425,
"Quantity": 537.27713514
},
{
"Rate": 0.00142853,
"Quantity": 6.59174681
}
]}
df = pd.DataFrame(d['sell'])
print (df)
Quantity Rate
0 537.277135 0.001425
1 6.591747 0.001429
df.plot(x='Quantity', y='Rate')
EDIT:
Also is possible use read_json for DataFrame.
|
Q: Easiest way to plot data from JSON with matplotlib? So I have some data in json format, here's a snippet:
"sell": [
{
"Rate": 0.001425,
"Quantity": 537.27713514
},
{
"Rate": 0.00142853,
"Quantity": 6.59174681
}
]
What's the easiest way to access Rate and Quantity so that I can plot it in Matplotlib? Do I have to flatten/normalize it, or create a for loop to generate an array, or can I use pandas or some other library to convert it into matplotlib friendly data automatically?
I know matplotlib can handle inputs in a few ways
plt.plot([1,2,3,4], [1,4,9,16])
plt.plot([1,1],[2,4],[3,9],[4,16])
A: The simpliest is DataFrame constructor with DataFrame.plot:
import pandas as pd
d = {"sell": [
{
"Rate": 0.001425,
"Quantity": 537.27713514
},
{
"Rate": 0.00142853,
"Quantity": 6.59174681
}
]}
df = pd.DataFrame(d['sell'])
print (df)
Quantity Rate
0 537.277135 0.001425
1 6.591747 0.001429
df.plot(x='Quantity', y='Rate')
EDIT:
Also is possible use read_json for DataFrame.
|
stackoverflow
|
{
"language": "en",
"length": 150,
"provenance": "stackexchange_0000F.jsonl.gz:889291",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618376"
}
|
28dfe5d21e63d80d9bab0cf1f9c9be6401e11007
|
Stackoverflow Stackexchange
Q: How to draw in two windows using OpenGL? I make game engine. The structure is as follow: There is Core class which object creates at start of program, modules(class Module) join to core and have workers(class Worker). Workers divided into two types: normal and graphical. I made it for game loop organization.
So, I create GLFWOpenGLModule, which, as the name suggests, use GLFW for creating of window and OpenGL for drawing in this window. But GLFW doesn't allow to create two windows and draw in each of them. I can make GLFWOpenGLModule singleton by adding this code:
static int objectsCount = 0;
objectsCount++;
if (objectsCount > 1)
throw SomeKindOfException("error message");
in constructor and not create two windows in module, but then I can't make two windows(for example for rendering multiple cameras, each camera in each window).
How should I do in this case? Maybe I should use another library instead of GLFW?
|
Q: How to draw in two windows using OpenGL? I make game engine. The structure is as follow: There is Core class which object creates at start of program, modules(class Module) join to core and have workers(class Worker). Workers divided into two types: normal and graphical. I made it for game loop organization.
So, I create GLFWOpenGLModule, which, as the name suggests, use GLFW for creating of window and OpenGL for drawing in this window. But GLFW doesn't allow to create two windows and draw in each of them. I can make GLFWOpenGLModule singleton by adding this code:
static int objectsCount = 0;
objectsCount++;
if (objectsCount > 1)
throw SomeKindOfException("error message");
in constructor and not create two windows in module, but then I can't make two windows(for example for rendering multiple cameras, each camera in each window).
How should I do in this case? Maybe I should use another library instead of GLFW?
|
stackoverflow
|
{
"language": "en",
"length": 153,
"provenance": "stackexchange_0000F.jsonl.gz:889295",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618387"
}
|
7dbfb05b2c25fe38e7388c5a9f3bcf3fb817a3b7
|
Stackoverflow Stackexchange
Q: how to abbreviate dimension following the PEP8 rules? I must add a function for creating 3D textures.
I am using snail case in the entire module.
My choices are:
def texture_3d(...):
pass
def texture_3D(...):
pass
def texture3D(...):
pass
What should be the name of the function?
I am not interested in opinions: which one looks better. I need a few references to other modules to see the best practice.
Please mention at least 1 module having similar functions.
A: PEP 8 states lowercase with underscore separation between words for function names. Now, because it seems opinionated if 3d/3D is an actual word, you'll get conflicts between the names texture_3d and texture3d (with d being lowercase).
Looking at a number of numpy functions, for example, lagval3d, laggrid3d, hermegrid3d the name texture3d looks like a good choice.
Searching for similar names in the matplotlib docs yields a mixed result between <name>3d and <name>_3d.
In short, both these names seem to be accepted, based on two major packages. Boils down to personal choice between the two.
|
Q: how to abbreviate dimension following the PEP8 rules? I must add a function for creating 3D textures.
I am using snail case in the entire module.
My choices are:
def texture_3d(...):
pass
def texture_3D(...):
pass
def texture3D(...):
pass
What should be the name of the function?
I am not interested in opinions: which one looks better. I need a few references to other modules to see the best practice.
Please mention at least 1 module having similar functions.
A: PEP 8 states lowercase with underscore separation between words for function names. Now, because it seems opinionated if 3d/3D is an actual word, you'll get conflicts between the names texture_3d and texture3d (with d being lowercase).
Looking at a number of numpy functions, for example, lagval3d, laggrid3d, hermegrid3d the name texture3d looks like a good choice.
Searching for similar names in the matplotlib docs yields a mixed result between <name>3d and <name>_3d.
In short, both these names seem to be accepted, based on two major packages. Boils down to personal choice between the two.
A: Rather than depending on mere human opinion, perhaps we could ask the horse? (As in 'getting it from the horse's mouth'.) In other words, use pylint.
I modified your code so that it would generate fewer messages.
''' some information here'''
def texture_3d(parameters):
''' a docstring'''
return parameters
def texture_3D(parameters):
''' a docstring'''
return parameters
def texture3D(parameters):
''' a docstring'''
return parameters
The results of pylint were:
************* Module temp
C: 7, 0: Invalid function name "texture_3D" (invalid-name)
C: 11, 0: Invalid function name "texture3D" (invalid-name)
------------------------------------------------------------------
Your code has been rated at 6.67/10 (previous run: 5.00/10, +1.67)
Which just leaves the option texture_3d.
A: From PEP-8:
Method Names and Instance Variables
Use the function naming rules:
lowercase with words separated by underscores as necessary to improve
readability.
This suggests to me that your first option is the most compliant of the three.
A: Short answer: texture_3d.
PEP-8 says about function names:
Function names should be lowercase, with words separated by
underscores as necessary to improve readability.
mixedCase is allowed only in contexts where that's already the
prevailing style (e.g. threading.py), to retain backwards
compatibility.
Since "texture" and "3d" are two separate words, it is good practice to put an underscore between them. Furthermore the function name should be lowercase, so 3D is not allowed.
|
stackoverflow
|
{
"language": "en",
"length": 390,
"provenance": "stackexchange_0000F.jsonl.gz:889298",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618391"
}
|
d4f66907097722685a7cf401a24a4b708c176a60
|
Stackoverflow Stackexchange
Q: Vuex | How to commit a global mutation in a module action? I have an action in a namespaced module and a global mutation (i.e. not in a module). I would like to be able to commit the global mutation inside the action.
// Global mutation
export default {
globalMutation (state, payload) {
...
}
}
// Action in a namespaced module
export default {
namespaced: true,
actions: {
namespacedAction ({ commit, dispatch, state }, payload) {
commit({ type: 'globalMutation' })
}
}
}
When the namespaced action is dispatched, Vuex displays:
[vuex] unknown local mutation type: globalMutation, global type: module/globalMutation
Is there an option I can pass to the commit function to call this global mutation?
A: Looks like I just found a way with the { root: true } parameter.
commit('globalMutation', payload, { root: true })
If module is namespaced, use global path instead:
commit('module/mutation', payload, { root: true })
|
Q: Vuex | How to commit a global mutation in a module action? I have an action in a namespaced module and a global mutation (i.e. not in a module). I would like to be able to commit the global mutation inside the action.
// Global mutation
export default {
globalMutation (state, payload) {
...
}
}
// Action in a namespaced module
export default {
namespaced: true,
actions: {
namespacedAction ({ commit, dispatch, state }, payload) {
commit({ type: 'globalMutation' })
}
}
}
When the namespaced action is dispatched, Vuex displays:
[vuex] unknown local mutation type: globalMutation, global type: module/globalMutation
Is there an option I can pass to the commit function to call this global mutation?
A: Looks like I just found a way with the { root: true } parameter.
commit('globalMutation', payload, { root: true })
If module is namespaced, use global path instead:
commit('module/mutation', payload, { root: true })
|
stackoverflow
|
{
"language": "en",
"length": 153,
"provenance": "stackexchange_0000F.jsonl.gz:889310",
"question_score": "52",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618440"
}
|
75c52558910e9889dfb6d8284a5bb2584cfff925
|
Stackoverflow Stackexchange
Q: Check if a string contains the list elements How to check if a string contains the elements in a list?
str1 = "45892190"
lis = [89,90]
A: str1 = "45892190"
lis = [89,90]
for i in lis:
if str(i) in str1:
print("The value " + str(i) + " is in the list")
OUTPUT:
The value 89 is in the list
The value 90 is in the list
If you want to check if all the values in lis are in str1, the code of cricket_007
all(str(l) in str1 for l in lis)
out: True
is what you are looking for
|
Q: Check if a string contains the list elements How to check if a string contains the elements in a list?
str1 = "45892190"
lis = [89,90]
A: str1 = "45892190"
lis = [89,90]
for i in lis:
if str(i) in str1:
print("The value " + str(i) + " is in the list")
OUTPUT:
The value 89 is in the list
The value 90 is in the list
If you want to check if all the values in lis are in str1, the code of cricket_007
all(str(l) in str1 for l in lis)
out: True
is what you are looking for
A: If no overlap is allowed, this problem becomes much harder than it looks at first.
As far as I can tell, no other answer is correct (see test cases at the end).
Recursion is needed because if a substring appears more than once, using one occurence instead of the other could prevent other substrings to be found.
This answer uses two functions. The first one finds every occurence of a substring in a string and returns an iterator of strings where the substring has been replaced by a character which shouldn't appear in any substring.
The second function recursively checks if there's any way to find all the numbers in the string:
def find_each_and_replace_by(string, substring, separator='x'):
"""
list(find_each_and_replace_by('8989', '89', 'x'))
# ['x89', '89x']
list(find_each_and_replace_by('9999', '99', 'x'))
# ['x99', '9x9', '99x']
list(find_each_and_replace_by('9999', '89', 'x'))
# []
"""
index = 0
while True:
index = string.find(substring, index)
if index == -1:
return
yield string[:index] + separator + string[index + len(substring):]
index += 1
def contains_all_without_overlap(string, numbers):
"""
contains_all_without_overlap("45892190", [89, 90])
# True
contains_all_without_overlap("45892190", [89, 90, 4521])
# False
"""
if len(numbers) == 0:
return True
substrings = [str(number) for number in numbers]
substring = substrings.pop()
return any(contains_all_without_overlap(shorter_string, substrings)
for shorter_string in find_each_and_replace_by(string, substring, 'x'))
Here are the test cases:
tests = [
("45892190", [89, 90], True),
("8990189290", [89, 90, 8990], True),
("123451234", [1234, 2345], True),
("123451234", [2345, 1234], True),
("123451234", [1234, 2346], False),
("123451234", [2346, 1234], False),
("45892190", [89, 90, 4521], False),
("890", [89, 90], False),
("8989", [89, 90], False),
("8989", [12, 34], False)
]
for string, numbers, should in tests:
result = contains_all_without_overlap(string, numbers)
if result == should:
print("Correct answer for %-12r and %-14r (%s)" % (string, numbers, result))
else:
print("ERROR : %r and %r should return %r, not %r" %
(string, numbers, should, result))
And the corresponding output:
Correct answer for '45892190' and [89, 90] (True)
Correct answer for '8990189290' and [89, 90, 8990] (True)
Correct answer for '123451234' and [1234, 2345] (True)
Correct answer for '123451234' and [2345, 1234] (True)
Correct answer for '123451234' and [1234, 2346] (False)
Correct answer for '123451234' and [2346, 1234] (False)
Correct answer for '45892190' and [89, 90, 4521] (False)
Correct answer for '890' and [89, 90] (False)
Correct answer for '8989' and [89, 90] (False)
Correct answer for '8989' and [12, 34] (False)
A: If you want non-overlapping matches I'd do it like this:
*
*create a copy of the initial string (as we'll modify it)
*go through each element of the list and if we find the element in our string, we replace it with x
*at the same time, if we find the number in our string, we increment a counter
*at the end, if the variable equals the length of the list, it means that all of its elements are there
str1 = "45890190"
lis1 = [89, 90]
copy, i = str1, 0
for el in lis1:
if str(el) in copy:
copy = copy.replace(str(el), 'x')
i = i + 1
if i == len(lis1):
print(True)
More, we don't really need a counter if we add an extra condition which will return False when an element isn't found in the string. That is, we get to the following, final solution:
def all_matches(_list, _string):
str_copy = _string
for el in _list:
if str(el) not in str_copy:
return False
str_copy = str_copy.replace(str(el), 'x')
return True
Which you can test by writing:
str1 = "4589190"
lis1 = [89, 90]
print(all_matches(lis1, str1))
> True
This might not be the best solution for what you're looking, but I guess it serves the purpose.
A: You can use all() function
In [1]: str1 = "45892190"
...: lis = [89,90]
...: all(str(l) in str1 for l in lis)
...:
Out[1]: True
A: def contains(s, elems):
for elem in elems:
index = s.find(elem)
if index == -1:
return False
s = s[:index] + s[index + len(elem) + 1:]
return True
Usage:
>>> str1 = "45892190"
>>> lis = [89,90]
>>> contains(str1, (str(x) for x in lis))
True
>>> contains("890", (str(x) for x in lis))
False
A: You can use the regular expression to search.
import re
str1 = "45892190"
lis = [89,90]
for i in lis:
x = re.search(str(i), str1)
print(x)
A: It is possible to implement this correctly using regular expressions. Generate all unique permutations of the input, for each permutation connect the terms with ".*" then connect all of the permutations with "|". For example, [89, 90, 8990] gets turned into 89.*8990.*90| 89.*90.*8990| 8990.*89.*90| 8990.*90.*89| 90.*89.*8990| 90.*8990.*89 , where I added a space after each "|" for clarity."
The following passes Eric Duminil's test suite.
import itertools
import re
def create_numbers_regex(numbers):
# Convert each into a string, and double-check that it's an integer
numbers = ["%d" % number for number in numbers]
# Convert to unique regular expression terms
regex_terms = set(".*".join(permutation)
for permutation in itertools.permutations(numbers))
# Create the regular expression. (Sorted so the order is invariant.)
regex = "|".join(sorted(regex_terms))
return regex
def contains_all_without_overlap(string, numbers):
regex = create_numbers_regex(numbers)
pat = re.compile(regex)
m = pat.search(string)
if m is None:
return False
return True
However, and this is a big however, the regular expression size, in the worst case, grows as the factorial of the number of numbers. Even with only 8 unique numbers, that's 40320 regex terms. It takes Python several seconds just to compile that regex.
The only time where this solution might be useful is if you have a handful of numbers and you wanted to search a lot of strings. In that case, you might also look into re2, which I believe could handle that regex without backtracking.
|
stackoverflow
|
{
"language": "en",
"length": 1025,
"provenance": "stackexchange_0000F.jsonl.gz:889316",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618466"
}
|
d667413d3be46770bf684d5ed1f36af66009984b
|
Stackoverflow Stackexchange
Q: How to change the color of an AlertDialog message? I have an AlertDialog and it's message is displayed, but the color of the text is white. It blends in with the background. I've tried changing the theme but it doesn't work. How do I change the color of the message?
The relevant code:
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(MainActivityGame.this);
builder.setTitle("Name");
builder.setMessage("Are you ");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Submit default name, go home
boolean isInserted = myDb.insertData(defaultName, triesTaken, difficultyText);
if (isInserted) {
Toast.makeText(MainActivityGame.this, "Your name was submitted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivityGame.this, "Error, your name wasn't submitted\n Have you entered a default name?\n Go to Settings/Default Name to set it up", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(MainActivityGame.this, MainActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
userName.setVisibility(View.VISIBLE);
submitName.setVisibility(View.VISIBLE);
submitName.setEnabled(true);
dialogInterface.dismiss();
}
});
builder.create();
builder.show();
A: you can give style to your alert dialog like this:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogStyle);
and the style is like always:
<style name="AlertDialogStyle" parent="Theme.AppCompat.Light.Dialog">
<item name="android:colorAccent">#f3f3f3</item>
<item name="android:textColor">#f3f3f3</item>
<item name="android:textColorPrimary">#f3f3f3</item>
</style>
|
Q: How to change the color of an AlertDialog message? I have an AlertDialog and it's message is displayed, but the color of the text is white. It blends in with the background. I've tried changing the theme but it doesn't work. How do I change the color of the message?
The relevant code:
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(MainActivityGame.this);
builder.setTitle("Name");
builder.setMessage("Are you ");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Submit default name, go home
boolean isInserted = myDb.insertData(defaultName, triesTaken, difficultyText);
if (isInserted) {
Toast.makeText(MainActivityGame.this, "Your name was submitted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivityGame.this, "Error, your name wasn't submitted\n Have you entered a default name?\n Go to Settings/Default Name to set it up", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(MainActivityGame.this, MainActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
userName.setVisibility(View.VISIBLE);
submitName.setVisibility(View.VISIBLE);
submitName.setEnabled(true);
dialogInterface.dismiss();
}
});
builder.create();
builder.show();
A: you can give style to your alert dialog like this:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogStyle);
and the style is like always:
<style name="AlertDialogStyle" parent="Theme.AppCompat.Light.Dialog">
<item name="android:colorAccent">#f3f3f3</item>
<item name="android:textColor">#f3f3f3</item>
<item name="android:textColorPrimary">#f3f3f3</item>
</style>
A: You can either use this method, like @KarimElGhandour mentioned or just create your custom Layout in the res\layout folder and then apply it with alertDialog.setView(LayoutInflater.inflate(R.layout.yourlayout), yourRootView.
A: In the Style even you can change gravity and Mode:
<style name="WelcomeStyle" parent="Theme.AppCompat.Light.Dialog">
<item name="android:background">#FFD600</item>
<item name="android:textColor">#C51162</item>
<item name="android:textColorPrimary">#00B8D4</item>
<item name="android:gravity">center</item>
<item name="android:justificationMode">inter_word</item>
</style>
A: AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.DialogStyle);
styles.xml
<style name="AlertDialogStyle" parent="Theme.AppCompat.Light.Dialog">
<item name="android:colorAccent">#303030</item>
<item name="android:textColor">#FFFFFF</item>
<item name="android:textColorPrimary">#494949</item>
<item name="android:windowBackground">#201D1D</item>
</style>
|
stackoverflow
|
{
"language": "en",
"length": 256,
"provenance": "stackexchange_0000F.jsonl.gz:889340",
"question_score": "26",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618542"
}
|
a37402a9ff1926e52dc80defb583641776e7f732
|
Stackoverflow Stackexchange
Q: Python TypeError: bad operand type for unary -: 'tuple' I am trying to make a tetris game, but I don't understand this error?
It seems to be line 34:
self.active_blk.move(-direction)
Here is my code:
import pygame
import random
from Block import Block
class Stage():
def __init__(self,cell_size,h_cells,v_cells):
self.cell_size=cell_size
self.width=h_cells
self.height=v_cells
self.blocks=[]
self.active_blk=self.add_block()
def add_block(self):
blk=Block(0,self.cell_size,(random.randint(0,255),random.randint(0,255),random.randint(0,255)))
self.blocks.append(blk)
return blk
def move_block(self,direction):
self.active_blk.move(direction)
obstacle=False
for cell in self.active_blk.cells:
if(cell.y>=self.height or
cell.x<0 or
cell.x>= self.width): obstacle=True
for blk in self.blocks:
if(blk is self.active_blk): continue
if(blk.collide_with(self.active_blk)):
obstacle=True
break;
if(obstacle):
self.active_blk.move(-direction)
def draw(self,screen):
screen.fill((0,0,0))
for blk in self.blocks:
blk.draw(screen)
A: Your direction argument is not a number than can be negated. Rather, it's a tuple of two numbers. Tuples are not numeric types, so even though its contents can be negated, the tuple itself cannot be. You need to negate the pieces yourself, with (-direction[0], -direction[1]).
|
Q: Python TypeError: bad operand type for unary -: 'tuple' I am trying to make a tetris game, but I don't understand this error?
It seems to be line 34:
self.active_blk.move(-direction)
Here is my code:
import pygame
import random
from Block import Block
class Stage():
def __init__(self,cell_size,h_cells,v_cells):
self.cell_size=cell_size
self.width=h_cells
self.height=v_cells
self.blocks=[]
self.active_blk=self.add_block()
def add_block(self):
blk=Block(0,self.cell_size,(random.randint(0,255),random.randint(0,255),random.randint(0,255)))
self.blocks.append(blk)
return blk
def move_block(self,direction):
self.active_blk.move(direction)
obstacle=False
for cell in self.active_blk.cells:
if(cell.y>=self.height or
cell.x<0 or
cell.x>= self.width): obstacle=True
for blk in self.blocks:
if(blk is self.active_blk): continue
if(blk.collide_with(self.active_blk)):
obstacle=True
break;
if(obstacle):
self.active_blk.move(-direction)
def draw(self,screen):
screen.fill((0,0,0))
for blk in self.blocks:
blk.draw(screen)
A: Your direction argument is not a number than can be negated. Rather, it's a tuple of two numbers. Tuples are not numeric types, so even though its contents can be negated, the tuple itself cannot be. You need to negate the pieces yourself, with (-direction[0], -direction[1]).
|
stackoverflow
|
{
"language": "en",
"length": 141,
"provenance": "stackexchange_0000F.jsonl.gz:889368",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618651"
}
|
788976052b53630ce3fbaaaaa607c66f2f049779
|
Stackoverflow Stackexchange
Q: Momentjs locale-specific weekdays() In moment there is a function moment.weekdays() that returns an array from sunday - saturday
If I change my locale to EU where first day of the week is monday, for example finland(moment.locale('fi'))
the result of moment.weekdays() is still starting with (translated) sunday
also: this doesn't change moment.weekdays() result but changes moment.weekday(1) to monday
moment.updateLocale('fi', {
week: {
dow : 1 // Monday is the first day of the week
}
});
Is there a way to get weekdays for current locale in the right order(starting with monday) or is modifying the moment.weekdays() array myself the only way?
A:
As of 2.13.0 you can pass a bool as the first parameter of the weekday functions. If true, the weekdays will be returned in locale specific order. For instance, in the Arabic locale, Saturday is the first day of the week
For your example in French, this would look like:
moment.locale("fr")
moment.weekdays(true)
output:
["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"]
link to documentation
|
Q: Momentjs locale-specific weekdays() In moment there is a function moment.weekdays() that returns an array from sunday - saturday
If I change my locale to EU where first day of the week is monday, for example finland(moment.locale('fi'))
the result of moment.weekdays() is still starting with (translated) sunday
also: this doesn't change moment.weekdays() result but changes moment.weekday(1) to monday
moment.updateLocale('fi', {
week: {
dow : 1 // Monday is the first day of the week
}
});
Is there a way to get weekdays for current locale in the right order(starting with monday) or is modifying the moment.weekdays() array myself the only way?
A:
As of 2.13.0 you can pass a bool as the first parameter of the weekday functions. If true, the weekdays will be returned in locale specific order. For instance, in the Arabic locale, Saturday is the first day of the week
For your example in French, this would look like:
moment.locale("fr")
moment.weekdays(true)
output:
["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"]
link to documentation
|
stackoverflow
|
{
"language": "en",
"length": 166,
"provenance": "stackexchange_0000F.jsonl.gz:889402",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618743"
}
|
40a1b12623c847967f1098f7aa12fb1305d99717
|
Stackoverflow Stackexchange
Q: Vue-router error: TypeError: Cannot read property 'matched' of undefined I'm trying to write my first Vuejs app. I'm using vue-cli and simple-webpack boilerplate.
When I add vue-router links to my app component I get this error in console
Error in render function: "TypeError: Cannot read property 'matched' of undefined"
Here is my code:
App.vue
<template>
<div>
<h2>Links</h2>
<ul>
<router-link to='/'>Home</router-link>
<router-link to='/query'>Query</router-link>
<router-view></router-view>
</ul>
</div>
</template>
<script>
export default {}
</script>
main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import routes from './routes.js'
import App from './App.vue'
const app = new Vue({
el: '#app',
routes,
render: h => h(App)
})
routes.js
import VueRouter from 'vue-router';
let routes=[
{
path: '/',
component: require('./Components/Home.vue')
},
{
path: '/query',
component: require('./Components/Query.vue')
}
];
export default new VueRouter({routes});
A: On my Vue file I had the following code:
Then, I modified my app.js file, and place the following code:
import router from './Router/router.js'
const app = new Vue({
el: '#app',
router
});
|
Q: Vue-router error: TypeError: Cannot read property 'matched' of undefined I'm trying to write my first Vuejs app. I'm using vue-cli and simple-webpack boilerplate.
When I add vue-router links to my app component I get this error in console
Error in render function: "TypeError: Cannot read property 'matched' of undefined"
Here is my code:
App.vue
<template>
<div>
<h2>Links</h2>
<ul>
<router-link to='/'>Home</router-link>
<router-link to='/query'>Query</router-link>
<router-view></router-view>
</ul>
</div>
</template>
<script>
export default {}
</script>
main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import routes from './routes.js'
import App from './App.vue'
const app = new Vue({
el: '#app',
routes,
render: h => h(App)
})
routes.js
import VueRouter from 'vue-router';
let routes=[
{
path: '/',
component: require('./Components/Home.vue')
},
{
path: '/query',
component: require('./Components/Query.vue')
}
];
export default new VueRouter({routes});
A: On my Vue file I had the following code:
Then, I modified my app.js file, and place the following code:
import router from './Router/router.js'
const app = new Vue({
el: '#app',
router
});
A: vue & vue router & match bug & solution
match bugs
solution
name must be router
https://stackoverflow.com/a/44618867/5934465
OK
import default module bug
import default module no need {}!
A: The name when you add it to Vue must be router.
import router from './routes.js'
const app = new Vue({
el: '#app',
router,
render: h => h(App)
})
If, for whatever reason, you want to call the variable routes you could assign it this way.
import routes from './routes.js'
const app = new Vue({
el: '#app',
router: routes,
render: h => h(App)
})
A: Adding to this, if you are putting the routes in the same page instead of importing it, It must be declared before the Vue component render.
Like this:-
const router = new VueRouter({
mode: 'history',
routes:[
{ path: '/dashboard', component: Dashboard},
{ path: '/signin', component: Signin}
]
});
new Vue({
el: '#app',
router,
render: h => h(App)
})
Not like this :
new Vue({
el: '#app',
router,
render: h => h(App)
})
const router = new VueRouter({
mode: 'history',
routes:[
{ path: '/dashboard', component: Dashboard},
{ path: '/signin', component: Signin}
]
});
A: Just to add my typo that caused this. I forgot the {} on the import
import { router } from './routes.js' //correct
import router from './routes.js' //causes same error
A: If you put some customized codes in router/index.js,
make sure you still export default router at the end.
const router = new Router({
mode: 'history'
});
export default router;
A: I have faced with this issue same as you. Then I realized at the end of the index.js that I forgot to add :
export default router
Then it solves the issue in my case.
|
stackoverflow
|
{
"language": "en",
"length": 443,
"provenance": "stackexchange_0000F.jsonl.gz:889412",
"question_score": "35",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618761"
}
|
a78c0cba6d43677a66621c87d2807b14aed5d0e6
|
Stackoverflow Stackexchange
Q: Creation of see through portal in SceneKit What I'm trying to achieve is a see through "portal" using SceneKit. I have two basic requirements for it:
*
*While moving around it user should be able to see scene inside a portal by different angles
*It should be thin "2D" levitating in the air portal
My approach is to create a .dae file with hollowed sphere and than add two textures to it - transparent onto the outside surface and non transparent textured inside, so the user can look through hole and see the inner contents. But I'm struggling to do so because basically making the outer texture transparent makes the inner visible. After hours of searching the web I still don't have any answer. How is functionality like this achieved?
Portals like this are pretty common in a different kind of games, so there is gotta be some basic technique to achieve this.
|
Q: Creation of see through portal in SceneKit What I'm trying to achieve is a see through "portal" using SceneKit. I have two basic requirements for it:
*
*While moving around it user should be able to see scene inside a portal by different angles
*It should be thin "2D" levitating in the air portal
My approach is to create a .dae file with hollowed sphere and than add two textures to it - transparent onto the outside surface and non transparent textured inside, so the user can look through hole and see the inner contents. But I'm struggling to do so because basically making the outer texture transparent makes the inner visible. After hours of searching the web I still don't have any answer. How is functionality like this achieved?
Portals like this are pretty common in a different kind of games, so there is gotta be some basic technique to achieve this.
|
stackoverflow
|
{
"language": "en",
"length": 154,
"provenance": "stackexchange_0000F.jsonl.gz:889447",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618852"
}
|
f50c918225008745a8baee2062db9d42e2a9c892
|
Stackoverflow Stackexchange
Q: Hide metric from tflearn fit? Write show_metric=False and snapshot_epoch=False
currentnetwork.model.fit(Xtrain, Ytrain, n_epoch=self['n_epoch'], shuffle=True, validation_set=(Xtest, Ytest),
show_metric=False,
snapshot_epoch=False,
)
But still get in output
> Training Step: 7 | total loss: 2.90061 | time: 7.083s | Adam | epoch:
> 007 | loss: 2.90061 -- iter: 40/40
|
Q: Hide metric from tflearn fit? Write show_metric=False and snapshot_epoch=False
currentnetwork.model.fit(Xtrain, Ytrain, n_epoch=self['n_epoch'], shuffle=True, validation_set=(Xtest, Ytest),
show_metric=False,
snapshot_epoch=False,
)
But still get in output
> Training Step: 7 | total loss: 2.90061 | time: 7.083s | Adam | epoch:
> 007 | loss: 2.90061 -- iter: 40/40
|
stackoverflow
|
{
"language": "en",
"length": 47,
"provenance": "stackexchange_0000F.jsonl.gz:889455",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618879"
}
|
4be1640467c9001346b8df0d8a69f29cb9601b82
|
Stackoverflow Stackexchange
Q: 'javac' is not recognized as an internal or external command, operable program or batch file. in VS Code, using Code Runner extension I am trying to run some java code in VS Code with the Code Runner extension, but i keep getting this:
'javac' is not recognized as an internal or external command,
operable program or batch file.
I checked all the paths and updated the path in VS Code, but it did nothing.
A: Assume you are on the Windows System.
First, you might want to add your jdk path to window system environment.
Then, open your VS Code, and go to User Settings located under File -> Preferences -> User Settings.
Add jdk PATH in your VS Code as the following shows.
Important Step: after all above steps are done, you might want to restart the VS Code to let change go in effect.
To test if it works, open Integrated Terminal in VS Code under View (or type Ctrl + ` (this key is located next to number 1)
Once the terminal shows up and is initialized, type javac to verify VS Code recognize the command.
|
Q: 'javac' is not recognized as an internal or external command, operable program or batch file. in VS Code, using Code Runner extension I am trying to run some java code in VS Code with the Code Runner extension, but i keep getting this:
'javac' is not recognized as an internal or external command,
operable program or batch file.
I checked all the paths and updated the path in VS Code, but it did nothing.
A: Assume you are on the Windows System.
First, you might want to add your jdk path to window system environment.
Then, open your VS Code, and go to User Settings located under File -> Preferences -> User Settings.
Add jdk PATH in your VS Code as the following shows.
Important Step: after all above steps are done, you might want to restart the VS Code to let change go in effect.
To test if it works, open Integrated Terminal in VS Code under View (or type Ctrl + ` (this key is located next to number 1)
Once the terminal shows up and is initialized, type javac to verify VS Code recognize the command.
A: [On Windows]
Although it is called "bin path", the "bin" folder is not supposed to be included in the path. If you do, you get an error and VSCode asks you to remove "bin" from the path in order to solve the issue.
So the path to be added in settings.json should be something like:
"C:/Program Files/YOUR JDK/(YOUR JDK VERSION)-hotspot".
(and not "...-hotspot/bin")
A: Try and add the jdk bin path to the system environment variable otherwise u need to save the Java code inside the bin folder and compile it from there.
|
stackoverflow
|
{
"language": "en",
"length": 284,
"provenance": "stackexchange_0000F.jsonl.gz:889475",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44618941"
}
|
01a821ac42aebc85213fb61de88d2d6964e9598c
|
Stackoverflow Stackexchange
Q: Pytesseract OCR multiple config options I am having some problems with pytesseract. I need to configure Tesseract to that it is configured to accept single digits while also only being able to accept numbers as the number zero is often confused with an 'O'.
Like this:
target = pytesseract.image_to_string(im,config='-psm 7',config='outputbase digits')
A: The reason you are having trouble is because character restriction does not work in version 4.0. You have to force legacy mode (oem 0) to have it limit found characters. There is a bug somewhere in the tesseract team that they have not yet addressed.
|
Q: Pytesseract OCR multiple config options I am having some problems with pytesseract. I need to configure Tesseract to that it is configured to accept single digits while also only being able to accept numbers as the number zero is often confused with an 'O'.
Like this:
target = pytesseract.image_to_string(im,config='-psm 7',config='outputbase digits')
A: The reason you are having trouble is because character restriction does not work in version 4.0. You have to force legacy mode (oem 0) to have it limit found characters. There is a bug somewhere in the tesseract team that they have not yet addressed.
A: tesseract-4.0.0a supports below psm. If you want to have single character recognition, set psm = 10. And if your text consists of numbers only, you can set tessedit_char_whitelist=0123456789.
Page segmentation modes:
0 Orientation and script detection (OSD) only.
1 Automatic page segmentation with OSD.
2 Automatic page segmentation, but no OSD, or OCR.
3 Fully automatic page segmentation, but no OSD. (Default)
4 Assume a single column of text of variable sizes.
5 Assume a single uniform block of vertically aligned text.
6 Assume a single uniform block of text.
7 Treat the image as a single text line.
8 Treat the image as a single word.
9 Treat the image as a single word in a circle.
10 Treat the image as a single character.
11 Sparse text. Find as much text as possible in no particular order.
12 Sparse text with OSD.
13 Raw line. Treat the image as a single text line,
bypassing hacks that are Tesseract-specific.
Here is a sample usage of image_to_string with multiple parameters.
target = pytesseract.image_to_string(image, lang='eng', boxes=False, \
config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789')
A: Page segmentation modes:
*Orientation and script detection (OSD) only.
*Automatic page segmentation with OSD.
*Automatic page segmentation, but no OSD, or OCR. (not implemented)
*Fully automatic page segmentation, but no OSD. (Default)
*Assume a single column of text of variable sizes.
*Assume a single uniform block of vertically aligned text.
*Assume a single uniform block of text.
*Treat the image as a single text line.
*Treat the image as a single word.
*Treat the image as a single word in a circle.
*Treat the image as a single character.
*Sparse text. Find as much text as possible in no particular order.
*Sparse text with OSD.
*Raw line. Treat the image as a single text line, bypassing hacks that are Tesseract-specific.
OCR Engine modes:
*Legacy engine only.
*Neural nets LSTM engine only.
*Legacy + LSTM engines.
*Default, based on what is available.
A: Tesseract version 5.0.0-alpha can use the following command: (use psm=13 and oem=1 or 3)
pytesseract.image_to_string(export_image ,lang='eng', config='--psm 13 --oem 1 -c tessedit_char_whitelist=ABCDEFG0123456789')
Note that eng trained dataset is taken: https://github.com/tesseract-ocr/tessdata_fast/blob/master/eng.traineddata
Note:Tested on binary input images of +-60x60px with single character
|
stackoverflow
|
{
"language": "en",
"length": 464,
"provenance": "stackexchange_0000F.jsonl.gz:889527",
"question_score": "61",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619077"
}
|
3fc0ea2475417dae13da80a559a7674ca9923aa0
|
Stackoverflow Stackexchange
Q: Return record with max column value using Entity Framework 6 Trying to get record with max datetime value for ReceivedDateTime column, however data set should be pre-filtered by some Id column (not unique). Solved this way:
using (var db = new SystemEntities())
{
var records = db.Table.Where(p => p.Id == Id);
var record = records.Where(p => p.ReceivedDateTime == records.Max(r => r.ReceivedDateTime)).FirstOrDefault();
if(record != null)
{
}
}
Is there more beautiful, simpler and shorter implementation, notation? Thanks!
A: You can simplify like the following using OrderByDescending:
using (var db = new SystemEntities())
{
var record = db.Table.Where(p => p.Id == Id).OrderByDescending(x => x.ReceivedDateTime).FirstOrDefault();
if(record != null){}
}
|
Q: Return record with max column value using Entity Framework 6 Trying to get record with max datetime value for ReceivedDateTime column, however data set should be pre-filtered by some Id column (not unique). Solved this way:
using (var db = new SystemEntities())
{
var records = db.Table.Where(p => p.Id == Id);
var record = records.Where(p => p.ReceivedDateTime == records.Max(r => r.ReceivedDateTime)).FirstOrDefault();
if(record != null)
{
}
}
Is there more beautiful, simpler and shorter implementation, notation? Thanks!
A: You can simplify like the following using OrderByDescending:
using (var db = new SystemEntities())
{
var record = db.Table.Where(p => p.Id == Id).OrderByDescending(x => x.ReceivedDateTime).FirstOrDefault();
if(record != null){}
}
A: Update
Between the time I opened the question and tried out a result, the original answer had been fixed. My apologies for not checking before I posted.
Update
Seeing as I cannot comment, I will post an answer on the side.
The above suggested var record = db.Table.Where(p => p.Id == Id).Max(x => x.ReceivedDateTime).FirstOrDefault() will not compile because Max will return for you a datetime.
You can do it using OrderByDescending they way you would in an SQL statement
// I used an in memory array but it should be the same.
var item = items.Where(x => x.Id == 2).OrderByDescending(x => x.ReceivedDate).FirstOrDefault();
|
stackoverflow
|
{
"language": "en",
"length": 211,
"provenance": "stackexchange_0000F.jsonl.gz:889537",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619119"
}
|
b184566a9442c1d93c7ad8a4ab08925a76e02f15
|
Stackoverflow Stackexchange
Q: How do I remove a local package installed with 'lein install'? Leiningen offers the ability to add a project to the local repository, the help text is:
> lein help install
Install jar and pom to the local repository; typically ~/.m2.
Cautious of making a mess while experimenting, is there a way within Leiningen of managing the local repository? And removing packages installed by mistake?
For Maven, I did find this question and answer - which suggests deleting files, is that the best way? (And anything to be careful of if deleting manually?)
A: Just delete the relevant files under ~/.m2; there's nothing to fear... (but fear itself)
Lein uses ~/.m2 for storing all dependencies locally
|
Q: How do I remove a local package installed with 'lein install'? Leiningen offers the ability to add a project to the local repository, the help text is:
> lein help install
Install jar and pom to the local repository; typically ~/.m2.
Cautious of making a mess while experimenting, is there a way within Leiningen of managing the local repository? And removing packages installed by mistake?
For Maven, I did find this question and answer - which suggests deleting files, is that the best way? (And anything to be careful of if deleting manually?)
A: Just delete the relevant files under ~/.m2; there's nothing to fear... (but fear itself)
Lein uses ~/.m2 for storing all dependencies locally
|
stackoverflow
|
{
"language": "en",
"length": 117,
"provenance": "stackexchange_0000F.jsonl.gz:889577",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619241"
}
|
a5e72fc992a8f4a33e6ce1b0841639fda5493038
|
Stackoverflow Stackexchange
Q: Laravel: The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths I installed Laravel and uploaded it to git
now I downloaded it
But when I'm trying to enter the site I get this error:
The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.
I found this answer: The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths. laravel 5.3
My config/app.php
'key' => env('APP_KEY'),
'cipher' => env('APP_KEY'),
I run
php artisan key:generate
my ENV file:
APP_KEY=base64:zJQUL0Kuwhb2JL6L7IJ+1UO7IUSQSw2Td40F9LNABfE=
I run composer update
but still the same error...
I tried to clear config and cache it but that didn't help.
What else can I do?
A: Your config/app.php is wrong, change the cipher entry to 'cipher' => 'AES-256-CBC'. You have key and cipher both pointing to the same .env variable.
|
Q: Laravel: The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths I installed Laravel and uploaded it to git
now I downloaded it
But when I'm trying to enter the site I get this error:
The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.
I found this answer: The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths. laravel 5.3
My config/app.php
'key' => env('APP_KEY'),
'cipher' => env('APP_KEY'),
I run
php artisan key:generate
my ENV file:
APP_KEY=base64:zJQUL0Kuwhb2JL6L7IJ+1UO7IUSQSw2Td40F9LNABfE=
I run composer update
but still the same error...
I tried to clear config and cache it but that didn't help.
What else can I do?
A: Your config/app.php is wrong, change the cipher entry to 'cipher' => 'AES-256-CBC'. You have key and cipher both pointing to the same .env variable.
A: The correct way of resolving this is as follows:
php artisan key:generate (Note the generated base 64 key)
php artisan config:cache
Check the .env file and confirm that the value of APP_KEY is equal to the value you noted during key:generate
Thats it!!
A: php artisan key:generate fixed for me . You can check the .env to be sure the APP_KEY get assigned a base64 value
A: APP_KEY cipher if AES-256-CBC is selected, the length must be 32 characters.
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
APP_KEY=base64:iT7PDx7j8yKVTj0AW81vTnEQmqLwnVfW => 32 characters
|
stackoverflow
|
{
"language": "en",
"length": 229,
"provenance": "stackexchange_0000F.jsonl.gz:889604",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619357"
}
|
1c6f30be63c89c573b565c30c3d80c068a274aa2
|
Stackoverflow Stackexchange
Q: Returning a Sequence in Swift 3 I have a protocol Points with a method that should return an ordered sequence of Point instances.
I could return an array, but can I return something more generic so that implementations of Points needn't copy data in to an array?
I tried to do this:
protocol Points {
var points: Sequence {get}
}
But get the error:
Protocol 'Sequence' can only be used as a generic constraint because it has Self or associated type requirements
In older questions I read about SequenceOf, but this doesn't seem to exist in Swift 3.
Here's an example implementation of the Points protocol:
extension PointSetNode: Points {
var points: ?????? {
return children.map{$0.points}.joined()
}
}
… here, children is an array.
A: As Hamish mentions you should use AnySequence for this. The protocol definition will be:
protocol Points {
var points: AnySequence<Point> {get}
}
An implementation of this might be:
var points: AnySequence<Point> {
return AnySequence(children.map{$0.points}.joined())
}
|
Q: Returning a Sequence in Swift 3 I have a protocol Points with a method that should return an ordered sequence of Point instances.
I could return an array, but can I return something more generic so that implementations of Points needn't copy data in to an array?
I tried to do this:
protocol Points {
var points: Sequence {get}
}
But get the error:
Protocol 'Sequence' can only be used as a generic constraint because it has Self or associated type requirements
In older questions I read about SequenceOf, but this doesn't seem to exist in Swift 3.
Here's an example implementation of the Points protocol:
extension PointSetNode: Points {
var points: ?????? {
return children.map{$0.points}.joined()
}
}
… here, children is an array.
A: As Hamish mentions you should use AnySequence for this. The protocol definition will be:
protocol Points {
var points: AnySequence<Point> {get}
}
An implementation of this might be:
var points: AnySequence<Point> {
return AnySequence(children.map{$0.points}.joined())
}
|
stackoverflow
|
{
"language": "en",
"length": 161,
"provenance": "stackexchange_0000F.jsonl.gz:889628",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619438"
}
|
c81be4ac665748111b4b8ad1d42b18bfe2175fda
|
Stackoverflow Stackexchange
Q: Reading Excel: evaluation error with zip file '..file.xlsx' cannot be opened I am using R with readxl package. I try to import an Excel file with the following command:
library(readxl)
city_codes <- read_excel("./data/file.xlsx", sheet = "city_codes")
It says it is a zip file and cannot be opened:
Error in sheets_fun(path) :
Evaluation error: zip file './data/file.xlsx' cannot be opened.
Any ideas?
A: For me the "Evaluation error: zip file" error message also appeared when the excel spreadsheet was still opened in MSExcel.
|
Q: Reading Excel: evaluation error with zip file '..file.xlsx' cannot be opened I am using R with readxl package. I try to import an Excel file with the following command:
library(readxl)
city_codes <- read_excel("./data/file.xlsx", sheet = "city_codes")
It says it is a zip file and cannot be opened:
Error in sheets_fun(path) :
Evaluation error: zip file './data/file.xlsx' cannot be opened.
Any ideas?
A: For me the "Evaluation error: zip file" error message also appeared when the excel spreadsheet was still opened in MSExcel.
A: I had this error, but for me, it was just that I had the sheet open in Excel while trying to read it into R. I guess the package wrongly perceives it as a zip file when it's trying to read it while Excel has partial ownership of it (and this blocks the read).
A: You can specify a path to a file, only if it is nested on the working directory.
For example: If your working directory is MyWD and there is a folder in it, named MyData and another folder within MyData named MyNestedData, and finally myExcelFile.xlsx
read_excel("MyData/MyNestedData/myExcelFile.xlsx",sheet = "Sheet2") #will work
read_excel("MyWD/MyData/MyNestedData/myExcelFile.xlsx",sheet = "Sheet2") #will not work
A: If your excel worksheet is password protected, read_excel won't be able to access it and will give you this error.
If it needs protection, I would suggest p/w protecting the folder it's in, and then unprotecting the worksheet.
A: You may also get this error if you are using the wrong read function.
For example, read_xlsx("file.xls" ...) will throw the error.
A: The error message is readxl's funny way of saying "file not found". That exact line of code gives me the exact same error, and the file doesn't even exist for me.
Note: I'm on version 1.0.0 of readxl
A: This can happen if you forget to do the following before you use the read_excel function
setwd("C:\\map\\map_in_map\\map_in_map_in_map_where_the_file_is")
A: Try to change file restrictions if you are working on company's computer. This worked for me to solve this issue.
A: You may try to specify the full path instead of ./path/to/file
A: Try to make a new file. click "save as" and make a new name. Run again your code. it worked well to me :)
A: Although the solution was already given, but for the sake of documentation I will leave my situation here:
I ran into the same problem and couldn't figure out why. It seems that my excel file had closed with an error or something similar. I had to open the excel file, and save it again. When I ran R, everything worked smoothly.
A: The issue was that there was hidden files inside my working directory. I copied them to outside and exclude all directories. Now it works when I run the code.
A: In my case the xlsx was created using Excel 2007, which caused this issue. Xlsx files from newer Excel versions work.
A: In my case the file was not visible in the directory although I had deleted it. I had to search for the file using a software called "Everyting" and I deleted it. After that it worked.
A: For me, I was downloading a file from Google Drive into a tempfile with extension .xlsx... Realised the file in Google Drive was .xls so I changed it to that and it worked. Kinda rare situation though.
A: I got the same error message.
In my case the line that worked properly specified the sheet by a string (copied from excel). Suddenly, it did not work anymore (with the mentioned error message). I tried several things explained here. Ended up specifying the sheet by its number in the excel file - worked!
read_xlsx("table.xlsx", sheet="name_of_sheet") # suddently corrupt
read_xlsx("table.xlsx", sheet=4) # works
Why? No update of the package or something. I dislike to have to use a less specific line.
UPDATE: Restarting the R session made the initial line work again (although, I HAD checked the wd before...)
|
stackoverflow
|
{
"language": "en",
"length": 660,
"provenance": "stackexchange_0000F.jsonl.gz:889672",
"question_score": "35",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619585"
}
|
cd299eee114d62ca16c33e4845f781cf9384524b
|
Stackoverflow Stackexchange
Q: Error accessing field by reflection for persistent property i got this error on my hibernate
Error accessing field [private java.lang.Integer br.com.moldargesso.moldar.entities.Cidade.id] by reflection for persistent property [br.com.moldargesso.moldar.entities.Cidade#id] : 1
Class obra
@Entity
@Table (name = "obras")
public class Obra {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
@Column (name = "id")
private Integer id;
@OneToOne
@JoinColumn (name = "fk_cliente")
private Cliente cliente;
@OneToOne
@JoinColumn (name = "fk_cidade")
private Cidade cidade;
Class CIDADE
@Entity
@Table (name = "cidade")
public class Cidade {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
@Column
private Integer id;
@Column
private String nome;
DAO
public List list(Integer cidade){
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Obra.class);
if(cidade != null){
criteria.add(Restrictions.and(
Restrictions.eq("cidade", cidade)));
}
criteria.addOrder(Order.asc("id"));
List<Obra> obraList = criteria.list();
session.close();
return obraList;
}
I don't know how to fix it, i'm a begginer and i'd like to fix it.
Could someone help me ?
Thanks.
|
Q: Error accessing field by reflection for persistent property i got this error on my hibernate
Error accessing field [private java.lang.Integer br.com.moldargesso.moldar.entities.Cidade.id] by reflection for persistent property [br.com.moldargesso.moldar.entities.Cidade#id] : 1
Class obra
@Entity
@Table (name = "obras")
public class Obra {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
@Column (name = "id")
private Integer id;
@OneToOne
@JoinColumn (name = "fk_cliente")
private Cliente cliente;
@OneToOne
@JoinColumn (name = "fk_cidade")
private Cidade cidade;
Class CIDADE
@Entity
@Table (name = "cidade")
public class Cidade {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
@Column
private Integer id;
@Column
private String nome;
DAO
public List list(Integer cidade){
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Obra.class);
if(cidade != null){
criteria.add(Restrictions.and(
Restrictions.eq("cidade", cidade)));
}
criteria.addOrder(Order.asc("id"));
List<Obra> obraList = criteria.list();
session.close();
return obraList;
}
I don't know how to fix it, i'm a begginer and i'd like to fix it.
Could someone help me ?
Thanks.
|
stackoverflow
|
{
"language": "en",
"length": 144,
"provenance": "stackexchange_0000F.jsonl.gz:889673",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619588"
}
|
256e0a63ff62c74a02425a11f9a61d5090727635
|
Stackoverflow Stackexchange
Q: Passive event listener in Select Tag Click on select element shows this warning:
[Violation] Added non-passive event listener to a scroll-blocking
'mousewheel' event. Consider marking event handler as 'passive' to
make the page more responsive.
The problem is that this also expand the height of HTML page in Google Chrome.
Tested in Chrome Version 59.0.3071.86 (Official Build) (64-bit)
In firefox this does not occur.
Simple code:
https://jsfiddle.net/gurigraphics/2399mnyb
<div>
<select>
<option>Option</option>
</select>
</div>
The same happens with "mouse hover" if you customize the scroll bar.
What is the better solution? I found this theory:
https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
A: Chrome automatically logs whenever a scroll-blocking event occurs.
Using Chrome's DevTools, I checked that there is no mousewheel listeners on the select box, and it still happens.
I suggest turning off 'Verbose' in the console.
|
Q: Passive event listener in Select Tag Click on select element shows this warning:
[Violation] Added non-passive event listener to a scroll-blocking
'mousewheel' event. Consider marking event handler as 'passive' to
make the page more responsive.
The problem is that this also expand the height of HTML page in Google Chrome.
Tested in Chrome Version 59.0.3071.86 (Official Build) (64-bit)
In firefox this does not occur.
Simple code:
https://jsfiddle.net/gurigraphics/2399mnyb
<div>
<select>
<option>Option</option>
</select>
</div>
The same happens with "mouse hover" if you customize the scroll bar.
What is the better solution? I found this theory:
https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
A: Chrome automatically logs whenever a scroll-blocking event occurs.
Using Chrome's DevTools, I checked that there is no mousewheel listeners on the select box, and it still happens.
I suggest turning off 'Verbose' in the console.
|
stackoverflow
|
{
"language": "en",
"length": 131,
"provenance": "stackexchange_0000F.jsonl.gz:889676",
"question_score": "23",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619595"
}
|
705b747a194cc911d2b5cb1928a4562a0d2a5a23
|
Stackoverflow Stackexchange
Q: Create particle effect in react-native I would like to create a particle effect in the background of my react-native app.
I am looking for something like this: http://vincentgarreau.com/particles.js/
I can't seem to find a package that does the job.
Thanks in advance!
A: I ended up creating my own library react-native-particles
The trick for getting a good performance was to pre-calculate the particle path and then use the Animated API with useNativeDriver:true.
|
Q: Create particle effect in react-native I would like to create a particle effect in the background of my react-native app.
I am looking for something like this: http://vincentgarreau.com/particles.js/
I can't seem to find a package that does the job.
Thanks in advance!
A: I ended up creating my own library react-native-particles
The trick for getting a good performance was to pre-calculate the particle path and then use the Animated API with useNativeDriver:true.
A: Use react-native webview as Background
|
stackoverflow
|
{
"language": "en",
"length": 79,
"provenance": "stackexchange_0000F.jsonl.gz:889727",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619762"
}
|
3d7855b2f25eadaa7e2cd45a31cf4fdee2580710
|
Stackoverflow Stackexchange
Q: eslint Parsing error: Unexpected token = Why is eslint throwing this error? The Javascript runs without issue inside of React Native. The code was taken from the react-navigation example at : https://reactnavigation.org/docs/intro/
Javascript:
static navigationOptions = { header: null };
eslint error:
error Parsing error: Unexpected token =
.eslintrc.js file:
module.exports = {
"extends": "standard",
"plugins": [
"react",
"react-native"
]
};
A: The syntax is not yet standardised, but a stage-2 proposal for inclusion in Javascript (see "Class Fields" on https://github.com/tc39/proposals).
Try adding the following option above "extends" in your .eslintrc.js:
"parser": "babel-eslint",
|
Q: eslint Parsing error: Unexpected token = Why is eslint throwing this error? The Javascript runs without issue inside of React Native. The code was taken from the react-navigation example at : https://reactnavigation.org/docs/intro/
Javascript:
static navigationOptions = { header: null };
eslint error:
error Parsing error: Unexpected token =
.eslintrc.js file:
module.exports = {
"extends": "standard",
"plugins": [
"react",
"react-native"
]
};
A: The syntax is not yet standardised, but a stage-2 proposal for inclusion in Javascript (see "Class Fields" on https://github.com/tc39/proposals).
Try adding the following option above "extends" in your .eslintrc.js:
"parser": "babel-eslint",
A: Sometimes I get this error out of blue for the code that worked previously, so I know it's not a syntax error. Restarting VSCode solves my issue.
|
stackoverflow
|
{
"language": "en",
"length": 122,
"provenance": "stackexchange_0000F.jsonl.gz:889741",
"question_score": "16",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619794"
}
|
46f5866533c3041e2f2e0975e4132ff03ceccd34
|
Stackoverflow Stackexchange
Q: How to enable background sync in Electron? I have a web app that i used electron to make it usable as a desktop app.
It uses service worker to make the app work offline. Any actions done on the tab change the local indexeddb and then add a task to the outbox. The service worker is triggered using registration.sync.register and it then clears the outbox.
This works fine on chrome but on electron i get an error:
Uncaught (in promise) DOMException: Background Sync is disabled.
Any idea how to get around this ?
|
Q: How to enable background sync in Electron? I have a web app that i used electron to make it usable as a desktop app.
It uses service worker to make the app work offline. Any actions done on the tab change the local indexeddb and then add a task to the outbox. The service worker is triggered using registration.sync.register and it then clears the outbox.
This works fine on chrome but on electron i get an error:
Uncaught (in promise) DOMException: Background Sync is disabled.
Any idea how to get around this ?
|
stackoverflow
|
{
"language": "en",
"length": 94,
"provenance": "stackexchange_0000F.jsonl.gz:889754",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619834"
}
|
35963c348bace003aced3f46280da3a254add23c
|
Stackoverflow Stackexchange
Q: Average of column skipping rows divisible by 5 using awk I want to compute the average of the 1st column of a text file, skipping rows divisible by 5. As an example, consider the following set of data.
1
2
3
4
5
6
7
8
9
10
For the data above, I can compute the average of the entire column using awk as
awk '{ sum += $1 } END { if (NR > 0) print sum / NR }' file
which prints the result 5.5.
How can I extend this code to exclude lines divisible by 5 from the average? For the example given above, this would exclude the numbers 5 and 10 from the average, resulting in a new average of 5.
A: Short awk solution:
awk '{ NR%5? s+=$0 : c++ }END{ print s/(NR-c) }' file
The output:
5
*
*NR%5? s+=$0 : c++ - ternary condition: sums all values s+=$0 if record number NR is not divisible by 5, else - count skipped records (to subtract them from average calculation)
|
Q: Average of column skipping rows divisible by 5 using awk I want to compute the average of the 1st column of a text file, skipping rows divisible by 5. As an example, consider the following set of data.
1
2
3
4
5
6
7
8
9
10
For the data above, I can compute the average of the entire column using awk as
awk '{ sum += $1 } END { if (NR > 0) print sum / NR }' file
which prints the result 5.5.
How can I extend this code to exclude lines divisible by 5 from the average? For the example given above, this would exclude the numbers 5 and 10 from the average, resulting in a new average of 5.
A: Short awk solution:
awk '{ NR%5? s+=$0 : c++ }END{ print s/(NR-c) }' file
The output:
5
*
*NR%5? s+=$0 : c++ - ternary condition: sums all values s+=$0 if record number NR is not divisible by 5, else - count skipped records (to subtract them from average calculation)
|
stackoverflow
|
{
"language": "en",
"length": 176,
"provenance": "stackexchange_0000F.jsonl.gz:889763",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619862"
}
|
52381c14990ed4660a778ea2cc8f94a50a1e9da3
|
Stackoverflow Stackexchange
Q: How to generate URL for the action with attribute routing in Asp.Net MVC public class HomeController : Controller
{
[Route("Users/about")]
[Route("Users/WhoareWe")]
[Route("Users/OurTeam")]
[Route("Users/aboutCompany")]
public ActionResult GotoAbout()
{
return View();
}
}
I have many routes defined for action GotoAbout().
How to create route URL in razor page programmatically when generate URL for action like home/users/about ?
A: Reference Attribute Routing in ASP.NET MVC 5 - Route Names
You can specify a name for a route, in order to easily allow URI generation for it.
For example, for the following route:
[RoutePrefix("Home")]
public class HomeController : Controller {
[Route("Users/about", Name = "Users_About")]
[Route("Users/WhoareWe")]
[Route("Users/OurTeam")]
[Route("Users/aboutCompany")]
public ActionResult GotoAbout() {
return View();
}
}
you could generate a link using Url.RouteUrl:
<a href="@Url.RouteUrl("Users_About")">About</a>
which would resolve to
<a href="home/users/about">About</a>
|
Q: How to generate URL for the action with attribute routing in Asp.Net MVC public class HomeController : Controller
{
[Route("Users/about")]
[Route("Users/WhoareWe")]
[Route("Users/OurTeam")]
[Route("Users/aboutCompany")]
public ActionResult GotoAbout()
{
return View();
}
}
I have many routes defined for action GotoAbout().
How to create route URL in razor page programmatically when generate URL for action like home/users/about ?
A: Reference Attribute Routing in ASP.NET MVC 5 - Route Names
You can specify a name for a route, in order to easily allow URI generation for it.
For example, for the following route:
[RoutePrefix("Home")]
public class HomeController : Controller {
[Route("Users/about", Name = "Users_About")]
[Route("Users/WhoareWe")]
[Route("Users/OurTeam")]
[Route("Users/aboutCompany")]
public ActionResult GotoAbout() {
return View();
}
}
you could generate a link using Url.RouteUrl:
<a href="@Url.RouteUrl("Users_About")">About</a>
which would resolve to
<a href="home/users/about">About</a>
|
stackoverflow
|
{
"language": "en",
"length": 128,
"provenance": "stackexchange_0000F.jsonl.gz:889769",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619883"
}
|
e02a678d39d3cabf2ce00c0848181c0967cb5d75
|
Stackoverflow Stackexchange
Q: Memory use increases with every call to function - Swift I've got a method which uses swift's String(contentsOf: ... function to pull data off a website asynchronously several times in a row. Using the SwiftSoup library, I'm able to parse data from the HTML. This data is then stored into an array of struct instances. The struct contains 3 Strings, 2 Ints, 1 Bool and 1 array of strings
It works great, but something what I've noticed is that whilst profiling my app's memory use, is that every time I call this method, persistent RAM usage increases by around 1.5MiB every time.
My question is, is this normal behavior? If not, how can I force my app to release unused variables or whatever to memory?
Do note that the peaks shown in the screenshot are from a different method which is called when changing to a different view controller, so they may be ignored.
|
Q: Memory use increases with every call to function - Swift I've got a method which uses swift's String(contentsOf: ... function to pull data off a website asynchronously several times in a row. Using the SwiftSoup library, I'm able to parse data from the HTML. This data is then stored into an array of struct instances. The struct contains 3 Strings, 2 Ints, 1 Bool and 1 array of strings
It works great, but something what I've noticed is that whilst profiling my app's memory use, is that every time I call this method, persistent RAM usage increases by around 1.5MiB every time.
My question is, is this normal behavior? If not, how can I force my app to release unused variables or whatever to memory?
Do note that the peaks shown in the screenshot are from a different method which is called when changing to a different view controller, so they may be ignored.
|
stackoverflow
|
{
"language": "en",
"length": 155,
"provenance": "stackexchange_0000F.jsonl.gz:889780",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619925"
}
|
9b7474b440ac18579a8ab58dedc40a792e96b31e
|
Stackoverflow Stackexchange
Q: Does MVC and WebApi controller share route table? Seems by error, I had put my config.Routes.MapHttpRoute(...) under RouteConfig.RegisterRoutes(...) instead of WebApiConfig.Register(...). But even then, the WebApi controller actions seemed to work just fine.
Does this mean that if the MVC controller and Web API controllers are in the same project and namespace, are their routes put into the same Route table?
A:
are their routes put into the same Route table
Short answer would be yes.
They all end up in the same route table. Which also explains why you tend to put Web API routes before MVC routes and also why there can be route conflicts.
RouteConfig.RegisterRoutes(...) and WebApiConfig.Register(...) are just ways to organize and group related code together.
|
Q: Does MVC and WebApi controller share route table? Seems by error, I had put my config.Routes.MapHttpRoute(...) under RouteConfig.RegisterRoutes(...) instead of WebApiConfig.Register(...). But even then, the WebApi controller actions seemed to work just fine.
Does this mean that if the MVC controller and Web API controllers are in the same project and namespace, are their routes put into the same Route table?
A:
are their routes put into the same Route table
Short answer would be yes.
They all end up in the same route table. Which also explains why you tend to put Web API routes before MVC routes and also why there can be route conflicts.
RouteConfig.RegisterRoutes(...) and WebApiConfig.Register(...) are just ways to organize and group related code together.
|
stackoverflow
|
{
"language": "en",
"length": 121,
"provenance": "stackexchange_0000F.jsonl.gz:889785",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619935"
}
|
dba2848b7ea86b39183e93f268cb1c2d388c3536
|
Stackoverflow Stackexchange
Q: How to change model class name without losing data? How do you change the model class name in Django without losing data? Does anybody knows? Thank you very much to all for the help in advance.
A: If you just go ahead and change the model name in your models.py file, the "makemigrations" command is usually smart enough to pick it up. It will ask you if you changed the model name and create a migration to rename the table accordingly if you confirm.
|
Q: How to change model class name without losing data? How do you change the model class name in Django without losing data? Does anybody knows? Thank you very much to all for the help in advance.
A: If you just go ahead and change the model name in your models.py file, the "makemigrations" command is usually smart enough to pick it up. It will ask you if you changed the model name and create a migration to rename the table accordingly if you confirm.
A: Usually in most cases, django makemigrations handles renaming of models on its own but if it doesn't and creates it as delete and addition of new model, you may have to manually add migrations.RenameModel in your migration file. Django Rename Model
A: The two suggested replies did not answer my case.
If you want to go from :
class OldClassName(models.Model):
class meta:
db_table = 'unchanged_table_name'
to :
class NewClassName(models.Model):
class meta:
db_table = 'unchanged_table_name'
Without having django understanding in migrations "I can see you deleted a model and want me to create a new one"
Here is how I went :
*
*in the first migration where your model appears ('migration.CreateModel'), update it for "name='NewClassName'"
*then, in all the other migrations since this one, update "model_name='newclassname'" where it concerns this specific Model
*don't forget also the refereneces to this model in other 'AddField(ForeignKey)'
If its the only change, you don't even have to run makemigrations, Django should simply see nothing.
|
stackoverflow
|
{
"language": "en",
"length": 246,
"provenance": "stackexchange_0000F.jsonl.gz:889795",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44619977"
}
|
0d5397169c20034a39d0bbcac0c548220ee969d0
|
Stackoverflow Stackexchange
Q: Title for matplotlib legend I know it seems fairly redundant to have a title for a legend, but is it possible using matplotlib?
Here's a snippet of the code I have:
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
one = mpatches.Patch(facecolor='#f3f300', label='label1', linewidth = 0.5, edgecolor = 'black')
two = mpatches.Patch(facecolor='#ff9700', label = 'label2', linewidth = 0.5, edgecolor = 'black')
three = mpatches.Patch(facecolor='#ff0000', label = 'label3', linewidth = 0.5, edgecolor = 'black')
legend = plt.legend(handles=[one, two, three], loc = 4, fontsize = 'small', fancybox = True)
frame = legend.get_frame() #sets up for color, edge, and transparency
frame.set_facecolor('#b4aeae') #color of legend
frame.set_edgecolor('black') #edge color of legend
frame.set_alpha(1) #deals with transparency
plt.show()
I would want the title of the legend above label1. For reference, this is the output:
A: Just to add to the accepted answer that this also works with an Axes object.
fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4], label='some_label') # Or however the Axes was created.
ax.legend(title='This is My Legend Title')
|
Q: Title for matplotlib legend I know it seems fairly redundant to have a title for a legend, but is it possible using matplotlib?
Here's a snippet of the code I have:
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
one = mpatches.Patch(facecolor='#f3f300', label='label1', linewidth = 0.5, edgecolor = 'black')
two = mpatches.Patch(facecolor='#ff9700', label = 'label2', linewidth = 0.5, edgecolor = 'black')
three = mpatches.Patch(facecolor='#ff0000', label = 'label3', linewidth = 0.5, edgecolor = 'black')
legend = plt.legend(handles=[one, two, three], loc = 4, fontsize = 'small', fancybox = True)
frame = legend.get_frame() #sets up for color, edge, and transparency
frame.set_facecolor('#b4aeae') #color of legend
frame.set_edgecolor('black') #edge color of legend
frame.set_alpha(1) #deals with transparency
plt.show()
I would want the title of the legend above label1. For reference, this is the output:
A: Just to add to the accepted answer that this also works with an Axes object.
fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4], label='some_label') # Or however the Axes was created.
ax.legend(title='This is My Legend Title')
A: Add the title parameter to the this line:
legend = plt.legend(handles=[one, two, three], title="title",
loc=4, fontsize='small', fancybox=True)
See also the official docs for the legend constructor.
A: In case you have an already created legend, you can modify its title with set_title(). For the first answer:
legend = plt.legend(handles=[one, two, three], loc=4, fontsize='small', fancybox=True)
legend.set_title("title")
# plt.gca().get_legend().set_title() if you didn't store the
# legend in an object or you're loading a saved figure.
For the second answer based on Axes:
fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4], label='some_label') # Or however the Axes was created.
ax.legend()
ax.get_legend().set_title("title")
|
stackoverflow
|
{
"language": "en",
"length": 268,
"provenance": "stackexchange_0000F.jsonl.gz:889812",
"question_score": "97",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620013"
}
|
1aa376cc0045cc4af630b0729ee5069227a57961
|
Stackoverflow Stackexchange
Q: Do I need Mono for using F# with Visual Studio Code? I have installed .net core on my Linux Box (Ubuntu) and created the ubiquitous "Hello World" app as follows:
dotnet new console -lang F# -o HelloWorld
The previous command followed by a dotnet restore and dotnet run is all I needed to run the app. Then I decided to use Visual Studio Code as a convenient Editor/Debugging environment. After some googling it turns out that I need the Ionide plugin in order to use Visual Studio Code with F# (and the plugin in turn relies on mono).
Is there an alternative to this (without requiring mono?)
A: Ionide is the plugin all the F#ers rave over, so, don't think there is many alternatives to it
However looks like it might go to .net core http://github.com/ionide/ionide-vscode-fsharp/issues/78
It's not actually needed to do .net core development, it's a plugin to vscode that gives lots of great toys for F#, it grew up in the mono world, so needs to be ported. (for instance, you could use Vim to write code instead )
|
Q: Do I need Mono for using F# with Visual Studio Code? I have installed .net core on my Linux Box (Ubuntu) and created the ubiquitous "Hello World" app as follows:
dotnet new console -lang F# -o HelloWorld
The previous command followed by a dotnet restore and dotnet run is all I needed to run the app. Then I decided to use Visual Studio Code as a convenient Editor/Debugging environment. After some googling it turns out that I need the Ionide plugin in order to use Visual Studio Code with F# (and the plugin in turn relies on mono).
Is there an alternative to this (without requiring mono?)
A: Ionide is the plugin all the F#ers rave over, so, don't think there is many alternatives to it
However looks like it might go to .net core http://github.com/ionide/ionide-vscode-fsharp/issues/78
It's not actually needed to do .net core development, it's a plugin to vscode that gives lots of great toys for F#, it grew up in the mono world, so needs to be ported. (for instance, you could use Vim to write code instead )
|
stackoverflow
|
{
"language": "en",
"length": 182,
"provenance": "stackexchange_0000F.jsonl.gz:889831",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620078"
}
|
f39e4e8fc36b48ec88990ae6875c60ecceadfdca
|
Stackoverflow Stackexchange
Q: Keras - use part of the input at later stage in sequential model I'm training a CNN. My input is an image and a few metadata. I'd like to train a CNN that only looks at the image in the convolutional stages, and then uses the output of the convolutional stages and the metadata in the final dense layers.
metadata -----------------
|-> dense -> output
image -> Convolutions -
How can I do this with Keras? Can I feed input that has not a rectangular shape?
For instance if the image is (255, 255, 3) and the metadata (10) how would this work?
I've found this issue that seems related but I don't get how they split the input and merge the second part with the intermediate output later on.
A: You need to use the Functional API with a multi-input model.
An example could be:
from keras.layers import Input, Conv1D, Dense, concatenate
#Image data
conv_input = Input(shape=conv_input_shape)
conv_output = Conv1D(nfilters,kernel_shape)(conv_input)
#Metadata
metadata_input = Input(shape=metadata_shape)
#Merge and add dense layer
merge_layer = concatenate([metadata_input, conv_output])
main_output = Dense(dense_size)(merge_layer)
# Define model with two inputs
model = Model(inputs=[conv_input, metadata_input], outputs=[main_output])
Hope this helps!
|
Q: Keras - use part of the input at later stage in sequential model I'm training a CNN. My input is an image and a few metadata. I'd like to train a CNN that only looks at the image in the convolutional stages, and then uses the output of the convolutional stages and the metadata in the final dense layers.
metadata -----------------
|-> dense -> output
image -> Convolutions -
How can I do this with Keras? Can I feed input that has not a rectangular shape?
For instance if the image is (255, 255, 3) and the metadata (10) how would this work?
I've found this issue that seems related but I don't get how they split the input and merge the second part with the intermediate output later on.
A: You need to use the Functional API with a multi-input model.
An example could be:
from keras.layers import Input, Conv1D, Dense, concatenate
#Image data
conv_input = Input(shape=conv_input_shape)
conv_output = Conv1D(nfilters,kernel_shape)(conv_input)
#Metadata
metadata_input = Input(shape=metadata_shape)
#Merge and add dense layer
merge_layer = concatenate([metadata_input, conv_output])
main_output = Dense(dense_size)(merge_layer)
# Define model with two inputs
model = Model(inputs=[conv_input, metadata_input], outputs=[main_output])
Hope this helps!
|
stackoverflow
|
{
"language": "en",
"length": 192,
"provenance": "stackexchange_0000F.jsonl.gz:889863",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620178"
}
|
38fb3f8de0c0d7a9f24aa31ec387ccc5cb387452
|
Stackoverflow Stackexchange
Q: Django get() returned more than one I have this error, how can I fix this?
get() returned more than one Event -- it returned 2!
Can you guys help me understand what that means and maybe tell me in advance how to avoid this error in future?
MODEL
class Event (models.Model):
name = models.CharField(max_length=100)
date = models.DateField(default='')
dicript = models.CharField(max_length=50, default='Описание отсутствует')
category = models.ForeignKey(Category,on_delete=models.CASCADE)
adress = models.TextField(max_length=300)
user = models.ForeignKey(User,related_name="creator",null=True)
subs = models.ManyToManyField(User, related_name='subs',blank=True)
@classmethod
def make_sub(cls, this_user, sub_event):
event, created = cls.objects.get_or_create(
user=this_user
)
sub_event.subs.add(this_user)
VIEWS
def cards_detail (request,pk=None):
# if pk:
event_detail = Event.objects.get(pk=pk)
subs = event_detail.subs.count()
# else:
# return CardsView()
args = {'event_detail':event_detail,'subs':subs}
return render(request,'events/cards_detail.html',args)
class CardsView (TemplateView):`
template_name = 'events/cards.html'
def get (self,request):
events = Event.objects.all()
return render(request,self.template_name,{'events':events })
def subs_to_event (request,pk=None):
event = Event.objects.filter(pk=pk)
Event.make_sub(request.user,event)
return redirect('events:cards')
A: from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
try:
instance = Instance.objects.get(name=name)
except (ObjectDoesNotExist, MultipleObjectsReturned):
pass
get() raises MultipleObjectsReturned if more than one object was found,more info here.
the error is cause by event_detail = Event.objects.get(pk=pk), check your event pk is unique.
|
Q: Django get() returned more than one I have this error, how can I fix this?
get() returned more than one Event -- it returned 2!
Can you guys help me understand what that means and maybe tell me in advance how to avoid this error in future?
MODEL
class Event (models.Model):
name = models.CharField(max_length=100)
date = models.DateField(default='')
dicript = models.CharField(max_length=50, default='Описание отсутствует')
category = models.ForeignKey(Category,on_delete=models.CASCADE)
adress = models.TextField(max_length=300)
user = models.ForeignKey(User,related_name="creator",null=True)
subs = models.ManyToManyField(User, related_name='subs',blank=True)
@classmethod
def make_sub(cls, this_user, sub_event):
event, created = cls.objects.get_or_create(
user=this_user
)
sub_event.subs.add(this_user)
VIEWS
def cards_detail (request,pk=None):
# if pk:
event_detail = Event.objects.get(pk=pk)
subs = event_detail.subs.count()
# else:
# return CardsView()
args = {'event_detail':event_detail,'subs':subs}
return render(request,'events/cards_detail.html',args)
class CardsView (TemplateView):`
template_name = 'events/cards.html'
def get (self,request):
events = Event.objects.all()
return render(request,self.template_name,{'events':events })
def subs_to_event (request,pk=None):
event = Event.objects.filter(pk=pk)
Event.make_sub(request.user,event)
return redirect('events:cards')
A: from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
try:
instance = Instance.objects.get(name=name)
except (ObjectDoesNotExist, MultipleObjectsReturned):
pass
get() raises MultipleObjectsReturned if more than one object was found,more info here.
the error is cause by event_detail = Event.objects.get(pk=pk), check your event pk is unique.
A: Basically, the cls object is getting more than one value on the get part of the 'get_or_create()'. get() returns only a single object whereas filter returns a dict(ish).
Put it in a try/except instead. So you'll have:
try:
event, created = cls.objects.get_or_create(
user=this_user
)
except cls.MultipleObjectsReturned:
event = cls.objects.filter(user=this_user).order_by('id').first()
This way if multiple objects are found, it handles the exception and changes the query to a filter to receive the multiple object queryset. No need to catch the Object.DoesNotExist as the create part creates a new object if no record is found.
A: I also face the same error:
get() returned more than one -- it returned 4!
The error was that I forgot to make a migration for the newly added fields in the model.
|
stackoverflow
|
{
"language": "en",
"length": 302,
"provenance": "stackexchange_0000F.jsonl.gz:889872",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620205"
}
|
4c9bbbf863324349fb546a497366bb5022d58d7e
|
Stackoverflow Stackexchange
Q: Removing special character from Java String I am trying to work around to remove symbols and special characters from a raw text in java and could not find way around. The text is taken from a free-text field in a website which may contain literally anything. I am taking this text from an external source and have no control to change setting. So I have to work around at my end.
Some examples are
1) belem should be--> belem
2) Ariana should be--> Ariana
3) Harlem should be--> Harlem
4) Yz ️ should be--> Yz
5) ここさけは7回は見に行くぞ should be--> ここさけは7回は見に行くぞ
6) دمي ازرق وطني ازرق should be--> دمي ازرق وطني ازرق
Any help please?
A: You can try this regex that find all emojis in a string :
regex = "[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]"
then remove all the emojis in it using replaceAll() method:
String text = "ここさけは7回は見に行くぞ ";
String regex = "[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]";
System.out.println(text.replaceAll(regex, ""));
Output:
ここさけは7回は見に行くぞ
|
Q: Removing special character from Java String I am trying to work around to remove symbols and special characters from a raw text in java and could not find way around. The text is taken from a free-text field in a website which may contain literally anything. I am taking this text from an external source and have no control to change setting. So I have to work around at my end.
Some examples are
1) belem should be--> belem
2) Ariana should be--> Ariana
3) Harlem should be--> Harlem
4) Yz ️ should be--> Yz
5) ここさけは7回は見に行くぞ should be--> ここさけは7回は見に行くぞ
6) دمي ازرق وطني ازرق should be--> دمي ازرق وطني ازرق
Any help please?
A: You can try this regex that find all emojis in a string :
regex = "[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]"
then remove all the emojis in it using replaceAll() method:
String text = "ここさけは7回は見に行くぞ ";
String regex = "[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]";
System.out.println(text.replaceAll(regex, ""));
Output:
ここさけは7回は見に行くぞ
A: If you mean "special characters" are surrogate pairs, try this.
static String removeSpecial(String s) {
int[] r = s.codePoints()
.filter(c -> c < Character.MIN_SURROGATE)
.toArray();
return new String(r, 0, r.length);
}
and
String[] testStrs = {
"belem ",
"Ariana ",
"Harlem ",
"Yz ️",
"ここさけは7回は見に行くぞ",
"دمي ازرق وطني ازرق "
};
for (String s : testStrs)
System.out.println(removeSpecial(s));
results
belem
Ariana
Harlem
Yz
ここさけは7回は見に行くぞ
دمي ازرق وطني ازرق
A: Use a character class for white space and the POSIX character class for "any letter or number from any language":
str = str.replaceAll("[^\\s\\p{Alnum}]", "");
|
stackoverflow
|
{
"language": "en",
"length": 249,
"provenance": "stackexchange_0000F.jsonl.gz:889904",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620294"
}
|
4486d791b9554b0ced4194e8b95d210c15cc5c92
|
Stackoverflow Stackexchange
Q: CMP and carry flag Processor: MSP430 16 bit RISC
Can someone explain the CMP instruction in terms of when the carry flag is actually set below. From the manual it says,
CMP(.B) src,dst ..... dst - src
If src is not equal to dst, will the carry flag be set?
cmp r15, r11
jnc #1234
A: The User's Guide says:
Description
The source operand is subtracted from the destination operand. This is made by adding
the 1s complement of the source + 1 to the destination. The result affects only the status
bits in SR.
[…]
Status Bits
C: Set if there is a carry from the MSB, reset otherwise
In other words, C is set if there is an unsigned overflow.
This can also be seen in the jump instructions: JC (jump if carry) and JHS (jump if higher or same) are the same instruction, as are JNC (jump if no carry) and JLO (jump if lower).
Example If R5 ≥ R6 (unsigned), the program continues at Label2.
CMP R6,R5 ; Is R5 >= R6? Info to C
JHS Label2 ; Yes, C = 1
... ; No, R5 < R6. Continue
|
Q: CMP and carry flag Processor: MSP430 16 bit RISC
Can someone explain the CMP instruction in terms of when the carry flag is actually set below. From the manual it says,
CMP(.B) src,dst ..... dst - src
If src is not equal to dst, will the carry flag be set?
cmp r15, r11
jnc #1234
A: The User's Guide says:
Description
The source operand is subtracted from the destination operand. This is made by adding
the 1s complement of the source + 1 to the destination. The result affects only the status
bits in SR.
[…]
Status Bits
C: Set if there is a carry from the MSB, reset otherwise
In other words, C is set if there is an unsigned overflow.
This can also be seen in the jump instructions: JC (jump if carry) and JHS (jump if higher or same) are the same instruction, as are JNC (jump if no carry) and JLO (jump if lower).
Example If R5 ≥ R6 (unsigned), the program continues at Label2.
CMP R6,R5 ; Is R5 >= R6? Info to C
JHS Label2 ; Yes, C = 1
... ; No, R5 < R6. Continue
|
stackoverflow
|
{
"language": "en",
"length": 194,
"provenance": "stackexchange_0000F.jsonl.gz:889927",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620368"
}
|
4298b6a97b01c57f490b8ce67ab6fa4edec89dc9
|
Stackoverflow Stackexchange
Q: Edit Microsoft ChatBot UI design I have setup a QnA Bot via the Azue BotService, and I want to use the WebChat channel, but the default MS Design for the chat interface is quite bland; is there a way for me to edit it?
Is it possible to go form the default theme on the left, so something like Air New Zealand's bot on the right in the image below?
A: It depends on how you want to integrate the webchat in your page but yes it is possible to change the aspect, it's only css and js
All the details are provided on the GitHub account for the Webchat: https://github.com/Microsoft/BotFramework-WebChat
In a few words:
Want to run a custom build of WebChat? Clone this repo, alter it, build it, and reference your built botchat.css and botchat.js files.
And for Styling:
Styling
In the /src/scss/ folder you will find the source files for generating
/botchat.css. Run npm run build-css to compile once you've made your
changes. For basic branding, change colors.scss to match your color
scheme. For advanced styling, change botchat.scss.
|
Q: Edit Microsoft ChatBot UI design I have setup a QnA Bot via the Azue BotService, and I want to use the WebChat channel, but the default MS Design for the chat interface is quite bland; is there a way for me to edit it?
Is it possible to go form the default theme on the left, so something like Air New Zealand's bot on the right in the image below?
A: It depends on how you want to integrate the webchat in your page but yes it is possible to change the aspect, it's only css and js
All the details are provided on the GitHub account for the Webchat: https://github.com/Microsoft/BotFramework-WebChat
In a few words:
Want to run a custom build of WebChat? Clone this repo, alter it, build it, and reference your built botchat.css and botchat.js files.
And for Styling:
Styling
In the /src/scss/ folder you will find the source files for generating
/botchat.css. Run npm run build-css to compile once you've made your
changes. For basic branding, change colors.scss to match your color
scheme. For advanced styling, change botchat.scss.
|
stackoverflow
|
{
"language": "en",
"length": 182,
"provenance": "stackexchange_0000F.jsonl.gz:889992",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620604"
}
|
f354033b184fe2f6e7d5a9fd4fea939f36e31128
|
Stackoverflow Stackexchange
Q: Data Analysis Pandas SettingWithCopyWarning numbers = LabelEncoder()
State_Data['Quality'] = numbers.fit_transform(State_Data['Quality
Parameter'].astype('str'))
this is generating the following error :
/opt/conda/lib/python3.5/site-packages/ipykernel/__main__.py:1:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
I'm getting this error while doing analysis on a water quality data set and couldn't resolve it.It suggests to use .loc but i've tried that too and it didn't work either.
Please tell me how to resolve this issue?
A: It's always better to use a different variable to store transformed data. You can try following code to avoid the warnings:
transformed = numbers.fit_transform(State_Data['Quality Parameter'].astype('str'))
State_Data['Quality_transformed'] = transformed
Using this approach, will not only help you to avoid warnings but also will not modify your actual raw data, modifying raw data sometimes becomes problematic as you might have to run the entire script again if anything goes wrong along the way.
|
Q: Data Analysis Pandas SettingWithCopyWarning numbers = LabelEncoder()
State_Data['Quality'] = numbers.fit_transform(State_Data['Quality
Parameter'].astype('str'))
this is generating the following error :
/opt/conda/lib/python3.5/site-packages/ipykernel/__main__.py:1:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
I'm getting this error while doing analysis on a water quality data set and couldn't resolve it.It suggests to use .loc but i've tried that too and it didn't work either.
Please tell me how to resolve this issue?
A: It's always better to use a different variable to store transformed data. You can try following code to avoid the warnings:
transformed = numbers.fit_transform(State_Data['Quality Parameter'].astype('str'))
State_Data['Quality_transformed'] = transformed
Using this approach, will not only help you to avoid warnings but also will not modify your actual raw data, modifying raw data sometimes becomes problematic as you might have to run the entire script again if anything goes wrong along the way.
|
stackoverflow
|
{
"language": "en",
"length": 154,
"provenance": "stackexchange_0000F.jsonl.gz:889996",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620612"
}
|
bec4cfc681040f6f63f9ec350fa63346dac376ad
|
Stackoverflow Stackexchange
Q: How to test whether component contains string? I am trying to get my head around jest. This is my test:
test('whether contains className', () => {
let list = [
{
id: 12,
name: 'two',
completed: true
}
];
const wrapper = shallow(
<Todos todos={list}>
</Todos>
);
expect(wrap).toMatch(/strikethrough/);
});
How can I check whether a component contains a (sub)string inside the component?
A: You can also use
expect('Something').toContain('thing');
|
Q: How to test whether component contains string? I am trying to get my head around jest. This is my test:
test('whether contains className', () => {
let list = [
{
id: 12,
name: 'two',
completed: true
}
];
const wrapper = shallow(
<Todos todos={list}>
</Todos>
);
expect(wrap).toMatch(/strikethrough/);
});
How can I check whether a component contains a (sub)string inside the component?
A: You can also use
expect('Something').toContain('thing');
A: You need to get the rendered text of the current render tree with .text() method.
expect(wrapper.text()).toMatch(/strikethrough/)
A: jest-extended package has extension toInclude
expect('hello world').toInclude('ell');
expect('hello world').not.toInclude('bob');
|
stackoverflow
|
{
"language": "en",
"length": 96,
"provenance": "stackexchange_0000F.jsonl.gz:890002",
"question_score": "17",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620633"
}
|
b299253799efd39516dd9f1e3b731aa5fdb25b86
|
Stackoverflow Stackexchange
Q: Digital numbers recognition with Opencv + OCR on android i'm currently developing an android application to recognize digital numbers of an electricity meter. i've done most of the work but i still not getting a good result. 80% of the time i get a false one.
This is an example (i'm testing with a kitchen scale which is very similar to the meter) :
Original photo :
image after cropping and processing with OpenCV :
image after OCR (expected result that was obtained after several shots) :
image after OCR (unexpected result which is obtained often) :
Method used to process the image with OpenCV :
public Bitmap Bildverarbeitung (Bitmap image){
Mat tmp = new Mat (image.getWidth(), image.getHeight(), CvType.CV_8UC1);
Utils.bitmapToMat(image, tmp);
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_RGB2GRAY);
Imgproc.GaussianBlur(tmp, tmp, new Size(3, 3), 0);
Imgproc.threshold(tmp, tmp, 0, 255, Imgproc.THRESH_OTSU);
Utils.matToBitmap(tmp, image);
return image;
}
I used two trained data but only one works better :
traineddata that works good
traineddata that doesn't work
can anyone help me get better results.. Is there any changes that i can do? or other methods that i can apply ? thanks in advance
|
Q: Digital numbers recognition with Opencv + OCR on android i'm currently developing an android application to recognize digital numbers of an electricity meter. i've done most of the work but i still not getting a good result. 80% of the time i get a false one.
This is an example (i'm testing with a kitchen scale which is very similar to the meter) :
Original photo :
image after cropping and processing with OpenCV :
image after OCR (expected result that was obtained after several shots) :
image after OCR (unexpected result which is obtained often) :
Method used to process the image with OpenCV :
public Bitmap Bildverarbeitung (Bitmap image){
Mat tmp = new Mat (image.getWidth(), image.getHeight(), CvType.CV_8UC1);
Utils.bitmapToMat(image, tmp);
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_RGB2GRAY);
Imgproc.GaussianBlur(tmp, tmp, new Size(3, 3), 0);
Imgproc.threshold(tmp, tmp, 0, 255, Imgproc.THRESH_OTSU);
Utils.matToBitmap(tmp, image);
return image;
}
I used two trained data but only one works better :
traineddata that works good
traineddata that doesn't work
can anyone help me get better results.. Is there any changes that i can do? or other methods that i can apply ? thanks in advance
|
stackoverflow
|
{
"language": "en",
"length": 186,
"provenance": "stackexchange_0000F.jsonl.gz:890049",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620742"
}
|
f5d9a1613c4f2ddd50cabdf3fb92e235f83a2305
|
Stackoverflow Stackexchange
Q: C++ The compiler is changing the alignment of my structures. How can I prevent this? I am writing some code to read bitmap files.
Here is the struct I am using to read the bitmap header. See also:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd183374(v=vs.85).aspx
struct BITMAPFILEHEADER
{
WORD bfType; // 2
DWORD bfSize; // 6
WORD bfReserved1; // 8
WORD bfReserved2; // 10
DWORD bfOffBits; // 14
}; // should add to 14 bytes
If I put the following code in my main function:
std::cout << "BITMAPFILEHEADER: " << sizeof(BITMAPFILEHEADER) << std::endl;
the program prints:
BITMAPFILEHEADER: 16
It appears to be re-aligning the data in the struct on 4-byte boundaries, presumably for efficiency. Of course this renders me unable to read a bitmap... Even though microsoft, and others, specifiy this is the way to do it...
How can I prevent the structure re-alignment?
A: The solution I found which works on gcc compilers, under linux:
struct BITMAPFILEHEADER
{
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} __attribute__((packed));
There is probably a better, more cross compiler/platform way of doing things, but I don't know what it is.
|
Q: C++ The compiler is changing the alignment of my structures. How can I prevent this? I am writing some code to read bitmap files.
Here is the struct I am using to read the bitmap header. See also:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd183374(v=vs.85).aspx
struct BITMAPFILEHEADER
{
WORD bfType; // 2
DWORD bfSize; // 6
WORD bfReserved1; // 8
WORD bfReserved2; // 10
DWORD bfOffBits; // 14
}; // should add to 14 bytes
If I put the following code in my main function:
std::cout << "BITMAPFILEHEADER: " << sizeof(BITMAPFILEHEADER) << std::endl;
the program prints:
BITMAPFILEHEADER: 16
It appears to be re-aligning the data in the struct on 4-byte boundaries, presumably for efficiency. Of course this renders me unable to read a bitmap... Even though microsoft, and others, specifiy this is the way to do it...
How can I prevent the structure re-alignment?
A: The solution I found which works on gcc compilers, under linux:
struct BITMAPFILEHEADER
{
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} __attribute__((packed));
There is probably a better, more cross compiler/platform way of doing things, but I don't know what it is.
A: To avoid this, you can obviously designate the compiling granularity. Just use this switch:
##pragma pack(1)
This tells the compiler to align to 1-byte boundaries (do nothing)
To resume normal padding (from before the previous #pragma pack):
#pragma pack(pop)
|
stackoverflow
|
{
"language": "en",
"length": 225,
"provenance": "stackexchange_0000F.jsonl.gz:890054",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620755"
}
|
d913848ba4414b1b7c8450c4caefad3feecbcc43
|
Stackoverflow Stackexchange
Q: Magento 2: How to get multiple selection attibute as list on list.phtml I've added a multiple select attribute to my products an now I'm trying to show the result on "list.phtml" template. (Product list).
Im getting all the values like this:
$attribute = $_product->getResource()->getAttribute('attribute_name')->getFrontend()->getValue($_product);
This returns a String with all the values, but I need it to be an array so I can transform it to a list with individual links.
Any help?
thanks!
A: Ended up using:
$attribute_string = $_product->getResource()->getAttribute('attribute')->getFrontend()->getValue($_product);
$attribute_array = explode(', ', $attribute_string);
|
Q: Magento 2: How to get multiple selection attibute as list on list.phtml I've added a multiple select attribute to my products an now I'm trying to show the result on "list.phtml" template. (Product list).
Im getting all the values like this:
$attribute = $_product->getResource()->getAttribute('attribute_name')->getFrontend()->getValue($_product);
This returns a String with all the values, but I need it to be an array so I can transform it to a list with individual links.
Any help?
thanks!
A: Ended up using:
$attribute_string = $_product->getResource()->getAttribute('attribute')->getFrontend()->getValue($_product);
$attribute_array = explode(', ', $attribute_string);
A: Converting object to array.
$data = array($attribute);
Or
$data = (array) $attribute;
A: Complete code to print in list.phtml
<?php
$attribute_string = $_product->getResource()->getAttribute('region')->getFrontend()->getValue($_product);
$attribute_array = explode(',', $attribute_string);
echo $attribute_string; ?>
|
stackoverflow
|
{
"language": "en",
"length": 118,
"provenance": "stackexchange_0000F.jsonl.gz:890064",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620789"
}
|
848add2e863994d2a8f62eb550be87f72df6bf3f
|
Stackoverflow Stackexchange
Q: Room cannot pick a constructor since multiple constructors are suitable error I try to implement persistent library in my android kotlin project, but catch this error on compile time:
error: Room cannot pick a constructor since multiple constructors are
suitable. Try to annotate unwanted constructors with @Ignore.
Error code:
@Entity
data class Site(
var name: String = "",
var url: String = "",
@PrimaryKey(autoGenerate = true) var id: Long = 0)
A: This worked for me:
@Entity
data class Site(
@PrimaryKey(autoGenerate = true) var id: Long = 0),
var name: String = "",
var url: String = "",
@Ignore var ignored: String? = null
)
|
Q: Room cannot pick a constructor since multiple constructors are suitable error I try to implement persistent library in my android kotlin project, but catch this error on compile time:
error: Room cannot pick a constructor since multiple constructors are
suitable. Try to annotate unwanted constructors with @Ignore.
Error code:
@Entity
data class Site(
var name: String = "",
var url: String = "",
@PrimaryKey(autoGenerate = true) var id: Long = 0)
A: This worked for me:
@Entity
data class Site(
@PrimaryKey(autoGenerate = true) var id: Long = 0),
var name: String = "",
var url: String = "",
@Ignore var ignored: String? = null
)
A: I had this error because Kotlin apparently generates multiple Java constructors for a single Kotlin constructor with default argument values. Working code see next:
@Entity
data class Site(
var name: String,
var url: String,
@PrimaryKey(autoGenerate = true) var id: Long)
A: None of the above solutions are good, since they work but may cause errors.
Kotlin's Data Class generates several Methods using the default constructor. That means that equals(), hashCode(),
toString(), componentN() functions and copy() is generated using the attributes you assign to your constructor.
Using the above solutions like
@Entity data class Site(@PrimaryKey(autoGenerate = true) var id: Long) {
@Ignore constructor() : this(0)
var name: String = ""
var url: String = ""
}
generates all the above listed methods only for id. Using equals leads to unwanted quality, same as toString(). Solving this requires you to have all attributes you want to process inside the constructor and add a second constructor using ignore like
@Entity data class Site(
@NonNull @PrimaryKey(autoGenerate = true) var id: Long,
var name: String = "",
var url: String = "") {
@Ignore constructor(id = 0, name = ", url = "") : this()
}
You should really keep in mind, that you usually use data classes to have methods like toString and copy. Only this solution is working to avoid unwanted bugs during runtime.
A: this works for me
@Entity
data class TaskDetail @Ignore constructor(
@PrimaryKey(autoGenerate = true)
var id:Long = 0,
var taskId:Long = 0,
var content:String = "")
{
constructor():this(id = 0)
}
I use @Ignore to forbid ROOM warning
There are multiple good constructors and Room will pick the no-arg constructor. You can use the @Ignore annotation to eliminate unwanted constructors.
And add a default constructor for ROOM.
A: @Entity
data class Site @JvmOverloads constructor(
@ColumnInfo(name = "name") var name: String = "",
@ColumnInfo(name = "url") var url: String = "",
@PrimaryKey(autoGenerate = true) var id: Long = 0)
Immutable model class for a Site. In order to compile with Room, we could use @JvmOverloads to handle multiple constructors.
A: I fix this issue by upgrading my Room and other dependency.
Just try to update all of your dependancy it should work without any change.
Thank you
A: Here you change your app database version and restart program agian, it will work:
@Database(entities = arrayOf(Site::class), version = 123) abstract class YourAppDatabase : RoomDatabase() {
abstract fun yourDao(): YourDao
}
and you can also try this data class:
@Entity
data class Site(@PrimaryKey(autoGenerate = true) var id: Long) {
@Ignore constructor() : this(0)
var name: String = "",
var url: String = "",
}
and the last instruction: your primary key id should be incremented manually.
Hope that works for you. :)
Test to show that above answers are invalid.
data class TestModel(var id: Int = 0) {
constructor() : this(0)
var name: String = "defaultname"
var testData: String = "defaulttestData"
}
val testModel = TestModel(5)
testModel.name = "test"
val testModel2 = TestModel(5)
testModel2.testData = "testdata"
testModel2.name = "test"
info { "Test with name set: $testModel" }
info { "Testdata equals Testdata2 ${testModel.equals(testModel2)}" }
returns Test with name set: TestModel(id=5) and Testdata equals Testdata2 true
A: Just leaving my answer in case that helps anyone. I ran into the same issue, none of the answers above worked. The only thing that worked was changing from a data class to a class. I invite anyone to try the same code and explain why It did the trick:
Before
@Entity
data class ImgurGalleryPost (
@NotNull @PrimaryKey
var id: String,
var title: String?,
var description: String?,
var datetime: Int?,
var cover: String?,
var coverWidth: Int?,
var coverHeight: Int?,
var accountUrl: String?,
var accountId: Int?,
var privacy: String?,
var layout: String?,
var views: Int?,
var link: String?,
var ups: Int?,
var downs: Int?,
var points: Int?,
var score: Int?,
var isAlbum: Boolean?,
var vote: Boolean?,
var favorite: Boolean?,
var nsfw: Boolean?,
var section: String?,
var commentCount: Int?,
var favoriteCount: Int?,
var topic: String?,
var topicId: Int?,
var imagesCount: Int?,
var inGallery: Boolean?,
var isAd: Boolean?,
@NotNull @Ignore
var tags: List<ImgurGalleryTag>,
var inMostViral: Boolean?,
@NotNull @Ignore
var images: List<ImgurGalleryImage>
)
After
@Entity
class ImgurGalleryPost (
@NotNull @PrimaryKey
var id: String,
var title: String?,
var description: String?,
var datetime: Int?,
var cover: String?,
var coverWidth: Int?,
var coverHeight: Int?,
var accountUrl: String?,
var accountId: Int?,
var privacy: String?,
var layout: String?,
var views: Int?,
var link: String?,
var ups: Int?,
var downs: Int?,
var points: Int?,
var score: Int?,
var isAlbum: Boolean?,
var vote: Boolean?,
var favorite: Boolean?,
var nsfw: Boolean?,
var section: String?,
var commentCount: Int?,
var favoriteCount: Int?,
var topic: String?,
var topicId: Int?,
var imagesCount: Int?,
var inGallery: Boolean?,
var isAd: Boolean?,
@NotNull @Ignore
var tags: List<ImgurGalleryTag>,
var inMostViral: Boolean?,
@NotNull @Ignore
var images:
List<ImgurGalleryImage>
)
It's really weird, but I doubt that is an Android Studio cache issue because changing it back to the data class causes the error to show up again. Seems that is some kind of issue with the collection fields. I checked the constructor in the generated class and It looked fine, I don't know why the build was failing even when the constructor was being generated properly:
public ImgurGalleryPost(@org.jetbrains.annotations.NotNull()
java.lang.String id, @org.jetbrains.annotations.Nullable()
java.lang.String title, @org.jetbrains.annotations.Nullable()
java.lang.String description, @org.jetbrains.annotations.Nullable()
java.lang.Integer datetime, @org.jetbrains.annotations.Nullable()
java.lang.String cover, @org.jetbrains.annotations.Nullable()
java.lang.Integer coverWidth, @org.jetbrains.annotations.Nullable()
java.lang.Integer coverHeight, @org.jetbrains.annotations.Nullable()
java.lang.String accountUrl, @org.jetbrains.annotations.Nullable()
java.lang.Integer accountId, @org.jetbrains.annotations.Nullable()
java.lang.String privacy, @org.jetbrains.annotations.Nullable()
java.lang.String layout, @org.jetbrains.annotations.Nullable()
java.lang.Integer views, @org.jetbrains.annotations.Nullable()
java.lang.String link, @org.jetbrains.annotations.Nullable()
java.lang.Integer ups, @org.jetbrains.annotations.Nullable()
java.lang.Integer downs, @org.jetbrains.annotations.Nullable()
java.lang.Integer points, @org.jetbrains.annotations.Nullable()
java.lang.Integer score, @org.jetbrains.annotations.Nullable()
java.lang.Boolean isAlbum, @org.jetbrains.annotations.Nullable()
java.lang.Boolean vote, @org.jetbrains.annotations.Nullable()
java.lang.Boolean favorite, @org.jetbrains.annotations.Nullable()
java.lang.Boolean nsfw, @org.jetbrains.annotations.Nullable()
java.lang.String section, @org.jetbrains.annotations.Nullable()
java.lang.Integer commentCount, @org.jetbrains.annotations.Nullable()
java.lang.Integer favoriteCount, @org.jetbrains.annotations.Nullable()
java.lang.String topic, @org.jetbrains.annotations.Nullable()
java.lang.Integer topicId, @org.jetbrains.annotations.Nullable()
java.lang.Integer imagesCount, @org.jetbrains.annotations.Nullable()
java.lang.Boolean inGallery, @org.jetbrains.annotations.Nullable()
java.lang.Boolean isAd, @org.jetbrains.annotations.NotNull()
java.util.List<com.kimboo.core.model.ImgurGalleryTag> tags, @org.jetbrains.annotations.Nullable()
java.lang.Boolean inMostViral, @org.jetbrains.annotations.NotNull()
java.util.List<com.kimboo.core.model.ImgurGalleryImage> images) {
super();
}
If anyone can figure out a way to fix this without changing from data class to class please feel free to comment below.
A: Try to change the variable datatype from val to var :
BEFORE :
@Entity
data class Product(
@PrimaryKey
val id: String = "",
val name: String = ""
)
AFTER :
@Entity
data class Product(
@PrimaryKey
var id: String = "",
var name: String = ""
)
A: Error is caused by initially set variables in constructor. If you have only one constructor, change your code to this.
@Entity
data class Site(
val name: String,
val url: String,
@PrimaryKey(autoGenerate = true) val id: Long)
If you need empty constructor too, then you should do like this
@Entity
data class Site() {
constructor(name: String, url: String): this() {
this.name = name
this.url = url
}
var name: String = "",
var url: String = "",
@PrimaryKey(autoGenerate = true) var id: Long = 0
}
|
stackoverflow
|
{
"language": "en",
"length": 1222,
"provenance": "stackexchange_0000F.jsonl.gz:890079",
"question_score": "23",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620835"
}
|
e229b00150a0af7aecb6611fc74311d12880c126
|
Stackoverflow Stackexchange
Q: Rounding elements in numpy array to the number of the same index in another array For example:
a=[[ 2.22323422 3.34342 ]
[ 24.324 97.56464 ]]
round_to= [[2 1]
[1 3]]
My expected output would be:
a_rounded= [[ 2.2 3. ]
[ 2. 97.6]]
I would like to do this without slicing out each element and doing it individually.
A: Three options:
*
*Something similar to list comprehension using NumPy's .item.
*itertools.starmap
*np.broadcast
Timing is below. Option 3 seems to be by far the fastest route.
from itertools import starmap
np.random.seed(123)
target = np.random.randn(2, 2)
roundto = np.arange(1, 5, dtype=np.int16).reshape((2, 2)) # must be type int
def method1():
return (np.array([round(target.item(i), roundto.item(j))
for i, j in zip(range(target.size),
range(roundto.size))])
.reshape(target.shape))
def method2():
return np.array(list(starmap(round, zip(target.flatten(),
roundto.flatten())))).reshape(target.shape)
def method3():
b = np.broadcast(target, roundto)
out = np.empty(b.shape)
out.flat = [round(u,v) for (u,v) in b]
return out
from timeit import timeit
timeit(method1, number=100)
Out[50]: 0.003252145578553467
timeit(method2, number=100)
Out[51]: 0.002063405777064986
timeit(method3, number=100)
Out[52]: 0.0009481473990007316
print('method 3 is %0.2f x faster than method 2' %
(timeit(method2, number=100) / timeit(method3, number=100)))
method 3 is 2.91 x faster than method 2
|
Q: Rounding elements in numpy array to the number of the same index in another array For example:
a=[[ 2.22323422 3.34342 ]
[ 24.324 97.56464 ]]
round_to= [[2 1]
[1 3]]
My expected output would be:
a_rounded= [[ 2.2 3. ]
[ 2. 97.6]]
I would like to do this without slicing out each element and doing it individually.
A: Three options:
*
*Something similar to list comprehension using NumPy's .item.
*itertools.starmap
*np.broadcast
Timing is below. Option 3 seems to be by far the fastest route.
from itertools import starmap
np.random.seed(123)
target = np.random.randn(2, 2)
roundto = np.arange(1, 5, dtype=np.int16).reshape((2, 2)) # must be type int
def method1():
return (np.array([round(target.item(i), roundto.item(j))
for i, j in zip(range(target.size),
range(roundto.size))])
.reshape(target.shape))
def method2():
return np.array(list(starmap(round, zip(target.flatten(),
roundto.flatten())))).reshape(target.shape)
def method3():
b = np.broadcast(target, roundto)
out = np.empty(b.shape)
out.flat = [round(u,v) for (u,v) in b]
return out
from timeit import timeit
timeit(method1, number=100)
Out[50]: 0.003252145578553467
timeit(method2, number=100)
Out[51]: 0.002063405777064986
timeit(method3, number=100)
Out[52]: 0.0009481473990007316
print('method 3 is %0.2f x faster than method 2' %
(timeit(method2, number=100) / timeit(method3, number=100)))
method 3 is 2.91 x faster than method 2
|
stackoverflow
|
{
"language": "en",
"length": 182,
"provenance": "stackexchange_0000F.jsonl.gz:890095",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620878"
}
|
0dd0530dec5a974fcdcfd4a2aafaba39bf702f45
|
Stackoverflow Stackexchange
Q: Pandas DataFrame: get rows with same pair of values in two specific columns Hi I have a data frame like below
id other_things Dist_1 Dist_2
1 a 20.3 16.4
2 b 15.4 480.2
3 a 12.6 480.2
4 c 20.3 16.4
5 d 12.6 480.2
6 e 52.5 584.5
And I want to get rows where the pair of values matches in columns "Dist_1" and "Dist_2". like follows,
id other_things Dist_1 Dist_2
1 a 20.3 16.4
4 c 20.3 16.4
3 a 12.6 480.2
5 d 12.6 480.2
Thank you.
A: This seems like what you want:
df[df.duplicated(['Dist_1','Dist_2'], keep=False)]
id other_things Dist_1 Dist_2
0 1 a 20.3 16.4
2 3 a 12.6 480.2
3 4 c 20.3 16.4
4 5 d 12.6 480.2
If sorting matters:
df[df.duplicated(['Dist_1','Dist_2'], keep=False)].sort_values('Dist_2')
id other_things Dist_1 Dist_2
0 1 a 20.3 16.4
3 4 c 20.3 16.4
2 3 a 12.6 480.2
4 5 d 12.6 480.2
|
Q: Pandas DataFrame: get rows with same pair of values in two specific columns Hi I have a data frame like below
id other_things Dist_1 Dist_2
1 a 20.3 16.4
2 b 15.4 480.2
3 a 12.6 480.2
4 c 20.3 16.4
5 d 12.6 480.2
6 e 52.5 584.5
And I want to get rows where the pair of values matches in columns "Dist_1" and "Dist_2". like follows,
id other_things Dist_1 Dist_2
1 a 20.3 16.4
4 c 20.3 16.4
3 a 12.6 480.2
5 d 12.6 480.2
Thank you.
A: This seems like what you want:
df[df.duplicated(['Dist_1','Dist_2'], keep=False)]
id other_things Dist_1 Dist_2
0 1 a 20.3 16.4
2 3 a 12.6 480.2
3 4 c 20.3 16.4
4 5 d 12.6 480.2
If sorting matters:
df[df.duplicated(['Dist_1','Dist_2'], keep=False)].sort_values('Dist_2')
id other_things Dist_1 Dist_2
0 1 a 20.3 16.4
3 4 c 20.3 16.4
2 3 a 12.6 480.2
4 5 d 12.6 480.2
|
stackoverflow
|
{
"language": "en",
"length": 153,
"provenance": "stackexchange_0000F.jsonl.gz:890107",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620923"
}
|
f024de1b7aa4c082020d6b257a645680e877b31a
|
Stackoverflow Stackexchange
Q: C++ Biginteger, what does this mean? I am puzzled about why we need a BASE=100000000 and WIDTH=8. This code is from a book, but I don't understand it.
struct Biginteger {
static const BASE = 100000000;
static const WIDTH = 8;
vector<int> s;
Biginteger(long long int num = 0) { *this = num; }
Biginteger operator=(long long num) {
s.clear();
do {
s.push_back(num % BASE);
num /= BASE;
} while (mun > 0);
return *this;
}
A: Primitive types is not able to store arbitrarily large numbers and this is why you need BigInteger here. The idea of BigInteger is to use sequence of small numbers in primitive types to represent a large number.
With BASE=100000000 and WIDTH=8, you are actually separating the original number 8 digits by 8 digits.
For example 254325623456546 will be (2543256, 23456546)
You can simply change to other (BASE, WIDTH). For example, BASE=10, WIDTH=1 means you are storing the number digit by digit. For instance, 254325623456546 will be (2, 5, 4, 3, 2, 5, 6, 2, 3, 4, 5, 6, 5, 4, 6).
|
Q: C++ Biginteger, what does this mean? I am puzzled about why we need a BASE=100000000 and WIDTH=8. This code is from a book, but I don't understand it.
struct Biginteger {
static const BASE = 100000000;
static const WIDTH = 8;
vector<int> s;
Biginteger(long long int num = 0) { *this = num; }
Biginteger operator=(long long num) {
s.clear();
do {
s.push_back(num % BASE);
num /= BASE;
} while (mun > 0);
return *this;
}
A: Primitive types is not able to store arbitrarily large numbers and this is why you need BigInteger here. The idea of BigInteger is to use sequence of small numbers in primitive types to represent a large number.
With BASE=100000000 and WIDTH=8, you are actually separating the original number 8 digits by 8 digits.
For example 254325623456546 will be (2543256, 23456546)
You can simply change to other (BASE, WIDTH). For example, BASE=10, WIDTH=1 means you are storing the number digit by digit. For instance, 254325623456546 will be (2, 5, 4, 3, 2, 5, 6, 2, 3, 4, 5, 6, 5, 4, 6).
|
stackoverflow
|
{
"language": "en",
"length": 179,
"provenance": "stackexchange_0000F.jsonl.gz:890117",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620943"
}
|
d92e8f3b25ac23aff39cb03f9ed3422bd7280dde
|
Stackoverflow Stackexchange
Q: How to remove Amazon skill at amazon alexa console? I need to remove an alexa skill from amazon alexa console, it had been Live months ago. But I cannot find any buttons or function at alexa console to remove it.
It's so strange that an developer cannot remove his developed skill from amazon alexa.
A: you can check here: https://forums.developer.amazon.com/articles/2749/how-do-i-suppress-my-alexa-skill.html
Summary:
Skill suppression means your skill will no longer be available to end users. There are two options for skill suppression:
Hard Take Down Suppression: Disables your skill for current users that have it enabled and also makes the skill unavailable for enablement by new users.
Soft Hidden Suppression: Skill remains active for current users that have it enabled, but the skill is unavailable for enablement by newer users
To suppress your skill, please sign into your developer account and file a contact us request here that includes the skill name, application id, type of suppression request, and reasoning for suppression:
https://developer.amazon.com/appsandservices/support/contact/contact-us
The skill, once back in 'development' in the developer portal, can be resubmitted at a later point with or without changes.
|
Q: How to remove Amazon skill at amazon alexa console? I need to remove an alexa skill from amazon alexa console, it had been Live months ago. But I cannot find any buttons or function at alexa console to remove it.
It's so strange that an developer cannot remove his developed skill from amazon alexa.
A: you can check here: https://forums.developer.amazon.com/articles/2749/how-do-i-suppress-my-alexa-skill.html
Summary:
Skill suppression means your skill will no longer be available to end users. There are two options for skill suppression:
Hard Take Down Suppression: Disables your skill for current users that have it enabled and also makes the skill unavailable for enablement by new users.
Soft Hidden Suppression: Skill remains active for current users that have it enabled, but the skill is unavailable for enablement by newer users
To suppress your skill, please sign into your developer account and file a contact us request here that includes the skill name, application id, type of suppression request, and reasoning for suppression:
https://developer.amazon.com/appsandservices/support/contact/contact-us
The skill, once back in 'development' in the developer portal, can be resubmitted at a later point with or without changes.
|
stackoverflow
|
{
"language": "en",
"length": 184,
"provenance": "stackexchange_0000F.jsonl.gz:890128",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44620986"
}
|
db8d4fae4220a7faa66f48abcd0fb44ae8c4a6ff
|
Stackoverflow Stackexchange
Q: How to do scoped external css in vue.js? I am new to vue.js and saw this video
https://www.youtube.com/watch?v=LsoLfELhG74
Which says you can do
<style scoped>
</style>
to scope the style, but this is if I embed it into the html page. What if I link to a .css file. How could you still scope the css?
Thanks
A: You can add a src attribute to the style tag like this:
<style scoped src="./test.css">
</style>
|
Q: How to do scoped external css in vue.js? I am new to vue.js and saw this video
https://www.youtube.com/watch?v=LsoLfELhG74
Which says you can do
<style scoped>
</style>
to scope the style, but this is if I embed it into the html page. What if I link to a .css file. How could you still scope the css?
Thanks
A: You can add a src attribute to the style tag like this:
<style scoped src="./test.css">
</style>
A: first create a scss file like styles/scss/_variables.scss.In that _variables.scss file import your required styles like $bg-color: red;
Next import that scss file in your required .vue file .
<style lang="scss">
@import "../styles/scss/_variables.scss";
.msg {
background-color: $bg-color;
}
</style>
|
stackoverflow
|
{
"language": "en",
"length": 114,
"provenance": "stackexchange_0000F.jsonl.gz:890147",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621052"
}
|
33b559dde9c0e12b13e4ffd8e6e0bbf210e75716
|
Stackoverflow Stackexchange
Q: Combine dataframes returned from python multiprocess calling function from multiprocessing import Pool
with Pool(processes=6) as p:
p.starmap(update_tabl, zip(r))
I am using the approach outlined here: https://web.archive.org/web/20170625154652/http://n-s-f.github.io/2016/12/23/starmap-pattern.html to parallelize calling of a function update_table that returns a dataframe as output.
How can I concatenate all these dataframes? I could use pd.concat if I were using a for loop but not sure how to do it in parallel
A: You can do the concat on the result of the starmap:
with Pool(processes=6) as p:
res = pd.concat(p.starmap(update_table, zip(rows)))
# do stuff with res
The concat won't happen in parallel, but once the starmap has finished.
|
Q: Combine dataframes returned from python multiprocess calling function from multiprocessing import Pool
with Pool(processes=6) as p:
p.starmap(update_tabl, zip(r))
I am using the approach outlined here: https://web.archive.org/web/20170625154652/http://n-s-f.github.io/2016/12/23/starmap-pattern.html to parallelize calling of a function update_table that returns a dataframe as output.
How can I concatenate all these dataframes? I could use pd.concat if I were using a for loop but not sure how to do it in parallel
A: You can do the concat on the result of the starmap:
with Pool(processes=6) as p:
res = pd.concat(p.starmap(update_table, zip(rows)))
# do stuff with res
The concat won't happen in parallel, but once the starmap has finished.
|
stackoverflow
|
{
"language": "en",
"length": 104,
"provenance": "stackexchange_0000F.jsonl.gz:890171",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621116"
}
|
aa76f244ac6dfc18a94b3544c06d72968ae54ef6
|
Stackoverflow Stackexchange
Q: Is there any different semantics between "(1..4)" and "{1..4}" iteration in Rust? I find using (1..4)
fn main() {
for v in (1..4) {
println!("{}", v);
}
}
and {1..4}
fn main() {
for v in {1..4} {
println!("{}", v);
}
}
gets the same result. Is there any different semantics between "(1..4)" and "{1..4}" iteration?
A: There's no real useful difference. Both parenthesis and braces count as a single expression and function to alter the precedence. I'm pretty sure they have slightly different parsing rules, but at that point I'd guess there's a cleaner way of writing the code.
Note that in your examples, the idiomatic way would be to use neither:
fn main() {
for v in 1..4 {
println!("{}", v);
}
}
When needed, I feel I've only ever seen parenthesis used, never braces:
fn main() {
println!("{}", (1..4).count());
}
There are rare cases where curly braces provide more power. Since they serve to start a new scope, you can use them to "manually" transfer ownership in some tricky locations. For the purposes of the simple iterator described, there won't be any visible difference.
|
Q: Is there any different semantics between "(1..4)" and "{1..4}" iteration in Rust? I find using (1..4)
fn main() {
for v in (1..4) {
println!("{}", v);
}
}
and {1..4}
fn main() {
for v in {1..4} {
println!("{}", v);
}
}
gets the same result. Is there any different semantics between "(1..4)" and "{1..4}" iteration?
A: There's no real useful difference. Both parenthesis and braces count as a single expression and function to alter the precedence. I'm pretty sure they have slightly different parsing rules, but at that point I'd guess there's a cleaner way of writing the code.
Note that in your examples, the idiomatic way would be to use neither:
fn main() {
for v in 1..4 {
println!("{}", v);
}
}
When needed, I feel I've only ever seen parenthesis used, never braces:
fn main() {
println!("{}", (1..4).count());
}
There are rare cases where curly braces provide more power. Since they serve to start a new scope, you can use them to "manually" transfer ownership in some tricky locations. For the purposes of the simple iterator described, there won't be any visible difference.
A: In addition to the existing answers I was interested what the difference would be in the mid-level IR.
Even though the braces introduce a new block, in this case there is virtually no difference even in the (Nightly) MIR - the compiler immediately recognizes that the block serves no other purpose than returning a Range.
A: They produce the same iterators. You can even omit parentheses/braces:
fn main() {
for v in 1..4 {
println!("{}", v);
}
}
You can enclose an expression with () or {} in general. There is a difference however: {} creates a block and you can write statements (like let) in it. There is also a very subtle difference in how expressions are parsed. Edit: I found a blog article that describes another difference in how coercion and borrowck works.
Usually () is preferred if you don't need statements.
|
stackoverflow
|
{
"language": "en",
"length": 333,
"provenance": "stackexchange_0000F.jsonl.gz:890176",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621129"
}
|
34234424c325362a83e8413f2dc928d5ae90fead
|
Stackoverflow Stackexchange
Q: Upload failed You should use both http and https as schemes for your web intent-filters Upload failed
You should use both http and https as schemes for your web intent-filters.
I am getting this error while uploading the instant app to Play Store. I have declared intent filters for both http and https in Manifest as below.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="http"
android:host="XXXX" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="https"
android:host="XXXX" />
</intent-filter>
Could you please let me know what could be wrong and why i am getting this error while uploading to Play Store ?
A: Try to declare IntentFilter like this
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:host="yourhost.ru" />
<data android:pathPattern="/featurePath" />
</intent-filter>
|
Q: Upload failed You should use both http and https as schemes for your web intent-filters Upload failed
You should use both http and https as schemes for your web intent-filters.
I am getting this error while uploading the instant app to Play Store. I have declared intent filters for both http and https in Manifest as below.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="http"
android:host="XXXX" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="https"
android:host="XXXX" />
</intent-filter>
Could you please let me know what could be wrong and why i am getting this error while uploading to Play Store ?
A: Try to declare IntentFilter like this
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:host="yourhost.ru" />
<data android:pathPattern="/featurePath" />
</intent-filter>
A: Don't change your intent filter code by your own in the Manifest file.
Just go to Tools > App Links Assistants and follow the steps from 1 to 4.
In step 1 itself android studio will automatically add those intent filter codes to your manifest file.
(Source : Developer Documentation > Add Android App Links )
Follow the steps from the link.
A: you have to define both in the same intent filter
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="XXXX"
android:scheme="http" />
<data
android:scheme="https"
android:host="XXXX" />
</intent-filter>
A:
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="http"
android:host="XYZ"
android:pathPattern="/app" />
<data
android:scheme="https"
android:host="XYZ"
android:pathPattern="/app" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="default-url"
android:value="https://XYZ/app" />
</activity>
Had the same problem. The above manifest solved my problem
A: Agrees with the previous answer, but also add android:autoVerify="true" into intent-filter
A: I did everything mentioned above but finally get rid of this error after adding these permissions in my base module's manifest.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
A: There are two potential reasons for this issue
#1 You need to check your manifiest.xml and Add both http and https schemes
e.g:
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:host="www.example.co" />
<data android:scheme="http" />
<data android:scheme="https" />
</intent-filter>
or
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="www.example.com"
android:scheme="https" />
<data
android:host="www.example.com"
android:scheme="http" />
</intent-filter>
#2 If you're using deeplinks in your navigation graph you need to include both http and https as well
e.g:
<deepLink
app:action="android.intent.action.MY_ACTION"
app:mimeType="type/subtype"
app:uri="https://www.example.com/example" />
<deepLink
app:action="android.intent.action.MY_ACTION"
app:mimeType="type/subtype"
app:uri="http://www.example.co/example" />
|
stackoverflow
|
{
"language": "en",
"length": 416,
"provenance": "stackexchange_0000F.jsonl.gz:890184",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621165"
}
|
e80fddbcfcde33630ed1e66bade7312c04b65c3c
|
Stackoverflow Stackexchange
Q: g++ and clang++ different behaviour with alias template Trying to respond to another question, I've written the following code that behave different in g++ (6.3.0) and in clang++ (3.8.1)
#include <iostream>
#include <type_traits>
template <typename>
struct foo
{ };
template <typename T>
using alias = foo<T>;
template <template <typename...> class, template <typename...> class>
struct bar : public std::false_type
{ };
template <template <typename...> class C>
struct bar<C, C> : public std::true_type
{ };
int main()
{
// g++ print 1
// clang++ print 0
std::cout << bar<foo, alias>::value << std::endl;
}
g++ prints 1 (that is: activate the specialization bar struct, that is treat foo and alias as equals) and clang++ prints 0 (that is: activate the generic bar struct, that is treat foo and alias as differents).
The question, as usual, is: who's right? g++ or clang++ ?
|
Q: g++ and clang++ different behaviour with alias template Trying to respond to another question, I've written the following code that behave different in g++ (6.3.0) and in clang++ (3.8.1)
#include <iostream>
#include <type_traits>
template <typename>
struct foo
{ };
template <typename T>
using alias = foo<T>;
template <template <typename...> class, template <typename...> class>
struct bar : public std::false_type
{ };
template <template <typename...> class C>
struct bar<C, C> : public std::true_type
{ };
int main()
{
// g++ print 1
// clang++ print 0
std::cout << bar<foo, alias>::value << std::endl;
}
g++ prints 1 (that is: activate the specialization bar struct, that is treat foo and alias as equals) and clang++ prints 0 (that is: activate the generic bar struct, that is treat foo and alias as differents).
The question, as usual, is: who's right? g++ or clang++ ?
|
stackoverflow
|
{
"language": "en",
"length": 140,
"provenance": "stackexchange_0000F.jsonl.gz:890197",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621204"
}
|
3ccc27e4168d0562c0461b0f070a004422b743ae
|
Stackoverflow Stackexchange
Q: How to make gap between x and y axis and protruded ticks in ggplot2 How can I create the following style of graph:
Notice the gap between x-y axis (red circle) and protruded ticks in x-y axis (arrow).
At best I can do is this now:
library(ggplot2)
p <- ggplot(mpg, aes(class, hwy)) +
geom_boxplot() +
theme_bw(base_size=10)
p
A: One option is to remove the built-in axis lines and then use geom_segment to add axes with a gap. In order to make it easier to get the broken axis lines in the right place, we also use scale_y_continuous to specify exactly where we want the axis breaks and limits. The code also shows how to increase the size of the tick marks.
ggplot(data=mpg, aes(class, hwy)) +
geom_segment(y=10, yend=50, x=0.4, xend=0.4, lwd=0.5, colour="grey30", lineend="square") +
geom_segment(y=5, yend=5, x=1, xend=length(unique(mpg$class)),
lwd=0.5, colour="grey30", lineend="square") +
geom_boxplot() +
scale_y_continuous(breaks=seq(10,50,10), limits=c(5,50), expand=c(0,0)) +
theme_classic(base_size=12) +
theme(axis.line = element_blank(),
axis.ticks.length = unit(7,"pt"))
|
Q: How to make gap between x and y axis and protruded ticks in ggplot2 How can I create the following style of graph:
Notice the gap between x-y axis (red circle) and protruded ticks in x-y axis (arrow).
At best I can do is this now:
library(ggplot2)
p <- ggplot(mpg, aes(class, hwy)) +
geom_boxplot() +
theme_bw(base_size=10)
p
A: One option is to remove the built-in axis lines and then use geom_segment to add axes with a gap. In order to make it easier to get the broken axis lines in the right place, we also use scale_y_continuous to specify exactly where we want the axis breaks and limits. The code also shows how to increase the size of the tick marks.
ggplot(data=mpg, aes(class, hwy)) +
geom_segment(y=10, yend=50, x=0.4, xend=0.4, lwd=0.5, colour="grey30", lineend="square") +
geom_segment(y=5, yend=5, x=1, xend=length(unique(mpg$class)),
lwd=0.5, colour="grey30", lineend="square") +
geom_boxplot() +
scale_y_continuous(breaks=seq(10,50,10), limits=c(5,50), expand=c(0,0)) +
theme_classic(base_size=12) +
theme(axis.line = element_blank(),
axis.ticks.length = unit(7,"pt"))
A: You can achieve something similar using ggthemes which provides geom_rangeframe and theme_tufte.
library(ggplot2)
library(ggthemes)
ggplot(mpg, aes(class, hwy)) +
geom_boxplot() +
geom_rangeframe() +
theme_tufte() +
theme(axis.ticks.length = unit(7, "pt"))
More inspiration here.
A: Originally posted as an answer to a related question, I was encouraged to share my answer here as well.
The ggh4x package has a truncated axis guide that solves this problem by taking advantage of position guide customisation introduced in ggplot2 v3.3.0. Because it uses the guide system directly instead of working through a geom, it is responsive to theme settings just as regular axes. (Disclaimer: I'm the author of ggh4x).
By default, it truncates the axis to the outermost breaks, but this can be adjusted.
library(ggplot2)
library(ggh4x)
ggplot(mpg, aes(class, hwy)) +
geom_boxplot() +
guides(x = "axis_truncated", y = "axis_truncated") +
theme(axis.line = element_line(colour = "black"))
Created on 2021-04-19 by the reprex package (v1.0.0)
A: The bars on the top and bottom of the lines are added with
geom_errorbar(aes(ymin = lower, ymax = upper), width = 0.2)
or by adding geom to another layer.
stat_summary(fun.data = mean_sdl,
fun.args = list(mult = 1),
geom = "errorbar",
width = 0.1)
|
stackoverflow
|
{
"language": "en",
"length": 347,
"provenance": "stackexchange_0000F.jsonl.gz:890205",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621231"
}
|
cc462c2db10cb79c06971d3b0067186f77bedb4d
|
Stackoverflow Stackexchange
Q: Traversal over last element of 'filtered' I'm looking to filter a traversal, then select the last element to use with over.
e.g. something like this (but which will actually compile):
[1,2,3,4] & traverse . filtered even . _last +~ 10
> [1,2,3,14]
Any ideas?
P.S. I'm aware that filtered is only valid when not affecting the number of elements in the traversal.
The actual use case I'm performing is to select only the lowest level of a recursive uniplate traversal that matches some predicate; if you have other ideas of how to do this I'd love to hear them!
A: [1,2,3,4] & partsOf (traverse . filtered even) . _last +~ 10
|
Q: Traversal over last element of 'filtered' I'm looking to filter a traversal, then select the last element to use with over.
e.g. something like this (but which will actually compile):
[1,2,3,4] & traverse . filtered even . _last +~ 10
> [1,2,3,14]
Any ideas?
P.S. I'm aware that filtered is only valid when not affecting the number of elements in the traversal.
The actual use case I'm performing is to select only the lowest level of a recursive uniplate traversal that matches some predicate; if you have other ideas of how to do this I'd love to hear them!
A: [1,2,3,4] & partsOf (traverse . filtered even) . _last +~ 10
A: This isn't really an answer, just a follow-up to @Gurkenglas that's too big for a comment. Note that @Gurkenglas's answer:
let t = partsOf (traverse . filtered even) . _last
may look like a Traversal, but it isn't, even if you maintain the element count, because it violates the second Traversal law (for obvious reasons):
let f = Identity . succ
[1,2,3,4] & fmap (t f) . t f -- yields [1,3,3,5] effectively
[1,2,3,4] & getCompose . t (Compose . fmap f . f)
-- yields [1,2,3,6] effectively
For it to be a traversal, you have to maintain both the element count and the filtering property as invariants.
Whether this will matter for your application, I don't know, but just be aware that partsOf comes with these sorts of caveats, and the documentation misleadingly suggests that the result of partsOf will be a Lens if you maintain the element count. (That's true for partsOf each, the example given in the documentation, but not in general.)
|
stackoverflow
|
{
"language": "en",
"length": 278,
"provenance": "stackexchange_0000F.jsonl.gz:890239",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621325"
}
|
eae3b5e5515a61aaffdf47a650f133b1080f0c26
|
Stackoverflow Stackexchange
Q: Error: Cannot convert value of type 'URL' to expected argument type 'String' I'm having trouble converting URL to string. The getScreenShotDirectory() path is file:///Users/Pat/Desktop/.
My goal is to convert it to String, so the path can look like /Users/Pat/Desktop/
let urlString = getScreenShotDirectory()
let pathURL = URL(string: getScreenShotDirectory())! // error
I would gladly provide more code if needed.
A: It appears that your getScreenShotDirectory() method is already a URL. So you get the error trying to pass a URL to the URL(string:) method which, of course, expects a String, not a URL.
The simple solution is to properly convert the URL to a path string:
let pathURL = getScreenShotDirectory() // URL
let pathString = pathURL.path // String
|
Q: Error: Cannot convert value of type 'URL' to expected argument type 'String' I'm having trouble converting URL to string. The getScreenShotDirectory() path is file:///Users/Pat/Desktop/.
My goal is to convert it to String, so the path can look like /Users/Pat/Desktop/
let urlString = getScreenShotDirectory()
let pathURL = URL(string: getScreenShotDirectory())! // error
I would gladly provide more code if needed.
A: It appears that your getScreenShotDirectory() method is already a URL. So you get the error trying to pass a URL to the URL(string:) method which, of course, expects a String, not a URL.
The simple solution is to properly convert the URL to a path string:
let pathURL = getScreenShotDirectory() // URL
let pathString = pathURL.path // String
|
stackoverflow
|
{
"language": "en",
"length": 118,
"provenance": "stackexchange_0000F.jsonl.gz:890244",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621344"
}
|
9541d269fa21cba3b10c30ed2058aa924de9ab17
|
Stackoverflow Stackexchange
Q: Can Shake track number of threads used by build commands which are themselves parallel? Shake builds things in parallel when possible, but what happens if an individual build step is itself parallelizable? For example I'm running BLAST commands. Each command compares two species' genomes. Several comparisons could be run in parallel, but there's also a flag to split a comparison into N chunks and run those in parallel. Do I need to pick one way of splitting the jobs up and stick with it, or can I tell Shake "Use N threads overall, and by the way each of these specific tasks takes up N threads on its own"?
(This comes up when comparing many small bacterial genomes and a few bigger eukaryotic ones)
EDIT: the question can be simplified to "how to tell how many Shake threads are currently running/queued from within Shake?"
A: No, but there is a ticket to add it: https://github.com/ndmitchell/shake/issues/603
|
Q: Can Shake track number of threads used by build commands which are themselves parallel? Shake builds things in parallel when possible, but what happens if an individual build step is itself parallelizable? For example I'm running BLAST commands. Each command compares two species' genomes. Several comparisons could be run in parallel, but there's also a flag to split a comparison into N chunks and run those in parallel. Do I need to pick one way of splitting the jobs up and stick with it, or can I tell Shake "Use N threads overall, and by the way each of these specific tasks takes up N threads on its own"?
(This comes up when comparing many small bacterial genomes and a few bigger eukaryotic ones)
EDIT: the question can be simplified to "how to tell how many Shake threads are currently running/queued from within Shake?"
A: No, but there is a ticket to add it: https://github.com/ndmitchell/shake/issues/603
|
stackoverflow
|
{
"language": "en",
"length": 156,
"provenance": "stackexchange_0000F.jsonl.gz:890257",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621383"
}
|
48aa9611555fdb5a41440499708ec57cecf9e4b6
|
Stackoverflow Stackexchange
Q: is there a modern react listener for database changes Is there a modern React listener library for database changes? We need to implement some kind of real time communication with DB and be able to propagate DB changes to our clients. I heard about SignalR (just for ASP.NET?) but it seems Websockects could be the tech to go.
A: If you're willing to adapt your persistence layer, you can achieve automatic DB->Web synchronization with Firebase Realtime Database:
https://firebase.google.com/docs/database/
It's not React-specific, but the technologies work fine together (used them together myself). The Javascript-client uses Websockets behind the scenes.
|
Q: is there a modern react listener for database changes Is there a modern React listener library for database changes? We need to implement some kind of real time communication with DB and be able to propagate DB changes to our clients. I heard about SignalR (just for ASP.NET?) but it seems Websockects could be the tech to go.
A: If you're willing to adapt your persistence layer, you can achieve automatic DB->Web synchronization with Firebase Realtime Database:
https://firebase.google.com/docs/database/
It's not React-specific, but the technologies work fine together (used them together myself). The Javascript-client uses Websockets behind the scenes.
|
stackoverflow
|
{
"language": "en",
"length": 99,
"provenance": "stackexchange_0000F.jsonl.gz:890272",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621424"
}
|
a204807b5a77aa4f98fd6d2592a6cfad91204513
|
Stackoverflow Stackexchange
Q: Screen is blank white when started on the Xcode simulator [swift 3.0] The screen is blank white when my app is started, but will go to normal once the screen is touched.
The error below comes up:
ERROR /BuildRoot/Library/Caches/com.apple.xbs/Sources/VectorKit_Sim/VectorKit-1230.34.9.30.27/GeoGL/GeoGL/GLCoreContext.cpp 1763: InfoLog SolidRibbonShader:
ERROR /BuildRoot/Library/Caches/com.apple.xbs/Sources/VectorKit_Sim/VectorKit-1230.34.9.30.27/GeoGL/GeoGL/GLCoreContext.cpp 1764: WARNING: Output of vertex shader 'v_gradient' not read by fragment shader
How can I fix this?
A: Vertex Shaders generally run directly on the GPU for which it's compiled. In this case the iOS simulator doesn't physically have the GPU it needs to work with, hence the white screen.
Usually if you run the code on the physical device it should work, so try running there. Also check out this other question/answer with a similar error that might be of interest.
A vertex shader is simply a tiny program that runs on the GPU, written
in a C++ like language called the Metal Shading Language.
↳ Metal Shading Language Specification
|
Q: Screen is blank white when started on the Xcode simulator [swift 3.0] The screen is blank white when my app is started, but will go to normal once the screen is touched.
The error below comes up:
ERROR /BuildRoot/Library/Caches/com.apple.xbs/Sources/VectorKit_Sim/VectorKit-1230.34.9.30.27/GeoGL/GeoGL/GLCoreContext.cpp 1763: InfoLog SolidRibbonShader:
ERROR /BuildRoot/Library/Caches/com.apple.xbs/Sources/VectorKit_Sim/VectorKit-1230.34.9.30.27/GeoGL/GeoGL/GLCoreContext.cpp 1764: WARNING: Output of vertex shader 'v_gradient' not read by fragment shader
How can I fix this?
A: Vertex Shaders generally run directly on the GPU for which it's compiled. In this case the iOS simulator doesn't physically have the GPU it needs to work with, hence the white screen.
Usually if you run the code on the physical device it should work, so try running there. Also check out this other question/answer with a similar error that might be of interest.
A vertex shader is simply a tiny program that runs on the GPU, written
in a C++ like language called the Metal Shading Language.
↳ Metal Shading Language Specification
|
stackoverflow
|
{
"language": "en",
"length": 156,
"provenance": "stackexchange_0000F.jsonl.gz:890274",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621430"
}
|
185c2c4960ebcbc5e0ddccd259992f1878773d5f
|
Stackoverflow Stackexchange
Q: How to use fastlane behind proxy I can't find any option about fastlane to set the proxy. So does there has a direct way to solve this?
Thanks very much for any help!
A: I had the same problem and for me this site helped as fastlane is using Faraday internally. You have to set up the proxy environment variables for faraday with the following commands:
$ export http_proxy="http://proxy_host:proxy_port"
$ export https_proxy="https://proxy_host:proxy_port"
|
Q: How to use fastlane behind proxy I can't find any option about fastlane to set the proxy. So does there has a direct way to solve this?
Thanks very much for any help!
A: I had the same problem and for me this site helped as fastlane is using Faraday internally. You have to set up the proxy environment variables for faraday with the following commands:
$ export http_proxy="http://proxy_host:proxy_port"
$ export https_proxy="https://proxy_host:proxy_port"
A: Any of the Fastlane tools that use spaceship (i.e. the Apple APIs) can be proxied using a combination of three environment variables.
*
*SPACESHIP_PROXY: set the http proxy to use (SPACESHIP_PROXY =https://localhost:9090)
*SPACESHIP_PROXY_SSL_VERIFY_NONE: when present, disables SSL verification (to allow inspecting HTTPS requests)
*SPACESHIP_DEBUG: equivalent to SPACESHIP_PROXY=https://127.0.0.1:8888 SPACESHIP_PROXY_SSL_VERIFY_NONE=1, preconfigured for Charles Proxy defaults.
To use these, set them as environment variables in your shell, or prepend them to any fastlane command. For example, SPACESHIP_PROXY=https://localhost:9090 bundle exec fastlane
Source: Spaceship debugging documentation
|
stackoverflow
|
{
"language": "en",
"length": 155,
"provenance": "stackexchange_0000F.jsonl.gz:890275",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621432"
}
|
951286577db83cf37c1d9e19d9dee9ed0b7982cc
|
Stackoverflow Stackexchange
Q: Ubuntu - Debugging in CLion exits with code 127 I am running CLion 2017.1.3 on Ubuntu 16.04 LTS. When I click the "Debug"
button, the C++ project builds and then the debugger stops and exits with the error:
"During startup program exited with code 127.
Process finished with exit code 0"
I searched for this issue in StackOverflow and other forums but could not find any answer to resolve my issue. Please help me resolve this error.
A: The issue was because my SHELL variable was pointing to the wrong path. I found that out when I faced another issue of not being able to install any python packages using pip. When I googled that error, I happened to find out this SHELL variable issue.
Execute echo $SHELL in a terminal and check if it is a valid shell that you are using. I use the bash shell and hence changed it to /bin/bash using the command chsh -s /bin/bash root
Also, some debug libraries went missing, which I was able to restore using Ubuntu's Software Updater. Now, I am able to debug :)
|
Q: Ubuntu - Debugging in CLion exits with code 127 I am running CLion 2017.1.3 on Ubuntu 16.04 LTS. When I click the "Debug"
button, the C++ project builds and then the debugger stops and exits with the error:
"During startup program exited with code 127.
Process finished with exit code 0"
I searched for this issue in StackOverflow and other forums but could not find any answer to resolve my issue. Please help me resolve this error.
A: The issue was because my SHELL variable was pointing to the wrong path. I found that out when I faced another issue of not being able to install any python packages using pip. When I googled that error, I happened to find out this SHELL variable issue.
Execute echo $SHELL in a terminal and check if it is a valid shell that you are using. I use the bash shell and hence changed it to /bin/bash using the command chsh -s /bin/bash root
Also, some debug libraries went missing, which I was able to restore using Ubuntu's Software Updater. Now, I am able to debug :)
|
stackoverflow
|
{
"language": "en",
"length": 185,
"provenance": "stackexchange_0000F.jsonl.gz:890280",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621447"
}
|
0408950758bb6cc4a87e86510247aedff722fa4d
|
Stackoverflow Stackexchange
Q: hierarchical classification in sklearn I would like to know if there is an implementation of hierarchical classification in the scikit-learn package or in any other python package.
Thank you so much in advance.
A: I couldn't find an implementation of Hierarchical Classification on scikit-learn official documentation. But I found this repository recently. This module is based on scikit-learn's interfaces and conventions. I hope this will be useful.
https://github.com/globality-corp/sklearn-hierarchical-classification
|
Q: hierarchical classification in sklearn I would like to know if there is an implementation of hierarchical classification in the scikit-learn package or in any other python package.
Thank you so much in advance.
A: I couldn't find an implementation of Hierarchical Classification on scikit-learn official documentation. But I found this repository recently. This module is based on scikit-learn's interfaces and conventions. I hope this will be useful.
https://github.com/globality-corp/sklearn-hierarchical-classification
A: The globality-corp repo was deleted, but I found this fork, so I am posting it:
https://github.com/fbenites/sklearn-hierarchical-classification
As above, it is a module following the scikit-learn's conventions and is used along with sklearn classifiers.
|
stackoverflow
|
{
"language": "en",
"length": 103,
"provenance": "stackexchange_0000F.jsonl.gz:890281",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621452"
}
|
dff2becb5a9d522e73231bf1df40addfb94a7132
|
Stackoverflow Stackexchange
Q: How does Chromecast determine inactivity? I've made a Chromecast app that displays multiple quotes and the whole idea is to basically connect it to a spare tv/monitor you have lying around and use it to have inspirational quotes change on the screen.
But the problem is, Chromecast automatically times out and goes back to the home screen after every few minutes of inactivity. I'd like to find out how it detects inactivity so I can prevent this behavior and allow my app to keep running on the Chromecast indefinitely, as a sort of replacement for the original photo screensaver.
A: I figured out how to keep my app running. There is a property of CastReceiverOptions called disableIdleTimeout that can be set.
const options = new cast.framework.CastReceiverOptions();
options.disableIdleTimeout = true;
const instance = cast.framework.CastReceiverContext.getInstance();
instance.start(options);
With this set to true, the receiver no longer times out after 5 minutes.
|
Q: How does Chromecast determine inactivity? I've made a Chromecast app that displays multiple quotes and the whole idea is to basically connect it to a spare tv/monitor you have lying around and use it to have inspirational quotes change on the screen.
But the problem is, Chromecast automatically times out and goes back to the home screen after every few minutes of inactivity. I'd like to find out how it detects inactivity so I can prevent this behavior and allow my app to keep running on the Chromecast indefinitely, as a sort of replacement for the original photo screensaver.
A: I figured out how to keep my app running. There is a property of CastReceiverOptions called disableIdleTimeout that can be set.
const options = new cast.framework.CastReceiverOptions();
options.disableIdleTimeout = true;
const instance = cast.framework.CastReceiverContext.getInstance();
instance.start(options);
With this set to true, the receiver no longer times out after 5 minutes.
A: You may check the setInactivityTimeout method then use the maxInactivity parameter which is interval in seconds before closing an unresponsive connection.
The setInactivityTimeout(maxInactivity) sets the receiver inactivity timeout. It is recommended to set the maximum inactivity value when calling Start and not changing it. This API is just provided for development/debugging purposes.
You may also refer with this SO answer which stated that:
Timeout value cannot be adjusted by application. It would help us to understand what is causing the timeout in your case. Timeout happens when either the sender does not reply to the receiver's ping requests in a timely manner, or when the sender has not received a ping from the receiver for a certain length of time. It might be the case that the media you are trying to load is tying up the CPU on the receiver so that it can't send its ping request to the sender.
Hope this helps!
|
stackoverflow
|
{
"language": "en",
"length": 305,
"provenance": "stackexchange_0000F.jsonl.gz:890289",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621478"
}
|
2b302292f90d4424390153b75c82d93b21876bb3
|
Stackoverflow Stackexchange
Q: Does RawSocket in Dart allow to send and receive directly IP packets? As I know raw socket allows to send and receive IP packets without any specific transport layer protocol.
Dart's "dart:io" comes with RawSocket class defined as a low-level interface to a socket (maybe they mean TCP socket).
My question is does Dart's RawSocket allow to directly send and receive IP packets? if not, is there're any way to do so in Dart?
A: As far as I know, there is no possible way to directly send and receive IP packets in Dart. RawSocket and its variants shouldn't be confused with what are known as raw sockets, as they just expose raw events signaled by the system. The fact that these socket classes have the Raw prefix is just the result of an unfortunate naming choice.
|
Q: Does RawSocket in Dart allow to send and receive directly IP packets? As I know raw socket allows to send and receive IP packets without any specific transport layer protocol.
Dart's "dart:io" comes with RawSocket class defined as a low-level interface to a socket (maybe they mean TCP socket).
My question is does Dart's RawSocket allow to directly send and receive IP packets? if not, is there're any way to do so in Dart?
A: As far as I know, there is no possible way to directly send and receive IP packets in Dart. RawSocket and its variants shouldn't be confused with what are known as raw sockets, as they just expose raw events signaled by the system. The fact that these socket classes have the Raw prefix is just the result of an unfortunate naming choice.
|
stackoverflow
|
{
"language": "en",
"length": 138,
"provenance": "stackexchange_0000F.jsonl.gz:890303",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621512"
}
|
97644df1d29e95dd0d205825735a07ecd9d1ae1a
|
Stackoverflow Stackexchange
Q: Is there a way for countof() to test if its argument is an array? A classic macro to compute the number of elements in an array is this:
#define countof(a) (sizeof(a) / sizeof(*(a)))
The problem with this is it fails silently if the argument is a pointer instead of an array. Is there a portable way to ensure this macro is only used with an actual array by generating a compile time error if a is not an array?
EDIT: my question seems to be a duplicate of this one: Array-size macro that rejects pointers
A: Using a non-portable built-in function, here is a macro to perform a static assertion that a is an array:
#define assert_array(a) \
(sizeof(char[1 - 2 * __builtin_types_compatible_p(typeof(a), typeof(&(a)[0]))]) - 1)
It works with both gcc and clang. I use it to make the countof() macro safer:
#define countof(a) (sizeof(a) / sizeof(*(a)) + assert_array(a))
But I don't have a portable solution for this problem.
|
Q: Is there a way for countof() to test if its argument is an array? A classic macro to compute the number of elements in an array is this:
#define countof(a) (sizeof(a) / sizeof(*(a)))
The problem with this is it fails silently if the argument is a pointer instead of an array. Is there a portable way to ensure this macro is only used with an actual array by generating a compile time error if a is not an array?
EDIT: my question seems to be a duplicate of this one: Array-size macro that rejects pointers
A: Using a non-portable built-in function, here is a macro to perform a static assertion that a is an array:
#define assert_array(a) \
(sizeof(char[1 - 2 * __builtin_types_compatible_p(typeof(a), typeof(&(a)[0]))]) - 1)
It works with both gcc and clang. I use it to make the countof() macro safer:
#define countof(a) (sizeof(a) / sizeof(*(a)) + assert_array(a))
But I don't have a portable solution for this problem.
A: In C11 you could use _Static_assert in conjunction with _Generic, but you'll also need to provide type info, which I see as a good thing as it provides extra granularity; you get the ability to assert based on element type, as well as whether it's an array or not from _Generic, and you get a nice friendly message from _Static_assert... For example:
assert_array_type.c:6:33: error: static assertion failed: "expected array of int; got (char[42]){0}"
assert_array_type.c:6:33: error: static assertion failed: "expected array of int; got (int *){0}"
These errors are produced by the following testcase, depending upon how you compile:
#define array_type(a, T) _Generic(a, T *: _Generic(&a, T **: 0 \
, default: 1)\
, default: 0)
#define assert_array_type(a, T) _Static_assert(array_type(a, T), "expected array of " #T "; got " #a)
int main(void) {
assert_array_type((int [42]){0}, int); // this should pass
# if defined(TEST_POINTER_FAIL)
assert_array_type((int * ){0}, int); // this should fail
# endif
# if defined(TEST_ELEMENT_FAIL)
assert_array_type((char[42]){0}, int); // this should fail
# endif
}
The two testcases can observed by defining TEST_POINTER_FAIL and/or TEST_ELEMENT_FAIL, i.e.
*
*cc -std=c11 -D'TEST_POINTER_FAIL' should cause an assertion failure at compilation time due to the fact that a pointer is passed, rather than an array.
*cc -std=c11 -D'TEST_ELEMENT_FAIL' should cause an assertion failure at compilation time due to the fact that the array is meant to be an array of int, rather than an array of char.
A: AFAIK, to make it generic in >=C11, you only need __typeof as a nonstandard extension:
#define STATICALLY_ENFORCE_TYPES_NOT_COMPATIBLE(X,Y) \
sizeof((char){_Generic((__typeof(X)*){0}, \
__typeof(__typeof(Y)*):(void)0,default:1)})
#define ARRAY_SIZEOF(X) \
((!STATICALLY_ENFORCE_TYPES_NOT_COMPATIBLE(X, &(X)[0]))?0:sizeof(X))
#define countof(X) (ARRAY_SIZEOF(X)/sizeof(*(X)))
|
stackoverflow
|
{
"language": "en",
"length": 423,
"provenance": "stackexchange_0000F.jsonl.gz:890313",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621553"
}
|
4ebeb776f5d7ddced82352189eda39525cda755e
|
Stackoverflow Stackexchange
Q: How to check that scroll is end of bottom in Angular 4? @HostListener('window:scroll', ['$event'])
onWindowScroll() {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
console.log('reached bottom');
}
}
It is working of this code as above, but it occured many times even not reached exactly end of bottom.
How to check wheather scroll is reached to end of bottom?
A: if (window.innerHeight + window.scrollY === document.body.scrollHeight) {
console.log('bottom');
}
I found it.
|
Q: How to check that scroll is end of bottom in Angular 4? @HostListener('window:scroll', ['$event'])
onWindowScroll() {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
console.log('reached bottom');
}
}
It is working of this code as above, but it occured many times even not reached exactly end of bottom.
How to check wheather scroll is reached to end of bottom?
A: if (window.innerHeight + window.scrollY === document.body.scrollHeight) {
console.log('bottom');
}
I found it.
A: This worked for me.
import { HostListener } from '@angular/core';
@HostListener('window:scroll', ['$event'])
onWindowScroll(event) {
// 200 is the height from bottom from where you want to trigger the infintie scroll, which can also be zero to detect bottom of window
if ((document.body.clientHeight + window.scrollY + 200) >= document.body.scrollHeight) {
console.log('triggred');
}
}
|
stackoverflow
|
{
"language": "en",
"length": 125,
"provenance": "stackexchange_0000F.jsonl.gz:890377",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621743"
}
|
8d8f022f2360e806ed0a0bdb6417dab8d85f56f5
|
Stackoverflow Stackexchange
Q: How do I ssh to nodes in ACS Kubernetes cluster? I have created an ACS Kubernetes cluster following the instructions here: https://learn.microsoft.com/en-us/azure/container-service/container-service-kubernetes-walkthrough .
I see that master node has a public IP and I can ssh into the master node using azureuser. But regular nodes has no public IP and I don't see how I can ssh into regular nodes from master node.
How do I SSH into the regular nodes?
A: You can use one of the k8s masters as a "bastion host" and avoid copying the keys over. Eg:
# In ~/.ssh/config
Host agent1_private_ip agent2_private_ip ....
IdentityFile ~/.ssh/<your_k8s_cluster_key>
ProxyCommand ssh user@master_public_ip -W %h:%p
Now just ssh user@agent1_private_ip
See more here: http://blog.scottlowe.org/2015/11/21/using-ssh-bastion-host/
PS: Here's a quickie to retrieve your agent private ips, in /etc/hosts format:
kubectl get nodes -o json | jq -r '.items[].status.addresses[].address' | paste - -
|
Q: How do I ssh to nodes in ACS Kubernetes cluster? I have created an ACS Kubernetes cluster following the instructions here: https://learn.microsoft.com/en-us/azure/container-service/container-service-kubernetes-walkthrough .
I see that master node has a public IP and I can ssh into the master node using azureuser. But regular nodes has no public IP and I don't see how I can ssh into regular nodes from master node.
How do I SSH into the regular nodes?
A: You can use one of the k8s masters as a "bastion host" and avoid copying the keys over. Eg:
# In ~/.ssh/config
Host agent1_private_ip agent2_private_ip ....
IdentityFile ~/.ssh/<your_k8s_cluster_key>
ProxyCommand ssh user@master_public_ip -W %h:%p
Now just ssh user@agent1_private_ip
See more here: http://blog.scottlowe.org/2015/11/21/using-ssh-bastion-host/
PS: Here's a quickie to retrieve your agent private ips, in /etc/hosts format:
kubectl get nodes -o json | jq -r '.items[].status.addresses[].address' | paste - -
A: You could copy the private key to your master VM. Then you could use ssh -i <path>/id_rsa user@<agent private IP> to k8s agent VM.
Note: agent's user name and private key is same with master VM.
A: Microsoft has released official docs at https://learn.microsoft.com/en-us/azure/aks/ssh. The idea is to SSH into an interactive POD session and use that as jump host to the agent node.
|
stackoverflow
|
{
"language": "en",
"length": 205,
"provenance": "stackexchange_0000F.jsonl.gz:890387",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621763"
}
|
e365407b5ade72b2916f4864864794dd7f92d2eb
|
Stackoverflow Stackexchange
Q: Angular - How to get current url in app component I am trying to get current url of application in AppComponent but it always returns the root path /. Example, if I visit /users in new tab, the expected result should be /users, but when I check in the console, it shows
/.
However, it works when I do the same in a child component. Below are my code:
import {Component} from '@angular/core'
import {ActivatedRoute, Router} from '@angular/router'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['app.component.scss'],
})
export class AppComponent {
constructor(router: Router) {
console.log(this.router.url) // return '/'
}
}
How is that possible?
A: In Angular 4, you can get the full path string from within app.component.ts by using the Location module.
Eg, In your browser, when you navigate to "http://yoursite.com/products/cars?color=red&model=202", the code below will output pathString "/products/cars?color=red&model=202".
In app.component.ts
import { Component } from '@angular/core';
import { Router} from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'app';
constructor(
private location: Location
) {
var pathString = location.path();
console.log('appComponent: pathString...');
console.log(pathString);
}
}
*Credit: https://tutorialedge.net/post/typescript/angular/angular-get-current-route-location/
|
Q: Angular - How to get current url in app component I am trying to get current url of application in AppComponent but it always returns the root path /. Example, if I visit /users in new tab, the expected result should be /users, but when I check in the console, it shows
/.
However, it works when I do the same in a child component. Below are my code:
import {Component} from '@angular/core'
import {ActivatedRoute, Router} from '@angular/router'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['app.component.scss'],
})
export class AppComponent {
constructor(router: Router) {
console.log(this.router.url) // return '/'
}
}
How is that possible?
A: In Angular 4, you can get the full path string from within app.component.ts by using the Location module.
Eg, In your browser, when you navigate to "http://yoursite.com/products/cars?color=red&model=202", the code below will output pathString "/products/cars?color=red&model=202".
In app.component.ts
import { Component } from '@angular/core';
import { Router} from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'app';
constructor(
private location: Location
) {
var pathString = location.path();
console.log('appComponent: pathString...');
console.log(pathString);
}
}
*Credit: https://tutorialedge.net/post/typescript/angular/angular-get-current-route-location/
A: you can subscribe to router.events and filter for NavigationEnd event to get the current active route url.
this.router.events.subscribe((e) => {
if (e instanceof NavigationEnd) {
console.log(e.url);
}
});
mention this will fail if that's no valid router defined.
A: If you want to get the current url, use the ActivatedRoute instead.
In your constructor add it like this
constructor(
private router: Router,
private route: ActivatedRoute) {
route.params.subscribe(p => {
//let's say you want to get id parameter.
console.log(p['id']);
});
}
A: for the very first access to the SPA, it seems that the current url app is not always accessible through an Angular way. No route has been loaded yet, but you still may need to access the requested url for some internal processes.
So I did this :
let strings = window.location.href.split(window.location.host);
let url = strings[strings.length-1];
A: you recursively iterate parent property until you reach topmost element which corresponds to root of your app.
|
stackoverflow
|
{
"language": "en",
"length": 346,
"provenance": "stackexchange_0000F.jsonl.gz:890428",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44621887"
}
|
4c89fb0eea6fd9cf9db53e1ab3317e7ca8f09c15
|
Stackoverflow Stackexchange
Q: Mark a function as deprecated in customised R package I built my first R package months ago and I now realise some of my older functions are looking a bit dated. I'm already writing better functions to replace them.
I've seen how other R packages warn of deprecated functions, and redirect users to the newer functions. I want to do the same.
How do I mark a function as deprecated in R? Do I just set a warning?
A: The answer is to call the .Deprecated function from base R:
f_old = function(x) {
.Deprecated("f_new")
return(x * x)
}
f_new = function(x) {
return(x^2)
}
This will give the appropriate warning:
> f_old(4)
[1] 16
Warning message:
'f_old' is deprecated.
Use 'f_new' instead.
See help("Deprecated")
|
Q: Mark a function as deprecated in customised R package I built my first R package months ago and I now realise some of my older functions are looking a bit dated. I'm already writing better functions to replace them.
I've seen how other R packages warn of deprecated functions, and redirect users to the newer functions. I want to do the same.
How do I mark a function as deprecated in R? Do I just set a warning?
A: The answer is to call the .Deprecated function from base R:
f_old = function(x) {
.Deprecated("f_new")
return(x * x)
}
f_new = function(x) {
return(x^2)
}
This will give the appropriate warning:
> f_old(4)
[1] 16
Warning message:
'f_old' is deprecated.
Use 'f_new' instead.
See help("Deprecated")
|
stackoverflow
|
{
"language": "en",
"length": 126,
"provenance": "stackexchange_0000F.jsonl.gz:890480",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44622054"
}
|
0fe847b3582529876573ec179c46876703e8f08d
|
Stackoverflow Stackexchange
Q: Test Google Adwords Server-to-server conversion tracking I am currently implementing server-to-server conversion tracking using this api: https://developers.google.com/app-conversion-tracking/api however I don't see any way to generate test ad clicks to test if it's working or not.. Does anyone know how to test this?
|
Q: Test Google Adwords Server-to-server conversion tracking I am currently implementing server-to-server conversion tracking using this api: https://developers.google.com/app-conversion-tracking/api however I don't see any way to generate test ad clicks to test if it's working or not.. Does anyone know how to test this?
|
stackoverflow
|
{
"language": "en",
"length": 43,
"provenance": "stackexchange_0000F.jsonl.gz:890506",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44622167"
}
|
2f1ba88ff529dcae096dd0d8c6ed74e5dac431dd
|
Stackoverflow Stackexchange
Q: Python 3.6 No module named pip I have just installed Python 3.6 on Fedora 25 (64 bits) by running dnf install python36 and I can't use any modules Python 3.5 can otherwise use just fine, for example, PyCharm complains about setup tools not being installed, also I can run python3 and issue:
import aiohttp
However, if run python36 and then:
import aiohttp
I instead get:
Traceback (most recent call last): File "", line 1, in
ModuleNotFoundError: No module named 'aiohttp'
Pip is also not present on python36, as python36 -m pip throws:
/usr/bin/python36: No module named pip
I have to note that I've got python 3.4, 3.5 and 3.6 installed at the same time, both 3.4 and 3.5 working just fine
A: In Debian distributions, you can run
sudo apt-get install python-pip ##for python2
sudo apt-get install python3-pip ##for python3
|
Q: Python 3.6 No module named pip I have just installed Python 3.6 on Fedora 25 (64 bits) by running dnf install python36 and I can't use any modules Python 3.5 can otherwise use just fine, for example, PyCharm complains about setup tools not being installed, also I can run python3 and issue:
import aiohttp
However, if run python36 and then:
import aiohttp
I instead get:
Traceback (most recent call last): File "", line 1, in
ModuleNotFoundError: No module named 'aiohttp'
Pip is also not present on python36, as python36 -m pip throws:
/usr/bin/python36: No module named pip
I have to note that I've got python 3.4, 3.5 and 3.6 installed at the same time, both 3.4 and 3.5 working just fine
A: In Debian distributions, you can run
sudo apt-get install python-pip ##for python2
sudo apt-get install python3-pip ##for python3
A: sudo dnf install python3
Try this.
A: On Fedora 25 Python 3.6 comes as a minimalistic version without pip and without additional dnf installable modules.
But you can manually install pip:
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
After that you can use it as python3.6 -m pip or just pip3.6.
|
stackoverflow
|
{
"language": "en",
"length": 191,
"provenance": "stackexchange_0000F.jsonl.gz:890511",
"question_score": "52",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44622182"
}
|
7175b853d74564afd0451647f4df7948b8cca12d
|
Stackoverflow Stackexchange
Q: How to Install Python 3.6 along with Python 2.7? Python Newbie here. I just bought a new Mac that came with Python 2.7. I'm using the older version of Python for a class so I need to keep it. I want to install the latest version of Python, 3.6, side by side the older version. The instruction I found online were either outdated or confusing. Can anyone point me in the right direction?
A: You can use brew to install python3.
$ brew install python3
$ python # to start the python 2.7
$ python3 # to start the python 3
This is the simplest way to get started with python 3 on macOS.
|
Q: How to Install Python 3.6 along with Python 2.7? Python Newbie here. I just bought a new Mac that came with Python 2.7. I'm using the older version of Python for a class so I need to keep it. I want to install the latest version of Python, 3.6, side by side the older version. The instruction I found online were either outdated or confusing. Can anyone point me in the right direction?
A: You can use brew to install python3.
$ brew install python3
$ python # to start the python 2.7
$ python3 # to start the python 3
This is the simplest way to get started with python 3 on macOS.
A: if you download anaconda, a very common download for python development, you get a great package manager and a very easy way to create sandboxed environments. After downloading anaconda (for your current Python, so 2.7), you can open up your terminal and enter:
conda create my_new_env_name python=3.6
that will create a new sandboxed environment with python3.6. to use that environment, enter in your shell
source active my_new_env_name
now if you enter python from the shell you're in python3.6, or you can run python somefile.py from the shell to run it in python3.6
This is a great way to maintain and manage different versions of libraries on your system as well. For example, if you need an old version of a specific Python library for a particular project, but don't want to downgrade that library for all your Python code.
More on managing conda environments at the documentation page
A: There is one more way of having multiple python versions, using virtual environment.
step1: Download python versions you want to run.
step2: virtualenv -p {python_location} {env_name}
step3: (for mac) . env_name/bin/activate
For example (Running Python 3.6):
~ abhinavkumar$ virtualenv -p /usr/local/bin/python3.6 py36
Running virtualenv with interpreter /usr/local/bin/python3.6
Using base prefix '/Library/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/abhinavkumar/py36/bin/python3.6
Also creating executable in /Users/abhinavkumar/py36/bin/python
Installing setuptools, pip, wheel...done.
~ abhinavkumar$ . py36/bin/activate
(py36) ~ abhinavkumar$ which python
/Users/abhinavkumar/py36/bin/python
Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Running python 2.7
~ abhinavkumar$ virtualenv -p /usr/bin/python2.7 py27
Running virtualenv with interpreter /usr/bin/python2.7
New python executable in /Users/abhinavkumar/py27/bin/python
Installing setuptools, pip, wheel...done.
~ abhinavkumar$ . py27/bin/activate
(py27) ~ abhinavkumar$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
You don't need to do this everytime, this is one time job. Once created you just have activate it and once done you can deactivate.
Additionally working with virtualenv help you to segregate your different packages versions, without messing up with your systems settings.
A: If you are using Ubuntu 17.10 python 3 is already installed.
You can invoke it by typing python3.
If you already installed python 2, by typing python --version it shows python 2 version
and by typing python3 --version it shows python 3 version.
so we can use both versions
|
stackoverflow
|
{
"language": "en",
"length": 507,
"provenance": "stackexchange_0000F.jsonl.gz:890513",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44622189"
}
|
11c46bb3210f9bc86b1ee3b281ae0403c2b2788f
|
Stackoverflow Stackexchange
Q: Is there something like AlarmManager in Flutter? I need to schedule the execution of some lines of code in the future just as AlarmManager does. That is:
*
*Schedule your application to be run at some point in the future.
*Automatically start the target application if it is not already running.
*Wake up the device if it is asleep.
Of course I would need to have support for iOS.
I found scheduled_notifications but it doesn't seem to cover all these conditions.
Any help is very welcome.
A: As of late 2017 we now have an android_alarm_manager package for accessing the Android AlarmManager service, and running Dart code in the background when alarms fire.
|
Q: Is there something like AlarmManager in Flutter? I need to schedule the execution of some lines of code in the future just as AlarmManager does. That is:
*
*Schedule your application to be run at some point in the future.
*Automatically start the target application if it is not already running.
*Wake up the device if it is asleep.
Of course I would need to have support for iOS.
I found scheduled_notifications but it doesn't seem to cover all these conditions.
Any help is very welcome.
A: As of late 2017 we now have an android_alarm_manager package for accessing the Android AlarmManager service, and running Dart code in the background when alarms fire.
A: Flutter doesn't currently provide a mechanism to run Dart code in the background without a FlutterView. Follow issue 3671 for updates.
You probably don't want to launch your main activity immediately when the alarm goes off, because that would be very disruptive, so your best bet for the moment is probably to solve this problem using regular Java and Objective-C code in the standard way.
|
stackoverflow
|
{
"language": "en",
"length": 180,
"provenance": "stackexchange_0000F.jsonl.gz:890536",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44622237"
}
|
fac6a3de934a4c64f76f8c63686a3e7ea04090dd
|
Stackoverflow Stackexchange
Q: How can I call OnActivityResult inside Fragment and how it work? I want to know is it possible on onActivityResult()to use inside Fragment and if yes then how it works please explain with example.
A: Yes you can use OnActivityResult inside Fragment.like this
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//super.onActivityResult(requestCode, resultCode, intent);
// perform your action here
}
EDIT
The for more information check this old question
https://stackoverflow.com/a/17085889/7666442
|
Q: How can I call OnActivityResult inside Fragment and how it work? I want to know is it possible on onActivityResult()to use inside Fragment and if yes then how it works please explain with example.
A: Yes you can use OnActivityResult inside Fragment.like this
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//super.onActivityResult(requestCode, resultCode, intent);
// perform your action here
}
EDIT
The for more information check this old question
https://stackoverflow.com/a/17085889/7666442
A: Use this code in the activity.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Fragment fragment = (Fragment) getSupportFragmentManager().findFragmentByTag(childTag);
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, intent);
}
}
A: Within your fragment, you need to call:
startActivityForResult(myIntent, MY_INTENT_REQUEST_CODE);
where myIntent is the intent you already defined, and MY_INTENT_REQUEST_CODE is the int constant you defined in this fragment as a global variable as the request code for this intent.
And then, still inside your fragment, you need to override this method:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data); comment this unless you want to pass your result to the activity.
}
A: Definitely it will work, It will work same like in activities. You have call startActivityForResult(intent, requestCode);
and normally get result in
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
A: if you call startActivityForResult() in fragment , result is delivered to parent activity.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);//will deliver result to desired fragment.
}
How is works
if you see requestCode in activity it will be like 655545, now
super.onActivityResult () will calculate desired fragment and request code.
if your fragment in ViewPager desired fragment index is found using
requestCode>>16
and requestCode is found by requestCode&0xffff.
A: In kotlin: - I can explain using two classes. if user go from one Activity to Another Activty and in back want data then this code help you
In class Abc
startActivityForResult(Intent(context, Bcd::class.java), 141)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 141) {
if (data!!.extras.get("add").equals("safal")) {
Log.e("Print Name",data!!.extras.get("add"))
}
}
}
In Class Bcd
val intent = Intent()
intent.putExtra("add", "safal")
setResult(Activity.RESULT_OK, intent)
A: you can call onActivityResult inside a Fragment in android studio 3.5 with ease
, first, there should be an activity where you are coming to get result . OnActivity result means it has to give a resultant view when prompted.
Now in the previous activity lets say
first is an activity and the other is a fragment in the second activity
Xml code for first activity may be like the following:
<RelativeLayout
xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_alignParentTop="true"
android:layout_marginTop="48dp"
android:text="Default Message" />
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:text="GetMessage" />
</RelativeLayout>
Xml code for second will be
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".SecondActivity" >
<EditText
android:id="@+id/et1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="61dp"
android:layout_toRightOf="@+id/textView1"
android:ems="10" />
<TextView
android:id="@+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="Enter Message:" />
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp"
android:text="Submit" />
</RelativeLayout>
Now we will add startActivityForResult() method and onActivityResult() method
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
if (message!=null){
profileNameText.setText(message);
}
}
}
@Override
public void onClick(View v) {
Intent i ;
switch (v.getId()){
case R.id.profile_option_menu:
Log.i("profileclicked","profile_menu_image_clicked()");
PopupMenu popupMenu = new PopupMenu(getActivity(),v);
MenuInflater inflater = popupMenu.getMenuInflater();
inflater.inflate(R.menu.profile_menu,popupMenu.getMenu());
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new
PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent i;
switch (item.getItemId()) {
case R.id.edit_det:
i = new Intent(getActivity().getApplicationContext(),
FirstActivity.class);
startActivityForResult(i, 2);
return true;
default:
return onOptionsItemSelected(item);
}
}
});
break;
}
}
the code for the first activity class will be like this
public class FirstActivity extends Activity {
EditText editText1;
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
editText1=(EditText)findViewById(R.id.et1);
button1=(Button)findViewById(R.id.b1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String message=editText1.getText().toString();
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(2,intent);
finish();//finishing activity
}
});
}
Here I am writing a method setResult(2, intent) where 2 is result code which will be checked inside fragment in first activity class it will check the result code and and if the condition satifies then it will change the text inside the TextView .
A: In Kotlin we can do this in a very simplistic way as followings:
In ExampleFragment.kt, let start activity to pic an image.
private val REQUEST_CODE_GALLERY = 101
private fun openGallery() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
requireActivity().startActivityFromFragment(this, intent, REQUEST_CODE_GALLERY)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_GALLERY) {
Log.d("TAG", "${data.toString()}")
}
}
Hope, this will be helpful!
|
stackoverflow
|
{
"language": "en",
"length": 767,
"provenance": "stackexchange_0000F.jsonl.gz:890553",
"question_score": "30",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44622311"
}
|
470b7dfee6acb4cbb9d24cccc72be9202a4c9f5f
|
Stackoverflow Stackexchange
Q: Working with Python, files I have some data files which I need to read. I know I should use Dataset, but is there a way how to download these files without downloading them manually but by its URL? How would it look like in my case. I am working with conda-python and netCDF4. Whatever I do I cannot read these files. Sorry for my English. The source is http://meop40.troja.mff.cuni.cz:11180/gw.projekt/data.stratopauza/netcdf.profily/
My first try:
from netCDF4 import Dataset
import numpy as np
my_example_nc_file = '/Users/Leif/Downloads/my_example_nc_data.nc'
fh = Dataset(my_example_nc_file, mode='r')
Another Try:
from mpl_toolkits.basemap import Basemap, shiftgrid, cm
import numpy as np
import matplotlib.pyplot as plt
from netCDF4 import Dataset
url = 'http://meop40.troja.mff.cuni.cz:11180/gw.projekt/data.stratopauza/netcdf.profily/atmPrf_C001.2010.227.00.03.G04_2013.3520_nc '
etopodata = Dataset(url) **Error**
A: Maybe save the contents to a temporary file?
import urllib.request
response = urllib.request.urlopen(url)
with open("./tempfile", "w") as f:
f.write(response.read())
Now the file ./tempfile can be used normally
|
Q: Working with Python, files I have some data files which I need to read. I know I should use Dataset, but is there a way how to download these files without downloading them manually but by its URL? How would it look like in my case. I am working with conda-python and netCDF4. Whatever I do I cannot read these files. Sorry for my English. The source is http://meop40.troja.mff.cuni.cz:11180/gw.projekt/data.stratopauza/netcdf.profily/
My first try:
from netCDF4 import Dataset
import numpy as np
my_example_nc_file = '/Users/Leif/Downloads/my_example_nc_data.nc'
fh = Dataset(my_example_nc_file, mode='r')
Another Try:
from mpl_toolkits.basemap import Basemap, shiftgrid, cm
import numpy as np
import matplotlib.pyplot as plt
from netCDF4 import Dataset
url = 'http://meop40.troja.mff.cuni.cz:11180/gw.projekt/data.stratopauza/netcdf.profily/atmPrf_C001.2010.227.00.03.G04_2013.3520_nc '
etopodata = Dataset(url) **Error**
A: Maybe save the contents to a temporary file?
import urllib.request
response = urllib.request.urlopen(url)
with open("./tempfile", "w") as f:
f.write(response.read())
Now the file ./tempfile can be used normally
|
stackoverflow
|
{
"language": "en",
"length": 144,
"provenance": "stackexchange_0000F.jsonl.gz:890555",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44622315"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.