id
stringlengths 40
40
| text
stringlengths 29
2.03k
| original_text
stringlengths 3
154k
| subdomain
stringclasses 20
values | metadata
dict |
---|---|---|---|---|
9948243ad0f7d6b3fba28bdbb066a3dd1e0a204e | Stackoverflow Stackexchange
Q: could not find gradle 3.0.0-alpha4 a few days ago i have installed android studio 3.0 (preview) and after that in stable version (studio 2.3.3) when i try to import project it give me an error.
In preview everything works fine.
this is an error:
Error:Could not find com.android.tools.build:gradle:3.0.0-alpha4.
Searched in the following locations:
file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha4/gradle-3.0.0-alpha4.pom
file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha4/gradle-3.0.0-alpha4.jar
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha4/gradle-3.0.0-alpha4.pom
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha4/gradle-3.0.0-alpha4.jar
Required by:
project :
A:
If you're opening an existing project using Android Studio 3.0 Preview
1 or later, follow the prompts to automatically update your project to
the latest version of the Android plugin. To manually update your
project, include the maven repo and change the plugin version in your
project-level build.gradle file as follows:
Open your Project level build.gradle Section .
You should add maven { url 'https://maven.google.com' } .
Example
buildscript {
repositories {
jcenter()
// You need to add the following repository to download the new plugin.
maven { url 'https://maven.google.com' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha4' // Same for alpha6
}
}
allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
}
}
| Q: could not find gradle 3.0.0-alpha4 a few days ago i have installed android studio 3.0 (preview) and after that in stable version (studio 2.3.3) when i try to import project it give me an error.
In preview everything works fine.
this is an error:
Error:Could not find com.android.tools.build:gradle:3.0.0-alpha4.
Searched in the following locations:
file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha4/gradle-3.0.0-alpha4.pom
file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha4/gradle-3.0.0-alpha4.jar
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha4/gradle-3.0.0-alpha4.pom
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha4/gradle-3.0.0-alpha4.jar
Required by:
project :
A:
If you're opening an existing project using Android Studio 3.0 Preview
1 or later, follow the prompts to automatically update your project to
the latest version of the Android plugin. To manually update your
project, include the maven repo and change the plugin version in your
project-level build.gradle file as follows:
Open your Project level build.gradle Section .
You should add maven { url 'https://maven.google.com' } .
Example
buildscript {
repositories {
jcenter()
// You need to add the following repository to download the new plugin.
maven { url 'https://maven.google.com' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha4' // Same for alpha6
}
}
allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
}
}
A: A better way may be just to use
buildscript {
repositories {
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
}
}
| stackoverflow | {
"language": "en",
"length": 202,
"provenance": "stackexchange_0000F.jsonl.gz:897920",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44645099"
} |
56315cb502e6a5f696e661e23540e4467acb5194 | Stackoverflow Stackexchange
Q: RxSwift - multiple Observable value within one Observable I want to make a function like this example.
example
let num1 = Driver<Int>
let num2 = Driver<Int>
let result = Driver<String>
num1 = Observable.just(...).asDriver()
num2 = Observable.just(...).asDriver()
result = ??? // When both num1 and num2 are subscribed, this becomes a higher value among them as String.
// This type of code will be used
/*
if $0 >= $1 {
return "num1 = \($0)"
} else {
return "num2 = \($1)"
}
*/
How to implement it?
A: Don't use a Variable if you can help it. You already have a couple of observables so use them, but yes, combineLatest is the solution here:
import RxSwift
let num1 = Observable.just(3)
let num2 = Observable.just(5)
let result = Observable.combineLatest(num1, num2).map { $0 >= $1 ? "num1 = \($0)" : "num2 = \($1)" }
_ = result.subscribe(onNext: { print($0) })
The above prints "num2 = 5" when it's placed in a properly configured playground.
| Q: RxSwift - multiple Observable value within one Observable I want to make a function like this example.
example
let num1 = Driver<Int>
let num2 = Driver<Int>
let result = Driver<String>
num1 = Observable.just(...).asDriver()
num2 = Observable.just(...).asDriver()
result = ??? // When both num1 and num2 are subscribed, this becomes a higher value among them as String.
// This type of code will be used
/*
if $0 >= $1 {
return "num1 = \($0)"
} else {
return "num2 = \($1)"
}
*/
How to implement it?
A: Don't use a Variable if you can help it. You already have a couple of observables so use them, but yes, combineLatest is the solution here:
import RxSwift
let num1 = Observable.just(3)
let num2 = Observable.just(5)
let result = Observable.combineLatest(num1, num2).map { $0 >= $1 ? "num1 = \($0)" : "num2 = \($1)" }
_ = result.subscribe(onNext: { print($0) })
The above prints "num2 = 5" when it's placed in a properly configured playground.
A: You can use RxSwift Variable here instead of the Driverand to to listen on the two Observables, you can use Observable.combineLatest(..)
method.
Below is an example how you can achieve it:
let num1: Variable<Int>!
let num2: Variable<Int>!
let bag = DisposeBag()
num1 = Variable(1)
num2 = Variable(2)
let result = Observable.combineLatest(num1.asObservable(), num2.asObservable()) { (n1, n2) -> String in
if n1 >= n2 {
return "num1 = \(n1)"
} else {
return "num2 = \(n2)"
}
}
result.subscribe(onNext: { (res) in
print("Result \(res)")
}).addDisposableTo(bag)
num1.value = 5
num1.value = 8
num2.value = 10
num2.value = 7
It outputs:
Result num2 = 2
Result num1 = 5
Result num1 = 8
Result num2 = 10
Result num1 = 8
| stackoverflow | {
"language": "en",
"length": 281,
"provenance": "stackexchange_0000F.jsonl.gz:897963",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44645257"
} |
f2682b50ab609d0eccb3ded8acce2bc18e338115 | Stackoverflow Stackexchange
Q: ECS network host mode and links = CannotCreateContainerError: Container already exists I'm using AWS ECS to deploy my group of docker containers and in bridge network mode all works perfectly but with a slow performance...
I've read that this problem resolves with a host network mode but if i use this, it causes an error on containers deploy (some of them), "CannotCreateContainerError: Container already exists".
Looking for the error, i've see that is caused by links in containers (https://github.com/aws/amazon-ecs-agent/issues/185) but i need it,
Any ideas of this?
Thanks a lot!
A: Solved!
Like in that issue comments, networkmode host don't allow links between containers, so if you remove them it works.
So now we have a new problem, how comunicate between containers? easy, point to localhost or 127.0.0.1 and its own port (obviously you can't deploy two containers with the same port).
| Q: ECS network host mode and links = CannotCreateContainerError: Container already exists I'm using AWS ECS to deploy my group of docker containers and in bridge network mode all works perfectly but with a slow performance...
I've read that this problem resolves with a host network mode but if i use this, it causes an error on containers deploy (some of them), "CannotCreateContainerError: Container already exists".
Looking for the error, i've see that is caused by links in containers (https://github.com/aws/amazon-ecs-agent/issues/185) but i need it,
Any ideas of this?
Thanks a lot!
A: Solved!
Like in that issue comments, networkmode host don't allow links between containers, so if you remove them it works.
So now we have a new problem, how comunicate between containers? easy, point to localhost or 127.0.0.1 and its own port (obviously you can't deploy two containers with the same port).
A: Essentially, Fargate requires usage of awsvpc as network mode, virtue of which, you wont be able to use "dnsSearchDomains, dnsServers, extraHosts, disableNetworking and hostName" in the task definition when using Fargate launch type.
When any of the above parameters are in your taskdefinition, the error " STOPPED(CannotCreateContainerError: container already exists)" will occur.
However, ECS team acknowledged that the above can be very useful features and working on enabling these parameters.
https://forums.aws.amazon.com/thread.jspa?threadID=250147
| stackoverflow | {
"language": "en",
"length": 215,
"provenance": "stackexchange_0000F.jsonl.gz:897993",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44645360"
} |
bfef27655a0f62a0dff1afd3f0b01155a65e313b | Stackoverflow Stackexchange
Q: Can't access swift files in Unit test target in Xcode Adding swift files to test target will work, but it is not the best way to do. My problem is I can't able to access Swift file whereas Objective-C files are accessible.
I have checked product module name and set configuration file same as project file for test target. Even removed the test target and readded, but, still encountering "Use of undeclared type in SlideViewController".
Can anyone help me with solving this issue?
A: Try to add this on top of your test file:
@testable import <YOUR_MODULE_NAME>
| Q: Can't access swift files in Unit test target in Xcode Adding swift files to test target will work, but it is not the best way to do. My problem is I can't able to access Swift file whereas Objective-C files are accessible.
I have checked product module name and set configuration file same as project file for test target. Even removed the test target and readded, but, still encountering "Use of undeclared type in SlideViewController".
Can anyone help me with solving this issue?
A: Try to add this on top of your test file:
@testable import <YOUR_MODULE_NAME>
A: By default you won't be able to access internal classes from your unit test target.
The apple docs on writing tests with swift say that you need to take two steps to get around this:
*
*Set the ENABLE_TESTABILITY build setting to YES.
*Add @testable to the import statement for your module. @testable import MySwiftApp
If you follow both of those steps your SlideViewController (as long as it is not a private class) should be accessible from your unit test file as if it was declared as an open class.
A: Sometimes you will need to add files to the build phases of your test target.
1.- Go to project navigator
2.- Select your project
3.- On the project and target list, select the target for your tests (Ex. "MyProjectTests")
4.- Select Build Phases tab
5.- Open "Compile Sources"
6.- Using the plus sign, add the files needed for the compilation
| stackoverflow | {
"language": "en",
"length": 250,
"provenance": "stackexchange_0000F.jsonl.gz:898013",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44645426"
} |
5c7edd6e9dc3a77b63447d7c9883b8feb7e29eb2 | Stackoverflow Stackexchange
Q: ModuleNotFoundError: No module named 'pandas' I'm following a practical machine learning tutorial and I am already stuck on the second video. https://www.youtube.com/watch?v=JcI5Vnw0b2c&t=195s
import pandas as pd
import Quandl
df = Quandl.get('WIKI/GOOGL')
print(df.head())
When I run the same code as the man in the video, all I get is
ModuleNotFoundError: No module named 'pandas'
I'm on Windows 10 using Visual Studio 2017 and I already did pip install pandas. I have python 3.6.1 installed.
*
*pip 9.0.1 from C:\Program Files\Anaconda3\lib\site-packages (python 3.6).
*pandas (0.19.2).
*Python 3.6.0 :: Anaconda 4.3.0 (64-bit)
A: To make sure that you're using the same pip as your python, execute the pip with whole path from python directory i.e.
C:\Program Files\Anaconda3\lib\site-packages (python 3.6)\pip install pandas
This will install the pandas in the same directory
Or C:\Python365\pip install pandas
Or C:\Python27\pip install pandas
Whichever Python you wand to use and install the pandas
If you want to use a specific version of Python in Windows cmd, just add the path of that Python in System Variables.
| Q: ModuleNotFoundError: No module named 'pandas' I'm following a practical machine learning tutorial and I am already stuck on the second video. https://www.youtube.com/watch?v=JcI5Vnw0b2c&t=195s
import pandas as pd
import Quandl
df = Quandl.get('WIKI/GOOGL')
print(df.head())
When I run the same code as the man in the video, all I get is
ModuleNotFoundError: No module named 'pandas'
I'm on Windows 10 using Visual Studio 2017 and I already did pip install pandas. I have python 3.6.1 installed.
*
*pip 9.0.1 from C:\Program Files\Anaconda3\lib\site-packages (python 3.6).
*pandas (0.19.2).
*Python 3.6.0 :: Anaconda 4.3.0 (64-bit)
A: To make sure that you're using the same pip as your python, execute the pip with whole path from python directory i.e.
C:\Program Files\Anaconda3\lib\site-packages (python 3.6)\pip install pandas
This will install the pandas in the same directory
Or C:\Python365\pip install pandas
Or C:\Python27\pip install pandas
Whichever Python you wand to use and install the pandas
If you want to use a specific version of Python in Windows cmd, just add the path of that Python in System Variables.
A: I had a similar problem which I fixed by doing
pip3 install pandas
Instead of
pip install pandas
A: I had this problem as well and tried a few different things until I realized my python path under settings.json (python.pythonPath) was incorrect and pointing to the wrong directory. The path should be to where the Python.exe file is under programs.
A: For python 3.7, type following in CMD:
CD C:\Users\[path]\Continuum\anaconda3\Lib\site-packages
then:
pip3 install pandas
A: In my case, I installed panda instead of pandas. My installation was missing the last letter s.
A: My problem was running pandas from an ipython shell. The error message from the original post kept cropping up, despite having pandas installed. Then I started reading messages (see below). Installing ipython in the virtual environment didn't help, BUT deactivating the virtual environment and activating it again did.
➜ ipython
/.../python3.10/site-packages/IPython/core/interactiveshell.py:887: UserWarning:
Attempting to work in a virtualenv. If you encounter problems, please install
IPython inside the virtualenv.
A: I think you can use conda update pandas and it should get the most current version for you dist.
Or, pip install --update pandas
Also in python 3 quandl will be lowercase.
Edit.. pandas in on ver. 0.21.0 currently.
| stackoverflow | {
"language": "en",
"length": 371,
"provenance": "stackexchange_0000F.jsonl.gz:898014",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44645433"
} |
8b1c5e65ae6f8b7493d95a7fb0456b1321c12b07 | Stackoverflow Stackexchange
Q: Copy redis database (.rdb file) from a remote server to local I was given a Redis server that is set up remotely.
I can access data in that and I can do CRUD operation with that server.
But I want the replica of the same database in my local.
I have Redis desktop manager setup in my local. And also redis-server setup running.
Things I have tried:
*
*using SAVE command.
I have connected to the remote server and executed save command. It ran
successfully and created dump.rdb file on that server. But I can't access that file as I don't have permission for server FTP.
*using BGSAVE
same scenario here also
*using redis-cli command
redis-cli -h server ip -p 6379 save > \\local ip\dump.rdb
Here I got an error The network name cannot be found.
Can anyone please suggest me on how can I copy the .rdb file from the server to local?
| Q: Copy redis database (.rdb file) from a remote server to local I was given a Redis server that is set up remotely.
I can access data in that and I can do CRUD operation with that server.
But I want the replica of the same database in my local.
I have Redis desktop manager setup in my local. And also redis-server setup running.
Things I have tried:
*
*using SAVE command.
I have connected to the remote server and executed save command. It ran
successfully and created dump.rdb file on that server. But I can't access that file as I don't have permission for server FTP.
*using BGSAVE
same scenario here also
*using redis-cli command
redis-cli -h server ip -p 6379 save > \\local ip\dump.rdb
Here I got an error The network name cannot be found.
Can anyone please suggest me on how can I copy the .rdb file from the server to local?
| stackoverflow | {
"language": "en",
"length": 155,
"provenance": "stackexchange_0000F.jsonl.gz:898053",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44645543"
} |
3026d337cf211d5dd8c690f5a3975a38f51dc932 | Stackoverflow Stackexchange
Q: Selenium webdriver polling time I'm looking forward for a proper explanation about the selenium webdriver polling time in Selenium.
As I know, below wait command will wait for 40 seconds until the specific element get clickable
public void CreateSalesOrder(){
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(btnNewSalesOrser));
btnNewSalesOrser.click();
}
In the 2nd code snippet I've added "Polling" command.
public void CreateSalesOrder(){
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.pollingEvery(2, TimeUnit.SECONDS);
wait.until(ExpectedConditions.elementToBeClickable(btnNewSalesOrser));
btnNewSalesOrser.click();
}
What is the use of polling time ?
A: Using WebDriverWait wait = new WebDriverWait(driver, 40); the driver will wait a maximum of 40 seconds until the condition is fulfilled.
Using wait.pollingEvery(2, TimeUnit.SECONDS); specifies that the driver will do the checks (to see if the condition is fulfilled) every 2 seconds until the condition is fulfilled.
In sum this means that your driver will do a check every 2 seconds for a period of 40 seconds.
You could also specify the polling interval as a shortcut in the Constructor:
WebDriverWait wait = new WebDriverWait(driver, 40, TimeUnit.SECONDS.toMillis(2));
| Q: Selenium webdriver polling time I'm looking forward for a proper explanation about the selenium webdriver polling time in Selenium.
As I know, below wait command will wait for 40 seconds until the specific element get clickable
public void CreateSalesOrder(){
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(btnNewSalesOrser));
btnNewSalesOrser.click();
}
In the 2nd code snippet I've added "Polling" command.
public void CreateSalesOrder(){
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.pollingEvery(2, TimeUnit.SECONDS);
wait.until(ExpectedConditions.elementToBeClickable(btnNewSalesOrser));
btnNewSalesOrser.click();
}
What is the use of polling time ?
A: Using WebDriverWait wait = new WebDriverWait(driver, 40); the driver will wait a maximum of 40 seconds until the condition is fulfilled.
Using wait.pollingEvery(2, TimeUnit.SECONDS); specifies that the driver will do the checks (to see if the condition is fulfilled) every 2 seconds until the condition is fulfilled.
In sum this means that your driver will do a check every 2 seconds for a period of 40 seconds.
You could also specify the polling interval as a shortcut in the Constructor:
WebDriverWait wait = new WebDriverWait(driver, 40, TimeUnit.SECONDS.toMillis(2));
A: If we didn't mention any polling time, selenium will take the default polling time as 500milli seconds. i.e.., script will check for the excepted condition for the webelement in the web page every 500 milli seconds. Your first code snippet works with this.
We use pollingEvery to override the default polling time. In the below example(your second code snippet), the script checks for the expected condition for every 2 seconds and not for 500 milliseconds.
public void CreateSalesOrder()
{
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.pollingEvery(2, TimeUnit.SECONDS);
wait.until(ExpectedConditions.elementToBeClickable(btnNewSalesOrser));
btnNewSalesOrser.click();
}
This polling frequency may actually help in reducing the CPU overload.
Refer this javadoc for more info pollingEvery.
Hope this helps you. Thanks.
A: For understanding the explanation, you have to understand the polling time for Explicit Wait.
WebDriverWait wait = new WebDriverWait(driver, 40);
This waits up to 40 seconds before throwing a TimeoutException unless it finds the element to return within 40 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully hence the default polling time for ExplicitWait is 500 milliseconds.
wait.pollingEvery(2, TimeUnit.SECONDS);
In this case, the polling time is 2 seconds i.e the Expected condition will not be checked after every 500 milliseconds, it should be checked after 2 seconds until the specific elements get clickable.
| stackoverflow | {
"language": "en",
"length": 382,
"provenance": "stackexchange_0000F.jsonl.gz:898065",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44645586"
} |
9deeb6e0387a3d83ead09c9ded9035f79807d01c | Stackoverflow Stackexchange
Q: How to use variables in Matlab App Designer in all callbacks I have different callbacks in an Matlab App Designer App. In my case several buttons. I need to use the same variables for that.
I only get an error when using a variable I created in one Callback in another...
A: I think I got your problem.
The easiest way is in beginning to create a new property (red button on the top left in EDITOR) and use it as a variable throughout the code.
Be careful to use app.variablename to address the variable.
If your code is already finished and you just discovered that error, you can set properties for only the variables you need to exchange and then get them like this:
set property:
properties (Access = private)
varone %first variable
vartwo % second variable
...
end
get Data for Exchange:
varone = app.varone; %(now you can use varone instead of app.varone)
make it public again at the end of your callback:
app.varone = varone;
| Q: How to use variables in Matlab App Designer in all callbacks I have different callbacks in an Matlab App Designer App. In my case several buttons. I need to use the same variables for that.
I only get an error when using a variable I created in one Callback in another...
A: I think I got your problem.
The easiest way is in beginning to create a new property (red button on the top left in EDITOR) and use it as a variable throughout the code.
Be careful to use app.variablename to address the variable.
If your code is already finished and you just discovered that error, you can set properties for only the variables you need to exchange and then get them like this:
set property:
properties (Access = private)
varone %first variable
vartwo % second variable
...
end
get Data for Exchange:
varone = app.varone; %(now you can use varone instead of app.varone)
make it public again at the end of your callback:
app.varone = varone;
| stackoverflow | {
"language": "en",
"length": 169,
"provenance": "stackexchange_0000F.jsonl.gz:898073",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44645612"
} |
b8f78589f33e36543288a74ca4abc17296e04e2e | Stackoverflow Stackexchange
Q: launchSettings.json commandName usage Everytime I find some launchSettings.json files, they have the following structure:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:40088/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express (Staging)": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Staging"
}
}
}
}
found here.
However, I can't find any document about the attribute commandName.
What is the usage of commandName?
A: The value of commandName can specify the web server to launch. commandName can be any one of the following:
*
*IISExpress : Launches IIS Express.
*IIS : No web server launched. IIS is expected to be available.
*Project : Launches Kestrel.
Source Microsoft => Use multiple environments in ASP.NET Core
Kestrel is a cross-platform web server for ASP.NET Core.
| Q: launchSettings.json commandName usage Everytime I find some launchSettings.json files, they have the following structure:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:40088/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express (Staging)": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Staging"
}
}
}
}
found here.
However, I can't find any document about the attribute commandName.
What is the usage of commandName?
A: The value of commandName can specify the web server to launch. commandName can be any one of the following:
*
*IISExpress : Launches IIS Express.
*IIS : No web server launched. IIS is expected to be available.
*Project : Launches Kestrel.
Source Microsoft => Use multiple environments in ASP.NET Core
Kestrel is a cross-platform web server for ASP.NET Core.
A: The command name maps to how the project should be started. Visual Studio uses this to run your project.
*
*IISExpress obviously indicates that IIS Express is used to start the project.
*Project indicates that the project is executed with the .NET CLI directly on the command line.
| stackoverflow | {
"language": "en",
"length": 188,
"provenance": "stackexchange_0000F.jsonl.gz:898125",
"question_score": "20",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44645775"
} |
03696d3418b92afd287518fefb51ab1ab3713607 | Stackoverflow Stackexchange
Q: Launch app using 3D touch from cold AND debug through Xcode? I am trying to debug an issue with the 3D touch implementation in my iOS app. The issue is only present when the app is not already running in the background (IE the app has been force closed previously, either by they system or user).
The issue is, when I force close the app after launching it through Xcode, then use a 3D touch action to open it, it's not running through the debugger and therefore I can't debug the issue.
I have tried going to Debug>Attach to Process but by the time I have done so, the code in question has already run.
TL;DR, is there a way to launch an app through Xcode, as if one of the 3D touch actions had done so?
Many Thanks,
| Q: Launch app using 3D touch from cold AND debug through Xcode? I am trying to debug an issue with the 3D touch implementation in my iOS app. The issue is only present when the app is not already running in the background (IE the app has been force closed previously, either by they system or user).
The issue is, when I force close the app after launching it through Xcode, then use a 3D touch action to open it, it's not running through the debugger and therefore I can't debug the issue.
I have tried going to Debug>Attach to Process but by the time I have done so, the code in question has already run.
TL;DR, is there a way to launch an app through Xcode, as if one of the 3D touch actions had done so?
Many Thanks,
| stackoverflow | {
"language": "en",
"length": 140,
"provenance": "stackexchange_0000F.jsonl.gz:898147",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44645869"
} |
f86e7359ea558d1d482f1df6026c2baba4739490 | Stackoverflow Stackexchange
Q: How to install latest version of nginx on raspbian? What to specify in source.list? because when I write
deb http://nginx.org/packages/debian/ jessie nginx
deb-src http://nginx.org/packages/debian/ jessie nginx
appears error:
Unable to find expected entry '' in Release file (Wrong sources.list entry or malformed file)
A: There is another way to install the last version of nginx on raspbian stretch, by using the repo of buster the next version of raspbian.
Only three commands are needed:
# Add the url to apt source list
echo "deb http://mirrordirector.raspbian.org/raspbian/ buster main contrib non-free rpi" | sudo tee -a /etc/apt/sources.list.d/10-buster.list
# Set preferences to give more priority to stretch
printf "Package: *\nPin: release n=stretch\nPin-Priority: 900\n\nPackage: *\nPin: release n=buster\nPin-Priority: 750" | sudo tee -a /etc/apt/preferences.d/10-buster
# Update and install: -t is used to target a release and -yqq to confirm and reduce output
sudo apt-get update && sudo apt-get install -t buster nginx -yqq
At the time of writing, the last stable version is 1.14.1. The same pointed out by sudo apt-get install -t buster -s nginx
Source: https://getgrav.org/blog/raspberrypi-nginx-php7-dev
| Q: How to install latest version of nginx on raspbian? What to specify in source.list? because when I write
deb http://nginx.org/packages/debian/ jessie nginx
deb-src http://nginx.org/packages/debian/ jessie nginx
appears error:
Unable to find expected entry '' in Release file (Wrong sources.list entry or malformed file)
A: There is another way to install the last version of nginx on raspbian stretch, by using the repo of buster the next version of raspbian.
Only three commands are needed:
# Add the url to apt source list
echo "deb http://mirrordirector.raspbian.org/raspbian/ buster main contrib non-free rpi" | sudo tee -a /etc/apt/sources.list.d/10-buster.list
# Set preferences to give more priority to stretch
printf "Package: *\nPin: release n=stretch\nPin-Priority: 900\n\nPackage: *\nPin: release n=buster\nPin-Priority: 750" | sudo tee -a /etc/apt/preferences.d/10-buster
# Update and install: -t is used to target a release and -yqq to confirm and reduce output
sudo apt-get update && sudo apt-get install -t buster nginx -yqq
At the time of writing, the last stable version is 1.14.1. The same pointed out by sudo apt-get install -t buster -s nginx
Source: https://getgrav.org/blog/raspberrypi-nginx-php7-dev
A: You can get the current latest, 1.13.1, which supports ALPN and HTTP 2.0 by using the Ubuntu sources. As an aside: it's best to put modifications to your apt sources in the sources dictionary rather than sources.list itself, it helps in terms of maintainability.
Create a file for the repository
sudo touch /etc/apt/sources.list.d/nginx.list
Run the following to add a reference to the Ubuntu repository, and debian jessie backports.
sudo bash -c 'cat << EOF >> /etc/apt/sources.list.d/nginx.list
# jessie-backports, from stretch-level but with no dependencies
deb http://httpredir.debian.org/debian/ jessie-backports main contrib non-free
deb-src http://httpredir.debian.org/debian/ jessie-backports main contrib non-free
# Nginx repository - use Ubuntu 16.04 LTS Xenial to get packages compiled with OpenSSL 1.0.2
deb http://nginx.org/packages/mainline/ubuntu/ xenial nginx
deb-src http://nginx.org/packages/mainline/ubuntu/ xenial nginx
EOF'
Update your sources:
sudo apt-get update
Install/Upgrade OpenSSL
sudo apt-get install -t jessie-backports openssl
Install/Upgrade Nginx:
sudo apt-get install nginx
Done.
A: I followed @Joe's suggestion, it did not work in Raspbian Stretch
nginx:
Installed: (none)
Candidate: 1.10.3-1+deb9u1
Version table:
1.10.3-1+deb9u1 500
500 http://mirrordirector.raspbian.org/raspbian stretch/main armhf Packages
1.10.3-1+deb9u1~bpo8+2 100
100 http://httpredir.debian.org/debian jessie-backports/main armhf Packages
Then I changed packages to refer to stretch backport and debian package instead of Ubuntu,
# stretch-backports
deb http://httpredir.debian.org/debian/ stretch-backports main contrib non-free
deb-src http://httpredir.debian.org/debian/ stretch-backports main contrib non-free
# Nginx pre built packages
deb http://nginx.org/packages/mainline/debian/ stretch nginx
deb-src http://nginx.org/packages/mainline/debian/ stretch nginx
The new one gives me
nginx:
Installed: (none)
Candidate: 1.13.3-1~bpo9+1
Version table:
1.13.3-1~bpo9+1 990
990 http://httpredir.debian.org/debian stretch-backports/main armhf Packages
1.10.3-1+deb9u1 500
500 http://mirrordirector.raspbian.org/raspbian stretch/main armhf Packages
| stackoverflow | {
"language": "en",
"length": 418,
"provenance": "stackexchange_0000F.jsonl.gz:898174",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44645954"
} |
9bb3fac64d77ada5b499b66c022b589d26f886f5 | Stackoverflow Stackexchange
Q: Getting null output when schema specified to read data in BigQuery select operation I am facing issue when selecting data from BigQuery table with specified schema.
val tableData:RDD[String] = sqlContext.sparkContext.newAPIHadoopRDD(
hadoopConf,
classOf[GsonBigQueryInputFormat],
classOf[LongWritable],
classOf[JsonObject]).map(_._2.toString)
val jsonSchema:StructType = (new StructType).add("f1",IntegerType,true).add("f2",FloatType,true).add("f3",StringType,true).add("f4",BooleanType,true).add("f5",DateType,true).add("f6",TimestampType,true)
val df = sqlContext.read.schema(jsonSchema).json(tableData)
When I specify schema like above I am getting null result in the data frame.But when no schema specified getting proper results.
df.printSchema()
root
|-- f1: integer (nullable = true)
|-- f2: float (nullable = true)
|-- f3: string (nullable = true)
|-- f4: boolean (nullable = true)
|-- f5: date (nullable = true)
|-- f6: timestamp (nullable = true)
df.show
+----+----+----+----+----+----+
| f1| f2| f3| f4| f5| f6|
+----+----+----+----+----+----+
|null|null|null|null|null|null|
When analyzed I found BigQuery exports table data in following format ex:
{"f1":"3","f2":2.7,"f3":"Anna","f4":true,"f5":"2014-10-15","f6":"2014-10-15 03:15:58 UTC"}.
When I read from tableData using json format it can't cast the data with specified schema and returns null result.
How can I get proper result with specified schema? Please suggest if you have any idea/solution for it.
| Q: Getting null output when schema specified to read data in BigQuery select operation I am facing issue when selecting data from BigQuery table with specified schema.
val tableData:RDD[String] = sqlContext.sparkContext.newAPIHadoopRDD(
hadoopConf,
classOf[GsonBigQueryInputFormat],
classOf[LongWritable],
classOf[JsonObject]).map(_._2.toString)
val jsonSchema:StructType = (new StructType).add("f1",IntegerType,true).add("f2",FloatType,true).add("f3",StringType,true).add("f4",BooleanType,true).add("f5",DateType,true).add("f6",TimestampType,true)
val df = sqlContext.read.schema(jsonSchema).json(tableData)
When I specify schema like above I am getting null result in the data frame.But when no schema specified getting proper results.
df.printSchema()
root
|-- f1: integer (nullable = true)
|-- f2: float (nullable = true)
|-- f3: string (nullable = true)
|-- f4: boolean (nullable = true)
|-- f5: date (nullable = true)
|-- f6: timestamp (nullable = true)
df.show
+----+----+----+----+----+----+
| f1| f2| f3| f4| f5| f6|
+----+----+----+----+----+----+
|null|null|null|null|null|null|
When analyzed I found BigQuery exports table data in following format ex:
{"f1":"3","f2":2.7,"f3":"Anna","f4":true,"f5":"2014-10-15","f6":"2014-10-15 03:15:58 UTC"}.
When I read from tableData using json format it can't cast the data with specified schema and returns null result.
How can I get proper result with specified schema? Please suggest if you have any idea/solution for it.
| stackoverflow | {
"language": "en",
"length": 168,
"provenance": "stackexchange_0000F.jsonl.gz:898269",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646267"
} |
54979384644fcacc7dca068a45fb410751118cac | Stackoverflow Stackexchange
Q: Merge changes from parent branch, in GIT I have the following structure:
----parent_branch
|
------ my_branch
I have worked in my_branch so far, and important changes were made in parent_branch. I want to merge only those changes into my_branch, without messing-up what I've worked on in my_branch. How can I safely do that?
A: It's as easy as to Follow Below Steps :
*
*git checkout my_branch
*git merge parent_branch
*git push origin my_branch
| Q: Merge changes from parent branch, in GIT I have the following structure:
----parent_branch
|
------ my_branch
I have worked in my_branch so far, and important changes were made in parent_branch. I want to merge only those changes into my_branch, without messing-up what I've worked on in my_branch. How can I safely do that?
A: It's as easy as to Follow Below Steps :
*
*git checkout my_branch
*git merge parent_branch
*git push origin my_branch
| stackoverflow | {
"language": "en",
"length": 75,
"provenance": "stackexchange_0000F.jsonl.gz:898306",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646405"
} |
91ba896018160d9494a8bd065f3c40c47c5a7c88 | Stackoverflow Stackexchange
Q: Kotlin inheritnce - No value passed for parameter context I'm trying to build an AccountAuthenticator class with kotlin for android. But when trying to implement the AbstractAccountAuthenticator class I get the following exception at compile:
No value passed for parameter context
I'm not entirely sure what it means and can't find anything on how to solve it.
Here is the relevant code:
import android.accounts.AbstractAccountAuthenticator
import android.accounts.Account
import android.accounts.AccountAuthenticatorResponse
import android.os.Bundle
class AccountAuthenticator: AbstractAccountAuthenticator() {}
Does anyone know what this means, why, and how to fix it?
A: AbstractAccountAuthenticator's constructor takes a Context context parameter. So you'll have to pass a Context to it somehow, for example, your AccountAuthenticator could also have a Context parameter:
class AccountAuthenticator(context: Context): AbstractAccountAuthenticator(context) {}
| Q: Kotlin inheritnce - No value passed for parameter context I'm trying to build an AccountAuthenticator class with kotlin for android. But when trying to implement the AbstractAccountAuthenticator class I get the following exception at compile:
No value passed for parameter context
I'm not entirely sure what it means and can't find anything on how to solve it.
Here is the relevant code:
import android.accounts.AbstractAccountAuthenticator
import android.accounts.Account
import android.accounts.AccountAuthenticatorResponse
import android.os.Bundle
class AccountAuthenticator: AbstractAccountAuthenticator() {}
Does anyone know what this means, why, and how to fix it?
A: AbstractAccountAuthenticator's constructor takes a Context context parameter. So you'll have to pass a Context to it somehow, for example, your AccountAuthenticator could also have a Context parameter:
class AccountAuthenticator(context: Context): AbstractAccountAuthenticator(context) {}
A: I don't know much about Kotlin but AbstractAccountAuthenticator constructor takes a Context see here.
So I guess you have to implement this constructor and other related abstract methods.
| stackoverflow | {
"language": "en",
"length": 149,
"provenance": "stackexchange_0000F.jsonl.gz:898322",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646461"
} |
eb9dd5339a84de2b1a151876acb8ae3f09e3dfda | Stackoverflow Stackexchange
Q: Stacked bar plot with hierarchical clustering (dendrogram) I am trying to get something like this but unfortunately, I could not find any package that could enable me to plot stacked bar plot with dendrogram like the one shown below:
Does anyone know how to do it?
A: A first stab at an answer - but it would require more work to make it really work. Specifically the alignment of the location of elements (as well as their order) needs to be thought of more carefully.
# library
library(ggplot2)
# create a dataset
specie=c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )
condition=rep(c("normal" , "stress" , "Nitrogen") , 4)
value=abs(rnorm(12 , 0 , 15))
data=data.frame(specie,condition,value)
dend <- as.dendrogram(hclust(dist(with(data, tapply(value, specie, mean)))))
data$specie <- factor(data$specie, levels = labels(dend))
# Stacked Percent
library(dendextend)
p1 <- ggplot(dend, horiz = T)
p2 <- ggplot(data, aes(fill=condition, y=value, x=specie)) +
geom_bar( stat="identity", position="fill") + coord_flip()
library(cowplot)
plot_grid(p1, p2, align = "h")
| Q: Stacked bar plot with hierarchical clustering (dendrogram) I am trying to get something like this but unfortunately, I could not find any package that could enable me to plot stacked bar plot with dendrogram like the one shown below:
Does anyone know how to do it?
A: A first stab at an answer - but it would require more work to make it really work. Specifically the alignment of the location of elements (as well as their order) needs to be thought of more carefully.
# library
library(ggplot2)
# create a dataset
specie=c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )
condition=rep(c("normal" , "stress" , "Nitrogen") , 4)
value=abs(rnorm(12 , 0 , 15))
data=data.frame(specie,condition,value)
dend <- as.dendrogram(hclust(dist(with(data, tapply(value, specie, mean)))))
data$specie <- factor(data$specie, levels = labels(dend))
# Stacked Percent
library(dendextend)
p1 <- ggplot(dend, horiz = T)
p2 <- ggplot(data, aes(fill=condition, y=value, x=specie)) +
geom_bar( stat="identity", position="fill") + coord_flip()
library(cowplot)
plot_grid(p1, p2, align = "h")
A: Almost three years later there is still no package capable of combining stacked bar plots with hierarchical clustering in ggplot (at least that I'm aware of). Here my solution based on that post joining a dendrogram and a heatmap:
library(tidyverse)
library(phangorn)
library(vegan)
library(ggdendro)
library(dendextend)
library(ggsci)
library(cowplot)
## generate example data ####
set.seed(500)
combined_matrix <- data.frame(a=runif(14, 0, 33), b=runif(14, 0, 33), c=runif(14, 0, 33))
combined_matrix$d <- 100 - combined_matrix$a - combined_matrix$b - combined_matrix$c
row.names(combined_matrix) <- paste0("s", seq(1,14))
# vegan::vegdist() to calculate Bray-Curtis distance matrix
dm <- vegdist(combined_matrix, method = "bray")
# calculate UPGMA tree with phangorn::upgma() and convert to dendrogram
dendUPGMA <- as.dendrogram(upgma(dm))
plot_dendro_bars_v <- function(df, dend, taxonomy) {
#convert dendrogram to segment data
dend_data <- dendro_data(dend, type="rectangle")
segment_data <- dend_data[["segments"]]
#sample positions df
sample_pos_table <- with(dend_data$labels,
data.frame(x_center = x, sample = as.character(label), width = 0.9))
#prepare input data
ptdf <- rownames_to_column(df, var = "sample") %>%
pivot_longer(-sample, names_to = taxonomy, values_to = "Frequency") %>%
group_by(sample) %>%
mutate(Frequency = Frequency/100,
ymax = cumsum(Frequency/sum(Frequency)),
ymin = ymax - Frequency/sum(Frequency),
y_center = ymax-(Frequency/2)) %>%
left_join(sample_pos_table) %>%
mutate(xmin = x_center-width/2,
xmax = x_center+width/2)
#plot stacked bars
axis_limits <- with(sample_pos_table,
c(min(x_center - 0.5 * width), max(x_center + 0.5 * width))) +
0.1 * c(-1, 1) # extra spacing: 0.1
plt_hbars <- ggplot(ptdf,
aes_string(x = "x_center", y = "y_center", fill = taxonomy, xmin = "xmin", xmax = "xmax",
height = "Frequency", width = "width")) +
geom_tile() +
geom_rect(ymin = 0, ymax = 1, color = "black", fill = "transparent") +
scale_fill_rickandmorty() +
scale_y_continuous(expand = c(0, 0)) +
# For the y axis, alternatively set the labels as: gene_position_table$gene
scale_x_continuous(breaks = sample_pos_table[, "x_center"],
labels = sample_pos_table$sample,
limits = axis_limits,
expand = c(0, 0)) +
labs(x = "", y = "Frequency") +
theme_bw() +
theme(# margin: top, right, bottom, and left
plot.margin = unit(c(-0.9, 0.2, 1, 0.2), "cm"),
panel.grid.minor = element_blank())
#plot dendrogram
plt_dendr <- ggplot(segment_data) +
geom_segment(aes(x = x, y = y, xend = xend, yend = yend)) +
scale_y_continuous(expand = c(0, 0.05)) +
scale_x_continuous(breaks = sample_pos_table$x_center,
labels = rep("", nrow(sample_pos_table)),
limits = axis_limits,
expand = c(0, 0)) +
labs(x = "", y = "Distance", colour = "", size = "") +
theme_bw() +
theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank())
#combine plots
comb <- plot_grid(plt_dendr, plt_hbars, align = 'v', ncol = 1, axis = "lr", rel_heights = c(0.3, 1))
comb
}
plot_dendro_bars_v(df = combined_matrix, dend = dendUPGMA, taxonomy = "example")
vertical
or horizontal
plot_dendro_bars_h <- function(df, dend, taxonomy) {
#convert dendrogram to segemnt data
dend_data <- dendro_data(dend, type="rectangle")
segment_data <- with(segment(dend_data),
data.frame(x = y, y = x, xend = yend, yend = xend))
#sample positions df
sample_pos_table <- with(dend_data$labels,
data.frame(y_center = x, sample = as.character(label), height = 0.9))
#prepare input data
ptdf <- rownames_to_column(df, var = "sample") %>%
pivot_longer(-sample, names_to = taxonomy, values_to = "Frequency") %>%
group_by(sample) %>%
mutate(Frequency = Frequency/100,
xmax = cumsum(Frequency/sum(Frequency)),
xmin = xmax - Frequency/sum(Frequency),
x_center = xmax-(Frequency/2)) %>%
left_join(sample_pos_table) %>%
mutate(ymin = y_center-height/2,
ymax = y_center+height/2)
#plot stacked bars
axis_limits <- with(sample_pos_table,
c(min(y_center - 0.5 * height), max(y_center + 0.5 * height))) +
0.1 * c(-1, 1) # extra spacing: 0.1
plt_hbars <- ggplot(ptdf,
aes_string(x = "x_center", y = "y_center", fill = taxonomy, ymin = "ymin", ymax = "ymax",
height = "height", width = "Frequency")) +
geom_tile() +
geom_rect(xmin = 0, xmax = 1, color = "black", fill = "transparent") +
scale_fill_rickandmorty() +
scale_x_continuous(expand = c(0, 0)) +
# For the y axis, alternatively set the labels as: gene_position_table$gene
scale_y_continuous(breaks = sample_pos_table[, "y_center"],
labels = rep("", nrow(sample_pos_table)),
limits = axis_limits,
expand = c(0, 0)) +
labs(x = "Frequency", y = "") +
theme_bw() +
theme(# margin: top, right, bottom, and left
plot.margin = unit(c(1, 0.2, 0.2, -0.9), "cm"),
panel.grid.minor = element_blank())
#plot dendrogram
plt_dendr <- ggplot(segment_data) +
geom_segment(aes(x = x, y = y, xend = xend, yend = yend)) +
scale_x_reverse(expand = c(0, 0.05)) +
scale_y_continuous(breaks = sample_pos_table$y_center,
labels = sample_pos_table$sample,
limits = axis_limits,
expand = c(0, 0)) +
labs(x = "Distance", y = "", colour = "", size = "") +
theme_bw() +
theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank())
#combine plots
comb <- plot_grid(plt_dendr, plt_hbars, align = 'h', rel_widths = c(0.3, 1))
return(comb)
}
plot_dendro_bars_h(df = combined_matrix, dend = dendUPGMA, taxonomy = "example")
horizontal
The data can be combined with any tree which can be coerced to a dendrogram (e.g. also UniFrac trees). Have fun with that, Roman.
A: Here's my version of Roman_G's script. It displays percentages inside the bars, and it uses vegan::reorder.hclust to reorder the branches of the dendrogram so that so that rows with the highest value for the first column tend to be placed to the top and rows with the highest value for the last column tend to be placed at the bottom. I also removed extra margins and ticks and axis.
library(tidyverse)
library(ggdendro)
library(vegan)
library(colorspace)
library(cowplot)
t=read.table(text="Spain_EN 0.028152 0.971828 0.000010 0.000010
Norway_Mesolithic 0.784705 0.083387 0.000010 0.131898
Russia_Sunghir4 0.000010 0.000010 0.999970 0.000010
Iran_Wezmeh_N 0.000010 0.492331 0.383227 0.124433
Russia_DevilsCave_N 0.000010 0.000010 0.000010 0.999970
Italy_North_Villabruna_HG 0.999970 0.000010 0.000010 0.000010
Russia_HG_Karelia 0.527887 0.133179 0.072342 0.266593
Russia_Yana_UP 0.000010 0.000014 0.999966 0.000010
Georgia_Kotias 0.000010 0.537322 0.381313 0.081355
China_SEastAsia_Island_EN 0.000010 0.000010 0.148652 0.851328
Turkey_N 0.000010 0.999970 0.000010 0.000010
USA_Ancient_Beringian 0.008591 0.000010 0.095008 0.896391
Russia_Sidelkino_HG 0.624076 0.045350 0.105615 0.224958
Russia_Kolyma_M 0.020197 0.000010 0.000010 0.979783
China_Tianyuan 0.000010 0.000010 0.423731 0.576249",row.names=1)
hc=hclust(dist(t),method="ward.D2")
hc=reorder(hc,wts=-as.matrix(t)%*%seq(ncol(t))^2) # vegan::reorder.hclust
tree=ggdendro::dendro_data(as.dendrogram(hc),type="rectangle")
p1=ggplot(ggdendro::segment(tree))+
geom_segment(aes(x=y,y=x,xend=yend,yend=xend),lineend="round",size=.4)+
scale_x_continuous(expand=expansion(add=c(0,.01)))+ # don't crop half of line between top-level nodes
scale_y_continuous(limits=.5+c(0,nrow(t)),expand=c(0,0))+
theme(
axis.text=element_blank(),
axis.ticks=element_blank(),
axis.ticks.length=unit(0,"pt"), # remove extra space occupied by ticks
axis.title=element_blank(),
panel.background=element_rect(fill="white"),
panel.grid=element_blank(),
plot.margin=margin(5,5,5,0)
)
t=t[hc$labels[hc$order],]
t2=data.frame(V1=rownames(t)[row(t)],V2=colnames(t)[col(t)],V3=unname(do.call(c,t)))
lab=round(100*t2$V3)
lab[lab==0]=""
p2=ggplot(t2,aes(x=factor(V1,level=rownames(t)),y=V3,fill=V2))+
geom_bar(stat="identity",width=1,position=position_fill(reverse=T))+
geom_text(aes(label=lab),position=position_stack(vjust=.5,reverse=T),size=3.5)+
coord_flip()+
scale_x_discrete(expand=c(0,0))+
scale_y_discrete(expand=c(0,0))+
scale_fill_manual(values=colorspace::hex(HSV(head(seq(0,360,length.out=ncol(t)+1),-1),.5,1)))+
theme(
axis.text=element_text(color="black",size=11),
axis.text.x=element_blank(),
axis.ticks=element_blank(),
axis.title=element_blank(),
legend.position="none",
plot.margin=margin(5,0,5,5)
)
cowplot::plot_grid(p2,p1,rel_widths=c(1,.4))
ggsave("a.png",height=.25*nrow(t),width=7)
There's also scale_x_dendrogram and scale_y_dendrogram from ggh4x, which use ggdendro::dendro_data: https://teunbrand.github.io/ggh4x/articles/PositionGuides.html#dendrograms. However I couldn't get them to work with horizontal stacked bars using coord_flip.
library(ggh4x)
t=head(USArrests,20)
t2=data.frame(V1=rownames(t)[row(t)],V2=colnames(t)[col(t)],V3=unname(do.call(c,t)))
hc=hclust(dist(t))
ggplot(t2,aes(x=factor(V1,level=rownames(t)),y=V3,fill=V2))+
geom_bar(stat="identity",width=1,position=position_stack(reverse=F))+
geom_text(aes(label=round(V3)),position=position_stack(vjust=.5,reverse=F),size=3)+
scale_x_dendrogram(hclust=hc)+
scale_y_discrete(expand=c(0,0))+
# scale_fill_manual(values=colorspace::hex(HSV(head(seq(0,360,length.out=ncol(t)+1),-1),.5,1)))+
theme(
axis.text=element_text(color="black",size=11),
axis.text.x=element_text(angle=90,hjust=1,vjust=.5),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.ticks.length=unit(14,"pt"), # height of dendrogram
axis.title=element_blank(),
legend.justification=c(0,1),
legend.key=element_rect(fill=NA), # remove gray border around color squares
legend.margin=margin(-6,0,0,0),
legend.position=c(0,1),
legend.title=element_blank(),
panel.background=element_rect(fill="white"),
plot.margin=margin(5,0,5,5)
)
ggsave("a.png",height=6,width=6)
Edit: a third option is to use circlize: https://jokergoo.github.io/circlize/reference/circos.barplot.html.
library(circlize)
library(vegan) # for reorder.hclust (may be masked by `seriation`)
library(dendextend) # for color_branches
t=read.table(text="Kalmyk 0.119357 0.725057 0.000010 0.037803 0.117774
Kyrgyz_China 0.039367 0.512079 0.230150 0.095038 0.123366
Altaian_Chelkan 0.034095 0.000010 0.919478 0.000010 0.046407
Azeri 0.051638 0.004671 0.010727 0.902646 0.030318
Uzbek 0.102725 0.273261 0.001854 0.452126 0.170033
Salar 0.000010 0.539636 0.460334 0.000010 0.000010
Tatar_Kazan 0.113456 0.057026 0.000010 0.099336 0.730171
Tatar_Siberian 0.251376 0.221389 0.000010 0.077505 0.449721
Finnish 0.007214 0.000010 0.000010 0.015174 0.977592
Yakut 0.505434 0.473202 0.000010 0.002914 0.018440
Mansi 0.572791 0.000010 0.000010 0.000010 0.427179
Altaian 0.222424 0.335614 0.358801 0.032694 0.050468
Shor_Mountain 0.233984 0.000010 0.724596 0.000010 0.041400
Chuvash 0.180171 0.011056 0.000010 0.006462 0.802301
Enets 0.920409 0.000010 0.000010 0.000010 0.079561
Yukagir_Tundra 0.710359 0.289611 0.000010 0.000011 0.000010
Kyrgyz_Tajikistan 0.104000 0.563708 0.000010 0.125799 0.206483
Khakass_Kachin 0.254253 0.416760 0.174200 0.005262 0.149525
Tuvinian 0.448940 0.448899 0.000010 0.031803 0.070348
Besermyan 0.209841 0.001487 0.000010 0.000460 0.788202
Nogai_Astrakhan 0.062497 0.463590 0.000010 0.183203 0.290701
Todzin 0.725173 0.257670 0.000010 0.005836 0.011312
Kazakh 0.067027 0.518213 0.087979 0.114550 0.212231
Tofalar 0.815599 0.110299 0.000010 0.009693 0.064398
Karakalpak 0.009983 0.316964 0.389103 0.158275 0.125676
Estonian 0.000010 0.000010 0.000010 0.004409 0.995561
Dolgan 0.694025 0.255361 0.000010 0.049624 0.000979
Tatar_Siberian_Zabolotniye 0.521637 0.020132 0.000010 0.000010 0.458212
Uyghur 0.043578 0.486742 0.000010 0.318983 0.150687
Udmurt 0.256391 0.000010 0.001010 0.000010 0.742579
Evenk_FarEast 0.241328 0.606202 0.000010 0.000010 0.152451
Selkup 0.804662 0.000010 0.000010 0.000010 0.195308
Kumyk 0.060751 0.000112 0.000010 0.823905 0.115222
Hungarian 0.000010 0.000010 0.000010 0.244311 0.755659
Tubalar 0.159517 0.009457 0.802778 0.000010 0.028238
Turkmen 0.123631 0.226543 0.000010 0.529793 0.120023
Karelian 0.012854 0.000010 0.000010 0.000010 0.987116
Kazakh_China 0.074285 0.573009 0.152931 0.069362 0.130412
Mongol 0.033174 0.847004 0.025135 0.005178 0.089509
Daur 0.000010 0.995215 0.000010 0.000010 0.004755
Evenk_Transbaikal 0.611414 0.388556 0.000010 0.000010 0.000010
Nogai_Karachay_Cherkessia 0.119988 0.120774 0.000010 0.617261 0.141967
Veps 0.026887 0.000010 0.000010 0.000010 0.973083
Even 0.441349 0.278457 0.000010 0.015239 0.264946
Nganasan 0.999960 0.000010 0.000010 0.000010 0.000010
Bashkir 0.114088 0.056493 0.251488 0.030390 0.547542
Xibo 0.000010 0.985541 0.000010 0.000362 0.014077
Khakass 0.202707 0.171413 0.530905 0.007675 0.087300
Shor_Khakassia 0.258218 0.000010 0.694889 0.000010 0.046873
Nanai 0.105903 0.894067 0.000010 0.000010 0.000010
Buryat 0.064420 0.848458 0.017066 0.001696 0.068360
Yukagir_Forest 0.379416 0.096266 0.000010 0.003580 0.520728
Karachai 0.067138 0.004534 0.000010 0.798982 0.129336
Mordovian 0.022303 0.001193 0.000010 0.025251 0.951243
Turkish_Balikesir 0.092314 0.038550 0.000010 0.804964 0.064163
Turkish 0.040918 0.012255 0.000010 0.873179 0.073639
Kyrgyz_Kyrgyzstan 0.090129 0.607265 0.000010 0.122885 0.179711
Balkar 0.075115 0.000010 0.000010 0.829730 0.095136
Gagauz 0.000010 0.027887 0.015891 0.601619 0.354593
Nogai_Stavropol 0.070584 0.403817 0.000010 0.244701 0.280888
Negidal 0.248518 0.751452 0.000010 0.000010 0.000010
Tatar_Mishar 0.066112 0.037441 0.010377 0.138008 0.748062",row.names=1)
hc=hclust(dist(t))
hc=reorder(hc,-(t[,1]+t[,2]-t[,4]-2*t[,5]))
labelcolor=hcl(c(260,90,120,60,0,210,180,310)+15,60,70)
barcolor=hcl(c(310,260,120,60,210)+15,60,70)
labels=hc$labels[hc$order]
cut=cutree(hc,8)
dend=color_branches(as.dendrogram(hc),k=length(unique(cut)),col=labelcolor[unique(cut[labels])])
t=t[hc$labels[hc$order],]
circos.clear()
png("a.png",w=2500,h=2500,res=300)
circos.par(cell.padding=c(0,0,0,0),gap.degree=5,points.overflow.warning=F)
circos.initialize("a",xlim=c(0,nrow(t)))
circos.track(ylim=c(0,1),bg.border=NA,track.height=.28,track.margin=c(.01,0),
panel.fun=function(x,y)for(i in 1:nrow(t))circos.text(i-.5,0,labels[i],adj=c(0,.5),facing="clockwise",niceFacing=T,cex=.65,col=labelcolor[cut[labels[i]]]))
circos.track(ylim=c(0,1),track.margin=c(0,0),track.height=.35,bg.lty=0,panel.fun=function(x,y){
mat=as.matrix(t)
pos=1:nrow(mat)-.5
barwidth=1
for(i in 1:ncol(mat)){
seq1=rowSums(mat[,seq(i-1),drop=F])
seq2=rowSums(mat[,seq(i),drop=F])
circos.rect(pos-barwidth/2,if(i==1){0}else{seq1},pos+barwidth/2,seq2,col=barcolor[i],border="gray20",lwd=.1)
}
for(i in 1:ncol(mat)){
seq1=rowSums(mat[,seq(i-1),drop=F])
seq2=rowSums(mat[,seq(i),drop=F])
lab=round(100*t[,i])
lab[lab<=1]=""
circos.text(pos,if(i==1){seq1/2}else{seq1+(seq2-seq1)/2},labels=lab,col="gray10",cex=.4,facing="downward")
}
})
circos.track(ylim=c(0,attr(dend,"height")),bg.border=NA,track.margin=c(0,.0015),track.height=.35,panel.fun=function(x,y)circos.dendrogram(dend))
circos.clear()
dev.off()
| stackoverflow | {
"language": "en",
"length": 1581,
"provenance": "stackexchange_0000F.jsonl.gz:898328",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646488"
} |
a7682c9048e9aec1c4003f5c038390f1c2b0e87c | Stackoverflow Stackexchange
Q: How to serve static directory from "ng serve" Can I ask if there are any similar config for webpack dev server config like this:
devServer : {
historyApiFallback : true,
stats : 'minimal',
contentBase: helpers.root('../src/static'),
}
I want to serve static files from static directory like how the webpack dev server is serving files.
Thanks
A: Yes you can. In angular.json, you can use entries named assets. Whatever file or directory you include in assets value array, will be served via ng serve. Whatever you add in projects/<your-project>/architect/build/options/assets, will be served in all build configurations and included in dist directory of production build.
If you want something to be available only during development or testing, you can use Build Configurations. By default, you have a section projects/<your-project>/architect/build/configurations/production. So, you could add your own section, such as ../build/configurations/dev (perhaps initially copying whatever is in production section). Then, you can add assets entry there. These assets won't be available in production configuration.
To launch ng serve to specific configuration, you use --configuration argument. For example, to match dev configuration:
ng serve --configuration=dev
Disclaimer: Didn't test above - just reading the manual :-)
| Q: How to serve static directory from "ng serve" Can I ask if there are any similar config for webpack dev server config like this:
devServer : {
historyApiFallback : true,
stats : 'minimal',
contentBase: helpers.root('../src/static'),
}
I want to serve static files from static directory like how the webpack dev server is serving files.
Thanks
A: Yes you can. In angular.json, you can use entries named assets. Whatever file or directory you include in assets value array, will be served via ng serve. Whatever you add in projects/<your-project>/architect/build/options/assets, will be served in all build configurations and included in dist directory of production build.
If you want something to be available only during development or testing, you can use Build Configurations. By default, you have a section projects/<your-project>/architect/build/configurations/production. So, you could add your own section, such as ../build/configurations/dev (perhaps initially copying whatever is in production section). Then, you can add assets entry there. These assets won't be available in production configuration.
To launch ng serve to specific configuration, you use --configuration argument. For example, to match dev configuration:
ng serve --configuration=dev
Disclaimer: Didn't test above - just reading the manual :-)
A: Yes there sure is.
Look in the root of your Angular app for a file called angular.json. There's an entry called "assets". Add your static directories here. Anything under them will be served directly via ng serve. And when you go live, all of these files will be copied to the /dist directory so they'll be served in a production environment also.
"projects": {
"YourCoolProject": {
"root": "",
...
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist",
...
"assets": [
"src/assets",
"myOtherStaticFiles" /* <-- Add *your* directory(s) here */
],
"styles": [
...
p.s. Yes, I know you can't really comment JSON. Give me a break.
A: This answer is verified against Angular 8+. In cases where your static files are outside sourceDir (find in your angular.json file), for example somewhere in your node_modules then you need to add something like this your angular.json file:
root: "",
architect: {
build: {
options:{
outputPath: "dist/smartui",
assets: {
{
"glob": "**/*",
"input": "node_modules/@cruxcode/smartpdf",
"output": "smartpdf/"
}
}
}
}
}
Once you do this, whenever you will build your project or use ng serve, the assets from the input will be copied to the output you mentioned in the angular.json file as shown above. The output directory will appear in the outputPath directory once you build or serve it.
glob is matched inside the input directory.
Your assets will be available at output/. In the above example, I can access the assets in my code as follows
<img src="smartpdf/web/index.html">
| stackoverflow | {
"language": "en",
"length": 441,
"provenance": "stackexchange_0000F.jsonl.gz:898337",
"question_score": "24",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646504"
} |
4ea685a06c073c1b975f279180011c802443eda7 | Stackoverflow Stackexchange
Q: Apple Watch base localisation shows wrong default language I have an app localised in three languages (Simplified Chinese, French and Czech) with English as the development language.
While the localisations work perfectly on the iPhone, there is an issue with the Apple Watch: If a user has set the Watch language in any other language than English/French/Chinese/Czech, then the content is shown in Chinese instead of English (that should be the default).
According to this Technical Note:
If none of the user’s preferred languages are supported by your app, iOS chooses the language matching your app's development region (CFBundleDevelopmentRegion).
Note: Be sure to set CFBundleDevelopmentRegion for your app. If you adopt Base Localization, make sure that the value of
CFBundleDevelopmentRegion matches the language used by your content in
the Base.lproj folder.
I have confirmed both the above requirements are being satisfied (CFBundleDevelopmentRegion="en" and all Base.lproj files are indeed in English). Is there something I'm missing? Again, this happens only for the Watch app and not for the iPhone one.
A: From https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/20001431-130430 , CFBundleDevelopmentRegion is the language and region, e.g. en-US, not just en.
| Q: Apple Watch base localisation shows wrong default language I have an app localised in three languages (Simplified Chinese, French and Czech) with English as the development language.
While the localisations work perfectly on the iPhone, there is an issue with the Apple Watch: If a user has set the Watch language in any other language than English/French/Chinese/Czech, then the content is shown in Chinese instead of English (that should be the default).
According to this Technical Note:
If none of the user’s preferred languages are supported by your app, iOS chooses the language matching your app's development region (CFBundleDevelopmentRegion).
Note: Be sure to set CFBundleDevelopmentRegion for your app. If you adopt Base Localization, make sure that the value of
CFBundleDevelopmentRegion matches the language used by your content in
the Base.lproj folder.
I have confirmed both the above requirements are being satisfied (CFBundleDevelopmentRegion="en" and all Base.lproj files are indeed in English). Is there something I'm missing? Again, this happens only for the Watch app and not for the iPhone one.
A: From https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/20001431-130430 , CFBundleDevelopmentRegion is the language and region, e.g. en-US, not just en.
A: I have both Traditional Chinese and Simplified Chinese but it choose Traditional Chinese as the default language. When I delete the Traditional Chinese translation English is selected.
I also set the CFBundleDevelopmentRegion to en which is the default.
From your screen shot I didn't see English - Development English.
A: I was having the same issue, and found the solution in this thread:
https://forums.developer.apple.com/thread/86889
Basically, the watch extension needs needed a Localizable.strings (Base) file. Ordinarily on the iOS side you don't actually need to specify a Base version of the file, only the translations. But on the watch it seems to requires a base version of the file for the system to work at all there. In fact, I only had an Interface translated (in the watch app) and didn't even have a Localizable.strings in the watch extension... so I had to add some localizable strings in the extension, export translations, import them again, and then manually add a Base version (by checking Base in the Localization section of the File Inspector) because this apparently required thing isn't created automatically.
| stackoverflow | {
"language": "en",
"length": 366,
"provenance": "stackexchange_0000F.jsonl.gz:898344",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646525"
} |
2e50d780aaa5fbbdaa24752b20b3fa4db5843c8a | Stackoverflow Stackexchange
Q: Is there something like a Safe Navigation Operator that can be used on Arrays? I have used Safe Navigation Operator for Objects to load on Asynchronous calls and it is pretty amazing. I thought I could reproduce the same for Arrays but it displays a template parse error in my Angular code. I know *ngIf is an alternative solution, but is there a more simpler(by code) way just like the Safe Navigation Operator?
<div class="mock">
<h5>{{data?.title}}</h5> //This works
<h6>{{data?.body}}</h6> //This works
<h6>{{simpleData?[0]}}</h6> // This is what I tried to implement
</div>
A: Of cause it's a matter of taste, but in such cases I tend to use a shorter approach:
<h6>{{(simpleData || [])[0]}}</h6>
| Q: Is there something like a Safe Navigation Operator that can be used on Arrays? I have used Safe Navigation Operator for Objects to load on Asynchronous calls and it is pretty amazing. I thought I could reproduce the same for Arrays but it displays a template parse error in my Angular code. I know *ngIf is an alternative solution, but is there a more simpler(by code) way just like the Safe Navigation Operator?
<div class="mock">
<h5>{{data?.title}}</h5> //This works
<h6>{{data?.body}}</h6> //This works
<h6>{{simpleData?[0]}}</h6> // This is what I tried to implement
</div>
A: Of cause it's a matter of taste, but in such cases I tend to use a shorter approach:
<h6>{{(simpleData || [])[0]}}</h6>
A:
Is there something like a Safe Navigation Operator that can be used on Arrays?
Yes, what you are looking for is known as the Optional Chaining operator (JavaScript / TypeScript).
The syntax shown in the MDN JavaScript documentation is:
obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)
So, to achieve what you want, you need to change your example from:
<h6>{{simpleData?[0]}}</h6>
To:
<h6>{{simpleData?.[0]}}</h6>
^
Also see How to use optional chaining with array in Typescript?.
A:
is there a more simpler(by code) way just like the Safe Navigation Operator?
There is ternary operator.
condition ? expr1 : expr2
<h6>{{simpleData?simpleData[0]:''}}</h6>
A: The other answers amount to the same thing, but I find foo && foo[0] to be the most readable. The right side of the logical-and operator won't be evaluated if the left side is falsy, so you safely get undefined (or I guess null, if you don't believe Douglas Crockford.) with minimal extra characters.
For that matter, you asked for a "simpler" solution, but actually *ngIf is probably correct for the use case you gave. If you use any of the answers here, you'll wind up with an empty h6 tag that you didn't need. If you make the tag itself conditional, you can just put foo[0] in the handlebars and be confident that it won't be evaluated when foo is still undefined, plus you never pollute the page with an empty tag.
| stackoverflow | {
"language": "en",
"length": 344,
"provenance": "stackexchange_0000F.jsonl.gz:898363",
"question_score": "24",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646597"
} |
fd934b13284db0187a6cfcdf8f19c21c7bfb78da | Stackoverflow Stackexchange
Q: while(i != i) { } - is it possible to have an assignment that is always true Recently I had an interview with a Software company where the following question was asked in the technical aptitude round:
Declare i in such a way that the condition is always true :
while(i != i) {
}
Is it technically possible in java to assign something of this sort??
A: NaN is not equal to itself, so
double i = Double.NaN;
But I don't think this is a good interview question.
Quote from the Java Language Specification:
NaN is unordered, so:
*
*The numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.20.1).
*The equality operator == returns false if either operand is NaN. In particular, (x<y) == !(x>=y) will be false if x or
y is NaN.
*The inequality operator != returns true if either operand is NaN (§15.21.1). In particular, x!=x is true if and only if x
is NaN.
| Q: while(i != i) { } - is it possible to have an assignment that is always true Recently I had an interview with a Software company where the following question was asked in the technical aptitude round:
Declare i in such a way that the condition is always true :
while(i != i) {
}
Is it technically possible in java to assign something of this sort??
A: NaN is not equal to itself, so
double i = Double.NaN;
But I don't think this is a good interview question.
Quote from the Java Language Specification:
NaN is unordered, so:
*
*The numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.20.1).
*The equality operator == returns false if either operand is NaN. In particular, (x<y) == !(x>=y) will be false if x or
y is NaN.
*The inequality operator != returns true if either operand is NaN (§15.21.1). In particular, x!=x is true if and only if x
is NaN.
| stackoverflow | {
"language": "en",
"length": 169,
"provenance": "stackexchange_0000F.jsonl.gz:898366",
"question_score": "13",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646603"
} |
ed6d6b767056e28f7c83d9d7cae84b1266f2bf4c | Stackoverflow Stackexchange
Q: Find the longest length of an array item - JS I need to find the length of the longest string in the given array. It should return 0 if the array is empty.
So here's my try:
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for(var i=0; i< arr.length; i++){
if(arr[i] > biggestNum){
biggestNum = arr[i];
}
}
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output); // --> MUST RETURN 5
But this one did not work. Any idea or is there any better option to do this?
A: To throw another alternative into the mix: Math.max can be fed the lengths as arguments (by mapping them on the input) to get the longest string:
function getLengthOfLongestElement(arr) {
return Math.max(0,...arr.map(s=>s.length));
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output);
| Q: Find the longest length of an array item - JS I need to find the length of the longest string in the given array. It should return 0 if the array is empty.
So here's my try:
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for(var i=0; i< arr.length; i++){
if(arr[i] > biggestNum){
biggestNum = arr[i];
}
}
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output); // --> MUST RETURN 5
But this one did not work. Any idea or is there any better option to do this?
A: To throw another alternative into the mix: Math.max can be fed the lengths as arguments (by mapping them on the input) to get the longest string:
function getLengthOfLongestElement(arr) {
return Math.max(0,...arr.map(s=>s.length));
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output);
A: This is apparently a reducing job and can simply be implemented as follows;
var ss = ['one', 'two', 'three'],
ln = ss.reduce((r,s) => r > s.length ? r : s.length, 0);
console.log(ln);
A: You should test with arr[i].length instead of arr[i] and you should return biggestNum at the end of your function:
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > biggestNum) {
biggestNum = arr[i].length;
}
}
return biggestNum;
}
Demo:
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > biggestNum) {
biggestNum = arr[i].length;
}
}
return biggestNum;
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output);
A: You should use the string length property. So instead of arr[i] it will be arr[i].length
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > biggestNum) {
biggestNum = arr[i].length;
}
}
return biggestNum;
}
A: My preferred solution is using reduce.
const arr = ['one', 'two', 'three'];
const maxLength = arr.reduce((acc, item) => Math.max(acc, item.length), 0);
console.log(maxLength)
A: For zero element just check if the array length is zero or not else arr[i].length will return the length of the string
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
if (arr.length > 0) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > biggestNum) {
biggestNum = arr[i].length;
}
}
} else if (arr.length == 0) {
biggestNum = 0
}
return biggestNum
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output);
| stackoverflow | {
"language": "en",
"length": 394,
"provenance": "stackexchange_0000F.jsonl.gz:898377",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646631"
} |
e2340fa6e229074cf8e6f5b61b86f3172445a692 | Stackoverflow Stackexchange
Q: Send a file through rabbitmq I have a python client and a symfony backend. They can send and receive messages using rabbitmq.
I use rabbitmq symfony bundle on my backend.
I send an id of a php entity to the python client which get i through my api, do some work (heavy work) and store the result in a zip file. I want to send this zip file through rabbitmq. Is it possible? The file is really large (like 5mo)
If it's possible how can i do it ? (in an efficient way)
A: I would not recommend using a message broker to send files.
I would store the zip file somewhere s3, nfs, disk and add the URI as a resource pointer in the message.
More information about messages queues and message sizes can be found here:
Maximum message size for RabbitMQ
| Q: Send a file through rabbitmq I have a python client and a symfony backend. They can send and receive messages using rabbitmq.
I use rabbitmq symfony bundle on my backend.
I send an id of a php entity to the python client which get i through my api, do some work (heavy work) and store the result in a zip file. I want to send this zip file through rabbitmq. Is it possible? The file is really large (like 5mo)
If it's possible how can i do it ? (in an efficient way)
A: I would not recommend using a message broker to send files.
I would store the zip file somewhere s3, nfs, disk and add the URI as a resource pointer in the message.
More information about messages queues and message sizes can be found here:
Maximum message size for RabbitMQ
| stackoverflow | {
"language": "en",
"length": 144,
"provenance": "stackexchange_0000F.jsonl.gz:898391",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646674"
} |
0c8805992725712b3a3f7dc0d93797ea4a3f772a | Stackoverflow Stackexchange
Q: UILabel or UITextView with first letter very big font in two line How to customize UILabel or UITextView like given image i-e big "T" is shown in two lines of the label. Or please suggest any library for that:
A: I think that you will find in here a lot of useful informations about this topic
So you need use CoreText to achieve your goal.
| Q: UILabel or UITextView with first letter very big font in two line How to customize UILabel or UITextView like given image i-e big "T" is shown in two lines of the label. Or please suggest any library for that:
A: I think that you will find in here a lot of useful informations about this topic
So you need use CoreText to achieve your goal.
A: Try this
Note this only for TextView
NSString *myTextString =@"Your are qualified as a lawyer specializing in marine cases, shipping, arbitration and commercial litigation";
UIBezierPath * imgRect = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 40, 40)]; // you can change this as per your needs
txtViewDescription.textContainer.exclusionPaths = @[imgRect];
txtViewDescription.text = myTextString;
txtViewDescription.text = [txtViewDescription.text substringFromIndex:1]; // Remove first letter from string
UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 80, 80)];// you can change this as per your needs
lbl.font = [UIFont fontWithName:Lato_BOLD size:50];
lbl.text = [myTextString substringToIndex: 1]; // get first letter of string
[self.view bringSubviewToFront:lbl];
[self.view addSubview:lbl];// if your textview added to self.view else change with your view
A: This is what I implemented on a playground (Swift 3 answer):
import UIKit
// declare the label:
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
label.numberOfLines = 2
label.backgroundColor = UIColor.white
// this should be the desired text
let myString = "This is my pretty string that should contains a couple of lines."
// setup the attributed string
let content = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 20)])
content.setAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 40), NSForegroundColorAttributeName: UIColor.red], range: NSRange(location: 0, length: 1))
// assign the string to the label
label.attributedText = content
Output:
A: @KKRocks's answer in Swift 3.0
let yourString = "This easy granola is inspired by a grain-free granola from Costco that I love. The ingredient list is short so I figured that I could make it at home quite easily."
let lbl = UILabel(frame: CGRect(x: 5, y: 5, width: 30, height: 30))
lbl.font = UIFont.boldSystemFont(ofSize: 40)
lbl.text = yourString[0]
txtView.addSubview(lbl)
txtView.bringSubview(toFront: lbl)
let bezierPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 35, height: 30))
txtView.textContainer.exclusionPaths = [bezierPath]
txtView.text = yourString.substring(from: 1)
// txtView.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10)
| stackoverflow | {
"language": "en",
"length": 353,
"provenance": "stackexchange_0000F.jsonl.gz:898406",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646718"
} |
23c7a2d42c8734693e4829561a1b831124173913 | Stackoverflow Stackexchange
Q: Does package-lock.json need to be versioned in git? npm 5 & nodejs 8 introduces a file named package-lock.json, I want to know if it is need to be versioned or be ignored in git
A: Short Answer : Yes It must be.
Long Answer :
As Per npmjs Documentaion :
package-lock.json is automatically generated for any operations
where npm modifies either the node_modules tree, or package.json.
It describes the exact tree that was generated, such that subsequent
installs are able to generate identical trees, regardless of
intermediate dependency updates.
This file is intended to be committed into source repositories, and serves various purposes:
*
*Describe a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to
install exactly the same dependencies.
*Provide a facility for users to time-travel to previous states of npm_modules without having to commit the directory itself.
*To facilitate greater visibility of tree changes through readable source control diffs.
*And optimize the installation process by allowing npm to skip repeated metadata resolutions for previously-installed packages.
| Q: Does package-lock.json need to be versioned in git? npm 5 & nodejs 8 introduces a file named package-lock.json, I want to know if it is need to be versioned or be ignored in git
A: Short Answer : Yes It must be.
Long Answer :
As Per npmjs Documentaion :
package-lock.json is automatically generated for any operations
where npm modifies either the node_modules tree, or package.json.
It describes the exact tree that was generated, such that subsequent
installs are able to generate identical trees, regardless of
intermediate dependency updates.
This file is intended to be committed into source repositories, and serves various purposes:
*
*Describe a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to
install exactly the same dependencies.
*Provide a facility for users to time-travel to previous states of npm_modules without having to commit the directory itself.
*To facilitate greater visibility of tree changes through readable source control diffs.
*And optimize the installation process by allowing npm to skip repeated metadata resolutions for previously-installed packages.
| stackoverflow | {
"language": "en",
"length": 175,
"provenance": "stackexchange_0000F.jsonl.gz:898407",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646719"
} |
1a4970bdea24641007df818a5bb0ed5ddf3b3243 | Stackoverflow Stackexchange
Q: Mocha:How to bail only failed describe() in nested describe()? My test structure is as follows
describe('Test Suite'){
describe('First Test Case'){
it('1st step'){};
it('2nd step'){};
it('3rd step'){};
}
describe('Second Test Case'){
it('1st step'){};
it('2nd step'){};
it('3rd step'){};
}
}
I want to use --bail such that if inside First Test Case any it() fails then that describe() should be bailed.But the Second Test Case should run.
I am getting the expected result by using:
describe('Test Suite'){
this.bail(false)
describe('First Test Case'){
this.bail(true);
it('1st step'){};
it('2nd step'){};
it('3rd step'){};
}
describe('Second Test Case'){
this.bail(true);
it('1st step'){};
it('2nd step'){};
it('3rd step'){};
}
}
Is there any other way to do it without explicitly assigning bail to true in each describe()?
A: I found workaround, maybe it will help.
You can set up your condition not by file but my function name or test name.
In setup file:
const FAILED_TESTS = {};
// Skip test if first test from folder failed
beforeEach(function() {
if (FAILED_TESTS[this.currentTest.file]) {
this.skip();
}
});
afterEach(function() {
if (this.currentTest.state === "failed") {
FAILED_TESTS[this.currentTest.file] = true;
}
});
| Q: Mocha:How to bail only failed describe() in nested describe()? My test structure is as follows
describe('Test Suite'){
describe('First Test Case'){
it('1st step'){};
it('2nd step'){};
it('3rd step'){};
}
describe('Second Test Case'){
it('1st step'){};
it('2nd step'){};
it('3rd step'){};
}
}
I want to use --bail such that if inside First Test Case any it() fails then that describe() should be bailed.But the Second Test Case should run.
I am getting the expected result by using:
describe('Test Suite'){
this.bail(false)
describe('First Test Case'){
this.bail(true);
it('1st step'){};
it('2nd step'){};
it('3rd step'){};
}
describe('Second Test Case'){
this.bail(true);
it('1st step'){};
it('2nd step'){};
it('3rd step'){};
}
}
Is there any other way to do it without explicitly assigning bail to true in each describe()?
A: I found workaround, maybe it will help.
You can set up your condition not by file but my function name or test name.
In setup file:
const FAILED_TESTS = {};
// Skip test if first test from folder failed
beforeEach(function() {
if (FAILED_TESTS[this.currentTest.file]) {
this.skip();
}
});
afterEach(function() {
if (this.currentTest.state === "failed") {
FAILED_TESTS[this.currentTest.file] = true;
}
});
| stackoverflow | {
"language": "en",
"length": 177,
"provenance": "stackexchange_0000F.jsonl.gz:898421",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646751"
} |
2fce8712d9c284211363f4323edf0c3d8e4e0d4c | Stackoverflow Stackexchange
Q: replace all combinations of non-alphanumeric characters I need to to create url from various strings.
So trying to replace all non-alphanumeric characters and all of their combinations - with a hyphen character (-)
$string = "blue - sky";
$string = preg_replace("/[^A-Za-z0-9 ]/", '-', $string);
echo $string;
result - blue---sky
expected - blue-sky.
A: use the + sign to replace more than one character with one replacement character:
string = preg_replace("/[^A-Za-z0-9]+/", '-', $string);
| Q: replace all combinations of non-alphanumeric characters I need to to create url from various strings.
So trying to replace all non-alphanumeric characters and all of their combinations - with a hyphen character (-)
$string = "blue - sky";
$string = preg_replace("/[^A-Za-z0-9 ]/", '-', $string);
echo $string;
result - blue---sky
expected - blue-sky.
A: use the + sign to replace more than one character with one replacement character:
string = preg_replace("/[^A-Za-z0-9]+/", '-', $string);
| stackoverflow | {
"language": "en",
"length": 73,
"provenance": "stackexchange_0000F.jsonl.gz:898437",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646833"
} |
e9d13437186a337b315b2c7563172f6b07fd1107 | Stackoverflow Stackexchange
Q: What is the significance of configuration.svc and configuration91.svc files when adding a service reference (WSDL)? When we generate a WSDL, there are multiple files along which what interests me is configuration.svc and configuration91.svc ?
Why there are two files generated ? And why are they being named as 91 at end ?
| Q: What is the significance of configuration.svc and configuration91.svc files when adding a service reference (WSDL)? When we generate a WSDL, there are multiple files along which what interests me is configuration.svc and configuration91.svc ?
Why there are two files generated ? And why are they being named as 91 at end ?
| stackoverflow | {
"language": "en",
"length": 53,
"provenance": "stackexchange_0000F.jsonl.gz:898444",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646864"
} |
0031c3a71c436fc8dcdfa46d70e9dbeafbddcab2 | Stackoverflow Stackexchange
Q: Vim key map in jupyter notebook When editing a .py file with jupyter, I have the option to choose the vim key map in the Edit dropdown menu (alongside the Default, emacs and Sublime text options). However, when opening a notebook file (.ipynb), I do not have this option. Is there a way to activate this?
I know there are some third party plugins out there, but they don't seem to support block select mode and other more advanced options like regex commands.
Not sure it matters, but I'm opening my notebooks with the Anaconda navigator.
A: Check this plugin lambdalisue/jupyter-vim-binding.
Attached screenshot to get an idea about the plugin:
| Q: Vim key map in jupyter notebook When editing a .py file with jupyter, I have the option to choose the vim key map in the Edit dropdown menu (alongside the Default, emacs and Sublime text options). However, when opening a notebook file (.ipynb), I do not have this option. Is there a way to activate this?
I know there are some third party plugins out there, but they don't seem to support block select mode and other more advanced options like regex commands.
Not sure it matters, but I'm opening my notebooks with the Anaconda navigator.
A: Check this plugin lambdalisue/jupyter-vim-binding.
Attached screenshot to get an idea about the plugin:
| stackoverflow | {
"language": "en",
"length": 111,
"provenance": "stackexchange_0000F.jsonl.gz:898457",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646907"
} |
5caf0a26dac44b122bff9847d78ed3e88f98a3ac | Stackoverflow Stackexchange
Q: Will it be possible to annotate lambda expression in Java 9? This question is now over 3 years old and specifically addressed Java 8, with the accepted answer also citing the Java SE 8 Final Specification.
I would be interested if something regarding this question will change in Java 9: Is there any way to annotate a lambda expression similar to annotating a corresponding anonymous class?
Example:
Annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface MyTypeAnnotation {
public String value();
}
Working annotation of anonymous class:
Consumer<String> consumer = new @MyTypeAnnotation("Hello ") Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
};
Annotating a lamba expression, currently not working in Java 8:
Consumer<String> myAnnotatedConsumer = @MyTypeAnnotation("Hello") (p -> System.out.println(p));
A: it's interesting that they do annotate the inner class that "represents" the lambda expression in InnerClassLambdaMetafactory.spinInnerClass via :
mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true)
But that is annotating a class obviously, not a lambda per-se.
Annotating a lambda would require changes to the invokedynamic and implicitly the LambdaMetafactory as far as I can see - and what would happen when invokedynamic would not create a class for the lambda, but something else, what would happen to those annotations?
| Q: Will it be possible to annotate lambda expression in Java 9? This question is now over 3 years old and specifically addressed Java 8, with the accepted answer also citing the Java SE 8 Final Specification.
I would be interested if something regarding this question will change in Java 9: Is there any way to annotate a lambda expression similar to annotating a corresponding anonymous class?
Example:
Annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface MyTypeAnnotation {
public String value();
}
Working annotation of anonymous class:
Consumer<String> consumer = new @MyTypeAnnotation("Hello ") Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
};
Annotating a lamba expression, currently not working in Java 8:
Consumer<String> myAnnotatedConsumer = @MyTypeAnnotation("Hello") (p -> System.out.println(p));
A: it's interesting that they do annotate the inner class that "represents" the lambda expression in InnerClassLambdaMetafactory.spinInnerClass via :
mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true)
But that is annotating a class obviously, not a lambda per-se.
Annotating a lambda would require changes to the invokedynamic and implicitly the LambdaMetafactory as far as I can see - and what would happen when invokedynamic would not create a class for the lambda, but something else, what would happen to those annotations?
A: According to the What's new in Oracle JDK 9 page, No. This has not changed in Java 9.
Of course, that is not definitive, but the JLS for Java 9 has not been released yet.
A: The existence of a Stack Overflow question is not sufficient to indicate that such a feature is planned, not even that someone is ever considering it.
If you look at the list of JEPs, you will see that there is no such JEP, not even in a draft state, suggesting such a feature.
Also, if you look at the current state of Java 9’s LambdaMetafactory, you will see that no change has been made to support passing the meta information that would be necessary to generate a runtime class with recorded annotation data.
There seems to be some desire to add plenty of meta-information to what actually should be a small piece of throw-away code, but I doubt that the language designer will follow it. Lambda expressions are meant to define a function which encapsulates behavior, not an alternative way to describe an anonymous class. The long term evolution will rather lead to lambda expression implementations which are even less of an ordinary class.
| stackoverflow | {
"language": "en",
"length": 394,
"provenance": "stackexchange_0000F.jsonl.gz:898460",
"question_score": "20",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646915"
} |
a5273fb53f006426a825fe271cd077a5aa54723e | Stackoverflow Stackexchange
Q: Paste option in CKeditor doesnt seem to work in Chrome and firefox Using the online ckeditor http://sdk.ckeditor.com/samples/classic.html
I see the past options (Paste, Paste as plain text and paste from word) doesn't copy from clipboard.
I gives the error 'Your browser does not allow you to paste plain text this way. Press Ctrl+Shift+V to paste.' But it seems to work in IE(it prompts for allow access) and not in Chrome or Firefox.
Is this a bug or some configurations needs to done from browser or ckEditor. Cause I remember I used the same behavior few months back and it used to give a popup to paste you content to the editor.
Thanks,
Vijai
A: Just add this code to config.js:
CKEDITOR.on("instanceReady", function(event) {
event.editor.on("beforeCommandExec", function(event) {
// Show the paste dialog for the paste buttons and right-click paste
if (event.data.name == "paste") {
event.editor._.forcePasteDialog = true;
}
// Don't show the paste dialog for Ctrl+Shift+V
if (event.data.name == "pastetext" && event.data.commandData.from == "keystrokeHandler") {
event.cancel();
}
})
});
| Q: Paste option in CKeditor doesnt seem to work in Chrome and firefox Using the online ckeditor http://sdk.ckeditor.com/samples/classic.html
I see the past options (Paste, Paste as plain text and paste from word) doesn't copy from clipboard.
I gives the error 'Your browser does not allow you to paste plain text this way. Press Ctrl+Shift+V to paste.' But it seems to work in IE(it prompts for allow access) and not in Chrome or Firefox.
Is this a bug or some configurations needs to done from browser or ckEditor. Cause I remember I used the same behavior few months back and it used to give a popup to paste you content to the editor.
Thanks,
Vijai
A: Just add this code to config.js:
CKEDITOR.on("instanceReady", function(event) {
event.editor.on("beforeCommandExec", function(event) {
// Show the paste dialog for the paste buttons and right-click paste
if (event.data.name == "paste") {
event.editor._.forcePasteDialog = true;
}
// Don't show the paste dialog for Ctrl+Shift+V
if (event.data.name == "pastetext" && event.data.commandData.from == "keystrokeHandler") {
event.cancel();
}
})
});
A: Chrome does not allow this because this is a security hole. Someone could steal your copied data so chrome and most other browsers do not allow you to do this. press ctrl shift and v to paste it.
A: According to official ckeditor team : right now there is no solution for this issue.
Refer this link:
https://github.com/ckeditor/ckeditor-dev/issues/469
I think currently the best possible solution is to just remove them using:
removeButtons : "Paste,PasteText,PasteFromWord"
I suggest everyone who are facing this issue keep commenting them so they'll do something for this issue. Or try using the lower version.
A: Use the CKEditor Upload Image plugin.
DEMO
We had the same issue. Added the plugin and image upload and download API action.
Then remove the past buttons from the editor.
config.removeButtons = 'Paste,PasteText,PasteFromWord';
Add the following code into CKEditor config.js
config.extraPlugins = 'uploadimage';
config.uploadUrl = '/uploader/upload.php';
config.filebrowserUploadUrl = '/uploader/upload.php';
After that, use CTRL + V to past the image from word doc.
I am using MVC5. So the configuration is
config.extraPlugins = 'uploadimage';
config.uploadUrl = '/CkEditorUploadSupport/UploadImage';
config.filebrowserUploadUrl = '/CkEditorUploadSupport/UploadImage';
MVC Controller Code ; (Controller Name "CkEditorUploadSupport" under project Controller folder)
public JsonResult UploadImage()
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var file = System.Web.HttpContext.Current.Request.Files["upload"];
var targetLocation = @"D:\CKTestFolder";
if (!Directory.Exists(targetLocation))
{
Directory.CreateDirectory(targetLocation);
}
var pattern = new Regex(@"[:!@#$%^&*()}{|\"":?><\[\]\\;'/,~]");
var modifiedFileName = pattern.Replace(file.FileName, "");
modifiedFileName = modifiedFileName.Replace("\"", " ");
modifiedFileName = modifiedFileName.Replace("4â€Â", " ");
// Some browsers send file names with full path.
// We are only interested in the file name.
var physicalPath = Path.Combine(targetLocation, modifiedFileName);
var fileName = Path.GetFileName(physicalPath);
var newName = fileName;
while (System.IO.File.Exists(physicalPath))
{
var newFileName = Path.GetFileNameWithoutExtension(fileName)
+ "_" + RandomString(3) +
Path.GetExtension(fileName);
physicalPath = Path.Combine(targetLocation, newFileName);
newName = newFileName;
}
file.SaveAs(physicalPath);
var response = new
{
uploaded = 1,
fileName = newName,
url = "/CkEditorUploadSupport/OpenImage?imageName=" + newName
};
return Json(response);
}
var response2 = new
{
uploaded = 0,
message = "Upload Error.."
};
return Json(response2);
}
public ActionResult OpenImage(string imageName)
{
var targetLocation = @"D:\CKTestFolder";
var physicalPath = Path.Combine(targetLocation, imageName);
if (!System.IO.File.Exists(physicalPath))
{
var response2 = new
{
uploaded = 0,
message = "File Not Found"
};
return Json(response2);
}
string mimeType = MimeMapping.GetMimeMapping(imageName);
return base.File(physicalPath, mimeType);
}
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
| stackoverflow | {
"language": "en",
"length": 556,
"provenance": "stackexchange_0000F.jsonl.gz:898472",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646968"
} |
5494fb28952f5ed71f841f6f2df0b523728671e7 | Stackoverflow Stackexchange
Q: Umbraco surface controller does not work I've got a site, and it works well on my local computer.
Then I upload it on a server and test it, but the surface controller I called with AJAX can not be routed, and returns 404 status.
My server is Windows Server 2016 Datacenter, and IIS version is 10.
My computer is Windows 10.....
Thanks ~
A: I found the solution, and the answer is kind of bizzare.
First of all, I tried:
*
*renaming my controllers namespace from [UmbracoProjectname].Controllers to Controllers (as seen in SO another post)
*making web.config identical in production as in local server where it works
*updating umbracoReservedPaths with my controller path
*lot of other stuff I forgot at the moment
The solution was this:
Instead of calling
https://domain.tld/umbraco/Surface/CustomSurface/test
I called it this way:
https://domain.tld//umbraco/Surface/CustomSurface/test
(Notice two slashes after domain)
So I guess it was some routing issue, I got it fixed this way. Hope it will help someone else.
| Q: Umbraco surface controller does not work I've got a site, and it works well on my local computer.
Then I upload it on a server and test it, but the surface controller I called with AJAX can not be routed, and returns 404 status.
My server is Windows Server 2016 Datacenter, and IIS version is 10.
My computer is Windows 10.....
Thanks ~
A: I found the solution, and the answer is kind of bizzare.
First of all, I tried:
*
*renaming my controllers namespace from [UmbracoProjectname].Controllers to Controllers (as seen in SO another post)
*making web.config identical in production as in local server where it works
*updating umbracoReservedPaths with my controller path
*lot of other stuff I forgot at the moment
The solution was this:
Instead of calling
https://domain.tld/umbraco/Surface/CustomSurface/test
I called it this way:
https://domain.tld//umbraco/Surface/CustomSurface/test
(Notice two slashes after domain)
So I guess it was some routing issue, I got it fixed this way. Hope it will help someone else.
A: Is it possible your live (server) site has a different root URL?
Maybe your local is http://localhost/controller but your uploaded live site might be http://www.myserver.com/myapp/controller
In that case you will need to check if you are referring to the URL using /controller - and you might have to introduce a setting to indicate the root URL of your site (and you then have a different setting value for each environment).
| stackoverflow | {
"language": "en",
"length": 233,
"provenance": "stackexchange_0000F.jsonl.gz:898473",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44646969"
} |
b82731d7a5c816db6ecacf4a304c24c57406918c | Stackoverflow Stackexchange
Q: How to remove “via” and server name when sending mails via laravel 5.4 not with php mail function I am sending emails using smtp in a laravel 5.4 project.
Mail::send('emails.passwordreset-user', ['token' => $originalToken, 'name' => $dataWithEmail->first_name,'email' => $supportEmail], function($message) use ($dataWithEmail) {
$message->to($dataWithEmail->email, $dataWithEmail->first_name)->replyTo($dataWithEmail->adminEmail, 'Sender name')
->subject('Password Reset');
});
I need to remove "via servername" that appears just after from email address in the email.
I found that we can solve using -f parameter in php mail function. But how to deal the same in laravel 5.4.
A: First, take a look at: https://stackoverflow.com/a/14964547/9764507. You need to set a SPF and DKIM.
Then, create a Mailable for your email and try with Return-Path header in build() method of Mailable:
public function build()
{
$this->view('emails.passwordreset-user');
$this->withSwiftMessage(function ($message) {
$message->getHeaders()
->addTextHeader('Return-Path', 'return@yourdomain.com');
});
}
More about Mailables here: Writing Mailables
| Q: How to remove “via” and server name when sending mails via laravel 5.4 not with php mail function I am sending emails using smtp in a laravel 5.4 project.
Mail::send('emails.passwordreset-user', ['token' => $originalToken, 'name' => $dataWithEmail->first_name,'email' => $supportEmail], function($message) use ($dataWithEmail) {
$message->to($dataWithEmail->email, $dataWithEmail->first_name)->replyTo($dataWithEmail->adminEmail, 'Sender name')
->subject('Password Reset');
});
I need to remove "via servername" that appears just after from email address in the email.
I found that we can solve using -f parameter in php mail function. But how to deal the same in laravel 5.4.
A: First, take a look at: https://stackoverflow.com/a/14964547/9764507. You need to set a SPF and DKIM.
Then, create a Mailable for your email and try with Return-Path header in build() method of Mailable:
public function build()
{
$this->view('emails.passwordreset-user');
$this->withSwiftMessage(function ($message) {
$message->getHeaders()
->addTextHeader('Return-Path', 'return@yourdomain.com');
});
}
More about Mailables here: Writing Mailables
| stackoverflow | {
"language": "en",
"length": 139,
"provenance": "stackexchange_0000F.jsonl.gz:898517",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647098"
} |
e809c0498fab248657d5504710fd96415ec65dde | Stackoverflow Stackexchange
Q: Are timestamps stored with a timezone in Apache Hive? The following discussion seems to indicate that Hive timestamps have a timezone:
https://community.hortonworks.com/questions/83523/timestamp-in-hive-without-timezone.html
The apache wiki says "Timestamps are interpreted to be timezoneless and stored as an offset from the UNIX epoch."
I am referring to: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Types#LanguageManualTypes-TimestampstimestampTimestamps
If I use code like the following:
from_unixtime(unix_timestamp(ts_field,'yyyy-MM-dd HH:mm:ss'), 'yyyy-MM-dd HH:mm:ss z') as ts_field_tz
This seems to expose an underlying timezone value.
A: The phrase "timezone-less" is misleading; what it means actually is that...
If you have data files written by Hive, those TIMESTAMP values
represent the local timezone of the host where the data was written
That is an excerpt from the Impala documentation -- and they make it very explicit, because it's a real pain when you need to access the same table from both Hive and Impala, since contrary to Hive...
By default, Impala does not store timestamps using the local timezone,
to avoid undesired results from unexpected time zone issues.
Timestamps are stored and interpreted relative to UTC
| Q: Are timestamps stored with a timezone in Apache Hive? The following discussion seems to indicate that Hive timestamps have a timezone:
https://community.hortonworks.com/questions/83523/timestamp-in-hive-without-timezone.html
The apache wiki says "Timestamps are interpreted to be timezoneless and stored as an offset from the UNIX epoch."
I am referring to: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Types#LanguageManualTypes-TimestampstimestampTimestamps
If I use code like the following:
from_unixtime(unix_timestamp(ts_field,'yyyy-MM-dd HH:mm:ss'), 'yyyy-MM-dd HH:mm:ss z') as ts_field_tz
This seems to expose an underlying timezone value.
A: The phrase "timezone-less" is misleading; what it means actually is that...
If you have data files written by Hive, those TIMESTAMP values
represent the local timezone of the host where the data was written
That is an excerpt from the Impala documentation -- and they make it very explicit, because it's a real pain when you need to access the same table from both Hive and Impala, since contrary to Hive...
By default, Impala does not store timestamps using the local timezone,
to avoid undesired results from unexpected time zone issues.
Timestamps are stored and interpreted relative to UTC
| stackoverflow | {
"language": "en",
"length": 169,
"provenance": "stackexchange_0000F.jsonl.gz:898529",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647134"
} |
391c985c6e81f5b556f5766f27eb76a5061f7930 | Stackoverflow Stackexchange
Q: Getting HIVE_CURSOR_ERROR while querying the table created in Amazon Athena I am getting the below error while querying the table created in Amazon Athena.
Error
HIVE_CURSOR_ERROR: Row is not a valid JSON Object - JSONException: A JSONObject text must end with '}' at 2
The sample file which I am using and the query to create table is below. The table gets successfully created by the below query but when I am fetching the result from table I am getting the error. Please provide your valuable suggestion.
Note Sample Data
Create table
A: AWS Athena does not support multi-line JSON.
Athena knowledge center
Make sure your JSON record is on a single line
Athena doesn't currently support multi-line JSON records.
| Q: Getting HIVE_CURSOR_ERROR while querying the table created in Amazon Athena I am getting the below error while querying the table created in Amazon Athena.
Error
HIVE_CURSOR_ERROR: Row is not a valid JSON Object - JSONException: A JSONObject text must end with '}' at 2
The sample file which I am using and the query to create table is below. The table gets successfully created by the below query but when I am fetching the result from table I am getting the error. Please provide your valuable suggestion.
Note Sample Data
Create table
A: AWS Athena does not support multi-line JSON.
Athena knowledge center
Make sure your JSON record is on a single line
Athena doesn't currently support multi-line JSON records.
A: I'm abusing the answer field to have more space and to have my thoughts on this a little bit structured. I hope this is useful input to anyone using Athena.
I'm using Athena to create two tables. Single-line-json-based and multi-line-json-based reports in two separate bucket folders and two according tables.
Single-line reports in JSON are straightforward. For table creation I use this driver:
ROW FORMAT serde 'org.apache.hive.hcatalog.data.JsonSerDe'
However if you use this exact one to consume multi-line you will get an error PLUS there are three more things (I, II and III) to be aware of. First of all the different driver:
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
then
I the (invalid) JSON format. My multi-line files look like this:
{"key": "value"}
{"key": "value"}
Notice there is one JSON object per line and objects are NOT comma separated!
You can read about this here:
Store multiple elements in json files in AWS Athena
II Create Statement
Contrary to your screenshot for table creation @abc I used it without nested structs:
CREATE EXTERNAL TABLE IF NOT EXISTS internal_reports (
`Date` Date,
impressions INT,
reach INT,
follower INT,
...
)
III Date property
I came across this whole driver-experimenting thing because the Date property caused issues in my single-line table because my values for Date had time information not equal to midnight. For the other multi-line reports my Dates were ok (the time was exactly midnight). You can read about this here:
https://developer.ibm.com/answers/questions/177238/timestamp-format-must-be-yyyy-mm-dd-hhmmssffffffff/
Athena - DATE column correct values from JSON
Cheers
| stackoverflow | {
"language": "en",
"length": 370,
"provenance": "stackexchange_0000F.jsonl.gz:898530",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647136"
} |
acf688462a48f4ef99a9529de746cbd0123effcf | Stackoverflow Stackexchange
Q: Convert Bigquery results to Pandas Data Frame Below is the code to convert BigQuery results into Pandas data frame.
Im learning Python&Pandas and wonder if i can get suggestion/ideas about any kind of improvements to the code?
#...code to run query, that returns 3 columns: 'date' DATE, 'currency' STRING,'rate' FLOAT...
rows, total_count, token = query.fetch_data()
currency = []
rate = []
dates = []
for row in rows:
dates.append(row[0])
currency.append(row[1])
rate.append(row[2])
dict = {
'currency' : currency,
'date' : dates,
'rate' : rate
}
df2 = pd.DataFrame(dict)
df2['date'] = pd.to_datetime(df2['date'])
df2 = df2.set_index('date')
The above works. But looks chunky. Is there any way to do the same thing more efficiently than the above?
I tried libraries such as sqlalchemy but they do not support BigQuery. And generally my question is about code and syntax above.
A: You should use read_gbq() instead: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_gbq.html
| Q: Convert Bigquery results to Pandas Data Frame Below is the code to convert BigQuery results into Pandas data frame.
Im learning Python&Pandas and wonder if i can get suggestion/ideas about any kind of improvements to the code?
#...code to run query, that returns 3 columns: 'date' DATE, 'currency' STRING,'rate' FLOAT...
rows, total_count, token = query.fetch_data()
currency = []
rate = []
dates = []
for row in rows:
dates.append(row[0])
currency.append(row[1])
rate.append(row[2])
dict = {
'currency' : currency,
'date' : dates,
'rate' : rate
}
df2 = pd.DataFrame(dict)
df2['date'] = pd.to_datetime(df2['date'])
df2 = df2.set_index('date')
The above works. But looks chunky. Is there any way to do the same thing more efficiently than the above?
I tried libraries such as sqlalchemy but they do not support BigQuery. And generally my question is about code and syntax above.
A: You should use read_gbq() instead: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_gbq.html
A: Per the Using BigQuery with Pandas page in the Google Cloud Client Library for Python:
As of version 0.29.0, you can use the to_dataframe() function to retrieve query results or table rows as a pandas.DataFrame.
Aside: See Migrating from pandas-gbq for the difference between the google-cloud-bigquery BQ Python client library and pandas-gbq.
| stackoverflow | {
"language": "en",
"length": 196,
"provenance": "stackexchange_0000F.jsonl.gz:898573",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647310"
} |
4bede84616230f357c29006b2d0165421c5802f6 | Stackoverflow Stackexchange
Q: Complication placeholder not showing I've just added a complication to my watchOS app. I was able to select it on simulator's watch face, but it shows blank items. Temporary all methods of CLKComplicationDataSource return nil. I've created a new assets group for complication, added all required .png images as specified here, setup Complication Group property in Xcode target, but nothing shows up!
What should I do to enable static placeholder images for my complications?
Configuration in Xcode:
A: The problem was that the .xcassets file with placeholder images must be included into the watch extension bundle, but it was included into the watch app instead. I spend all day trying to figure this out.
| Q: Complication placeholder not showing I've just added a complication to my watchOS app. I was able to select it on simulator's watch face, but it shows blank items. Temporary all methods of CLKComplicationDataSource return nil. I've created a new assets group for complication, added all required .png images as specified here, setup Complication Group property in Xcode target, but nothing shows up!
What should I do to enable static placeholder images for my complications?
Configuration in Xcode:
A: The problem was that the .xcassets file with placeholder images must be included into the watch extension bundle, but it was included into the watch app instead. I spend all day trying to figure this out.
| stackoverflow | {
"language": "en",
"length": 115,
"provenance": "stackexchange_0000F.jsonl.gz:898597",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647379"
} |
812ce9cd5d70697b31ad6ea4f7fb8e3e0936d21d | Stackoverflow Stackexchange
Q: How do I configure Spring Cloud Consul to not de-register on shutdown I have a microservice which is automatically registered with Consul using Spring Cloud however when the service shuts down it's de-registered which means alerting we have configured using Prometheus fires once and then auto-resolves. How can I disable this functionality so the service remains registered unless manually removed.
| Q: How do I configure Spring Cloud Consul to not de-register on shutdown I have a microservice which is automatically registered with Consul using Spring Cloud however when the service shuts down it's de-registered which means alerting we have configured using Prometheus fires once and then auto-resolves. How can I disable this functionality so the service remains registered unless manually removed.
| stackoverflow | {
"language": "en",
"length": 61,
"provenance": "stackexchange_0000F.jsonl.gz:898605",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647397"
} |
1043d2a996460055514fddcc3da2a534dfdd547e | Stackoverflow Stackexchange
Q: How do I use j2html without rendering everything I am converting my html rendering code to use j2html. Whilst I like the library it is not easy for me to convert all the code in one go so sometimes I may convert the outer html to use j2html but not able to convert the inner html to j2html at the same time. So I would like j2html to be able to accept text passed to it as already rendered, but it always re-renders it so
System.out.println(p("<b>the bridge</b>"));
returns
<p><b>the bridge</b></p>
is there a way I get it to output
<p><b>the bridge</b></p>
Full Test Case
import j2html.tags.Text;
import static j2html.TagCreator.b;
import static j2html.TagCreator.p;
public class HtmlTest
{
public static void main(String[] args)
{
System.out.println(p(b("the bridge")));
System.out.println(p("<b>the bridge</b>"));
}
}
A: import static j2html.TagCreator.b;
import static j2html.TagCreator.p;
import static j2html.TagCreator.rawHtml;
public class HtmlTest
{
public static void main(String[] args)
{
System.out.println(p(b("the bridge")));
System.out.println(p(rawHtml("<b>the bridge</b>")));
}
}
Result:
<p><b>the bridge</b></p>
<p><b>the bridge</b></p>
| Q: How do I use j2html without rendering everything I am converting my html rendering code to use j2html. Whilst I like the library it is not easy for me to convert all the code in one go so sometimes I may convert the outer html to use j2html but not able to convert the inner html to j2html at the same time. So I would like j2html to be able to accept text passed to it as already rendered, but it always re-renders it so
System.out.println(p("<b>the bridge</b>"));
returns
<p><b>the bridge</b></p>
is there a way I get it to output
<p><b>the bridge</b></p>
Full Test Case
import j2html.tags.Text;
import static j2html.TagCreator.b;
import static j2html.TagCreator.p;
public class HtmlTest
{
public static void main(String[] args)
{
System.out.println(p(b("the bridge")));
System.out.println(p("<b>the bridge</b>"));
}
}
A: import static j2html.TagCreator.b;
import static j2html.TagCreator.p;
import static j2html.TagCreator.rawHtml;
public class HtmlTest
{
public static void main(String[] args)
{
System.out.println(p(b("the bridge")));
System.out.println(p(rawHtml("<b>the bridge</b>")));
}
}
Result:
<p><b>the bridge</b></p>
<p><b>the bridge</b></p>
A: In j2html 1.1.0 you can disable text-escaping by writing
Config.textEscaper = text -> text;
Be careful though..
| stackoverflow | {
"language": "en",
"length": 178,
"provenance": "stackexchange_0000F.jsonl.gz:898621",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647449"
} |
7a535b764f19cc395d4cf6efa0b4c5eed4d66f82 | Stackoverflow Stackexchange
Q: Eclipse segmentation fault I updated my ubuntu 14.04 and since then my eclipse is crashing.
On Starting, it is giving segmentation fault as soon as i click the menu buttons or try to use any short-cut keys.
I have tried most of workarounds, which i could find on internet.
This is my eclipse.ini file contents
-startup plugins/org.eclipse.equinox.launcher_1.3.0.dist.jar --launcher.GTK_version 2 --launcher.library plugins/org.eclipse.equinox.launcher.gtk.linux.x86_1.1.200.dist -showsplash org.eclipse.platform --launcher.XXMaxPermSize 256m --launcher.defaultAction openFile -vmargs -Xms40m -Xmx1024m -Dorg.eclipse.equinox.p2.reconciler.dropins.directory=/usr/share/eclipse/dropins -Dorg.eclipse.swt.browser.DefaultType=mozilla
I enable the core dump and checked using gdb, the stack seems to be corrupted.
There is nothing i could find in /var/logs/system.log
If i remember it correctly, the update had to do something with some C++ libraries.
Kindly help
A: we experienced the same problem within our company.
The fix we implemented was to call java directly with -vm option.
Unknown why it solves it but I found it by accident when investigating the
issue.
Open the eclipse.ini file and add the following directly after the openFile:
-vm
/usr/bin/java
That should resolve the issue.
| Q: Eclipse segmentation fault I updated my ubuntu 14.04 and since then my eclipse is crashing.
On Starting, it is giving segmentation fault as soon as i click the menu buttons or try to use any short-cut keys.
I have tried most of workarounds, which i could find on internet.
This is my eclipse.ini file contents
-startup plugins/org.eclipse.equinox.launcher_1.3.0.dist.jar --launcher.GTK_version 2 --launcher.library plugins/org.eclipse.equinox.launcher.gtk.linux.x86_1.1.200.dist -showsplash org.eclipse.platform --launcher.XXMaxPermSize 256m --launcher.defaultAction openFile -vmargs -Xms40m -Xmx1024m -Dorg.eclipse.equinox.p2.reconciler.dropins.directory=/usr/share/eclipse/dropins -Dorg.eclipse.swt.browser.DefaultType=mozilla
I enable the core dump and checked using gdb, the stack seems to be corrupted.
There is nothing i could find in /var/logs/system.log
If i remember it correctly, the update had to do something with some C++ libraries.
Kindly help
A: we experienced the same problem within our company.
The fix we implemented was to call java directly with -vm option.
Unknown why it solves it but I found it by accident when investigating the
issue.
Open the eclipse.ini file and add the following directly after the openFile:
-vm
/usr/bin/java
That should resolve the issue.
A: Steps using grub:
First, you must have it when starting the computer. If not, do this in the terminal:
sudo gedit /etc/default/grub
Now, change the line
GRUB_HIDDEN_TIMEOUT=0
to
#GRUB_HIDDEN_TIMEOUT=0
Then, update grub:
sudo update-grub
Check your actual kernel version:
uname -r
Now, you have grub when starting the machine. Restart the machine. A new black screen will appear with the grub options. Select the "advanced options". Then choose your previous linux-generic for booting.
Once booted, test your actual kernel version:
uname -r
Now, try to start eclipse. Good luck!!
To remove the last update, for normal booting you must do
sudo apt-get purge linux-image-x.x.x linux-headers-x.x.x
A: Seems to be caused by an eclipse.ini setting like below:
-vm
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/libjvm.so
A: Yesterday I had the same problem with eclipse before the ubuntu update. I could not open the workspace (the splash window started but there was no more option) and always returned segmentation fault before pressing a button.
I've seen in /var/log/apt/history.log that this update installed linux-image-3.13.0-121-generic.
I've downgrade the installation with grub to the previous linux-image and now I can start eclipse properly.
A: I'm using eclipse STS and there isn't an eclipse.ini file... There is an STS.ini file but adding the vm arg here didn't work.
What worked for me was to pass it on the command line:
./STS -vm /usr/lib/jvm/java-8-openjdk-i386/jre/bin/java
A: I've experienced this same problem. It seems it was triggered by an update. To solve the problem I did the following:
By reviewing eclipse.ini file I've seen that it did not contain
-vm
/usr/lib/jvm/java-8-openjdk-i386/jre/bin/java
By simply adding it Eclipse no longer reported "segment violation". Note that I had to include "java" at the end; by simply using /usr/lib/jvm/java-8-openjdk-i386/jre/bin/ (as suggested elsewhere) it didn't work
I hope this helps
A: From what I read, adding the -vm flag does the trick, the other option is setting it in the eclipse.ini file, see above... I guess both of the solutions are equivalent.
/usr/bin/java is a link so it resolves to the eclipse.ini option stated above
ls -l /usr/bin/java
lrwxrwxrwx 1 root root 22 Jul 22 2014 /usr/bin/java -> /etc/alternatives/java
ls -l /etc/alternatives/java
lrwxrwxrwx 1 root root 45 Jun 5 2016 /etc/alternatives/java -> usr/lib/jvm/java-8-openjdk-i386/jre/bin/java
A: i updated the kernel to 4.11.8-041108-generic using UKUU and the eclipse segmentation fault is no longer happening.
| stackoverflow | {
"language": "en",
"length": 550,
"provenance": "stackexchange_0000F.jsonl.gz:898651",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647525"
} |
dba3ba4e84391eeb782702c7cf289b2c3ef495a2 | Stackoverflow Stackexchange
Q: Declarative Jenkinsfile CIFS share i have another question about the jenkins pipeline.
How can i publish the build artifacts to a windows share? In normal build jobs there is a "CIFS Publisher" post build action. But how can i use it in
post{
success {
//publish build artifacts
}
}
Is there any example?
A: I've succesfully managed it in this way:
cifsPublisher alwaysPublishFromMaster: false, continueOnError: false, failOnError: false, publishers: [[
configName: 'NAME_OF_THE_CIFS_CONFIG', transfers: [[
cleanRemote: false,
excludes: '',
flatten: false,
makeEmptyDirs: false,
noDefaultExcludes: false,
patternSeparator: '[, ]+',
remoteDirectory: '$BUILD_NUMBER',
remoteDirectorySDF: false,
removePrefix: '',
sourceFiles: 'myfile']],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: true
]]
| Q: Declarative Jenkinsfile CIFS share i have another question about the jenkins pipeline.
How can i publish the build artifacts to a windows share? In normal build jobs there is a "CIFS Publisher" post build action. But how can i use it in
post{
success {
//publish build artifacts
}
}
Is there any example?
A: I've succesfully managed it in this way:
cifsPublisher alwaysPublishFromMaster: false, continueOnError: false, failOnError: false, publishers: [[
configName: 'NAME_OF_THE_CIFS_CONFIG', transfers: [[
cleanRemote: false,
excludes: '',
flatten: false,
makeEmptyDirs: false,
noDefaultExcludes: false,
patternSeparator: '[, ]+',
remoteDirectory: '$BUILD_NUMBER',
remoteDirectorySDF: false,
removePrefix: '',
sourceFiles: 'myfile']],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: true
]]
A: Please use the auto generate tool in Jenkins to help you.
As you can see the highlight link. Click it.
Fill all the required value that you expected.
After scroll down and click Generate pipeline script, you will see the syntax that you need.
Last step, copy the generated script into success clause.
| stackoverflow | {
"language": "en",
"length": 158,
"provenance": "stackexchange_0000F.jsonl.gz:898653",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647539"
} |
b6d46cb30d39849f73925141b57ffc9f769fc9b1 | Stackoverflow Stackexchange
Q: Handle change on checkbox Angular2 I have checkbox and I want use (change) on it. Default is "checked", but after click I want clear input text "Activation key". After re-checked I want generate guid and add again to input. How to get if the checkbox is selected or no?
<div class="checkbox">
<label>
<input type="checkbox" checked (change)="handleChange($event)" >
Generate key
</label>
</div>
TS
handleChange(e) {
var isChecked = e.isChecked;
if (isChecked) {
this.gatewayForm.patchValue({ 'activationKey': this.guid() });
}
else {
this.gatewayForm.controls['activationKey']
.setValue('', { onlySelf: true });
}
}
A: you can get checkbox status by e.target.checked
handleChange(e) {
var isChecked = e.target.checked;
...
}
| Q: Handle change on checkbox Angular2 I have checkbox and I want use (change) on it. Default is "checked", but after click I want clear input text "Activation key". After re-checked I want generate guid and add again to input. How to get if the checkbox is selected or no?
<div class="checkbox">
<label>
<input type="checkbox" checked (change)="handleChange($event)" >
Generate key
</label>
</div>
TS
handleChange(e) {
var isChecked = e.isChecked;
if (isChecked) {
this.gatewayForm.patchValue({ 'activationKey': this.guid() });
}
else {
this.gatewayForm.controls['activationKey']
.setValue('', { onlySelf: true });
}
}
A: you can get checkbox status by e.target.checked
handleChange(e) {
var isChecked = e.target.checked;
...
}
| stackoverflow | {
"language": "en",
"length": 103,
"provenance": "stackexchange_0000F.jsonl.gz:898662",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647572"
} |
6ccaa294de1c0fa92c830dfc2db42de05e40d40a | Stackoverflow Stackexchange
Q: How can I get a reference to a Kotlin object by name? If I have a top level object declaration
package com.example
object MyObject {}
how can I convert the string com.example.MyObject into a reference to MyObject?
A: If you have kotlin-reflect on the classpath then you can use the objectInstance property of KClass
fun main(args: Array<String>) {
val fqn = "com.example.MyObject"
val clz: Class<*> = Class.forName(fqn)
val instance = clz.kotlin.objectInstance
println(instance) // com.example.MyObject@71623278
}
if you don't have kotlin-reflect then you can do it in a plain old java-way
fun main(args: Array<String>) {
val fqn = "com.example.MyObject"
val clz: Class<*> = Class.forName(fqn)
val field: Field = clz.getDeclaredField("INSTANCE")
val instance = field.get(null)
println(instance) // com.example.MyObject@76ed5528
}
| Q: How can I get a reference to a Kotlin object by name? If I have a top level object declaration
package com.example
object MyObject {}
how can I convert the string com.example.MyObject into a reference to MyObject?
A: If you have kotlin-reflect on the classpath then you can use the objectInstance property of KClass
fun main(args: Array<String>) {
val fqn = "com.example.MyObject"
val clz: Class<*> = Class.forName(fqn)
val instance = clz.kotlin.objectInstance
println(instance) // com.example.MyObject@71623278
}
if you don't have kotlin-reflect then you can do it in a plain old java-way
fun main(args: Array<String>) {
val fqn = "com.example.MyObject"
val clz: Class<*> = Class.forName(fqn)
val field: Field = clz.getDeclaredField("INSTANCE")
val instance = field.get(null)
println(instance) // com.example.MyObject@76ed5528
}
A: you can using kotlin reflection, for example:
val it = Class.forName("com.example.MyObject").kotlin.objectInstance as MyObject;
A: Same a java code, you need use Class.forName("com.example.MyObject"). Now you have a Java class, but using kotlin extension, it convert to Kotlin class. Class.forName("com.example.MyObject").kotlin
| stackoverflow | {
"language": "en",
"length": 156,
"provenance": "stackexchange_0000F.jsonl.gz:898681",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647626"
} |
8f0187a0580661df0e3c7e475022db81e35f06db | Stackoverflow Stackexchange
Q: Adding a function() to .zshrc I would like to create a shortcut for rebasing x number of commits:- git rebase -i HEAD~3. I have a function function gri() { git rebase --interactive HEAD~"$1"; } and have tried adding it to my .zshrc file, .bashrc & .bash_profile. But where ever I add it when I try and run gri(2) for example, I get the error zsh: command not found: gri(2)
SOLVED
Just needed to remove function, gri() { git rebase --interactive HEAD~"$1"; } works a treat :D
| Q: Adding a function() to .zshrc I would like to create a shortcut for rebasing x number of commits:- git rebase -i HEAD~3. I have a function function gri() { git rebase --interactive HEAD~"$1"; } and have tried adding it to my .zshrc file, .bashrc & .bash_profile. But where ever I add it when I try and run gri(2) for example, I get the error zsh: command not found: gri(2)
SOLVED
Just needed to remove function, gri() { git rebase --interactive HEAD~"$1"; } works a treat :D
| stackoverflow | {
"language": "en",
"length": 87,
"provenance": "stackexchange_0000F.jsonl.gz:898726",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647789"
} |
0726f961d1c0f296409ebcde81765866483199f3 | Stackoverflow Stackexchange
Q: select the sum of positive and negative values: postgres I have a simple task of computing the sum or average of a user's account balance.
The user may have a negative balance or a positive balance during the month. Here is an example of a user balance during the current month
95.63
97.13
72.14
45.04
20.04
10.63
-29.37
-51.35
-107.55
-101.35
-157.55
-159.55
-161.55
I would like to
*
*choose the negative values, compute their sum/average
*choose the positive values, compute their sum/average
*represent them in 2 columns
Desired result
340.61 -768.27
When I use the UNION operator, I get two rows. When using CASE.. WHEN.. it groups the balances, and I receive multiple rows.
I have other aggregate functions in my postgres query, so I want each of them to be shown in a separate column.
Is there any way to do that?
A: In Postgres 9.1:
select
sum(case when val >= 0 then val end) as positive,
sum(case when val < 0 then val end) as negative
from the_data;
An alternative solution for Postgres 9.4+:
select
sum(val) filter (where val >= 0) as positive,
sum(val) filter (where val < 0) as negative
from the_data;
| Q: select the sum of positive and negative values: postgres I have a simple task of computing the sum or average of a user's account balance.
The user may have a negative balance or a positive balance during the month. Here is an example of a user balance during the current month
95.63
97.13
72.14
45.04
20.04
10.63
-29.37
-51.35
-107.55
-101.35
-157.55
-159.55
-161.55
I would like to
*
*choose the negative values, compute their sum/average
*choose the positive values, compute their sum/average
*represent them in 2 columns
Desired result
340.61 -768.27
When I use the UNION operator, I get two rows. When using CASE.. WHEN.. it groups the balances, and I receive multiple rows.
I have other aggregate functions in my postgres query, so I want each of them to be shown in a separate column.
Is there any way to do that?
A: In Postgres 9.1:
select
sum(case when val >= 0 then val end) as positive,
sum(case when val < 0 then val end) as negative
from the_data;
An alternative solution for Postgres 9.4+:
select
sum(val) filter (where val >= 0) as positive,
sum(val) filter (where val < 0) as negative
from the_data;
A: v=# select sum(case when f < 0 then f end) n, sum(case when f >= 0 then f end) p from s170;
n | p
---------+--------
-768.27 | 340.61
(1 row)
this?.. why not using case twice?
| stackoverflow | {
"language": "en",
"length": 235,
"provenance": "stackexchange_0000F.jsonl.gz:898745",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44647849"
} |
47ceaf6c4a7a659550a7416e3f98e94733b3876c | Stackoverflow Stackexchange
Q: What is the mechanism of using param 'scale_pos_weight' in xgboost? My dataset has 90% negative samples and 10% positive samples which is very imbalanced. I try to use the parameter of scale_pos_weight and set it as 9. What is the mechanism of this param do. I am curious about what it actually means: does it mean repeat the positive samples 9 times? Or everytime pull out 1/9 samples of negative samples and train the model in many times. besides, if I have a dataset whose negative samples just a little more than the positive ones, should I need to specify the parameter again?
A: scale_pos_weight in xgboost is just used to multiply the weights as is source code. There is no subsampling done based on this parameter.
| Q: What is the mechanism of using param 'scale_pos_weight' in xgboost? My dataset has 90% negative samples and 10% positive samples which is very imbalanced. I try to use the parameter of scale_pos_weight and set it as 9. What is the mechanism of this param do. I am curious about what it actually means: does it mean repeat the positive samples 9 times? Or everytime pull out 1/9 samples of negative samples and train the model in many times. besides, if I have a dataset whose negative samples just a little more than the positive ones, should I need to specify the parameter again?
A: scale_pos_weight in xgboost is just used to multiply the weights as is source code. There is no subsampling done based on this parameter.
A: I've never seen anywhere in the documentation that states explicitly what this parameter does. However, I am quite confident that it is the latter, i.e. it builds trees based on 1/9th of the negative samples. Although both should have approximately the same effect if the data are good, taking a subset of the negatives is the convention for modeling because it allows for easier cross-validation, since you now have 9 training sets that you can check against each other.
As a side note, I wouldn't necessarily assume that a 90/10 split is so unbalanced. That's a lot better than you'll get in many situations, and there's some debate over whether re-balancing is always helpful.
| stackoverflow | {
"language": "en",
"length": 243,
"provenance": "stackexchange_0000F.jsonl.gz:898834",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648120"
} |
a78937245f43f441cd4b9da916754940c1d5cbc4 | Stackoverflow Stackexchange
Q: Changing a property to expression-bodied based on ReSharper leads to error? one of my properties looks like this:
public string Name
{
get{ return _name; }
set { _name = value; }
}
but ReSharper is advising me to change it to:
public string Name
{
get => _name;
set => _name = value;
}
if I refactor like that then compilation throws error
Is it not possible to have expression body in a Property ?
A: Before c# 6 you couldn't use expression bodies in properties and had to write something like this.
public string FullName
{
get { return string.Format("{0} {1}", FirstName, LastName); }
}
In c# 6 you can create readonly experession bodies.
public string FullName => $"{FirstName} {LastName}";
In c# 7 you got expression bodies for members like you showed.
public string Name
{
get => _name;
set => _name = value;
}
| Q: Changing a property to expression-bodied based on ReSharper leads to error? one of my properties looks like this:
public string Name
{
get{ return _name; }
set { _name = value; }
}
but ReSharper is advising me to change it to:
public string Name
{
get => _name;
set => _name = value;
}
if I refactor like that then compilation throws error
Is it not possible to have expression body in a Property ?
A: Before c# 6 you couldn't use expression bodies in properties and had to write something like this.
public string FullName
{
get { return string.Format("{0} {1}", FirstName, LastName); }
}
In c# 6 you can create readonly experession bodies.
public string FullName => $"{FirstName} {LastName}";
In c# 7 you got expression bodies for members like you showed.
public string Name
{
get => _name;
set => _name = value;
}
A: If you want ReSharper not to adapt this behavior you can change it:
Resharper > Options > Code Editing > C# > Code Style
and change the following property:
Code body > Properties, indexers and events from Expression body to Accessors with block body
If you just want to disable the suggestion change the notification state of the property mentioned above.
| stackoverflow | {
"language": "en",
"length": 210,
"provenance": "stackexchange_0000F.jsonl.gz:898840",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648134"
} |
ff7cd992bceb182490c2aa0d2e7bd5cd00200133 | Stackoverflow Stackexchange
Q: Touchable elements like Buttons,TouchableHighlight etc not working within FlatList Touchable elements within a FlatList do not register touches. Why is the following code not working? Any help is appreciated. Thankyou.
_listener = () => {
Alert.alert('Touched');
}
renderItem({item, index}){
return<View>
<Button
title = "Button"
color = "#ccc"
onPress={this._listener}
/>
</View>
}
A: If you add extraData={this.state} within the flatlist you can get it to register touches.
| Q: Touchable elements like Buttons,TouchableHighlight etc not working within FlatList Touchable elements within a FlatList do not register touches. Why is the following code not working? Any help is appreciated. Thankyou.
_listener = () => {
Alert.alert('Touched');
}
renderItem({item, index}){
return<View>
<Button
title = "Button"
color = "#ccc"
onPress={this._listener}
/>
</View>
}
A: If you add extraData={this.state} within the flatlist you can get it to register touches.
A: You need to bind your function, so you would have something like this:
<Button
title = "Button"
color = "#ccc"
onPress={this._listener.bind(this)}
/>
| stackoverflow | {
"language": "en",
"length": 90,
"provenance": "stackexchange_0000F.jsonl.gz:898886",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648321"
} |
8de4fa750a14117aebf26ae688c4b1c6cf5bbbe8 | Stackoverflow Stackexchange
Q: Re-use result of last line Jupyter In Jupyter notebook, is there any way to re-use the output the line above, within a cell?
Coming from Mathematica, I often find it useful to write things commands which work on the output of the last line using %, here's a stupid example:
Integrate[f[x],x]
Limit[%,x->1] - Limit[%,x->0]
In general one can write %%% for 3rd-last output etc. https://reference.wolfram.com/language/ref/Out.html
@nostradamus reminds me that underscore _ is the output of the last cell, at least in Python. (Get last answer .) I didn't initially ask this, but would particularly like to be able to do this within a cell, so as to be able to execute multiple steps with one shift-enter.
I would also like to know if there's a way of doing either of these in Julia instead of Python.
A: In julia, ans stores the result of evaluating the last statement.
4*2
ans/2
You may also be interested in checking out the piping syntax
4*2 |>
sqrt
| Q: Re-use result of last line Jupyter In Jupyter notebook, is there any way to re-use the output the line above, within a cell?
Coming from Mathematica, I often find it useful to write things commands which work on the output of the last line using %, here's a stupid example:
Integrate[f[x],x]
Limit[%,x->1] - Limit[%,x->0]
In general one can write %%% for 3rd-last output etc. https://reference.wolfram.com/language/ref/Out.html
@nostradamus reminds me that underscore _ is the output of the last cell, at least in Python. (Get last answer .) I didn't initially ask this, but would particularly like to be able to do this within a cell, so as to be able to execute multiple steps with one shift-enter.
I would also like to know if there's a way of doing either of these in Julia instead of Python.
A: In julia, ans stores the result of evaluating the last statement.
4*2
ans/2
You may also be interested in checking out the piping syntax
4*2 |>
sqrt
A: You can use "_" and works generally in python environment.
A: In case someone else finds this with google, I just discovered a package that does roughly what I wanted, in Julia: ChainRecursive.jl uses it as the magic word, like so:
julia> using ChainRecursive
julia> @chain for k=1:4
k^2 + k^3
print(" $k -> $it ")
end
1 -> 2 2 -> 12 3 -> 36 4 -> 80
There appears to be no performance lost by using this, as it is un-wrapped before compilation.
| stackoverflow | {
"language": "en",
"length": 251,
"provenance": "stackexchange_0000F.jsonl.gz:898913",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648387"
} |
ccf5a6479731f062671de8a193e49467c499d128 | Stackoverflow Stackexchange
Q: unable to load script from assets 'index.android.bundle' I'm new in react-native.
I have run react native project on Ubuntu by using 'react-native run-android' command. And I got the error on emulator
"Unable to load script from assets 'index.android.bundle'.Make sure your bundle is packaged correctly or you are running a package server."
A: For this error :
unable to load script from assets 'index.android.bundle'
1) Check for "assets" folder at :
mkdir android\app\src\main\assets
If the folder is not available, create a folder with name "assets" manually. and execute the Curl command in terminal.
2). Curl command:
curl "http://localhost:8081/index.android.bundle?platform=android" -o"android/app/src/main/assets/index.android.bundle"
It will create the "index.android.bundle" file in assets folder automatically and resolved the issue.
3) Then:
react-native run-android
| Q: unable to load script from assets 'index.android.bundle' I'm new in react-native.
I have run react native project on Ubuntu by using 'react-native run-android' command. And I got the error on emulator
"Unable to load script from assets 'index.android.bundle'.Make sure your bundle is packaged correctly or you are running a package server."
A: For this error :
unable to load script from assets 'index.android.bundle'
1) Check for "assets" folder at :
mkdir android\app\src\main\assets
If the folder is not available, create a folder with name "assets" manually. and execute the Curl command in terminal.
2). Curl command:
curl "http://localhost:8081/index.android.bundle?platform=android" -o"android/app/src/main/assets/index.android.bundle"
It will create the "index.android.bundle" file in assets folder automatically and resolved the issue.
3) Then:
react-native run-android
A: I also got this and I resolved this using following commands in your project directory:
$ mkdir android/app/src/main/assets
$ react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
$ react-native run-android
A: This helped me resolve the problem in following steps.
*
*If not than (in project directory) mkdir android/app/src/main/assets
*react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
*react-native run-android
A:
Ubuntu
first time, I created new app with react-native init project-name. I got the same error. so i do the following steps to resolve this in my case.
*
*Firstly run sudo chown user-name-of-pc /dev/kvm in my case.
*While debugging from your Android phone, select Use USB to Transfer photos (PTP).
*Create Folder assets in 'project-name/android/app/src/main'.
*make sure index.js be avaiable into your project root directory and then run below command from console after cd project-name directory.
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
or for index.android.js then
react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
*run command ./studio.sh in android-studio/bin directory. It will opens up Android Studio.
*run command react-native run-android.
A: Using
npm version 4.3.0
react-native-cli version 2.01
react-native version 0.49.5
In project directory,
*
*mkdir android/app/src/main/assets
*react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
*react-native run-android
The file name has changed from index.android.js to index.js
A: In my case (embedding React Native as a new Activity into an existing Android Code Base), the problem was Android Studio had auto-imported the wrong BuildConfig.
Wrong:
import com.facebook.react.BuildConfig;
Right:
import com.mywebdomain.myapp.BuildConfig;
This would apply to the wherever you are housing this block of code:
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModulePath("index")
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
A: It seems to be a problem in the newest version of React Native (0.46). Using the previous version seems to solve the problem react-native init name --version react-native@0.45.1 and removes the error when running react-native run-android.
Edit: It is now fixed in version 0.46.1.
A: In my case the problem was in this row in the React Activity file:
mReactInstanceManager = ReactInstanceManager.builder()
...
.setUseDeveloperSupport(BuildConfig.DEBUG)
...
BuildConfig.DEBUG must be set to true, while in my case it was false
A: For Windows user only:
*
*Copy the path of adb location and set into PATH in your system variable,
*Open project structure and delete node module folder.
*Edit your project package.JSON file
change react-native version "react-native": "0.55.2", and
babel "babel-preset-react-native": "4", after that run npm install
*Restart cmd and js server and run your react native project by react-native run-android
A: I was stuck in the same problem for hours and what solved my issue is this :
Create "assets" folder in main directory of project as well as in "newreactproject\android\app\src\main". Then put this script in package.json "android-android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-android"
like:
"name": "newreactproject",
"version": "0.0.1",
"private": true,
"scripts": {
"android-android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-android",
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
}
A: I discovered a solution suggested in the thread at https://github.com/facebook/react-native/issues/15388
It is to manually set the Debug server host & port for device setting for the app on the phone.
Step by Step to eject and run a CRNA on Android
In terminal:
*
*create-react-native-app myApp
*cd myApp
*yarn run eject (I used default options "regular React Native project")
*react-native run-android
(now the app should be compiled and installed on the phone)
On phone:
*Run the app (expect to see the red error screen! - click Dismiss button in bottom left)
*Shake the phone and pick Dev Settings
*Pick Debug server host & port for device and set to 192.168.x.x:8081 (make it your actual LAN IP of course)
*Restart app on phone and you should see green bar at the top "Loading from 192.168.x.x:8081..."
*You should also see some "Bundling index.js" action in the Metro Bundler (that opened when running react-native run-android)
*After the bundle is finished, the app should be running on your Android device!
Live Reload (when source files change) also works - just shake the phone and touch "Enable Live Reload"
You can run the project from Android Studio, but you need to first start the Metro Bundler with the command react-native start in the CRNA project root.
A: I was getting this error too. But adb reverseworked for me
A: i'm using ubuntu 18.04 LTS ,react-native: 0.55.2. In my case here are few solutions for the problem .
*
*in the terminal before you run npm run android type npm start. you might see an error
ERROR Metro Bundler can't listen on port 8081.
this occurs because there might be a process which is already running
Solution- type sudo lsof -i :8081
you will see an output similar to this
**COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 5670 tasif 17u IPv6 80997 0t0 TCP *:tproxy (LISTEN)**
type kill -9 (PID number)then run npm android.
*if it still doesnt work type again npm start . you might see this error
ERROR ENOSPC: no space left on device, watch'....../......./.....'
solution :
$ sudo sysctl fs.inotify.max_user_watches=524288
$ sudo sysctl -p
then type npm run android.
please go to this link to see different solutions and more details https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers#the-technical-details
*delete the emulator and build it again. kill the recent terminal and then build emulator and start again.
| stackoverflow | {
"language": "en",
"length": 1024,
"provenance": "stackexchange_0000F.jsonl.gz:898935",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648466"
} |
4d08e52f986a033a799fc99dfe45dc5514bebbde | Stackoverflow Stackexchange
Q: Move gradle temporary cache dir to other directory I have some trouble with the temporary gradle cache directory.
Gradle downloads all dependencies at first to /tmp/gradle_download...bin before it moves them to their target directory.
10:55:12.932 [DEBUG] [org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor] Downloading https://${myNexusURL}/nexus/content/groups/../myArtefact.zip to /tmp/gradle_download1430290155040442921bin
Our space on /tmp is very limited but on other directories we have enough space.
Is there a way to change that directory?
./gradlew -version
------------------------------------------------------------
Gradle 3.0
------------------------------------------------------------
Build time: 2016-08-15 13:15:01 UTC
Revision: ad76ba00f59ecb287bd3c037bd25fc3df13ca558
Groovy: 2.4.7
Ant: Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM: 1.8.0_91 (Oracle Corporation 25.91-b14)
OS: Linux 3.0.101-0.40-default amd64
Thanks for help
A: As mentioned by the OP in his own answer, the temporary directory used by Gradle can be set via the java.io.tmpdir system property. Maybe the following is obvious but just in case: you can also configure this system property with an environment variable for Gradle so that you don’t have to separately configure it with each Gradle call.
For example, you could add the following to your .bashrc:
export GRADLE_OPTS=-Djava.io.tmpdir=/path/to/tmpdir
GRADLE_OPTS should be recognized by both gradle and the Gradle Wrapper (gradlew).
| Q: Move gradle temporary cache dir to other directory I have some trouble with the temporary gradle cache directory.
Gradle downloads all dependencies at first to /tmp/gradle_download...bin before it moves them to their target directory.
10:55:12.932 [DEBUG] [org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor] Downloading https://${myNexusURL}/nexus/content/groups/../myArtefact.zip to /tmp/gradle_download1430290155040442921bin
Our space on /tmp is very limited but on other directories we have enough space.
Is there a way to change that directory?
./gradlew -version
------------------------------------------------------------
Gradle 3.0
------------------------------------------------------------
Build time: 2016-08-15 13:15:01 UTC
Revision: ad76ba00f59ecb287bd3c037bd25fc3df13ca558
Groovy: 2.4.7
Ant: Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM: 1.8.0_91 (Oracle Corporation 25.91-b14)
OS: Linux 3.0.101-0.40-default amd64
Thanks for help
A: As mentioned by the OP in his own answer, the temporary directory used by Gradle can be set via the java.io.tmpdir system property. Maybe the following is obvious but just in case: you can also configure this system property with an environment variable for Gradle so that you don’t have to separately configure it with each Gradle call.
For example, you could add the following to your .bashrc:
export GRADLE_OPTS=-Djava.io.tmpdir=/path/to/tmpdir
GRADLE_OPTS should be recognized by both gradle and the Gradle Wrapper (gradlew).
A: Solving it via -Djava.io.tmpdir=/path/to/tmpdir
| stackoverflow | {
"language": "en",
"length": 190,
"provenance": "stackexchange_0000F.jsonl.gz:898988",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648664"
} |
04bda015166d9c4bbd75b642ef437ff5b27c01b5 | Stackoverflow Stackexchange
Q: Getting probability of detected face in dlib I am using the dlib library(with python2) for face detection in static images, if the probability/quality of the detected face is less, I would like to discard those faces. Thus I would like a function which would give the probability of the detected face. Or another metric which can be used to discard faces on its quality will be helpful.
A: Extraction from the official example:
# Finally, if you really want to you can ask the detector to tell you the score
# for each detection. The score is bigger for more confident detections.
# The third argument to run is an optional adjustment to the detection threshold,
# where a negative value will return more detections and a positive value fewer.
# Also, the idx tells you which of the face sub-detectors matched. This can be
# used to broadly identify faces in different orientations.
if (len(sys.argv[1:]) > 0):
img = io.imread(sys.argv[1])
dets, scores, idx = detector.run(img, 1, -1)
for i, d in enumerate(dets):
print("Detection {}, score: {}, face_type:{}".format(
d, scores[i], idx[i]))
| Q: Getting probability of detected face in dlib I am using the dlib library(with python2) for face detection in static images, if the probability/quality of the detected face is less, I would like to discard those faces. Thus I would like a function which would give the probability of the detected face. Or another metric which can be used to discard faces on its quality will be helpful.
A: Extraction from the official example:
# Finally, if you really want to you can ask the detector to tell you the score
# for each detection. The score is bigger for more confident detections.
# The third argument to run is an optional adjustment to the detection threshold,
# where a negative value will return more detections and a positive value fewer.
# Also, the idx tells you which of the face sub-detectors matched. This can be
# used to broadly identify faces in different orientations.
if (len(sys.argv[1:]) > 0):
img = io.imread(sys.argv[1])
dets, scores, idx = detector.run(img, 1, -1)
for i, d in enumerate(dets):
print("Detection {}, score: {}, face_type:{}".format(
d, scores[i], idx[i]))
| stackoverflow | {
"language": "en",
"length": 182,
"provenance": "stackexchange_0000F.jsonl.gz:898995",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648689"
} |
c410f099d96e7131562c5fbe97947bfc6f1009f4 | Stackoverflow Stackexchange
Q: Checkpoint end to end duration increasing due to stream alignment I have a flink job, which reads user events, uses session windows and writes back to kafka.
The state backend that I'm using is s3 (no hdfs cluster, just using the libs).
The problem is that the end to end checkpointing time keeps rising until checkpoints are dropped, and most of the time is spent on "Alignment".
The question is - why?, how can I solve this without setting the checkpointing mode to AT_LEAST_ONCE?
A: After looking further into the issue, this was due to high GC times (which occur frequently during checkpoints).
We were using the FS state backend, while there is FS in it's name, that only refers to the output location of the checkpoint, while the entire state is still stored in memory (as opposed to rocksdb state backend).
We are still using FS state backend though, due to rocks-db high(er) latency, which we cannot permit in this application.
| Q: Checkpoint end to end duration increasing due to stream alignment I have a flink job, which reads user events, uses session windows and writes back to kafka.
The state backend that I'm using is s3 (no hdfs cluster, just using the libs).
The problem is that the end to end checkpointing time keeps rising until checkpoints are dropped, and most of the time is spent on "Alignment".
The question is - why?, how can I solve this without setting the checkpointing mode to AT_LEAST_ONCE?
A: After looking further into the issue, this was due to high GC times (which occur frequently during checkpoints).
We were using the FS state backend, while there is FS in it's name, that only refers to the output location of the checkpoint, while the entire state is still stored in memory (as opposed to rocksdb state backend).
We are still using FS state backend though, due to rocks-db high(er) latency, which we cannot permit in this application.
| stackoverflow | {
"language": "en",
"length": 163,
"provenance": "stackexchange_0000F.jsonl.gz:899001",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648708"
} |
21e3c58670787c987c0d913cd106793808090abb | Stackoverflow Stackexchange
Q: Git status shows a weird string as an untracked file Git status gives me this:
$ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
"\357\200\233\357\200\233OB\357\200\233q"
nothing added to commit but untracked files present (use "git add" to track)
There is no such file or directory:
$ cat $"\357\200\233\357\200\233OB\357\200\233q"
cat: '\357\200\233\357\200\233OB\357\200\233q': No such file or directory
Another weird thing is that the status command before the last commit did not show this weird path string.
Any idea what is going on? should I "git clean -f"? is it safe?
A: For Ubuntu/Linux :
Simply remove it command using :
sudo rm -rf "\357\200\233\357\200\233OB\357\200\233q"
This Happens when a script/command outputs as a newfile with such characters.
For Windows :
1) Go to Folder Options => Select Show Hidden & System Files
2) Browse to your Repository folder.
3) Remove the file named with "\357\200\233\357\200\233OB\357\200\233q"
| Q: Git status shows a weird string as an untracked file Git status gives me this:
$ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
"\357\200\233\357\200\233OB\357\200\233q"
nothing added to commit but untracked files present (use "git add" to track)
There is no such file or directory:
$ cat $"\357\200\233\357\200\233OB\357\200\233q"
cat: '\357\200\233\357\200\233OB\357\200\233q': No such file or directory
Another weird thing is that the status command before the last commit did not show this weird path string.
Any idea what is going on? should I "git clean -f"? is it safe?
A: For Ubuntu/Linux :
Simply remove it command using :
sudo rm -rf "\357\200\233\357\200\233OB\357\200\233q"
This Happens when a script/command outputs as a newfile with such characters.
For Windows :
1) Go to Folder Options => Select Show Hidden & System Files
2) Browse to your Repository folder.
3) Remove the file named with "\357\200\233\357\200\233OB\357\200\233q"
| stackoverflow | {
"language": "en",
"length": 153,
"provenance": "stackexchange_0000F.jsonl.gz:899011",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648754"
} |
54aa4f45840d7d98799ff3513b913b3e95be5fb4 | Stackoverflow Stackexchange
Q: How to use multiple remotes with GitKraken I'm using GitKraken quite frequently, but I cannot manage how to set to which remote I want to push. In the context menu I cannot find any entry like "use this remote for push/pull".
I have to set it via the command line, then it works as expected.
git push -u origin2 dev/mybranch
is this really a missing feature?
A: *
*Right-Click on the local branch from which you want to pull, click on Set Upstream.
*Select the origin that you want to push, click submit.
Now, pushing (clicking on the Push button) will push to the selected origin! And when you want to change the origin the next time, repeat the step-1 and push.
| Q: How to use multiple remotes with GitKraken I'm using GitKraken quite frequently, but I cannot manage how to set to which remote I want to push. In the context menu I cannot find any entry like "use this remote for push/pull".
I have to set it via the command line, then it works as expected.
git push -u origin2 dev/mybranch
is this really a missing feature?
A: *
*Right-Click on the local branch from which you want to pull, click on Set Upstream.
*Select the origin that you want to push, click submit.
Now, pushing (clicking on the Push button) will push to the selected origin! And when you want to change the origin the next time, repeat the step-1 and push.
A:
I'm currently trying to configure correctly more than one remote repo.
I understood that you have already setup correctly your remotes (by click plus simbole near REMOTE).
Now :
*
*if you fetch (pull) some branches from remotes: the default are automatically set to remote you chose/click in REMOTE section.
*if you create a new branch: when you push first time, at the top of gitkraken window appear confirmation message. There you can chose which remote to push. Your chose will set as default for that branch.
*if you want to change remote of a branch already in use: right click on desired brach in LOCAL section, in the menu you can find "set ", in my case "set upstream". So appear at the top of gitkraken window the confirmation message to setup the default remote for that branch.
You can check the result in the .git/config file in the home dir of your project.
Edit:
Ok, I've tested this solution for some day. It's running structurally and I confirm this solution. Evenif when you switch from one branch with some remote to an other brach with different remote, some times the ui not responding correctly (freez or stop refreshing). So a I need to close and reopen gitkraken.
| stackoverflow | {
"language": "en",
"length": 333,
"provenance": "stackexchange_0000F.jsonl.gz:899017",
"question_score": "15",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648772"
} |
bc02141efdcbfc5598803a12d5df4edb69b9187a | Stackoverflow Stackexchange
Q: Send an ARP request manually from Windows I'm training myself on network scanning and i'm focusing on how to identify a sniffer on my net.
Searching on the web, i find that a possible way is the ARP method: i must send an ARP request to a suspect no broadcast IP to check if it's in promiscuous mode.
My doubt is: if my pc is a Windows 7 machine, is there a way to send manually an ARP resuest? Possibly from command line?
A: You can use tools like nmap.
nmap -sP -PR <IP address/subnet>
For windows you can use the GUI version of nmap - zenmap.
| Q: Send an ARP request manually from Windows I'm training myself on network scanning and i'm focusing on how to identify a sniffer on my net.
Searching on the web, i find that a possible way is the ARP method: i must send an ARP request to a suspect no broadcast IP to check if it's in promiscuous mode.
My doubt is: if my pc is a Windows 7 machine, is there a way to send manually an ARP resuest? Possibly from command line?
A: You can use tools like nmap.
nmap -sP -PR <IP address/subnet>
For windows you can use the GUI version of nmap - zenmap.
A: You can use this version of arping for Windows. If you want an already compiled executable you can find it Here (under the "examples" folder).
Usage:
Arping.exe -i <IP_ADDRESS_OF_YOUR_INTERFACE> -T <TARGET_IP_ADDRESS>
A: another simple way:
*
*ping TARGET_IP_ADDRESS
then
*
*arp -a
the TARGET_IP_ADDRESS shall be shown as type dynamic.
| stackoverflow | {
"language": "en",
"length": 159,
"provenance": "stackexchange_0000F.jsonl.gz:899030",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648808"
} |
a113a1266b0cb33cec437a5c3353734a0fb28c54 | Stackoverflow Stackexchange
Q: How to set default timezone in angular js I want to set default Timezone offset (America/Chicago) in date field. new Date function added into the code and call it properly into HTML file. its showing date and time properly but i want to set time zone default to America/chicago.
code in controller :
<script>
mainApp.controller('depositController', ['$scope', '$http', '$filter', function($scope, $http, $filter) {
$scope.myDate = new Date();
}]);
</script>
html code:
<div class="col-lg-8">
<input id="deposit_date" name="deposit_date"
class="form-control"
type="text"
ng-init="deposit_time=(myDate | date:'HH:mm:ss a' : '-0500')"
ng-model="deposit_time"
readonly="readonly"/>
</div>
I want to show America/Chicago (Central Standard Time) current time.
A: You can't. AngularJS uses browsers timezone settings.
Look at the documentation:
Timezones
- The AngularJS datetime filter uses the time zone settings of the browser.
- The same application will show different time information depending on the time zone settings of the computer that the application is running on.
- Neither JavaScript nor AngularJS currently supports displaying the date with a timezone specified by the developer.
| Q: How to set default timezone in angular js I want to set default Timezone offset (America/Chicago) in date field. new Date function added into the code and call it properly into HTML file. its showing date and time properly but i want to set time zone default to America/chicago.
code in controller :
<script>
mainApp.controller('depositController', ['$scope', '$http', '$filter', function($scope, $http, $filter) {
$scope.myDate = new Date();
}]);
</script>
html code:
<div class="col-lg-8">
<input id="deposit_date" name="deposit_date"
class="form-control"
type="text"
ng-init="deposit_time=(myDate | date:'HH:mm:ss a' : '-0500')"
ng-model="deposit_time"
readonly="readonly"/>
</div>
I want to show America/Chicago (Central Standard Time) current time.
A: You can't. AngularJS uses browsers timezone settings.
Look at the documentation:
Timezones
- The AngularJS datetime filter uses the time zone settings of the browser.
- The same application will show different time information depending on the time zone settings of the computer that the application is running on.
- Neither JavaScript nor AngularJS currently supports displaying the date with a timezone specified by the developer.
A: You can't. It's depends on the browser settings
*
*The AngularJS datetime filter uses the time zone settings of the browser.
*The same application will show different time information depending on the time zone settings of the computer that the application is running on.
*Neither JavaScript nor AngularJS currently supports displaying the date with a timezone specified by the developer
| stackoverflow | {
"language": "en",
"length": 225,
"provenance": "stackexchange_0000F.jsonl.gz:899035",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648823"
} |
c04a7196ed28862d1143c0360c37397463f67fbb | Stackoverflow Stackexchange
Q: Obtain the DFS path of a network location in Python I want to obtain a ping-like response from a Windows network location that has a Distributed File System architecture e.g.
path = r'\\path\to\some\shared\folder_x'
delay = ping_func(path)
print delay # return response in milliseconds ?
234
Once I have host computer I can easily ping the location.
I can determine the host name for folder_x by looking at the DFS tab in the windows explorer which will look like e.g.
\\hostcomputer.server.uk\shared$\folder_x
How can I do this programmatically in Python?
A: Since you are using Windows, your always install pywin32 and WMI to get the WMI functions. And below should help you connect to remote DFS. Can't test it as I don't have Windows or DFS
import wmi
c = wmi.WMI (ip, user="user", password="pwd")
for share in c.Win32_Share (Type=0):
print share.Caption, share.Path
for session in share.associators (
wmi_result_class="Win32_ServerConnection"
):
print " ", session.UserName, session.ActiveTime
| Q: Obtain the DFS path of a network location in Python I want to obtain a ping-like response from a Windows network location that has a Distributed File System architecture e.g.
path = r'\\path\to\some\shared\folder_x'
delay = ping_func(path)
print delay # return response in milliseconds ?
234
Once I have host computer I can easily ping the location.
I can determine the host name for folder_x by looking at the DFS tab in the windows explorer which will look like e.g.
\\hostcomputer.server.uk\shared$\folder_x
How can I do this programmatically in Python?
A: Since you are using Windows, your always install pywin32 and WMI to get the WMI functions. And below should help you connect to remote DFS. Can't test it as I don't have Windows or DFS
import wmi
c = wmi.WMI (ip, user="user", password="pwd")
for share in c.Win32_Share (Type=0):
print share.Caption, share.Path
for session in share.associators (
wmi_result_class="Win32_ServerConnection"
):
print " ", session.UserName, session.ActiveTime
A: I've been able to directly call the NetDfsGetInfo function using Python's "ctypes" module.
Some stumbling points I had was understanding the C++/Python interface and variable marshalling - that's what the dfs.argtypes helps with.
The C++ calls return their structures by placing pointers into a buffer you supply to the call. Using byref you are matching the function prototype LPBYTE *Buffer
Processing the output requires defining a "Structure" that matches the function return, in this case DFS_INFO_3. The python "buffer" variable is cast as a pointer to DFS_INFO_3 and ctypes.Structure defines the field names and the types the struct is build from. Then you can access them via attribute name, eg, dfs_info.EntryPath
There was a pointer to a variable-length array (DFS_STORAGE_INFO) returned too, which is able to be accessed via normal Python storage[i] syntax.
import ctypes as ct
from ctypes import wintypes as win
dfs = ct.windll.netapi32.NetDfsGetInfo
dfs.argtypes = [
win.LPWSTR,
win.LPWSTR,
win.LPWSTR,
win.DWORD,
ct.POINTER(win.LPBYTE),
]
class DFS_STORAGE_INFO(ct.Structure):
"""Contains information about a DFS root or link target in a DFS namespace."""
_fields_ = [ # noqa: WPS120
("State", win.ULONG),
("ServerName", win.LPWSTR),
("ShareName", win.LPWSTR),
]
class DFS_INFO_3(ct.Structure): # noqa: WPS114
"""Contains information about a Distributed File System (DFS) root or link."""
_fields_ = [ # noqa: WPS120
("EntryPath", win.LPWSTR),
("Comment", win.LPWSTR),
("State", win.DWORD),
("NumberOfStorages", win.DWORD),
("Storage", ct.POINTER(DFS_STORAGE_INFO)),
]
# ----- Function call -----
buffer = win.LPBYTE() # allocate a LPBYTE type buffer to be used for return pointer
dret = dfs(r"\\something.else\here", None, None, 3, ct.byref(buffer))
# specify that buffer now points to a DFS_INFO_3 struct
dfs_info = ct.cast(buffer, ct.POINTER(DFS_INFO_3)).contents
print(dfs_info.EntryPath)
for i in range(dfs_info.NumberOfStorages):
storage = dfs_info.Storage[i]
print(
f"{storage.ServerName=}",
f"{storage.ShareName=}",
)
| stackoverflow | {
"language": "en",
"length": 423,
"provenance": "stackexchange_0000F.jsonl.gz:899042",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648846"
} |
0d92fa16e8ac26a3d20089e54badf632b8da6fc7 | Stackoverflow Stackexchange
Q: Add attribute to i18n strings in React Native I've already known how to generate i18n string through react-native-i18n. For example,
// en.js source
{
"hello": "Hello, {{name}}."
}
// use
I18n.t("hello", { name: "John" })
and it shows Hello, John..
I've also known how to generate attributed string:
<Text>
This is a <Text style={{fontWeight: 'bold'}}>bold<Text> word.
<Text>
and it shows This is aboldword.
The problem is, how can I add attributes to a i18n template string? Any library for this?
// en.js source
{
"hello": "Hello, <b>{{guest}}</b>. I'm {{host}}."
}
// use
I18n.t("hello", { guest: "John", host: "Sam" })
*
*Expected: Hello,John. I'm Sam.
*What I got: Hello, <b>John</b>. I'm Sam.
A: You can do something like that
const splitTitle = (title, style) => {
const [left, center, right] = title.split(/<b>|<\/b>/)
return (
<Text style={style}>
{left}
<Text style={{ fontFamily: 'font-name', fontWeight: 'font-weight' }}>{center}</Text>
{right}
</Text>
)
}
And call it
splitTitle(i18n.t("key"), style)
| Q: Add attribute to i18n strings in React Native I've already known how to generate i18n string through react-native-i18n. For example,
// en.js source
{
"hello": "Hello, {{name}}."
}
// use
I18n.t("hello", { name: "John" })
and it shows Hello, John..
I've also known how to generate attributed string:
<Text>
This is a <Text style={{fontWeight: 'bold'}}>bold<Text> word.
<Text>
and it shows This is aboldword.
The problem is, how can I add attributes to a i18n template string? Any library for this?
// en.js source
{
"hello": "Hello, <b>{{guest}}</b>. I'm {{host}}."
}
// use
I18n.t("hello", { guest: "John", host: "Sam" })
*
*Expected: Hello,John. I'm Sam.
*What I got: Hello, <b>John</b>. I'm Sam.
A: You can do something like that
const splitTitle = (title, style) => {
const [left, center, right] = title.split(/<b>|<\/b>/)
return (
<Text style={style}>
{left}
<Text style={{ fontFamily: 'font-name', fontWeight: 'font-weight' }}>{center}</Text>
{right}
</Text>
)
}
And call it
splitTitle(i18n.t("key"), style)
A: You can use react-i18next it supports react content inside its translation component:
<Trans i18nKey="userMessagesUnread" count={count}>
Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>.
</Trans>
In the dictionary,
"userMessagesUnread": "Hello <1>{{name}}</1>, you have {{count}} unread message. <5>Go to message</5>.",
"userMessagesUnread_plural": "Hello <1>{{name}}</1>, you have {{count}} unread messages. <5>Go to messages</5>.",
Learn more https://react.i18next.com/latest/trans-component#using-with-react-components
| stackoverflow | {
"language": "en",
"length": 210,
"provenance": "stackexchange_0000F.jsonl.gz:899083",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648976"
} |
5ade39b9720cd7e158ab174e868b708b0d8ecd99 | Stackoverflow Stackexchange
Q: FluentValidation and collection of object its property should be unique I have class:
Sponsored { int Order };
And I have collection of it:
IEnumerable<Sponsored> sponsored;
I want to check if Order is unique for this collection.
Can I do it via FluentValidation?
I have:
SponsoredValidator : AbstractValidator<IEnumerable<Sponsored>>
and
SponsoredValidator : AbstractValidator<Sponsored>
@Edit:
It should be connected with WebAPI POST method via ValidationAttribute
[Validator(typeof(SponsoredValidator))]
A: public class SponsoredCollectionValidator : AbstractValidator<IEnumerable<Sponsored>>
{
private class SponsoredComparer : IEqualityComparer<Sponsored>
{
public bool Equals(Sponsored x, Sponsored y) => x?.Order == y?.Order;
public int GetHashCode(Sponsored obj) => obj.Order;
}
public SponsoredCollectionValidator()
{
RuleFor(coll => coll)
.Must(coll => coll.Distinct(new SponsoredComparer()).Count() == coll.Count())
.WithMessage("Elements are not unique.");
}
}
| Q: FluentValidation and collection of object its property should be unique I have class:
Sponsored { int Order };
And I have collection of it:
IEnumerable<Sponsored> sponsored;
I want to check if Order is unique for this collection.
Can I do it via FluentValidation?
I have:
SponsoredValidator : AbstractValidator<IEnumerable<Sponsored>>
and
SponsoredValidator : AbstractValidator<Sponsored>
@Edit:
It should be connected with WebAPI POST method via ValidationAttribute
[Validator(typeof(SponsoredValidator))]
A: public class SponsoredCollectionValidator : AbstractValidator<IEnumerable<Sponsored>>
{
private class SponsoredComparer : IEqualityComparer<Sponsored>
{
public bool Equals(Sponsored x, Sponsored y) => x?.Order == y?.Order;
public int GetHashCode(Sponsored obj) => obj.Order;
}
public SponsoredCollectionValidator()
{
RuleFor(coll => coll)
.Must(coll => coll.Distinct(new SponsoredComparer()).Count() == coll.Count())
.WithMessage("Elements are not unique.");
}
}
| stackoverflow | {
"language": "en",
"length": 113,
"provenance": "stackexchange_0000F.jsonl.gz:899085",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44648980"
} |
b600caa7f7e3d63d1b823f857f8f64bfd839c236 | Stackoverflow Stackexchange
Q: Xcode 8.3.2 : Could not hardlink copy I am getting this error message while trying to launch my app in simulator. What is the actual issue?
A: Do below steps,
*
*Clean Build
*Delete Derived Data
*Simulator (Reset Content and Settings)
*Quit Xcode
& Run Again
| Q: Xcode 8.3.2 : Could not hardlink copy I am getting this error message while trying to launch my app in simulator. What is the actual issue?
A: Do below steps,
*
*Clean Build
*Delete Derived Data
*Simulator (Reset Content and Settings)
*Quit Xcode
& Run Again
A: The apps installed in the simulator could have become inconsistent.
Resetting the Content and Settings will solve the issue.
Also try to clear Derived Data then clean and build the project.
A: In my case the Build number was wrong.
So in the Info.plist the Build number disappeared, it was blank.
To fix this, I had to re-enter the build number.
Delete the app from the simulator
Then when I built the app it installed again on the Simulator and started to work fine in subsequent builds as well.
A: In my case this problem is caused by special character in Product Name
Note that Product Name differs from Display Name which is displayed below app icon as your app name.
So don't worry about changing Product Name requires change your app name, just choose an ascii name and error gone
A: *
*Follow the steps to fix the issues.
Press add to open a window
enter image description here
| stackoverflow | {
"language": "en",
"length": 208,
"provenance": "stackexchange_0000F.jsonl.gz:899108",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649039"
} |
8aeb424678ec6afda6419b0bb7fb66638d390a06 | Stackoverflow Stackexchange
Q: Missing Simulator in Xcode 8.3.2 after installing Xcode 9.0 Beta I am using Xcode 8.3.2 for iOS Application Development.
I have just installed Xcode 9.0 Beta and suddenly I found that My old simulators are missing from my Xcode 8.3.2.
This issue occurred after installing Xcode 9.0 Beta.
See Pictures Below.
1. Xcode 8.3.2.
2. Xcode 9.0 Beta.
I go through links below but none of them is helpful.
*
*Xcode Simulators Missing After Installing Beta?
*There is no simulator in my xcode 5 after I install xcode 6 beta
So please help me for this.
A: I had the same issue, solution is: MacBook restart :)
| Q: Missing Simulator in Xcode 8.3.2 after installing Xcode 9.0 Beta I am using Xcode 8.3.2 for iOS Application Development.
I have just installed Xcode 9.0 Beta and suddenly I found that My old simulators are missing from my Xcode 8.3.2.
This issue occurred after installing Xcode 9.0 Beta.
See Pictures Below.
1. Xcode 8.3.2.
2. Xcode 9.0 Beta.
I go through links below but none of them is helpful.
*
*Xcode Simulators Missing After Installing Beta?
*There is no simulator in my xcode 5 after I install xcode 6 beta
So please help me for this.
A: I had the same issue, solution is: MacBook restart :)
A: Check your deployment target in the deployment info.
This might have been changed if you are using latest version of Xcode where your deployment target will be automatically changed to higher versions of OS.
Just switch to older version of OS which will display all the simulators required.
A: You can select Xcode > Open Developer Tool > Simulator and after simulator simulator loads, restart and then you will get whole list back.
Note : You can not work on both Xcode with all simulator same time. You have to close one Xcode with it's simulator then you can work on another.
Restart Xcode after simulator loading process is done. You will get whole list of Simulators.
A: For Xcode 10.3 you can get back the simulators by running following command in terminal
sudo killall -9 com.apple.CoreSimulator.CoreSimulatorService
A: Running multiple versions of Xcode at the same time is only supported if all versions are Xcode 9+.
You can have older versions installed but only one running at a time.
If you try running multiple versions of Xcode that don't support it, the currently running one will loose access to simulator services until it is restarted (at which point the other one will loose access to its simulators).
Note that Console.app uses CoreSimulator.framework from the version of Xcode selected by xcode-select. If you launch Console, and xcode-select points to a different version of Xcode, it will cause the running Xcode to loose access to its sims.
A: Not launch several xCode in the same time
I was getting this error because i was running two different version of xCode
A: Follow the below steps to fix this issue.
Step 1: Quit the Xcode 9 and its simulator.
Step 2: Open Xcode 8 and go to Xcode Menu -> Open Developer tool -> Simulator.
Step 3: Quit the Xcode 8 and reopen.
A: after performing all troubleshooting that people suggest if it does not work for you, then go to preference and tap location tab and verify command line tool version is same as your xcode version , might your xcode command line tool version set to 9 or 9+ , set it back to 8. Hope so this will work for you.after that quit your xcode and open again
| stackoverflow | {
"language": "en",
"length": 487,
"provenance": "stackexchange_0000F.jsonl.gz:899138",
"question_score": "24",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649141"
} |
a3548ca3b2b821c20a95ef279c7581df2e742b23 | Stackoverflow Stackexchange
Q: Fit gaussians (or other distributions) on my data using python I have a database of features, a 2D np.array (2000 samples and each sample contains 100 features, 2000 X 100). I want to fit gaussian distributions to my database using python. My code is the following:
data = load_my_data() # loads a np.array with size 2000x200
clf = mixture.GaussianMixture(n_components= 50, covariance_type='full')
clf.fit(data)
I am not sure about the parameters for example the covariance_type and how can I investigate whether the fit was occured succesfully or not.
EDIT: I debug the code to investigate what is happening with the clf.means_ and appartently it produced a matrix n_components X size_of_features 50 X 20). Is there a way that i can check that the fitting was successful, or to plot data? What are the alternatives to Gaussian mixtures (mixtures of exponential for example, I cannot find any available implementation)?
A: I think you are using sklearn package.
Once you have fit, then type
print clf.means_
If it has output, then the data is fitted, if it raise errors, not fitted.
Hope this helps you.
| Q: Fit gaussians (or other distributions) on my data using python I have a database of features, a 2D np.array (2000 samples and each sample contains 100 features, 2000 X 100). I want to fit gaussian distributions to my database using python. My code is the following:
data = load_my_data() # loads a np.array with size 2000x200
clf = mixture.GaussianMixture(n_components= 50, covariance_type='full')
clf.fit(data)
I am not sure about the parameters for example the covariance_type and how can I investigate whether the fit was occured succesfully or not.
EDIT: I debug the code to investigate what is happening with the clf.means_ and appartently it produced a matrix n_components X size_of_features 50 X 20). Is there a way that i can check that the fitting was successful, or to plot data? What are the alternatives to Gaussian mixtures (mixtures of exponential for example, I cannot find any available implementation)?
A: I think you are using sklearn package.
Once you have fit, then type
print clf.means_
If it has output, then the data is fitted, if it raise errors, not fitted.
Hope this helps you.
A: You can do dimensionality reduction using PCA to 3D space (let's say) and then plot means and data.
A: Is is always preferred to choose a reduced set of candidate before trying to identify the distribution (in other words, use Cullen & Frey to reject the unlikely candidates) and then go for goodness of fit a select the best result,
You can just create a list of all available distributions in scipy. An example with two distributions and random data:
import numpy as np
import scipy.stats as st
data = np.random.random(10000)
#Specify all distributions here
distributions = [st.laplace, st.norm]
mles = []
for distribution in distributions:
pars = distribution.fit(data)
mle = distribution.nnlf(pars, data)
mles.append(mle)
results = [(distribution.name, mle) for distribution, mle in
zip(distributions, mles)]
best_fit = sorted(zip(distributions, mles), key=lambda d: d[1])[0]
print 'Best fit reached using {}, MLE value: {}'.format(best_fit[0].name, best_fit[1])
A: I understand, you may like to do regression of two different distributions, more than fitting them to an arithmetic curve. If this is the case, you may be interested in plotting one against the other one, and make a linear (or polynomial) regression, checking the coefficients
If this is the case, linear regression of two distributions, may tell you if there linear dependent or not.
Linear Regression using Scipy documentation
| stackoverflow | {
"language": "en",
"length": 395,
"provenance": "stackexchange_0000F.jsonl.gz:899178",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649272"
} |
905c08fd65823bd229b548d81afc89e129646fff | Stackoverflow Stackexchange
Q: Getting eBay Access Token (Exchanging auth token) with python requests I'm trying to use this guide to get access token.
Here is my main file:
import requests
from utils import make_basic_auth_header, conf
code = '<Auth code here>'
url = "%s/identity/v1/oauth2/token" % conf('EBAY_API_PREFIX')
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': make_basic_auth_header()
}
data = {
'grant_type': 'authorization_code',
# 'grant_type': 'refresh_token',
'state': None,
'code': code,
'redirect_uri': conf('EBAY_RUNAME')
}
r = requests.post(
url,
data=data,
headers=headers,
)
Here's the make_basic_auth_header() function:
def make_basic_auth_header():
auth_header_payload = '%s:%s' % (conf('EBAY_APP_ID'), conf('EBAY_CERT_ID'))
auth_header_base64 = base64.b64encode(auth_header_payload)
auth_header = 'Basic %s' % auth_header_base64
return auth_header
But all I get in r.json() is:
{u'error_description': u'request is missing a required parameter or malformed.', u'error': u'invalid_request'}
I'm frustrated - what am I doing wrong?
A: sorry, I was stupid enough and I didn't see the tickbox on ebay.
| Q: Getting eBay Access Token (Exchanging auth token) with python requests I'm trying to use this guide to get access token.
Here is my main file:
import requests
from utils import make_basic_auth_header, conf
code = '<Auth code here>'
url = "%s/identity/v1/oauth2/token" % conf('EBAY_API_PREFIX')
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': make_basic_auth_header()
}
data = {
'grant_type': 'authorization_code',
# 'grant_type': 'refresh_token',
'state': None,
'code': code,
'redirect_uri': conf('EBAY_RUNAME')
}
r = requests.post(
url,
data=data,
headers=headers,
)
Here's the make_basic_auth_header() function:
def make_basic_auth_header():
auth_header_payload = '%s:%s' % (conf('EBAY_APP_ID'), conf('EBAY_CERT_ID'))
auth_header_base64 = base64.b64encode(auth_header_payload)
auth_header = 'Basic %s' % auth_header_base64
return auth_header
But all I get in r.json() is:
{u'error_description': u'request is missing a required parameter or malformed.', u'error': u'invalid_request'}
I'm frustrated - what am I doing wrong?
A: sorry, I was stupid enough and I didn't see the tickbox on ebay.
| stackoverflow | {
"language": "en",
"length": 136,
"provenance": "stackexchange_0000F.jsonl.gz:899193",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649316"
} |
0880ad2f864c0901908bc653213bcaff6c72472a | Stackoverflow Stackexchange
Q: brew installation of Python 3.6.1: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed I installed python 3.6 using
brew install python3
and tried to download a file with six.moves.urllib.request.urlretrieve from an https, but it throws the error
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)
In the Python installation (from .pkg), the README indicates that one needs to run the Install Certificates.command after the installation to
*
*install certifi
*symlink the certification path to certify path
to be able to use certificates.
However, in brew install, this file does not exist and it does not seem to be run.
A: For temporary, following will disable the ssl checking,
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
| Q: brew installation of Python 3.6.1: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed I installed python 3.6 using
brew install python3
and tried to download a file with six.moves.urllib.request.urlretrieve from an https, but it throws the error
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)
In the Python installation (from .pkg), the README indicates that one needs to run the Install Certificates.command after the installation to
*
*install certifi
*symlink the certification path to certify path
to be able to use certificates.
However, in brew install, this file does not exist and it does not seem to be run.
A: For temporary, following will disable the ssl checking,
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
A: If you need to make your local root certificate (e.g. local_RootCA.crt) become trusted by python, you can add it into the end of certifi/cacert.pem file:
cat local_RootCA.crt >> `python -c 'import certifi; print(certifi.where())'`
That solution works good for macos brew python 3 installation as well.
A: My solution for Mac OS X:
1) Upgrade to Python 3.6.5 using the native app Python installer downloaded from the official Python language website https://www.python.org/downloads/
I've found that this installer is taking care of updating the links and symlinks for the new Python a lot better than homebrew.
2) Install a new certificate using "./Install Certificates.command" which is in the refreshed Python 3.6 directory
cd "/Applications/Python 3.6/"
sudo "./Install Certificates.command"
A: *
*find out default cafile:
python -c 'import ssl; print(ssl.get_default_verify_paths().openssl_cafile)'
/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/etc/ssl/cert.pem
sudo mkdir -p /Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/etc/ssl/certs
*
*find out ca file of certifi
python -c 'import certifi; print(certifi.where())'
'/usr/local/lib/python3.7/site-packages/certifi/cacert.pem'
*
*copy to
sudo cp /usr/local/lib/python3.7/site-packages/certifi/cacert.pem
/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/etc/ssl/certs/cert.pem
A: It seems that, for some reason, Brew has not run the Install Certificates.command that comes in the Python3 bundle for Mac. The solution to this issue is to run the following script (copied from Install Certificates.command) after brew install python3:
# install_certifi.py
#
# sample script to install or update a set of default Root Certificates
# for the ssl module. Uses the certificates provided by the certifi package:
# https://pypi.python.org/pypi/certifi
import os
import os.path
import ssl
import stat
import subprocess
import sys
STAT_0o775 = ( stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
| stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP
| stat.S_IROTH | stat.S_IXOTH )
def main():
openssl_dir, openssl_cafile = os.path.split(
ssl.get_default_verify_paths().openssl_cafile)
print(" -- pip install --upgrade certifi")
subprocess.check_call([sys.executable,
"-E", "-s", "-m", "pip", "install", "--upgrade", "certifi"])
import certifi
# change working directory to the default SSL directory
os.chdir(openssl_dir)
relpath_to_certifi_cafile = os.path.relpath(certifi.where())
print(" -- removing any existing file or link")
try:
os.remove(openssl_cafile)
except FileNotFoundError:
pass
print(" -- creating symlink to certifi certificate bundle")
os.symlink(relpath_to_certifi_cafile, openssl_cafile)
print(" -- setting permissions")
os.chmod(openssl_cafile, STAT_0o775)
print(" -- update complete")
if __name__ == '__main__':
main()
A: positionning SSL_CERT_FILE env var to your ca file also works and it is not invasive.
| stackoverflow | {
"language": "en",
"length": 456,
"provenance": "stackexchange_0000F.jsonl.gz:899238",
"question_score": "42",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649449"
} |
90562f8bf661c63ef8df5dc2ace2c049209f4474 | Stackoverflow Stackexchange
Q: Replace single and double quotes prefixed with backward slashes Folks,
I have been trying to get a sed command which will replace \' to ' and \\" to \" in a file. I tried the below using sed but am not able to figure out how to segregate single and double quotes.
$ cat temp
\'
\\"
$ cat temp | sed 's#\\\\"#\\"#' | sed 's#\\'#'#'
'
"
desired output is
'
\"
Can someone point out what i am doing wrong.
Note: I want to apply this change to all the occurrence in the file
A: awk solution:
awk '{ gsub(/\\\047/,"\047",$0); gsub(/\\\\\042/,"\\\042",$0) }1' temp
The output:
'
\"
| Q: Replace single and double quotes prefixed with backward slashes Folks,
I have been trying to get a sed command which will replace \' to ' and \\" to \" in a file. I tried the below using sed but am not able to figure out how to segregate single and double quotes.
$ cat temp
\'
\\"
$ cat temp | sed 's#\\\\"#\\"#' | sed 's#\\'#'#'
'
"
desired output is
'
\"
Can someone point out what i am doing wrong.
Note: I want to apply this change to all the occurrence in the file
A: awk solution:
awk '{ gsub(/\\\047/,"\047",$0); gsub(/\\\\\042/,"\\\042",$0) }1' temp
The output:
'
\"
A: With any sed on any UNIX box:
$ sed 's/\\'\''/'\''/g; s/\\\\"/\\"/g' file
'
\"
with GNU or OSX sed for EREs enabled with -E:
$ sed -E 's/\\('\''|\\")/\1/g' file
'
\"
A: Tested with GNU sed 4.2.2, not sure about portability
I've modified input sample to show working of command better:
$ cat temp
\' and \\' and \\\'
\" and \\" and \\\"
$ sed -E 's/\\([\x27"])/\1/g' temp
' and \' and \\'
" and \" and \\"
*
*-E use ERE, some sed versions use -r
*\\([\x27"]) will match \ followed by ' or " and the quote character alone is captured
*\1 the captured group is used as replacement
*g modifier will replace all such occurrences in line
To change only \\" and not any occurrence of \"
$ sed -E 's/\\\x27/\x27/g; s/\\\\"/\\"/g;' temp
' and \' and \\'
\" and \" and \\"
A: This might work for you (GNU sed):
sed 's/\\\(\\['\''"]\)/\1/g' file
or:
sed -r 's/\\(\\['\'"])/\1/g' file
The problem is the single quote is used to quote the sed expression and therefore needs to be quoted in the shell hence \'. Using a character class for the single quote or the double quote allows the substitution to use a back reference and hence simplify the righthandside of the substitution.
A: One of the difficulties you have is that you're writing your expression as a command-line argument to sed, and hence need to quote it for your shell. It's much easier if you write your sed program in a file:
#!/bin/sed -f
s/\\'/'/g
s/\\\\"/\\"/g
You need to double each \ to quote them to the s command, but there's no extra quoting that the shell would require.
Demonstration:
$ cat 44649501.input
\'
\\"
$ ./44649501.sed <44649501.input
'
\"
| stackoverflow | {
"language": "en",
"length": 404,
"provenance": "stackexchange_0000F.jsonl.gz:899252",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649501"
} |
6b7d449cb4c71cd9af880b6539bb78e4011766c7 | Stackoverflow Stackexchange
Q: Examining variables while debugging in Android Studio I'm looking for a way to examine the value of variables while debugging in Android Studio. In Xcode, you can type commands into the terminal window to execute code. For example: po user.name would print the user's name. There is a similar facility in the Chrome debugger. You could just type user.getFriends() and it would output the list of friends.
Does something like this exist in Android Studio? At the moment I'm limited to having to examine the variables in the Variables window which is slower and much less flexible because you can't print the value of functions.
A: When debugging an application, you can set a breakpoint and when that triggers, you can right click in the editor and select 'Evaluate Expression...' I believe this will give you close to what you are looking for.
| Q: Examining variables while debugging in Android Studio I'm looking for a way to examine the value of variables while debugging in Android Studio. In Xcode, you can type commands into the terminal window to execute code. For example: po user.name would print the user's name. There is a similar facility in the Chrome debugger. You could just type user.getFriends() and it would output the list of friends.
Does something like this exist in Android Studio? At the moment I'm limited to having to examine the variables in the Variables window which is slower and much less flexible because you can't print the value of functions.
A: When debugging an application, you can set a breakpoint and when that triggers, you can right click in the editor and select 'Evaluate Expression...' I believe this will give you close to what you are looking for.
| stackoverflow | {
"language": "en",
"length": 144,
"provenance": "stackexchange_0000F.jsonl.gz:899258",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649523"
} |
77a6b5aaaa991b78af7931d6cab52d9968077c1a | Stackoverflow Stackexchange
Q: Boto3: Get aws_security_token I am able to get access_key and secret_key but I am not able to get security token.
This works:
import boto3
session = boto3.Session()
credentials = session.get_credentials()
print credentials.access_key
print credentials.secret_key
This doesn't:
print credentials.session_token
neither this:
print credentials.security_token
nor this:
client = boto3.client('sts')
client.get_session_token()
gives me this error:
ClientError: An error occurred (AccessDenied) when calling the GetSessionToken operation: Cannot call GetSessionToken with session credentials
Please help!
A: This works:
import boto3
session = boto3.Session()
credentials = session.get_credentials()
print credentials.token
I discovered that via print credentials.__dict__
| Q: Boto3: Get aws_security_token I am able to get access_key and secret_key but I am not able to get security token.
This works:
import boto3
session = boto3.Session()
credentials = session.get_credentials()
print credentials.access_key
print credentials.secret_key
This doesn't:
print credentials.session_token
neither this:
print credentials.security_token
nor this:
client = boto3.client('sts')
client.get_session_token()
gives me this error:
ClientError: An error occurred (AccessDenied) when calling the GetSessionToken operation: Cannot call GetSessionToken with session credentials
Please help!
A: This works:
import boto3
session = boto3.Session()
credentials = session.get_credentials()
print credentials.token
I discovered that via print credentials.__dict__
| stackoverflow | {
"language": "en",
"length": 90,
"provenance": "stackexchange_0000F.jsonl.gz:899263",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649543"
} |
c4c4e0c4dd943996498956db159edbede55dd9cb | Stackoverflow Stackexchange
Q: Format a number with decimal mark How do I format a number like this:
95263.51
to be with decimal mark (comma):
95.263,51
or even with decimal point (which is more common):
95,263.51 ?
A: Found the way to do it,
using the Number package:
iex> Number.Delimit.number_to_delimited(98765432.98, delimiter: ".",separator: ",")
"98 765 432,98"
| Q: Format a number with decimal mark How do I format a number like this:
95263.51
to be with decimal mark (comma):
95.263,51
or even with decimal point (which is more common):
95,263.51 ?
A: Found the way to do it,
using the Number package:
iex> Number.Delimit.number_to_delimited(98765432.98, delimiter: ".",separator: ",")
"98 765 432,98"
| stackoverflow | {
"language": "en",
"length": 53,
"provenance": "stackexchange_0000F.jsonl.gz:899276",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649585"
} |
f8e9954d7e0a768415dc40e0a151b3ebb44f4e30 | Stackoverflow Stackexchange
Q: Element UI and font-awesome Can anyone explane if it is possible to use font-awesome or another big icon font with Element UI? I've seen FAQ but cannot make it work for me.
https://github.com/ElemeFE/element/blob/dev/FAQ.md
Thanks.
A: You can just include those libraries / or NPM them and they work, Element UI has a limited set of icons so I have include vue-awesome (font awesome) but I notice the position of the icons if out a bit so you need some CSS to adjust top margins (I needed -4px) and line them with say button text.
| Q: Element UI and font-awesome Can anyone explane if it is possible to use font-awesome or another big icon font with Element UI? I've seen FAQ but cannot make it work for me.
https://github.com/ElemeFE/element/blob/dev/FAQ.md
Thanks.
A: You can just include those libraries / or NPM them and they work, Element UI has a limited set of icons so I have include vue-awesome (font awesome) but I notice the position of the icons if out a bit so you need some CSS to adjust top margins (I needed -4px) and line them with say button text.
| stackoverflow | {
"language": "en",
"length": 95,
"provenance": "stackexchange_0000F.jsonl.gz:899288",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649614"
} |
a638f9b131856fccd8e6fe2f9a52d8dbfc005adc | Stackoverflow Stackexchange
Q: localStorage not working in iphone (ionic app) I have a problem with localStorage on an ionic app on iphone.
on android it seems to work ok.
on iphone the localstorage just expires after awhile.
I've tried with
$localStorage.test
using angular ngStorage.js.
and with:
window.localStorage.test
same results.
anyone experienced this? any solution?
Thanks.
Rafi.
A: If there is low internal memory on iPhone, iOS automatically delete some caches and localstorage.
LocalStorage works well if there is sufficient memory on the device(usually more than 20mb at least)
So better to use sqlite instead of localstorage :)
| Q: localStorage not working in iphone (ionic app) I have a problem with localStorage on an ionic app on iphone.
on android it seems to work ok.
on iphone the localstorage just expires after awhile.
I've tried with
$localStorage.test
using angular ngStorage.js.
and with:
window.localStorage.test
same results.
anyone experienced this? any solution?
Thanks.
Rafi.
A: If there is low internal memory on iPhone, iOS automatically delete some caches and localstorage.
LocalStorage works well if there is sufficient memory on the device(usually more than 20mb at least)
So better to use sqlite instead of localstorage :)
| stackoverflow | {
"language": "en",
"length": 95,
"provenance": "stackexchange_0000F.jsonl.gz:899305",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649673"
} |
e1f83f9745d75ddcff7fda13001e3e0146219bfd | Stackoverflow Stackexchange
Q: NEWSEQUENTIALID() is broken in SQL Server for linux? I am running MS SQL Server for linux from a Docker image (https://hub.docker.com/r/microsoft/mssql-server-linux/)
I've discovered in my log files, that there are many PRIMARY KEY violations on my log table, which has ID uniqueidentifier DEFAULT NEWSEQUENTIALID() column.
Exception is:
Exception: System.Data.SqlClient.SqlException:
Violation of PRIMARY KEY constraint 'PK_Logs'.
Cannot insert duplicate key in object 'dbo.Logs'.
The duplicate key value is (20c0423e-f36b-1410-8020-800000000000).
As stated in documentation
NEWSEQUENTIALID is a wrapper over the Windows UuidCreateSequential function.
(source: https://learn.microsoft.com/en-us/sql/t-sql/functions/newsequentialid-transact-sql)
How does it work on linux then? Is the behaviour broken, since generated GUIDs should be unique, and they are clearly not.
Reproduction steps
*
*start mssql-server-linux docker image docker run mssql-server-linux (refer to https://hub.docker.com/r/microsoft/mssql-server-linux/ for details)
*Create table CREATE TABLE SequentialIdTest(ID uniqueidentifier PRIMARY KEY DEFAULT NEWSEQUENTIALID(), ColA int );
*Insert new row
INSERT INTO SequentialIdTest(ColA) VALUES (0);
*restart docker image docker restart {CONTAINER_NAME}
*Try to insert new row again INSERT INTO SequentialIdTest(ColA) VALUES (0);
| Q: NEWSEQUENTIALID() is broken in SQL Server for linux? I am running MS SQL Server for linux from a Docker image (https://hub.docker.com/r/microsoft/mssql-server-linux/)
I've discovered in my log files, that there are many PRIMARY KEY violations on my log table, which has ID uniqueidentifier DEFAULT NEWSEQUENTIALID() column.
Exception is:
Exception: System.Data.SqlClient.SqlException:
Violation of PRIMARY KEY constraint 'PK_Logs'.
Cannot insert duplicate key in object 'dbo.Logs'.
The duplicate key value is (20c0423e-f36b-1410-8020-800000000000).
As stated in documentation
NEWSEQUENTIALID is a wrapper over the Windows UuidCreateSequential function.
(source: https://learn.microsoft.com/en-us/sql/t-sql/functions/newsequentialid-transact-sql)
How does it work on linux then? Is the behaviour broken, since generated GUIDs should be unique, and they are clearly not.
Reproduction steps
*
*start mssql-server-linux docker image docker run mssql-server-linux (refer to https://hub.docker.com/r/microsoft/mssql-server-linux/ for details)
*Create table CREATE TABLE SequentialIdTest(ID uniqueidentifier PRIMARY KEY DEFAULT NEWSEQUENTIALID(), ColA int );
*Insert new row
INSERT INTO SequentialIdTest(ColA) VALUES (0);
*restart docker image docker restart {CONTAINER_NAME}
*Try to insert new row again INSERT INTO SequentialIdTest(ColA) VALUES (0);
| stackoverflow | {
"language": "en",
"length": 159,
"provenance": "stackexchange_0000F.jsonl.gz:899355",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649830"
} |
2b46172b321d3346f4d054985fc6797308327dba | Stackoverflow Stackexchange
Q: angular2 array of boolean When declaring this :
public isCollapsedDet : boolean[][];
public isCollapsedCyc : boolean[] ;
I got the following error message :
/nestedForm/src/app/app.component.ts (95,7): Type 'boolean' is not assignable to type 'boolean[][]'.
I just need to get array as the following :
isCollapsedCyc[0] = true;
isCollapsedCyc[1] = false;
//
isCollapsedDet[0, 0] = true;
isCollapsedDet[0, 1] = true;
isCollapsedDet[1, 0] = false;
isCollapsedDet[1, 1] = true;
A: You cannot add values to an array by nesting them with comma.
Type boolean[][] means that there will be an array of arrays of booleans, so something like for example:
[[true, false], [false, true]] // this is boolean[][] or Array<Array<boolean>>
if you want to set the value for it, you need to nest it as an ordinary array:
isCollapsedDet[0, 0] = true;
// error - comma has nothing to do there
isCollapsedDet[0][0] = true;
// success - element isCollapsedDet[0][0] in array isCollapsedDet[0] is true
More about arrays in TypeScript can be found here - and a bit more advanced types here
Some useful answers found here: Multidimensional array initialization
Other links: TypeScript Multidimensional Arrays
| Q: angular2 array of boolean When declaring this :
public isCollapsedDet : boolean[][];
public isCollapsedCyc : boolean[] ;
I got the following error message :
/nestedForm/src/app/app.component.ts (95,7): Type 'boolean' is not assignable to type 'boolean[][]'.
I just need to get array as the following :
isCollapsedCyc[0] = true;
isCollapsedCyc[1] = false;
//
isCollapsedDet[0, 0] = true;
isCollapsedDet[0, 1] = true;
isCollapsedDet[1, 0] = false;
isCollapsedDet[1, 1] = true;
A: You cannot add values to an array by nesting them with comma.
Type boolean[][] means that there will be an array of arrays of booleans, so something like for example:
[[true, false], [false, true]] // this is boolean[][] or Array<Array<boolean>>
if you want to set the value for it, you need to nest it as an ordinary array:
isCollapsedDet[0, 0] = true;
// error - comma has nothing to do there
isCollapsedDet[0][0] = true;
// success - element isCollapsedDet[0][0] in array isCollapsedDet[0] is true
More about arrays in TypeScript can be found here - and a bit more advanced types here
Some useful answers found here: Multidimensional array initialization
Other links: TypeScript Multidimensional Arrays
A: If you really only need the elements you mentioned, you could do:
let isCollapsedDet: boolean[][] = [[], []];
let isCollapsedCyc: boolean[] = [];
isCollapsedCyc[0] = true;
isCollapsedCyc[1] = false;
isCollapsedDet[0][0] = true;
isCollapsedDet[0][1] = true;
isCollapsedDet[1][0] = false;
isCollapsedDet[1][1] = true;
Or simply:
let isCollapsedDet: boolean[][] = [
[true, true], [false, true]
];
let isCollapsedCyc: boolean[] = [true, false];
which can be reduced further because the compiler will infer the types based on the initialization:
let isCollapsedDet = [
[true, true], [false, false]
];
let isCollapsedCyc = [true, false];
A: When you are accessing a property in any class and if you want to make it as a class member then don't forget to mention this and as Dawid said you can't assign values by separating indexes with comma(,)
export class HelloWorld implements OnInit{
// Declaring the variable for binding with initial value
yourName: string = '';
public isCollapsedDet : boolean[][] = [[], []];
isCollapsedCyc : boolean[] = [];
ngOnInit() {
this.isCollapsedCyc[0] = true;
this.isCollapsedCyc[1] = false;
//
this.isCollapsedDet[0][0] = true;
this.isCollapsedDet[0][1] = true;
this.isCollapsedDet[1][0] = false;
this.isCollapsedDet[1][1] = true;
}
}
| stackoverflow | {
"language": "en",
"length": 366,
"provenance": "stackexchange_0000F.jsonl.gz:899399",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649957"
} |
b1afbbe5f4ed05801029a4f7248c37cf9131e2f1 | Stackoverflow Stackexchange
Q: How to run mongo db script on remote server? how to run a Mongo db script on a remote server?
I know below command can be used for the same on local as mentioned here:How to execute mongo commands through shell scripts?
mongo < yourFile.js
I want to run this script on a remote server
mongodb:uri:mongodb://user:password@mongodb01d.mydomain.com:27017/mydb
A: With Mongo on local machine :
mongo -u <user> -p <password> mongodb01d.mydomain.com:27017/mydb <yourFile.js>
| Q: How to run mongo db script on remote server? how to run a Mongo db script on a remote server?
I know below command can be used for the same on local as mentioned here:How to execute mongo commands through shell scripts?
mongo < yourFile.js
I want to run this script on a remote server
mongodb:uri:mongodb://user:password@mongodb01d.mydomain.com:27017/mydb
A: With Mongo on local machine :
mongo -u <user> -p <password> mongodb01d.mydomain.com:27017/mydb <yourFile.js>
A: It might be a little bit off topic, but in case you want to / have to use Powershell for a lack of options, you can run:
(Get-Content yourFile.js) | & mongo.exe 'mongodb://user:password@mongodb01d.mydomain.com:27017/mydb'
or
"print('Hello');print('Hello')" | & mongo.exe 'mongodb://user:password@mongodb01d.mydomain.com:27017/mydb'
or
& 'mongo.exe' 'mongodb://user:password@mongodb01d.mydomain.com:27017/mydb' --eval "print('Hello');print('Hello')"
I had some difficulties with $regex, because Powershell interpreted it as a variable, so I had to use `$regex (with an additional backtick) instead.
| stackoverflow | {
"language": "en",
"length": 141,
"provenance": "stackexchange_0000F.jsonl.gz:899404",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649974"
} |
4638382ce4d0bb6107aaf8f022f50fe9f5f4d8bc | Stackoverflow Stackexchange
Q: Spring boot actuator "/health" is not working I have a running Springboot application which serves the URL http://localhost:8081/topics and returns me JSON response as expected.
I added actuator dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<scope>test</scope>
</dependency>
as suggested in tutorial
But when I hit http://localhost:8081/health it does not give expected result. It says
{
"timestamp": 1497952368055,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/health"
}
Spring boot version is 1.5.4.RELEASE. And Java 1.8
What additional settings do I need to do ?
A: Do the following steps : -
*
*Change the scope of actuator dependency from test to compile
*Instead of using /health use /actuator/health
*If you want to see details of the health status then addmanagement.endpoint.health.show-details=always in the application.properties file.
| Q: Spring boot actuator "/health" is not working I have a running Springboot application which serves the URL http://localhost:8081/topics and returns me JSON response as expected.
I added actuator dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<scope>test</scope>
</dependency>
as suggested in tutorial
But when I hit http://localhost:8081/health it does not give expected result. It says
{
"timestamp": 1497952368055,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/health"
}
Spring boot version is 1.5.4.RELEASE. And Java 1.8
What additional settings do I need to do ?
A: Do the following steps : -
*
*Change the scope of actuator dependency from test to compile
*Instead of using /health use /actuator/health
*If you want to see details of the health status then addmanagement.endpoint.health.show-details=always in the application.properties file.
A: In your dependency you have declared
<scope>test</scope>
It means that
test
This scope indicates that the dependency is not required for normal
use of the application, and is only available for the test compilation
and execution phases.
If you want it available for normal use of the application remove <scope>test</scope> or change it to <scope>compile</scope>
A: Add Maven dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Application.properties
management.endpoints.web.exposure.include= "*" include all endpoints on actuator
or
management.endpoints.web.exposure.include= health if need only health endpoint
A: In Spring Boot 2.0.0 you have to use /actuator/health
and in the application.properties file add the following line:
management.endpoint.health.show-details=always
A: Maven dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Application.properties
spring.profiles.active=local
server.port = 9292
management.endpoints.web.exposure.include=env,health,metrics
For reference use below link:(step by step explanation)
https://www.youtube.com/watch?v=0Dj2tsK2V2g
| stackoverflow | {
"language": "en",
"length": 246,
"provenance": "stackexchange_0000F.jsonl.gz:899412",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44649988"
} |
46a9d7d64b1edc4e5e2d0c0603e5b0a6383cad9d | Stackoverflow Stackexchange
Q: How to permute one column in pandas I have pandas dataframe with 3 columns:
X1 X2 Y
1 2 1
2 4 0
3 6 1
I want to permute only one column X1 and the result is:
X1 X2 Y
3 2 1
1 4 0
2 6 1
I only found how permute all columns by reindexing them but not how to do this only for one column.
A: Just in case you don't want a random permutation and you want a specific "permutation" you can always roll columns:
>>> import numpy as np
>>> df['X1'] = np.roll(df['X1'], 1) # move each item one row down (with wraparound)
>>> df
X1 X2 Y
0 3 2 1
1 1 4 0
2 2 6 1
| Q: How to permute one column in pandas I have pandas dataframe with 3 columns:
X1 X2 Y
1 2 1
2 4 0
3 6 1
I want to permute only one column X1 and the result is:
X1 X2 Y
3 2 1
1 4 0
2 6 1
I only found how permute all columns by reindexing them but not how to do this only for one column.
A: Just in case you don't want a random permutation and you want a specific "permutation" you can always roll columns:
>>> import numpy as np
>>> df['X1'] = np.roll(df['X1'], 1) # move each item one row down (with wraparound)
>>> df
X1 X2 Y
0 3 2 1
1 1 4 0
2 2 6 1
A: Use numpy.random.permutation:
df['X1'] = np.random.permutation(df['X1'])
print (df)
X1 X2 Y
0 3 2 1
1 2 4 0
2 1 6 1
| stackoverflow | {
"language": "en",
"length": 151,
"provenance": "stackexchange_0000F.jsonl.gz:899467",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650135"
} |
f866bb10fe8d72c3b9a3527f3de3c57f3d2adfbc | Stackoverflow Stackexchange
Q: XWPFDocument returning 1 number of pages for docx file I am using XWPFDocument library to find number of pages in docx file. Below is my code snippet :
XWPFDocument docx = null;
try {
docx = new XWPFDocument(POIXMLDocument.openPackage(filePath));
totalPages = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();
} catch (IOException e) {
logger.error("Error while loading word document at file location {}", filePath);
totalPages = 0;
}
For some .docx it is working fine but for some files it is returning 1 inspite of having more than 30 pages.
| Q: XWPFDocument returning 1 number of pages for docx file I am using XWPFDocument library to find number of pages in docx file. Below is my code snippet :
XWPFDocument docx = null;
try {
docx = new XWPFDocument(POIXMLDocument.openPackage(filePath));
totalPages = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();
} catch (IOException e) {
logger.error("Error while loading word document at file location {}", filePath);
totalPages = 0;
}
For some .docx it is working fine but for some files it is returning 1 inspite of having more than 30 pages.
| stackoverflow | {
"language": "en",
"length": 83,
"provenance": "stackexchange_0000F.jsonl.gz:899473",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650147"
} |
88528118e80892253509c85ad38d0f6c5495cb06 | Stackoverflow Stackexchange
Q: Disable HTTPS on AWS S3 using Java API I want to use the Java API for S3 (getting an object) with plain HTTP (instead of HTTPS), but can't find the parameters to do so.
Currently I'm using a REST client to call http://s3.amazonaws.com instead of https://s3.amazonaws.com
Java API I am using:
AmazonS3 amazonS3 = AmazonS3ClientBuilder.defaultClient();
S3ObjectInputStream s3ObjectInputStream = amazonS3.getObject(getS3BotBucket(), resourceFile).getObjectContent();
A: Get an instance of the client builder with AmazonS3ClientBuilder.standard().
Call withClientConfiguration(new ClientConfiguration.withProtocol(Protocol.HTTP)) on the client builder instance, then call the builder's build method to get your S3 client instance that will use http instead of https
| Q: Disable HTTPS on AWS S3 using Java API I want to use the Java API for S3 (getting an object) with plain HTTP (instead of HTTPS), but can't find the parameters to do so.
Currently I'm using a REST client to call http://s3.amazonaws.com instead of https://s3.amazonaws.com
Java API I am using:
AmazonS3 amazonS3 = AmazonS3ClientBuilder.defaultClient();
S3ObjectInputStream s3ObjectInputStream = amazonS3.getObject(getS3BotBucket(), resourceFile).getObjectContent();
A: Get an instance of the client builder with AmazonS3ClientBuilder.standard().
Call withClientConfiguration(new ClientConfiguration.withProtocol(Protocol.HTTP)) on the client builder instance, then call the builder's build method to get your S3 client instance that will use http instead of https
A: As long as your GET request does not use the SSL endpoint, you can specify the bucket for the request by using the HTTP Host header.
http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html#VirtualHostingSpecifyBuckety
| stackoverflow | {
"language": "en",
"length": 126,
"provenance": "stackexchange_0000F.jsonl.gz:899476",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650168"
} |
dbd451475c86dd2342187726f4947a96812b4668 | Stackoverflow Stackexchange
Q: Check if it is the last element in an array inside map() function I have an array of strings and I want to print them on different lines.
I'm using <hr /> for this but as it is now in my code, it will put another break after the last string, fact that I want to avoid. Any ideas?
This is my code:
return myArray.map((text, index) => (
<span key={index}>
{myArray[index]}
{<hr />}
</span>
));
A: You can check if its last element by checking if there is next element arr[i + 1]
var arr = ['a', 'b', 'c']
var html = arr.map(function(e, i) {
return `<span key="${i}">${e}</span>${arr[i+1] ? '<hr>' : ''}`
})
document.body.innerHTML += html.join('')
| Q: Check if it is the last element in an array inside map() function I have an array of strings and I want to print them on different lines.
I'm using <hr /> for this but as it is now in my code, it will put another break after the last string, fact that I want to avoid. Any ideas?
This is my code:
return myArray.map((text, index) => (
<span key={index}>
{myArray[index]}
{<hr />}
</span>
));
A: You can check if its last element by checking if there is next element arr[i + 1]
var arr = ['a', 'b', 'c']
var html = arr.map(function(e, i) {
return `<span key="${i}">${e}</span>${arr[i+1] ? '<hr>' : ''}`
})
document.body.innerHTML += html.join('')
A: Wrap them in a pragraph and not in a span
return myArray.map((text, index) => (
<p key={index}>
{text}
</p>
));
A: myArray.map((text, index, {length}) => (
/* ... your code ... */
if(index + 1 === length){ //last element
}
));
//{length} === myArray.length; third argument is an array
A: You just need to check upon iterated index, if(index < (myArray.length-1)) :
return myArray.map((text, index) => (
<span key={index}>
{myArray[index]}
if(index < (myArray.length-1))
{<hr />}
</span>
));
| stackoverflow | {
"language": "en",
"length": 195,
"provenance": "stackexchange_0000F.jsonl.gz:899488",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650201"
} |
1527a3029b99258f2e8f8169d8e1f9a8cf95fb0a | Stackoverflow Stackexchange
Q: How to set the cursor to the editText I have two EditText, how can I set the cursor in the right EditText
EditText emailE = (EditText) findViewById(R.id.editTextEmailLogin);
EditText passwordE = (EditText)findViewById(R.id.editTextPasswordLogin);
String email = emailE.getText().toString().trim();
String password = passwordE.getText().toString().trim();
if the user pressing Singin and the email EditText is empty, set the cursor in the email EditText.
and the same for password EditText
if (TextUtils.isEmpty(email)){
Toast.makeText(this, getResources()"email is empty", Toast.LENGTH_SHORT).show();
//set cursor in Email editText
emailE.setSelection(0);
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this,"password is empty", Toast.LENGTH_SHORT).show();
//set cursor in Password editText
passwordE.setSelection(0);
return;
}
A: Try using the .requestFocus(); method
| Q: How to set the cursor to the editText I have two EditText, how can I set the cursor in the right EditText
EditText emailE = (EditText) findViewById(R.id.editTextEmailLogin);
EditText passwordE = (EditText)findViewById(R.id.editTextPasswordLogin);
String email = emailE.getText().toString().trim();
String password = passwordE.getText().toString().trim();
if the user pressing Singin and the email EditText is empty, set the cursor in the email EditText.
and the same for password EditText
if (TextUtils.isEmpty(email)){
Toast.makeText(this, getResources()"email is empty", Toast.LENGTH_SHORT).show();
//set cursor in Email editText
emailE.setSelection(0);
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this,"password is empty", Toast.LENGTH_SHORT).show();
//set cursor in Password editText
passwordE.setSelection(0);
return;
}
A: Try using the .requestFocus(); method
A: Try this:
if (TextUtils.isEmpty(email)){
Toast.makeText(this, getResources()"email is empty", Toast.LENGTH_SHORT).show();
//set cursor in Email editText
emailE.requestFocus();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this,"password is empty", Toast.LENGTH_SHORT).show();
//set cursor in Password editText
passwordE.requestFocus();
return;
}
A: you can use requestFocus(); method of edittext like this
if (TextUtils.isEmpty(email)){
Toast.makeText(this, getResources()"email is empty", Toast.LENGTH_SHORT).show();
//set cursor in Email editText
emailE.requestFocus();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this,"password is empty", Toast.LENGTH_SHORT).show();
//set cursor in Password editText
passwordE.requestFocus();
return;
}
A: etext1.setSelection(Your position)
or
EditText etext1 = (EditText)findViewById(R.id.etext1 );
etext1.setSelection(etext1.getText().length());
or
etext1 .requestFocus(Your_Text.length());
Try this one also;
Check this
A: EditText editText = (EditText) findViewById(R.id.myTextViewId);
if (TextUtils.isEmpty(email)){
Toast.makeText(this, getResources()"email is empty", Toast.LENGTH_SHORT).show();
//set cursor in Email editText
emailE.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(emailE, InputMethodManager.SHOW_IMPLICIT);
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this,"password is empty", Toast.LENGTH_SHORT).show();
//set cursor in Password editText
passwordE.requestFocus();
InputMethodManager imm2 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm2.showSoftInput(passwordE, InputMethodManager.SHOW_IMPLICIT);
return;
}
| stackoverflow | {
"language": "en",
"length": 234,
"provenance": "stackexchange_0000F.jsonl.gz:899506",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650250"
} |
4237ce9c4a2a53136e12efdd8a61589cdaecb1fc | Stackoverflow Stackexchange
Q: MongoDB find vs aggregate performance I am trying to measure MongoDB's find vs aggregate performance.
is there any way to compare aggregate with match and find query performance.
currently I am using JavaScript to measure it.
as find():
var start = (new Date).getTime();
db.assets.find({
"catalog_id":"f1a7669654584a42958d9589cf37d173",
"albums":{"$elemMatch":{"id":"5f7938ce6e2718eb776f82474f2e093f","order":{"$exists":false}}}
});
var end = (new Date).getTime();
print("elapsed " + (end - start) +" msec");
as aggregate():
var start = (new Date).getTime();
db.assets.aggregate([
{
"$match":{
"catalog_id":"f1a7669654584a42958d9589cf37d173",
"albums":{"$elemMatch":{"id":"5f7938ce6e2718eb776f82474f2e093f","order":{"$exists":false}}}
}
}
]);
var end = (new Date).getTime();
print("elapsed " + (end - start) +" msec");
but it doesn't seems right to me.
Can someone suggest some other way to do it.
A: The db.collection.explain() operations can return information regarding:
*
*queryPlanner, which details the plan selected by the query optimizer and lists the rejected plans;
*executionStats, which details the execution of the winning plan and the rejected plans; and
*serverInfo, which provides information on the MongoDB instance.
How to explain in find()?
db.assets.explain("executionStats").find({
"catalog_id":"f1a7669654584a42958d9589cf37d173",
"albums":{"$elemMatch":{"id":"5f7938ce6e2718eb776f82474f2e093f","order":{"$exists":false}}}
});
How to explain in aggregate()?
db.assets.explain("executionStats").aggregate([
{
"$match":{
"catalog_id":"f1a7669654584a42958d9589cf37d173",
"albums":{"$elemMatch":{"id":"5f7938ce6e2718eb776f82474f2e093f","order":{"$exists":false}}}
}
}
]);
| Q: MongoDB find vs aggregate performance I am trying to measure MongoDB's find vs aggregate performance.
is there any way to compare aggregate with match and find query performance.
currently I am using JavaScript to measure it.
as find():
var start = (new Date).getTime();
db.assets.find({
"catalog_id":"f1a7669654584a42958d9589cf37d173",
"albums":{"$elemMatch":{"id":"5f7938ce6e2718eb776f82474f2e093f","order":{"$exists":false}}}
});
var end = (new Date).getTime();
print("elapsed " + (end - start) +" msec");
as aggregate():
var start = (new Date).getTime();
db.assets.aggregate([
{
"$match":{
"catalog_id":"f1a7669654584a42958d9589cf37d173",
"albums":{"$elemMatch":{"id":"5f7938ce6e2718eb776f82474f2e093f","order":{"$exists":false}}}
}
}
]);
var end = (new Date).getTime();
print("elapsed " + (end - start) +" msec");
but it doesn't seems right to me.
Can someone suggest some other way to do it.
A: The db.collection.explain() operations can return information regarding:
*
*queryPlanner, which details the plan selected by the query optimizer and lists the rejected plans;
*executionStats, which details the execution of the winning plan and the rejected plans; and
*serverInfo, which provides information on the MongoDB instance.
How to explain in find()?
db.assets.explain("executionStats").find({
"catalog_id":"f1a7669654584a42958d9589cf37d173",
"albums":{"$elemMatch":{"id":"5f7938ce6e2718eb776f82474f2e093f","order":{"$exists":false}}}
});
How to explain in aggregate()?
db.assets.explain("executionStats").aggregate([
{
"$match":{
"catalog_id":"f1a7669654584a42958d9589cf37d173",
"albums":{"$elemMatch":{"id":"5f7938ce6e2718eb776f82474f2e093f","order":{"$exists":false}}}
}
}
]);
| stackoverflow | {
"language": "en",
"length": 173,
"provenance": "stackexchange_0000F.jsonl.gz:899507",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650254"
} |
0ec7a51274b742eca7080aa7ffdce1e600ed28d7 | Stackoverflow Stackexchange
Q: .htaccess - Remove one query parameter from URL I have a URL that looks something like this:
https://www.example.com/about-us?stage=Stage&utm_source=abc&utm_medium=xyz
I want to just remove the stage=Stage part.
I tried the below code:
RewriteCond %{QUERY_STRING} ^stage=Stage$
RewriteRule (.*) $Stage? [R=permanent]
but it only seems to work if the URL is:
https://www.example.com/about-us?stage=Stage
without the rest of the parameters.
How can I make the other parameters pass over apart from the stage=Stage parameter?
A: You can use this rule at the top of your .htaccess:
RewriteCond %{QUERY_STRING} ^(.*&)?stage=Stage(?:&(.*))?$ [NC]
RewriteRule ^ %{REQUEST_URI}?%1%2 [L,R=301,NE]
| Q: .htaccess - Remove one query parameter from URL I have a URL that looks something like this:
https://www.example.com/about-us?stage=Stage&utm_source=abc&utm_medium=xyz
I want to just remove the stage=Stage part.
I tried the below code:
RewriteCond %{QUERY_STRING} ^stage=Stage$
RewriteRule (.*) $Stage? [R=permanent]
but it only seems to work if the URL is:
https://www.example.com/about-us?stage=Stage
without the rest of the parameters.
How can I make the other parameters pass over apart from the stage=Stage parameter?
A: You can use this rule at the top of your .htaccess:
RewriteCond %{QUERY_STRING} ^(.*&)?stage=Stage(?:&(.*))?$ [NC]
RewriteRule ^ %{REQUEST_URI}?%1%2 [L,R=301,NE]
| stackoverflow | {
"language": "en",
"length": 90,
"provenance": "stackexchange_0000F.jsonl.gz:899512",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650266"
} |
b7da233afe6d8b669414df71184faaf73f7f0db4 | Stackoverflow Stackexchange
Q: Tomcat JAR Scanner trying to scan apache-tomcat/lib/lib/ for JARs I'm upgrading to Apache Tomcat 8.5.15 from 6.0.44. When I start up the web server and deploy my web application, I get lots of warnings from org.apache.tomcat.util.scan.StandardJarScanner.scan with the message
Failed to scan [file:/path/to/apache-tomcat/lib/lib/tomcat-jaspic-api-8.5.15.jar] from class loader hierarchy
java.io.FileNotFoundException: /path/to/apache-tomcat/lib/lib/tomcat-jaspic-api-8.5.15.jar (No such file or directory)
I don't understand why the scanner is looking inside apache-tomcat/lib for another directory named lib, which doesn't exist. My CATALINA_HOME is set to /path/to/apache-tomcat and the common.loader property in catalina.properties is set to the default:
common.loader="${catalina.base}/lib","${catalina.base}/lib/*.jar","${catalina.home}/lib","${catalina.home}/lib/*.jar"
I know that the warning can be safely ignored without affecting the web application, and that I can turn off JAR scanning in apache-tomcat/conf/context.xml, but I'd still like to know the reason behind the lib/lib oddness.
| Q: Tomcat JAR Scanner trying to scan apache-tomcat/lib/lib/ for JARs I'm upgrading to Apache Tomcat 8.5.15 from 6.0.44. When I start up the web server and deploy my web application, I get lots of warnings from org.apache.tomcat.util.scan.StandardJarScanner.scan with the message
Failed to scan [file:/path/to/apache-tomcat/lib/lib/tomcat-jaspic-api-8.5.15.jar] from class loader hierarchy
java.io.FileNotFoundException: /path/to/apache-tomcat/lib/lib/tomcat-jaspic-api-8.5.15.jar (No such file or directory)
I don't understand why the scanner is looking inside apache-tomcat/lib for another directory named lib, which doesn't exist. My CATALINA_HOME is set to /path/to/apache-tomcat and the common.loader property in catalina.properties is set to the default:
common.loader="${catalina.base}/lib","${catalina.base}/lib/*.jar","${catalina.home}/lib","${catalina.home}/lib/*.jar"
I know that the warning can be safely ignored without affecting the web application, and that I can turn off JAR scanning in apache-tomcat/conf/context.xml, but I'd still like to know the reason behind the lib/lib oddness.
| stackoverflow | {
"language": "en",
"length": 127,
"provenance": "stackexchange_0000F.jsonl.gz:899532",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650337"
} |
446c5fea0971a0e03a4abf59e25e123907355bab | Stackoverflow Stackexchange
Q: osx monday date current week bash I need to get an array of all the dates
of the current week in BASH 4, in OSX.
I tried to get the monday date,
but on OSX the date doesn't work the same as Linux (gdate)
The result I need :
array=(
'YYYY-MM-DD', # MONDAY
'YYYY-MM-DD', # TUESDAY
'YYYY-MM-DD', # WEDNESDAY
'YYYY-MM-DD', # THURSDAY
'YYYY-MM-DD', # FRIDAY
'YYYY-MM-DD', # SATURDAY
'YYYY-MM-DD') # SUNDAY
I'm a novice in bash and tried for 2 hour
to find something on internet, without success.
Thanks a lot for your help.
A: have You tried man date?
date -v-monday
Gets the date adjusted so the weekday is the previous Monday. If it is Monday it gives the current day, so if You discard hours, minutes and seconds You get the date of the first day of the week.
date -v-monday +'%Y-%m-%d'
gets the format that You requested. To get next dates You can use -v to adjust further, e.g. date -v-monday -v+1d +'%Y-%m-%d' gives the date of current week's Tuesday.
So to answer Your question fully:
#!/bin/bash
for i in $(seq 0 6)
do
WEEKDAYS[$i]=`date -v-monday -v+"$i"d +'%Y-%m-%d'`
done;
| Q: osx monday date current week bash I need to get an array of all the dates
of the current week in BASH 4, in OSX.
I tried to get the monday date,
but on OSX the date doesn't work the same as Linux (gdate)
The result I need :
array=(
'YYYY-MM-DD', # MONDAY
'YYYY-MM-DD', # TUESDAY
'YYYY-MM-DD', # WEDNESDAY
'YYYY-MM-DD', # THURSDAY
'YYYY-MM-DD', # FRIDAY
'YYYY-MM-DD', # SATURDAY
'YYYY-MM-DD') # SUNDAY
I'm a novice in bash and tried for 2 hour
to find something on internet, without success.
Thanks a lot for your help.
A: have You tried man date?
date -v-monday
Gets the date adjusted so the weekday is the previous Monday. If it is Monday it gives the current day, so if You discard hours, minutes and seconds You get the date of the first day of the week.
date -v-monday +'%Y-%m-%d'
gets the format that You requested. To get next dates You can use -v to adjust further, e.g. date -v-monday -v+1d +'%Y-%m-%d' gives the date of current week's Tuesday.
So to answer Your question fully:
#!/bin/bash
for i in $(seq 0 6)
do
WEEKDAYS[$i]=`date -v-monday -v+"$i"d +'%Y-%m-%d'`
done;
| stackoverflow | {
"language": "en",
"length": 193,
"provenance": "stackexchange_0000F.jsonl.gz:899535",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650349"
} |
9f5d4207aebc0302c0a5f8a229355e4afc8797a9 | Stackoverflow Stackexchange
Q: React RTL. Conditional Import CSS I am incorporating RTL to my React application. I have two CSS files, one for LTR and one for RTL. I have a drop down from where user select either English version or Arabic version.
I am stuck with that how to conditional import my RTL CSS file when user select Arabic version and back to normal CSS file when user select English.
Any help or guidance on this will be highly appreciated
I am using React & webpack
Regards
A: I have faced this problem before, What I have done is that when my main container is mounting, I check for the language, if it's Arabic, I require the Arabic CSS file, if not I require the other.
Example:
class Main extends Component {
componentWillMount() {
if(this.props.language === 'ar') {
require('arabic.css');
} else {
require('english.css');
}
}
}
I'm using Redux as well, which makes it easier for me to get the initial or default language, and change all the other components accordingly as well.
Just make sure you have the CSS loader configured in your webpack configuration file.
| Q: React RTL. Conditional Import CSS I am incorporating RTL to my React application. I have two CSS files, one for LTR and one for RTL. I have a drop down from where user select either English version or Arabic version.
I am stuck with that how to conditional import my RTL CSS file when user select Arabic version and back to normal CSS file when user select English.
Any help or guidance on this will be highly appreciated
I am using React & webpack
Regards
A: I have faced this problem before, What I have done is that when my main container is mounting, I check for the language, if it's Arabic, I require the Arabic CSS file, if not I require the other.
Example:
class Main extends Component {
componentWillMount() {
if(this.props.language === 'ar') {
require('arabic.css');
} else {
require('english.css');
}
}
}
I'm using Redux as well, which makes it easier for me to get the initial or default language, and change all the other components accordingly as well.
Just make sure you have the CSS loader configured in your webpack configuration file.
A: Use React.Lazy and React.Suspense to conditionally import them.
Read this article
| stackoverflow | {
"language": "en",
"length": 198,
"provenance": "stackexchange_0000F.jsonl.gz:899572",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650466"
} |
1c15157901a65eb47e340bd94407babd7def2a2a | Stackoverflow Stackexchange
Q: How to sort data in a PrimeNG DataTable with Row Grouping What I want to do is to sort the data already grouped in alphabetical order or custom order. I used the sortField attribute which specify the groupheader order but I need to order the data inside the group too.
A: I have the same issues. I have added customized sort to solve this issues
To add a customized sort
<p-column field="color" header="color" sortable="custom" (sortFunction)="sortByColor($event)"></p-column>
In the typescript create a customSort
sortByColor(e) {
this.cars.sort(function (a, b) {
let aGroup = a.name.toLowerCase();
let bGroup = b.name.toLowerCase();
if (aGroup > bGroup) return 1;
if (aGroup < bGroup) return -1;
let aSort = a.color.toLowerCase();
let bSort = b.color.toLowerCase();
if (aSort > bSort) return 1;
if (aSort < bSort) return -1;
return 0
});
}
| Q: How to sort data in a PrimeNG DataTable with Row Grouping What I want to do is to sort the data already grouped in alphabetical order or custom order. I used the sortField attribute which specify the groupheader order but I need to order the data inside the group too.
A: I have the same issues. I have added customized sort to solve this issues
To add a customized sort
<p-column field="color" header="color" sortable="custom" (sortFunction)="sortByColor($event)"></p-column>
In the typescript create a customSort
sortByColor(e) {
this.cars.sort(function (a, b) {
let aGroup = a.name.toLowerCase();
let bGroup = b.name.toLowerCase();
if (aGroup > bGroup) return 1;
if (aGroup < bGroup) return -1;
let aSort = a.color.toLowerCase();
let bSort = b.color.toLowerCase();
if (aSort > bSort) return 1;
if (aSort < bSort) return -1;
return 0
});
}
A: For those who have the problem with TurboTable <p-table>, here is the solution:
<p-table sortField="name" sortMode="single" (onSort)="onSort($event)" (sortFunction)="customSort($event)" [customSort]="true">
OnSort() implementation:
onSort() {
// function to properly work with turbotable and rowgroup, see: https://www.primefaces.org/primeng/#/table/rowgroup
this.updateRowGroupMetaData();
}
customSort() implementation:
customSort(e) {
this.budgets.sort((a, b) => {
const aGroup = a.name.toLowerCase();
const bGroup = b.name.toLowerCase();
if (aGroup > bGroup) { return 1; }
if (aGroup < bGroup) { return -1; }
const aSort = a.color;
const bSort = b.color;
if (aSort > bSort) { return 1; }
if (aSort < bSort) { return -1; }
return 0;
});
}
A: I was facing the same issue.I have used custom sorting.Below is the code:
In Template:
<p-column field="color" header="color" sortable="custom" (sortFunction)="sortByColor($event,sortOrder)"></p-column>
Below is the sortByColor function in typescript:
sortOrder = 1;//1 means ascending order, 2 means descending order
sortByField(e, order) {
this.cars.Data.sort(function (a, b) {
let aGroup = a.name.toLowerCase();
let bGroup = b.name.toLowerCase();
if (aGroup > bGroup) return 1;
else if (aGroup < bGroup) return -1;
let aSort = a.color.toLowerCase();
let bSort = b.color.toLowerCase();
if (aGroup == bGroup) {
//ascending order
if (order == 1 && aSort < bSort) {
return -1;
}
//ascending order
else if (order == 1 && aSort > bSort) {
return 1;
}
//descending order
else if (order == 2 && aSort > bSort) {
return -1;
}
//descending order
else if (order == 2 && aSort < bSort) {
return 1;
}
}
return 1
});
this.sortOrder = this.sortOrder == 1 ? 2 : 1;
}
This is working for me.Hope this will work in your case also.
| stackoverflow | {
"language": "en",
"length": 393,
"provenance": "stackexchange_0000F.jsonl.gz:899574",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650472"
} |
57f3838568a73033c5823091bdd1e234dd346849 | Stackoverflow Stackexchange
Q: Is it safe to cast void (*p)(SomeType*) to void (*p)(void*) Suppose I have a function like below:
void fun(void* p){
SomeType* p = reinterpret_cast<SomeType*>(p);
...
}
The signature is require by the api. I just wonder can I just write it as.
void fun(SomeType* p){
...
}
And cast it to void (*)(void*).
A: While you can cast function pointers to other function pointers and back, calling a function through a pointer that doesn't match its signature is undefined behavior. You cannot just cast it and pass to an API.
In C and C++03, you'd have to create a named wrapper function that matches the signature and preforms the cast. In C++11 and beyond, you can just use a capture-less lambda instead (properly cast):
void fun(SomeType* p){
...
}
int main() {
api_call(+[](void *v) {
fun(static_cast<SomeType*>(v));
});
}
The + in front of the lambda causes it to be converted into a regular function pointer so long as it's not capturing. It's not strictly needed, but it makes the intent more explicit IMO, without too much verbosity.
| Q: Is it safe to cast void (*p)(SomeType*) to void (*p)(void*) Suppose I have a function like below:
void fun(void* p){
SomeType* p = reinterpret_cast<SomeType*>(p);
...
}
The signature is require by the api. I just wonder can I just write it as.
void fun(SomeType* p){
...
}
And cast it to void (*)(void*).
A: While you can cast function pointers to other function pointers and back, calling a function through a pointer that doesn't match its signature is undefined behavior. You cannot just cast it and pass to an API.
In C and C++03, you'd have to create a named wrapper function that matches the signature and preforms the cast. In C++11 and beyond, you can just use a capture-less lambda instead (properly cast):
void fun(SomeType* p){
...
}
int main() {
api_call(+[](void *v) {
fun(static_cast<SomeType*>(v));
});
}
The + in front of the lambda causes it to be converted into a regular function pointer so long as it's not capturing. It's not strictly needed, but it makes the intent more explicit IMO, without too much verbosity.
| stackoverflow | {
"language": "en",
"length": 178,
"provenance": "stackexchange_0000F.jsonl.gz:899610",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650608"
} |
33ad4f68272c9137dac6d9bdcd8f2117c133cd3d | Stackoverflow Stackexchange
Q: Where in AWS the instances made by docker-machine Using AWS free tire, I can create instance using GUI and I see it by clicking on Instance menu. I'm using AWS to learn about docker.
Yesterday I created my first instance remotely, using docker-machine, from the command line. I expected that I could find that as a regular instance in EC2 console, but I failed to find any related instance there.
Could anyone please tell me where in AWS panel it is located?
A: I just ran into the same problem, here's how I found it.
EC2 shows instances depending on what 'region' has been selected. Select different regions inside AWS console using the dropdown tab in the top right corner of your screen. By default, instances created by docker-machine end up in us-east-1 (N. Virginia).
| Q: Where in AWS the instances made by docker-machine Using AWS free tire, I can create instance using GUI and I see it by clicking on Instance menu. I'm using AWS to learn about docker.
Yesterday I created my first instance remotely, using docker-machine, from the command line. I expected that I could find that as a regular instance in EC2 console, but I failed to find any related instance there.
Could anyone please tell me where in AWS panel it is located?
A: I just ran into the same problem, here's how I found it.
EC2 shows instances depending on what 'region' has been selected. Select different regions inside AWS console using the dropdown tab in the top right corner of your screen. By default, instances created by docker-machine end up in us-east-1 (N. Virginia).
| stackoverflow | {
"language": "en",
"length": 136,
"provenance": "stackexchange_0000F.jsonl.gz:899630",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650662"
} |
be426572d41957605f26a5bb08b0bdf1edacaa24 | Stackoverflow Stackexchange
Q: Peer authentication failed for user "postgres" I have been using postgreSQL, trying to dump plain backup file using command:
psql -U postgres DATABASE < path to file.backup
But getting peer authentication failure. Even tried changing pg_hba.conf from peer to md5, but didn't work.
A: peer means you are not OS user postgres, while trying to connect as one,
*
*sudo su - postgres
*and then psql DBNAME >file.sql
https://www.postgresql.org/docs/current/static/auth-methods.html#AUTH-PEER
The peer authentication method works by obtaining the client's
operating system user name from the kernel and using it as the allowed
database user name (with optional user name mapping). This method is
only supported on local connections.
| Q: Peer authentication failed for user "postgres" I have been using postgreSQL, trying to dump plain backup file using command:
psql -U postgres DATABASE < path to file.backup
But getting peer authentication failure. Even tried changing pg_hba.conf from peer to md5, but didn't work.
A: peer means you are not OS user postgres, while trying to connect as one,
*
*sudo su - postgres
*and then psql DBNAME >file.sql
https://www.postgresql.org/docs/current/static/auth-methods.html#AUTH-PEER
The peer authentication method works by obtaining the client's
operating system user name from the kernel and using it as the allowed
database user name (with optional user name mapping). This method is
only supported on local connections.
| stackoverflow | {
"language": "en",
"length": 108,
"provenance": "stackexchange_0000F.jsonl.gz:899666",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650783"
} |
8266c2d7b41d71116452f85965e4207f076d0f7f | Stackoverflow Stackexchange
Q: Treenode not expanding after removing node I am trying to replace a tree node while expanding node (parent node). Replacing works fine. But the expansion not happening. Do you have any work around?
Code below:
<asp:TreeView ID="tvContentTree" runat="server" RootNodeStyle-CssClass="RootAllKeys"
ParentNodeStyle-CssClass="ParentAllKeys" ShowCheckBoxes="All" ImageSet="Simple" NodeIndent="10" OnTreeNodeExpanded="Populate_Node" >
<HoverNodeStyle Font-Underline="True" ForeColor="#DD5555" />
<NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="0px" NodeSpacing="0px" VerticalPadding="0px" />
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle Font-Underline="True" ForeColor="#DD5555" HorizontalPadding="0px" VerticalPadding="0px" />
</asp:TreeView>
public void Populate_Node(Object sender, TreeNodeEventArgs e)
{
foreach (System.Web.UI.WebControls.TreeNode tn in tvContentTree.Nodes)
{
tn.ChildNodes.RemoveAt(1);
tn.ChildNodes.AddAt(1,ParentNode);
}
}
if i comment the line
"tn.ChildNodes.RemoveAt(1);"
Then expansion works fine. So removeat function is causing the issue.
A: You should find the node by its name & then remove it.
TreeNode tn = tvContentTree.FindNode("tn1");
tn.ChildNodes.RemoveAt(1);
| Q: Treenode not expanding after removing node I am trying to replace a tree node while expanding node (parent node). Replacing works fine. But the expansion not happening. Do you have any work around?
Code below:
<asp:TreeView ID="tvContentTree" runat="server" RootNodeStyle-CssClass="RootAllKeys"
ParentNodeStyle-CssClass="ParentAllKeys" ShowCheckBoxes="All" ImageSet="Simple" NodeIndent="10" OnTreeNodeExpanded="Populate_Node" >
<HoverNodeStyle Font-Underline="True" ForeColor="#DD5555" />
<NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="0px" NodeSpacing="0px" VerticalPadding="0px" />
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle Font-Underline="True" ForeColor="#DD5555" HorizontalPadding="0px" VerticalPadding="0px" />
</asp:TreeView>
public void Populate_Node(Object sender, TreeNodeEventArgs e)
{
foreach (System.Web.UI.WebControls.TreeNode tn in tvContentTree.Nodes)
{
tn.ChildNodes.RemoveAt(1);
tn.ChildNodes.AddAt(1,ParentNode);
}
}
if i comment the line
"tn.ChildNodes.RemoveAt(1);"
Then expansion works fine. So removeat function is causing the issue.
A: You should find the node by its name & then remove it.
TreeNode tn = tvContentTree.FindNode("tn1");
tn.ChildNodes.RemoveAt(1);
| stackoverflow | {
"language": "en",
"length": 120,
"provenance": "stackexchange_0000F.jsonl.gz:899672",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650795"
} |
25d60d3e830309c53cd11d076d15e3f0e57412be | Stackoverflow Stackexchange
Q: Mocking static method I want to mock static method which is called within other static method.
public class MyClass
{
public static void methodA(String s)
{
...
methodB(s);
...
}
public static void methodB(String s)
{
...
}
}
So, I want to mock methodA, but I want to skip calling methodB.
I tried almost all solutions that I was able to find, without any success. Every time methodB is called.
Some solutions that I used:
PowerMockito.suppress(method(MyClass.class, "methodB"));
MyClass.methodA("s");
_
PowerMockito.stub(method(MyClass.class, "methodB"));
MyClass.methodA("s");
_
PowerMockito.mockStatic(MyClass.class);
doNothing().when(MyClass.class, "methodB", anyString());
MyClass.methodA("s");
And many others...
Anyone have an idea how to solve this problem?
A: In my opinion you should Spy your class instead of mocking it.
In that situation all the static methods will be called with real implementation and on top of that you could instruct to not call methodB:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
class MyClassTest
{
@Test
public void test()
{
PowerMockito.spy(MyClass.class);
doNothing().when(MyClass.class, "methodB", anyString());
MyClass.methodA("s");
}
}
I have written an article on Mocking Static Methods if you need a further read.
| Q: Mocking static method I want to mock static method which is called within other static method.
public class MyClass
{
public static void methodA(String s)
{
...
methodB(s);
...
}
public static void methodB(String s)
{
...
}
}
So, I want to mock methodA, but I want to skip calling methodB.
I tried almost all solutions that I was able to find, without any success. Every time methodB is called.
Some solutions that I used:
PowerMockito.suppress(method(MyClass.class, "methodB"));
MyClass.methodA("s");
_
PowerMockito.stub(method(MyClass.class, "methodB"));
MyClass.methodA("s");
_
PowerMockito.mockStatic(MyClass.class);
doNothing().when(MyClass.class, "methodB", anyString());
MyClass.methodA("s");
And many others...
Anyone have an idea how to solve this problem?
A: In my opinion you should Spy your class instead of mocking it.
In that situation all the static methods will be called with real implementation and on top of that you could instruct to not call methodB:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
class MyClassTest
{
@Test
public void test()
{
PowerMockito.spy(MyClass.class);
doNothing().when(MyClass.class, "methodB", anyString());
MyClass.methodA("s");
}
}
I have written an article on Mocking Static Methods if you need a further read.
| stackoverflow | {
"language": "en",
"length": 172,
"provenance": "stackexchange_0000F.jsonl.gz:899681",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650835"
} |
8180cdf93bd62d8ce2bf02cde9786dbb1b7ac10d | Stackoverflow Stackexchange
Q: Signing executables with EV-Certificate with Install4J our company ordered an EV-Certificate from GlobalSign.
Before we had a normal code signing certificate as a p12 file which we could use in Install4J.
Now, with the new certificate we have no cert-files but a usb-token.
Is there a built-in way to use the usb-token to sign executables/jars? Or do I need to use the "Executable processing" step of media wizard like mentioned here?
Maybe a way to sign all installers (win, mac, linux) from one machine (like macos)?
A: Based on Ingo's answer, it's not possible to use an EV Code Sign certificate. I hope, in future, it will.
As I said in my question, you have to use "Executable processing" in media wizard (for windows only).
You can use microsoft's codesign on windows itself or you can you a little tool called jsign which you can use on all platforms to sign windows executables with EV Code Sign certificate.
This is our call to jsign:
java -jar jsign-2.0.jar --keystore ./eToken.cfg --alias %GetAliasOfYourToken% --storetype PKCS11 --tsaurl http://timestamp.comodoca.com/authenticode --storepass %WriteTokenPasswordHere% $EXECUTABLE
eToken.cfg is a simple text-file with two lines:
name=eToken
library=/usr/local/lib/libeTPkcs11.dylib (because I'm on MacOS)
for Windows it should be:
library=c:\WINDOWS\system32\eTPKCS11.dll
| Q: Signing executables with EV-Certificate with Install4J our company ordered an EV-Certificate from GlobalSign.
Before we had a normal code signing certificate as a p12 file which we could use in Install4J.
Now, with the new certificate we have no cert-files but a usb-token.
Is there a built-in way to use the usb-token to sign executables/jars? Or do I need to use the "Executable processing" step of media wizard like mentioned here?
Maybe a way to sign all installers (win, mac, linux) from one machine (like macos)?
A: Based on Ingo's answer, it's not possible to use an EV Code Sign certificate. I hope, in future, it will.
As I said in my question, you have to use "Executable processing" in media wizard (for windows only).
You can use microsoft's codesign on windows itself or you can you a little tool called jsign which you can use on all platforms to sign windows executables with EV Code Sign certificate.
This is our call to jsign:
java -jar jsign-2.0.jar --keystore ./eToken.cfg --alias %GetAliasOfYourToken% --storetype PKCS11 --tsaurl http://timestamp.comodoca.com/authenticode --storepass %WriteTokenPasswordHere% $EXECUTABLE
eToken.cfg is a simple text-file with two lines:
name=eToken
library=/usr/local/lib/libeTPkcs11.dylib (because I'm on MacOS)
for Windows it should be:
library=c:\WINDOWS\system32\eTPKCS11.dll
A:
Or do I need to use the "Executable processing" step of media wizard like
mentioned here?
Yes, that's the only way.
Maybe a way to sign all installers (win, mac, linux) from one machine (like macos)?
Unfortunately, that's not possible.
Update 2019-10-22
Since install4j 8.0, hardware security modules (PKCS#11) are supported for Windows code signing and can be configured on the General Settings->Code Signing step.
| stackoverflow | {
"language": "en",
"length": 265,
"provenance": "stackexchange_0000F.jsonl.gz:899686",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650852"
} |
2810a1044d3c1185419a4795a80775b4d089e787 | Stackoverflow Stackexchange
Q: Can I get the scores calculated by whoosh for each document while searching? I am trying to implement Okapi BM25 to search documents by query using python whoosh library.
My understanding is that whoosh calculates the scores for each documents using BM25 according to the query and then sorts it to give the best result.
I use
results = searcher.search(query)
to get the document best matched to the query.
How can I get the scores for each document?
Is there any other way to get scores for BM25 ranking?
A: You can get the computed score by using the score attribute:
for r in results:
print r, r.score
| Q: Can I get the scores calculated by whoosh for each document while searching? I am trying to implement Okapi BM25 to search documents by query using python whoosh library.
My understanding is that whoosh calculates the scores for each documents using BM25 according to the query and then sorts it to give the best result.
I use
results = searcher.search(query)
to get the document best matched to the query.
How can I get the scores for each document?
Is there any other way to get scores for BM25 ranking?
A: You can get the computed score by using the score attribute:
for r in results:
print r, r.score
A: You can get the different scoring alog or retrieval.
For an example Tf-IDF, Frequency, BM25.
If you want score then here is the method.
results = searcher.search(query)
for hit in results:
print("the Score", hit.score)
print("the rank", hit.rank)
print("the document number", hit.docnum)
| stackoverflow | {
"language": "en",
"length": 151,
"provenance": "stackexchange_0000F.jsonl.gz:899688",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650856"
} |
e6ce0c1406d81ae213f19a15195cc33f5b180927 | Stackoverflow Stackexchange
Q: Best method for inspecting Elastic Beanstalk JVM heap I'm need to get a JVM heap dump from an Elastic Beanstalk server, but the server doesn't have jcmd or jmap. Amazon doesn't natively install them with the JDK. Here's what's installed:
[ec2-user@ip-x-x-x-x ~]$ sudo yum list installed|grep jdk
java-1.7.0-openjdk.x86_64 1:1.7.0.111-2.6.7.2.68.amzn1 @amzn-updates
java-1.8.0-openjdk.x86_64 1:1.8.0.101-3.b13.24.amzn1 @amzn-updates
java-1.8.0-openjdk-headless.x86_64 1:1.8.0.101-3.b13.24.amzn1 @amzn-updates
What's the best way to get a heap dump from the JVM on Elastic Beanstalk?
A: I have found you can install jmap by installing the correct package:
sudo yum install java-1.8.0-openjdk-devel
This should at least allow a heap dump to be generated.
In addition, to make sure all functions in jmap run, also install:
sudo yum --enablerepo='*-debug*' install java-1.8.0-openjdk-debuginfo
Although this might depend on the baseline, tomcat version etc you use.
When creating a heap dump, use the tomcat user:
sudo -u tomcat jmap -dump:live,file=/tmp/test.hprof <pid>
| Q: Best method for inspecting Elastic Beanstalk JVM heap I'm need to get a JVM heap dump from an Elastic Beanstalk server, but the server doesn't have jcmd or jmap. Amazon doesn't natively install them with the JDK. Here's what's installed:
[ec2-user@ip-x-x-x-x ~]$ sudo yum list installed|grep jdk
java-1.7.0-openjdk.x86_64 1:1.7.0.111-2.6.7.2.68.amzn1 @amzn-updates
java-1.8.0-openjdk.x86_64 1:1.8.0.101-3.b13.24.amzn1 @amzn-updates
java-1.8.0-openjdk-headless.x86_64 1:1.8.0.101-3.b13.24.amzn1 @amzn-updates
What's the best way to get a heap dump from the JVM on Elastic Beanstalk?
A: I have found you can install jmap by installing the correct package:
sudo yum install java-1.8.0-openjdk-devel
This should at least allow a heap dump to be generated.
In addition, to make sure all functions in jmap run, also install:
sudo yum --enablerepo='*-debug*' install java-1.8.0-openjdk-debuginfo
Although this might depend on the baseline, tomcat version etc you use.
When creating a heap dump, use the tomcat user:
sudo -u tomcat jmap -dump:live,file=/tmp/test.hprof <pid>
A: Disclamer: I've never worked with Elastic Beanstalk, but I can recommend to check the following:
Consider taking the heap dump programmatically, I mean from within the Java application itself. There are many ways of doing that:
*
*Via JMX - the chances are that you'll find HotSpotDiagnostic bean and will be able to invoke the heap dump operation (Here there is a tutorial for doing this)
*If your application is new and you have Spring Boot, then probably its possible to plug Spring Actuator that has a "/heapdump" endpoint just for this purpose
| stackoverflow | {
"language": "en",
"length": 238,
"provenance": "stackexchange_0000F.jsonl.gz:899711",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650942"
} |
bd1a609c1330b23f0fc0a8ee9becd13a83c197b3 | Stackoverflow Stackexchange
Q: Set read-only for only 1 table in postgresql I want to set read only for only 1 table in a database.
I tried the command
ALTER TABLE table SET READ ONLY;
but it doesn't work.
Is there anyway to do that?
A: I saw an answer, i hope its helpfully
REVOKE INSERT, UPDATE, DELETE, TRUNCATE
ON ALL TABLES IN SCHEMA public
FROM public, <target_role>;
Possibly add more roles to the list, but do not forget the role
public. Possibly add more schemas to the list, but do not forget the
schema public.
| Q: Set read-only for only 1 table in postgresql I want to set read only for only 1 table in a database.
I tried the command
ALTER TABLE table SET READ ONLY;
but it doesn't work.
Is there anyway to do that?
A: I saw an answer, i hope its helpfully
REVOKE INSERT, UPDATE, DELETE, TRUNCATE
ON ALL TABLES IN SCHEMA public
FROM public, <target_role>;
Possibly add more roles to the list, but do not forget the role
public. Possibly add more schemas to the list, but do not forget the
schema public.
| stackoverflow | {
"language": "en",
"length": 93,
"provenance": "stackexchange_0000F.jsonl.gz:899719",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650968"
} |
fbc925024b5246cc1e0bd3e3e9a5c7bff0b03da7 | Stackoverflow Stackexchange
Q: How to get local time zone date in swift 3 I am getting year,month and day from a given date in this way.
let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day=components.day
But I'm getting one day ahead from my current day. How can I solve this?
A: let date = Date().description(with: Locale.current)
print("date ---> \(date)")
Result: date ---> Tuesday, June 20, 2017 at 4:35:15 PM India Standard Time
I'm getting perfect system/local time.
You code is working,
let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: today)
let day = components.day
let hour = components.hour
let minute = components.minute
print("day = \(day)\nhour = \(hour)\nminute = \(minute)")
Result: day = Optional(20) hour = Optional(16) minute = Optional(35)
| Q: How to get local time zone date in swift 3 I am getting year,month and day from a given date in this way.
let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day=components.day
But I'm getting one day ahead from my current day. How can I solve this?
A: let date = Date().description(with: Locale.current)
print("date ---> \(date)")
Result: date ---> Tuesday, June 20, 2017 at 4:35:15 PM India Standard Time
I'm getting perfect system/local time.
You code is working,
let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: today)
let day = components.day
let hour = components.hour
let minute = components.minute
print("day = \(day)\nhour = \(hour)\nminute = \(minute)")
Result: day = Optional(20) hour = Optional(16) minute = Optional(35)
A: Get Local Date and Time
Swift 5:
let today = Date()
let timeZone = Double(TimeZone.current.secondsFromGMT(for: today))
let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZone), to: today) ?? Date()
A: As per the documentation:
If you want “date information in a given time zone” in order to
display it, you should use DateFormatter to format the date.
eg:
// If date is "Dec 7, 2018 at 6:34 AM" UTC
let today=Date() // is always UTC
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day = components.day // Is 7
// To print with local version
let myFormatter = DateFormatter()
myFormatter.timeZone = TimeZone(secondsFromGMT: 3600*10)
myFormatter.dateFormat = "dd"
print(myFormatter.string(from: today)) // prints "07\n"
myFormatter.timeZone = TimeZone(secondsFromGMT: -3600*11)
print(myFormatter.string(from: today)) // prints "06\n"
| stackoverflow | {
"language": "en",
"length": 264,
"provenance": "stackexchange_0000F.jsonl.gz:899732",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44650999"
} |
59799b904c798d69d0a2154a3878f9e772c38f28 | Stackoverflow Stackexchange
Q: Xcode 9: Could not attach to pid I've been facing an issue (frequently) with the recent major release of the iOS application development tool - Xcode 9-beta.
It's showing me the following error frequently while running/debugging app in Simulator (iOS 11).
Could not attach to pid : “2370”
Ensure <project title> is not already running, and <system username> has permission to debug it.
Here is a snapshot for the same issue:
What would be permanent solution of this issue, as it's disturbing frequently?
A: I had this issue too. There seems to be an issue with having two Xcode version installed at the same time. (9.4.1 and 10.0 Beta)
It works with the beta, but not with the stable version. Everything is set to the tools of the Xcode 9.4.1 stable version. I can only run my unit tests with the beta.
After removing the beta, it worked with the stable version.
| Q: Xcode 9: Could not attach to pid I've been facing an issue (frequently) with the recent major release of the iOS application development tool - Xcode 9-beta.
It's showing me the following error frequently while running/debugging app in Simulator (iOS 11).
Could not attach to pid : “2370”
Ensure <project title> is not already running, and <system username> has permission to debug it.
Here is a snapshot for the same issue:
What would be permanent solution of this issue, as it's disturbing frequently?
A: I had this issue too. There seems to be an issue with having two Xcode version installed at the same time. (9.4.1 and 10.0 Beta)
It works with the beta, but not with the stable version. Everything is set to the tools of the Xcode 9.4.1 stable version. I can only run my unit tests with the beta.
After removing the beta, it worked with the stable version.
A: delete derived data and clean the project, wait until processing is complete, this may take some time. The idea is to give some processing time. Works fine after that
A: I have been dealing with this issue for days. I have been able to build but not launch on Simulator, and I get the same "pid:.." error message.
I am using:
- Xcode v9.2
- Swift 3.2
- Building for iOS
The things that I tried that DID NOT WORK were:
restarting the computer; deleting content and settings (of Simulator, I do not have "reset"); uninstalling and reinstalling Xcode; changing "Deployment Target"; changing the device in the simulator's Hardware->Manage Device; deleting Derived Data, Cleaning and Building, or just waiting...forever.
What WORKED was as @Rajasekhar mentioned:
*
*checked out the Keychain certificates.
*deleted the exiting ones by right clicking (they'd passed expiration)
*and unchecked "automatically manage signing" in Targets->General
After that it successfully launched in Simulator. I don't know if the issue will come back but hopefully this works.
A: Even on Xcode 11.1/2/3
It is an Authorization issue with Simulator,
When Simulator does not have the necessary access. It raises the issue.
Try following in Terminal
sudo DevToolsSecurity -enable
or
sudo /usr/sbin/DevToolsSecurity -enable
Details can be found here
A: I hate to add more noise to this, but for me, the answer is to, nonsensically, use sudo.
Run normally, Xcode 9.4.1 (9F2000) and Xcode 10.0 beta 4 (10L213o) both failed to attach to my app after multiple tries, giving the error quoted in the original post.
What worked was to run Xcode (9.4) with sudo,
sudo /Applications/Xcode.app/Contents/MacOS/Xcode
I don't see why sudo is necessary. The Cocoa app to which I am attaching is a Debug build that I just built in Xcode 9.4.1 and dragged into /Applications. It is not codesigned. Posix permissions on the .app, its Contents, its MacOS, and the executable are all octal 755. Owner is me. It works fine if I leave it in the Build folder, build and debug in the normal way.
The problem is apparently with lldb. I also tried using lldb (lldb-902.0.79.7) from the command line. I got the same result. It works only with sudo. Without sudo,
error: attach failed: unable to attach
A: I had same issue. Check screenshot.
Below are few solutions that should work:
*
*Rerun project
*Clean (Shortcut: cmd + shift + K) and Rerun project
*Quit Xcode and Simulator. Open project and run again
*Reset content of Simulator (Select Simulator -> Goto Hardware tab -> Erase All Content and Settings…) and rerun project.
Solution 4 worked for me.
A: If issue is on OS Mojave and you are trying, like me to run tests on older Xcode version (lower than 10.0), make sure that in your scheme, when you select Test, Debug executable is disabled
You won't be able to debug tests from this point
A: This seems to be a temporary issue when you are trying to build too fast after a build has started. Try stopping and running the project again.
A: (most likely solution) 1. Simulator-> Hardware-> Erase all contents and Settings
(less likely solution) 2. keychain-> upper right lock-> unlock and lock again (or the other way around)
A: In my case (Xcode 10.1), this was the error in the console:
kernel macOSTaskPolicy: (com.apple.debugserver) may not get the taskport of (bin) (pid: 10132): (bin) is hardened, (bin) doesn't have get-task-allow, (com.apple.debugserver) is a declared debugger
So the solution was to disable the Hardened Runtime, clean the build folder and run again.
A: I was seeing this in Xcode 10.2 and the cause for me was that lldb-rpc-server was crashing. I worked around it by ensuring either Address Sanitizer or Thread Sanitizer is enabled in the debug options. I also filed a bug report viewable on Open Radar.
A: I tried all the answers above. The only thing worked to me is changing the build number.
A: This is the issue with the untrusted certificates in key-chain access, please remove such a type of certificates and re-build again.
A: Still not a permanent solution, but I had to quit and restart Xcode as the other solutions did not work for me.
A: This happens on my machine, when I set the 'new build system'
Go to menu file=>workspace settings and set Build System to "Standard".
A: I realise this is not a problem with a single solution, from all the other answers. So, here's what worked for me:
1) Reboot the machine
2) The first run always works for me. The only thing that helps me avoid this error after this first run, is to stop the application from XCode, instead of just clicking the Run button to re-run the application.
Another thing, when I lock my computer the issue re-appears sometimes (probably when I forget to stop the application). So I have to reboot my machine again.
A: This worked for me:
Edit Scheme -> Info -> Executable -> Ask on launch
Credits to @nastya-gorban's answer here
Update
After spending a considerable time with examples on Apple bug report, they basically disregarded the issue as using manual certificates is not "expected".
Long story short, if you don't have a business account and hence multiple developers on the same account, you should be fine with using the automatic signing and should not see the issue.
If you do have a business account with multiple users (which I found it breaks automatic signing), this is their suggestion:
We suggest that you use automatic signing for your debug builds and
manual signing for your distribution builds.
A: Killing my simulator and then running it again from Xcode.
A: After doing some digging, this worked for me on Xcode 10.3.
sudo /usr/sbin/DevToolsSecurity -enable
A: In my case the only thing that worked was switching back from the "New Build System" to the "Legacy Build System" in the Workspace Settings. Bummer.
A: It's an issue with authorization. Try this in the Terminal:
sudo DevToolsSecurity -enable
A: First, close app completely via sim (not sleep - close app totally)
If not working yet: reboot whole PC, ensure only 1 simulator is active upon reboot.
More than 1 sim can confuse it if it's bugging.
| stackoverflow | {
"language": "en",
"length": 1190,
"provenance": "stackexchange_0000F.jsonl.gz:899743",
"question_score": "66",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44651029"
} |
68da04e89c18db0a9b19b34d3d1469ee9d181228 | Stackoverflow Stackexchange
Q: Error with Eigen vector logarithm invalid use of incomplete type I am trying to compute the element-wise natural logarithm of a vector using the Eigen library, here's my code:
#include <Eigen/Core>
#include <Eigen/Dense>
void function(VectorXd p, VectorXd q) {
VectorXd kld = p.cwiseQuotient(q);
kld = kld.log();
std::cout << kld << std::endl;
}
However when compiling with
g++ -I eigen_lib -std=c++11 -march=native test_eigen.cpp -o test_eigen
I get
test_eigen.cpp:15:23: error: invalid use of incomplete type ‘const class Eigen::MatrixLogarithmReturnValue<Eigen::Matrix<double, -1, 1> >’ kld = kld.log();
What is it that I'm missing?
A: VectorXd::log() is MatrixBase<...>::log() which computes the matrix logarithm of a square matrix. If you want the element-wise logarithm you need to use the array functionality:
kld = kld.array().log();
// or:
kld = log(kld.array());
If all your operations are element-wise, consider using ArrayXd instead of VectorXd:
void function(const Eigen::ArrayXd& p, const Eigen::ArrayXd& q) {
Eigen::ArrayXd kld = log(p/q);
std::cout << kld << std::endl;
}
| Q: Error with Eigen vector logarithm invalid use of incomplete type I am trying to compute the element-wise natural logarithm of a vector using the Eigen library, here's my code:
#include <Eigen/Core>
#include <Eigen/Dense>
void function(VectorXd p, VectorXd q) {
VectorXd kld = p.cwiseQuotient(q);
kld = kld.log();
std::cout << kld << std::endl;
}
However when compiling with
g++ -I eigen_lib -std=c++11 -march=native test_eigen.cpp -o test_eigen
I get
test_eigen.cpp:15:23: error: invalid use of incomplete type ‘const class Eigen::MatrixLogarithmReturnValue<Eigen::Matrix<double, -1, 1> >’ kld = kld.log();
What is it that I'm missing?
A: VectorXd::log() is MatrixBase<...>::log() which computes the matrix logarithm of a square matrix. If you want the element-wise logarithm you need to use the array functionality:
kld = kld.array().log();
// or:
kld = log(kld.array());
If all your operations are element-wise, consider using ArrayXd instead of VectorXd:
void function(const Eigen::ArrayXd& p, const Eigen::ArrayXd& q) {
Eigen::ArrayXd kld = log(p/q);
std::cout << kld << std::endl;
}
A: To do element-wise operations on Eigen objects (Matrix or Vector), you need to specify that. This is done by by adding .array() to the Matrix/Vector object like so:
kld = kld.array().log();
See this tutorial.
P.S. MatrixLogarithmReturnValue is part of the unsupported modules for matrix functions.
| stackoverflow | {
"language": "en",
"length": 199,
"provenance": "stackexchange_0000F.jsonl.gz:899759",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44651097"
} |
a9a03b41f6bb0786fbda813f03068ed79ef33b12 | Stackoverflow Stackexchange
Q: can we use for loop without condition? My question is simple,thus I will not go in deep
can we use for() loop without condition like this
for(;;space+=1)
{
printf(" ");
break;
}
A: Yes it is perfectly correct to do so.
But since you have provided a break immediately after printf, it will only execute once. I'm not sure whether this is what you wanted. But if so, then this works fine.
| Q: can we use for loop without condition? My question is simple,thus I will not go in deep
can we use for() loop without condition like this
for(;;space+=1)
{
printf(" ");
break;
}
A: Yes it is perfectly correct to do so.
But since you have provided a break immediately after printf, it will only execute once. I'm not sure whether this is what you wanted. But if so, then this works fine.
A: Of course you can. An empty condition is taken to evaluate to 1.
for (;;){/*ToDo - your code here*/} is idiomatic C.
| stackoverflow | {
"language": "en",
"length": 96,
"provenance": "stackexchange_0000F.jsonl.gz:899768",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44651123"
} |
1cc9d0ce3deee00401663bc1288534bb74c92bf3 | Stackoverflow Stackexchange
Q: How to rename an agent pool in TFS How to rename an existing agent pool in Team Foundation Server 2017?
I've created an agent pool in TFS 2017. Now I want to rename it for a better understanding.
A: We cannot rename the existing agent pool in TFS, you can delete the existing agent pool, then create a new pool with the name for a better understanding, then reconfigure the agents with the new pool.
On the Settings->Agent Pools, for each Pool Name on its right there is a small black triangle pointing down, left click on it, a context menu will appear, last menu item is 'Delete', click on that the Agent Pool will be gone after a confirmation dialog.
Deploy an agent on Windows
| Q: How to rename an agent pool in TFS How to rename an existing agent pool in Team Foundation Server 2017?
I've created an agent pool in TFS 2017. Now I want to rename it for a better understanding.
A: We cannot rename the existing agent pool in TFS, you can delete the existing agent pool, then create a new pool with the name for a better understanding, then reconfigure the agents with the new pool.
On the Settings->Agent Pools, for each Pool Name on its right there is a small black triangle pointing down, left click on it, a context menu will appear, last menu item is 'Delete', click on that the Agent Pool will be gone after a confirmation dialog.
Deploy an agent on Windows
A: It is possible to change the name of the pool if you resort to using the rest API, at least for later Azure releases.
Microsoft description found here
https://learn.microsoft.com/en-us/rest/api/azure/devops/distributedtask/pools/update?view=azure-devops-server-rest-6.0
| stackoverflow | {
"language": "en",
"length": 157,
"provenance": "stackexchange_0000F.jsonl.gz:899772",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44651143"
} |
a31fe09579a7ea509555f9f70bf4280e6d2b3b93 | Stackoverflow Stackexchange
Q: comparing current time in unit test I'm currently writing a unit test that compares to strings. The first string is generated using a function. The other one is hard coded and serves as reference. My problem is, that the function creating the first string injects the current time (time.Now()) with precision in seconds into the string. At the moment I do the same for the reference but this seems very ugly to me. My machine runs fast enough so that the test passes but I don't want to rely on that.
What are general techniques to do such tests?
A: You can stub functions like time.Now() in your _test.go files, via the init() function, this will give deterministic time values:
package main
import (
"fmt"
"time"
)
var timeNow = time.Now
func main() {
fmt.Println(timeNow())
}
func init() {
// Uncomment and add to _test.go init()
// timeNow = func() time.Time {
// t, _ := time.Parse("2006-01-02 15:04:05", "2017-01-20 01:02:03")
// return t
// }
}
See: https://play.golang.org/p/hI6MrQGyDA
| Q: comparing current time in unit test I'm currently writing a unit test that compares to strings. The first string is generated using a function. The other one is hard coded and serves as reference. My problem is, that the function creating the first string injects the current time (time.Now()) with precision in seconds into the string. At the moment I do the same for the reference but this seems very ugly to me. My machine runs fast enough so that the test passes but I don't want to rely on that.
What are general techniques to do such tests?
A: You can stub functions like time.Now() in your _test.go files, via the init() function, this will give deterministic time values:
package main
import (
"fmt"
"time"
)
var timeNow = time.Now
func main() {
fmt.Println(timeNow())
}
func init() {
// Uncomment and add to _test.go init()
// timeNow = func() time.Time {
// t, _ := time.Parse("2006-01-02 15:04:05", "2017-01-20 01:02:03")
// return t
// }
}
See: https://play.golang.org/p/hI6MrQGyDA
A: we can stub time.Now() by using go package "github.com/tkuchiki/faketime".
package main
import (
"fmt"
"github.com/tkuchiki/faketime"
"time"
)
func main() {
fmt.Println("Current Time Before Faking : ", time.Now().UTC())
f := faketime.NewFaketime(2021, time.March, 01, 01, 01, 01, 0, time.UTC)
defer f.Undo()
f.Do()
fmt.Println("Current Time After Faking : ", time.Now())
}
Output from the above code is :
Current Time Before Faking : 2009-11-10 23:00:00 +0000 UTC
Current Time After Faking : 2021-03-01 01:01:01 +0000 UTC
checkout the sample code : go-playground sample
| stackoverflow | {
"language": "en",
"length": 250,
"provenance": "stackexchange_0000F.jsonl.gz:899808",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44651266"
} |
3541e2fd68bf520f11bfae14a4e8b29a06c66758 | Stackoverflow Stackexchange
Q: CSP issues with checksession using oidc-client.js I'm building a SPA using oidc-client to sign in to an IDP built using Identity Server 4.
The login redirections seems to work fine but on Firefox I'm getting the following CSP issues
Content Security Policy: Ignoring "'unsafe-inline'" within script-src or style-src: nonce-source or hash-source specified (unknown)
Content Security Policy: The page's settings blocked the loading of a resource at self ("script-src 'unsafe-inline' 'sha256-VDXN0nOpFPQ102CIVz+eimHA5e+wTeoUUQj5ZYbtn8w='"). Source: !function(t){function __webpack_require_.... checksession:1
Content Security Policy: The page's settings blocked the loading of a resource at self ("script-src 'unsafe-inline' 'sha256-VDXN0nOpFPQ102CIVz+eimHA5e+wTeoUUQj5ZYbtn8w='"). Source: window.devToolsOptions = Object.assign(w.... checksession:1
Load denied by X-Frame-Options: http://localhost:5007/home/error?errorId=a74accc61bb821ee1f42f7013a306e90 does not permit cross-origin framing. (unknown)
I'm not setting any CSP meta tags on my SPA and I'm wondering if I have to.
Digging a little bit it seems that oidc-client is adding an iframe into my application which points to the checksession page in Identity Server (which does include the CSP header "default-src 'none'; script-src 'unsafe-inline' 'sha256-VDXN0nOpFPQ102CIVz+eimHA5e+wTeoUUQj5ZYbtn8w='")
Can someone help me solving this or lead me into the right direction? My knowledge about CSP is very basic.
A: It was the Redux devtools addon trying to inject their code on the page.
| Q: CSP issues with checksession using oidc-client.js I'm building a SPA using oidc-client to sign in to an IDP built using Identity Server 4.
The login redirections seems to work fine but on Firefox I'm getting the following CSP issues
Content Security Policy: Ignoring "'unsafe-inline'" within script-src or style-src: nonce-source or hash-source specified (unknown)
Content Security Policy: The page's settings blocked the loading of a resource at self ("script-src 'unsafe-inline' 'sha256-VDXN0nOpFPQ102CIVz+eimHA5e+wTeoUUQj5ZYbtn8w='"). Source: !function(t){function __webpack_require_.... checksession:1
Content Security Policy: The page's settings blocked the loading of a resource at self ("script-src 'unsafe-inline' 'sha256-VDXN0nOpFPQ102CIVz+eimHA5e+wTeoUUQj5ZYbtn8w='"). Source: window.devToolsOptions = Object.assign(w.... checksession:1
Load denied by X-Frame-Options: http://localhost:5007/home/error?errorId=a74accc61bb821ee1f42f7013a306e90 does not permit cross-origin framing. (unknown)
I'm not setting any CSP meta tags on my SPA and I'm wondering if I have to.
Digging a little bit it seems that oidc-client is adding an iframe into my application which points to the checksession page in Identity Server (which does include the CSP header "default-src 'none'; script-src 'unsafe-inline' 'sha256-VDXN0nOpFPQ102CIVz+eimHA5e+wTeoUUQj5ZYbtn8w='")
Can someone help me solving this or lead me into the right direction? My knowledge about CSP is very basic.
A: It was the Redux devtools addon trying to inject their code on the page.
| stackoverflow | {
"language": "en",
"length": 195,
"provenance": "stackexchange_0000F.jsonl.gz:899822",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44651318"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.