text:
Q: How to plot Chow-test results in R? I have run a Chow-test in R using the following code:
mydata <- read.csv(file="chow.csv", header=TRUE, sep=",")
sctest(fuel~pred, data=mydata, type="Chow", point=44)

I am able to successfully obtain the F Statistic and p-value, but I would like to see the graph, i.e. the splitting regression where you have a curve divided into two (at point 44), like the image attached.
Could anybody tell me if R can plot this graph with the information given? Thank you.
enter image description here

A: I don't think that you can plot this with the results from sctest but it should be easy to plot it from your data. Simply create each of the relevant linear regressions and then plot the line segments.
Since you do not provide any data, I will illustrate with the NHANES data from the NHANES package.
library(NHANES)
data(NHANES)
plot(Height ~ Age, data=NHANES, pch=20, col="#00000022")

There seems to be a structural change in Height as a function of Age at Age=16.
You want to compare the linear model on the full data with the two linear models, Age<=16 and Age > 16. So just generate them and plot them.
## Full data
LM0 = lm(Height ~ Age, data=NHANES)
abline(LM0, col="red", type=2, lwd=3)

## Age <= 16
LM1 = lm(Height ~ Age, data=NHANES[NHANES$Age <= 16,])
y1 = predict(LM1, newdata=data.frame(Age=c(0,16)))

## Age > 16
LM2 = lm(Height ~ Age, data=NHANES[NHANES$Age > 16,])
y2 = predict(LM2, newdata=data.frame(Age=c(16,80)))

lines(x=c(0,16), y=y1, col="green", lty=3, lwd=3)
lines(x=c(16,80), y=y2, col="green", lty=3, lwd=3)

Edit
Based on data provided in the comments, here is another example. At least with the few points given,  dividing this data into two models does not seem obvious, but I picked a division point that emphasized different models.
mydata =  structure(list(fuel = c(346591L, 344841L, 369015L, 346062L,
    337494L, 355830L, 380516L, 391917L, 356761L, 359326L, 348208L,
    358639L, 351659L, 323356L, 364712L), pred = c(346293.4, 344855.5,
    355014.2, 342456.1, 347042.1, 371000.1, 376011.6, 391521.4,
    364751.5, 358650, 356547.3, 355159.8, 359598.2, 349122.6, 357969.6)),
    .Names = c("fuel", "pred"), row.names = c(NA, 15L), class = "data.frame")

plot(pred ~ fuel, data=mydata)
LM0 = lm(pred ~ fuel, data=mydata)
abline(LM0, lty=2)

LM1 = lm(pred ~ fuel, data=mydata[mydata$fuel <= 347500,])
y1  = predict(LM1, newdata=data.frame(fuel=c(320000,347500)))
lines(c(320000,350000), y1, lty=3)

LM2 = lm(pred ~ fuel, data=mydata[mydata$fuel >  347500,])
y2  = predict(LM2, newdata=data.frame(fuel=c(347500,395000)))
lines(c(350000,395000), y2, lty=3)


text:
Q: Python: ValueError (CSV row has different number of fields) with CSV and Tensorflow this is my first question.
I´m working on a program, that predicts a number of people in a room. I got a CSV-file with data for this. The CSV has 6 columns and 96 rows (including header).
But when I run the program, this error occurs:
ValueError: Problem inferring types: CSV row has different number of fields than expected.
The Code:
from __future__ import absolute_import, division, print_function, unicode_literals
import functools

import tensorflow as tf

import xlrd

import pandas as pd
import csv
import numpy as np

train_data_url = "https://www.dropbox.com/s/mug8rjlniftu065/train_data_csv.csv?dl=0"

test_data_url = "https://www.dropbox.com/s/std8rt6lezl79ti/test_data_csv.csv?dl=0"

train_file_path = tf.keras.utils.get_file("training_data_csv.csv", train_data_url)
test_file_path = tf.keras.utils.get_file("test_data_csv.csv", test_data_url)

np.set_printoptions(precision = 3, suppress=True)

#!head {train_file_path}

Label_Column = 'Besucher'
Labels = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 200, 300, 400, 500, 600, 700, 800, 900]

def get_dataset(file_path, **kwargs):

    dataset = tf.data.experimental.make_csv_dataset(
        file_path,
        batch_size=96,
        label_name = Label_Column,
        na_value="?",
        num_epochs = 1,
        ignore_errors=True,
        **kwargs
    )
    return dataset

Please ignore the "Labels"-variable. Normally, the value of my prediction can be anything between 0 and 900, I didn´t figure out so far how to display this properly.
Does anyone know, what this error means? I wasn´t able to find this exact same error again. As far as I can see, all my Csv-files have the exact same number of fileds per row in each row.
Kind regards and thank you in advance.

A: I suggest you to check your csv file to check which line as the issue. Because it can be a blank line at the end of the file or a missing comma or so many others things...
import csv

with open(filename, 'r') as f1:
    csvlines = csv.reader(f1, delimiter=',')
    for lineNum, line in enumerate(csvlines):
        if not len(line)==6:
            print(f"line:{lineNum} \t length:{len(line)}")

A: Doch, you can just put the name of the csv file in this function.
dataset = tf.data.experimental.make_csv_dataset('filename_for_datasetCSV.csv', batch_size = 1, select_columns = ['short_description','Label'], label_name = 'Label', num_epochs = 1 ,shuffle = True

Use this above function after replacing the names of the columns and filename.

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS - programmatically cancel all sounds/music? I am developing an iPhone game using Xcode's sprite kit and was wondering if there is a simple or best-practice method of canceling all sound-effects/ music programatically? The most obvious method to me is to create some boolean variable "isSoundAllowed" and set it to true/false when the user toggles sound on/off in my game, but I'd like to learn better techniques if available. Thanks!
P.S: the following is 1) the sound and 2) the music:
1)
_ActionExplodeSound = [SKAction playSoundFileNamed:@"explosion.wav" waitForCompletion:NO];

2)
-(void)playBackgroundMusic
{
NSError *error;
NSURL *backgroundMusicURL = [[NSBundle mainBundle] URLForResource:@"backgroundMusic.mp3" withExtension:nil];
_backgroundMusicPlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
_backgroundMusicPlayer.numberOfLoops = -1;
[_backgroundMusicPlayer play];
}

edit: actually I can use [_backgroundMusicPlayer stop]; to stop the music, but is there a simple way like this to disable all sound effects (I have more than i list in #1 but they are of the same type)?

A: My solution so far is this, but I'm confident there is a better/more compact of doing this:
-(void)toggleSound
{
BoolSoundEnabled=!BoolSoundEnabled;
if (BoolSoundEnabled==TRUE) {
    _ActionExplodeSound = [SKAction playSoundFileNamed:@"explosion.wav" waitForCompletion:NO];
    [_backgroundMusicPlayer play];
} else if (BoolSoundEnabled==FALSE) {
    _ActionExplodeSound=Nil ;
    [_backgroundMusicPlayer stop];
}

}


text:
Q: Downloading multiple .SAO files via http via Python3 I need to use python3 to download multiple .SAO files from http.  Each file has a distinct url which differs by a number in the url (for example, https://www.1.SAO, https://www.2.SAO, etc.).  How do I achieve this, and how do I control where the files will be downloaded to?

A: Downloading a file is pretty simple using wget, and changing the URL can be done by modifying the string before executing the download() function.
to install wget, do pip install wget which will install wget to your default python instance. After that, just import it and you're good to go!
For example, if I wanted to download the .sao files from 1 to 10:
import wget
for i in range(1,11):
    url = "https://www.{0}.SAO".format(i) #adds the value of "i" in at "{0}"
    wget.download(url)

this will download all the files between https://www.1.SAO and https://www.10.SAO and save it to the working directory of the script.
If you wanted to change the directory, wget.download() has an optional second argument. For example, if I wanted to save my file to a directory called downloads which is located in the same directory as the script, I could call:
wget.download(url,"downloads/")
It would then save all my files in that subdirectory, instead of the working directory. If my directory is in an entire different part of the system (Let's say I wanted to download them to /usr/bin/ or something, I can specify that as well, the same way as using a normal Unix file path:
wget.download(url,"/usr/bin/")
Hopefully this helps you get started.


text:
Q: Probability at a poorly planned gift exchange. Need help with this problem.  I have an idea on a but not sure if a is right nor what to do with b or c.  I went to a poorly planned "gift exchange" All five of us tossed our gifts into a bin, and then picked one at random. It was bad, because there was a good chance someone would receive his or her own gift!
a.  What is the probability that nobody received his or her own gift?
I was thinking 4!/5!, but not sure.
b. What is the probability that at least one person received his or her own gift?
c.  What is the probability that at least two people received their own gifts?

A: For a, you are looking for the probability of a derangement, which is very close to $\frac 1e$  OEIS gives the exact values.  For five, it is $\frac {44}{120}$
Given a, can you solve b?
For c, to get the chance that exactly two people got their own gifts, you have ${5\choose 2}$ ways to get those people and $2$ derangements of the remaining gifts, for $20$ ways to do this and a chance of $\frac {20}{120}=\frac 16$  You should be able to do the others.
d What is the probability that exactly four people received their own gifts?


text:
Q: Can this binomial summation be simplified? I got something like
$\displaystyle\sum_{i=0}^K{ \binom{n+i}{i}  \cdot \alpha^i} $
where $n,\ K,\ \alpha$ are definite values, $\binom{n+i}{i}$ is the Combinatorial number that choose $i$ from $n+i$, can this summation be simplified? Thank you.

A: The summand, being a product of a binomial coefficient and something to the power of the iterand, looks like a hypergeometric function.
In fact, symbolic algebra
reveals that it is equal to
$$
\left(1-\alpha\right)^{-n-1}-\alpha^{K+1}\binom{K+n+1}{K+1}{}_{2}F_{1}\left(1,K+n+2;K+2;\alpha\right).
$$
Naturally, the trouble term is the hypergeometric $_{2}F_{1}$. I
do not think this is a particularly useful form, other than being
"closed" in some sense.


text:
Q: why does Ubuntu boot so slowly? (13.04) I wonder if anyone has any idea why my system boots so slowly. It's taking 40 seconds to reach the login screen, another 20 or so to display the desktop, and another minute or so  before my main software (Firefox and LibreOffice Writer) are ready to go.
I'm running Ubuntu 13.04 (the secure remix), dual booting with Win8 (which actually boots a lot snappier, frustratingly).
My last bootlog .png is here
I've done a fair bit of googling, but none of the suggestions I've come across have helped. (I did find one useful bit of info here, which displays ALL the start-up applications in 'Startup Applications', not just a couple of them. But even after unchecking all but the essentials (and the unknowns) I'm still booting slowly.
Any advice would be really appreciated. Let me know if any more info would be useful.
Thanks!

A: In your boot log, it looks like fsck is taking about 10 seconds to check your disks for errors.  That shouldn't happen on every boot, so it's an obvious place to start looking for problems.  In particular, it's taking time checking a vfat drive.
Try booting to rescue mode and check your disks for errors from there. There are certain filesystem problems that need to be resolved interactively.
If you are mounting windows drives, check them for errors from windows.


text:
Q: s4sdk - MTA build throwing error in Jenkins I am developing MTA project and have to integrate CI/CD for Cloud Foundry using s4sdk-pipeline however Jenkins fails to build the node project. Showing below error in Jenkins log
SAP Multitarget Application Archive Builder 1.1.8

Module "ProjectName": invoking npm

ERROR: An unexpected error has occurred; please tell us about it in our Community page:

---------------------------------------------------------

--- ERROR OCCURRED IN LIBRARY STEP: mtaBuild

----------------------------------------------------------

FOLLOWING PARAMETERS WERE AVAILABLE TO THIS STEP:

***

[script:Script1@ee5197a]

***

ERROR WAS:

***

hudson.AbortException: script returned exit code 1

***

FURTHER INFORMATION:

* Documentation of library step mtaBuild: https://sap.github.io/jenkins-library/steps/mtaBuild/

* Source code of library step mtaBuild: https://github.com/SAP/jenkins-library/blob/master/vars/mtaBuild.groovy

* Library documentation: https://sap.github.io/jenkins-library/

* Library repository: https://github.com/SAP/jenkins-library

----------------------------------------------------------

--- END LIBRARY STEP: mtaBuild ---

script returned exit code 1

Any help appreciated.
Thanks in advance.
screen capture: Jenkins Log Error list
as mentioned please see below Console Output log
Skipping 6 KB.. Full Log
PYMCpDfOQzp/bUe1sxGHFaM0ojAAAApx+LCAAAAAAAAP9tjTEOwjAUQ3+LOrAycohUCDbE1DXKwglCE0La6P/yk9JOnIircQdaKjHhwbItWe/1hiIynIidaCy2HmPtRRd6NyUxELfXQINo6CJqwkjBCmUHRcZWS1WULCzKclhJWFusA0WPLsFGNvqhy6DRlefE03aUkHtzhydkciInzelbRobtrTeR8Mf5C4CxS5Dv9rMd5mfxAbNWnxXCAAAA[0m[Pipeline] {
[Pipeline] stage
[Pipeline] { (Init)
[Pipeline] milestone
07:40:42 Trying to pass milestone 10
[Pipeline] library
07:40:42 Loading library s4sdk-pipeline-library@master
07:40:42 Attempting to resolve master from remote references...
07:40:42  > git --version # timeout=10
07:40:42  > git ls-remote -h https://github.com/SAP/cloud-s4-sdk-pipeline-lib.git # timeout=10
07:40:42 Found match: refs/heads/master revision a8a2909dadaff3c66b5008374e957a87509818ec
07:40:42 No credentials specified
07:40:42  > git rev-parse --is-inside-work-tree # timeout=10
07:40:42 Fetching changes from the remote Git repository
07:40:42  > git config remote.origin.url https://github.com/SAP/cloud-s4-sdk-pipeline-lib.git # timeout=10
07:40:42 Fetching without tags
07:40:42 Fetching upstream changes from https://github.com/SAP/cloud-s4-sdk-pipeline-lib.git
07:40:42  > git --version # timeout=10
07:40:42  > git fetch --no-tags --progress https://github.com/SAP/cloud-s4-sdk-pipeline-lib.git +refs/heads/*:refs/remotes/origin/*
07:40:42 Checking out Revision a8a2909dadaff3c66b5008374e957a87509818ec (master)
07:40:42  > git config core.sparsecheckout # timeout=10
07:40:42  > git checkout -f a8a2909dadaff3c66b5008374e957a87509818ec
07:40:42 Commit message: "Prepare for new piper library name"
07:40:42  > git rev-list --no-walk a8a2909dadaff3c66b5008374e957a87509818ec # timeout=10
[Pipeline] library
07:40:45 Loading library piper-library-os@def66f4ffa9e614eeb3747599a0be7ea9a108453
07:40:45 Attempting to resolve def66f4ffa9e614eeb3747599a0be7ea9a108453 from remote references...
07:40:45  > git --version # timeout=10
07:40:45  > git ls-remote -h https://github.com/SAP/jenkins-library.git # timeout=10
07:40:46 Could not find def66f4ffa9e614eeb3747599a0be7ea9a108453 in remote references. Pulling heads to local for deep search...
07:40:46  > git rev-parse --is-inside-work-tree # timeout=10
07:40:46 Setting origin to https://github.com/SAP/jenkins-library.git
07:40:46  > git config remote.origin.url https://github.com/SAP/jenkins-library.git # timeout=10
07:40:46 Fetching origin...
07:40:46 Fetching upstream changes from origin
07:40:46  > git --version # timeout=10
07:40:46  > git config --get remote.origin.url # timeout=10
07:40:46  > git fetch --tags --progress origin +refs/heads/*:refs/remotes/origin/*
07:40:46  > git rev-parse def66f4ffa9e614eeb3747599a0be7ea9a108453^{commit} # timeout=10
07:40:46  > git branch -a -v --no-abbrev --contains def66f4ffa9e614eeb3747599a0be7ea9a108453 # timeout=10
07:40:46 Selected match: cst revision def66f4ffa9e614eeb3747599a0be7ea9a108453
07:40:46 No credentials specified
07:40:46  > git rev-parse --is-inside-work-tree # timeout=10
07:40:46 Fetching changes from the remote Git repository
07:40:46  > git config remote.origin.url https://github.com/SAP/jenkins-library.git # timeout=10
07:40:46 Fetching without tags
07:40:46 Fetching upstream changes from https://github.com/SAP/jenkins-library.git
07:40:46  > git --version # timeout=10
07:40:46  > git fetch --no-tags --progress https://github.com/SAP/jenkins-library.git +refs/heads/*:refs/remotes/origin/*
07:40:46 Checking out Revision def66f4ffa9e614eeb3747599a0be7ea9a108453 (cst)
07:40:46  > git config core.sparsecheckout # timeout=10
07:40:47  > git checkout -f def66f4ffa9e614eeb3747599a0be7ea9a108453
07:40:47 Commit message: "extend Analytics (#439)"
07:40:47  > git rev-list --no-walk def66f4ffa9e614eeb3747599a0be7ea9a108453 # timeout=10
[Pipeline] echo
07:40:47 Sending telemetry data is disabled.
[Pipeline] echo
07:40:47 --- BEGIN LIBRARY STEP: initS4sdkPipeline.groovy ---
[Pipeline] node
07:40:47 Running on Jenkins in /var/jenkins_home/workspace/projectui_PR-1@3
[Pipeline] {
[Pipeline] echo
07:40:47 --- BEGIN LIBRARY STEP: unstashFiles.groovy ---
[Pipeline] deleteDir
[Pipeline] echo
07:40:47 Unstashing []
[Pipeline] echo
07:40:47 --- END LIBRARY STEP: unstashFiles.groovy ---
[Pipeline] fileExists
[Pipeline] fileExists
[Pipeline] checkout
07:40:48 using credential JDNew
07:40:48 Cloning the remote Git repository
07:40:48 Cloning with configured refspecs honoured and without tags
07:40:48 Cloning repository https://github.com/.../l....git
07:40:48  > git init /var/jenkins_home/workspace/projectui_PR-1@3 # timeout=10
07:40:48 Fetching upstream changes from https://github.com/.../l....git
07:40:48  > git --version # timeout=10
07:40:48 using GIT_ASKPASS to set credentials
07:40:48  > git fetch --no-tags --progress https://github.com/.../l....git +refs/pull/1/head:refs/remotes/origin/PR-1 +refs/heads/master:refs/remotes/origin/master
07:40:49  > git config remote.origin.url https://github.com/.../l....git # timeout=10
07:40:49  > git config --add remote.origin.fetch +refs/pull/1/head:refs/remotes/origin/PR-1 # timeout=10
07:40:49  > git config --add remote.origin.fetch +refs/heads/master:refs/remotes/origin/master # timeout=10
07:40:49  > git config remote.origin.url https://github.com/.../l....git # timeout=10
07:40:49 Fetching without tags
07:40:49 Fetching upstream changes from https://github.com/.../l....git
07:40:49 using GIT_ASKPASS to set credentials
07:40:49  > git fetch --no-tags --progress https://github.com/.../l....git +refs/pull/1/head:refs/remotes/origin/PR-1 +refs/heads/master:refs/remotes/origin/master
07:40:49 Merging remotes/origin/master commit 28f2a2d55051a061c9aaec44b2b697822b8378de into PR head commit 567cacb5d338b222a318166d6570948ffe0162af
07:40:49  > git config core.sparsecheckout # timeout=10
07:40:49  > git checkout -f 567cacb5d338b222a318166d6570948ffe0162af
07:40:49  > git merge 28f2a2d55051a061c9aaec44b2b697822b8378de # timeout=10
07:40:49  > git rev-parse HEAD^{commit} # timeout=10
07:40:49 Merge succeeded, producing 567cacb5d338b222a318166d6570948ffe0162af
07:40:49 Checking out Revision 567cacb5d338b222a318166d6570948ffe0162af (PR-1)
07:40:49  > git config core.sparsecheckout # timeout=10
07:40:49  > git checkout -f 567cacb5d338b222a318166d6570948ffe0162af
07:40:49 Commit message: "changed"
[Pipeline] echo
07:40:49 --- BEGIN LIBRARY STEP: initS4SdkPipelineLibrary.groovy ---
[Pipeline] library
07:40:49 Only using first definition of library piper-library-os
[Pipeline] echo
07:40:49 Sending telemetry data is disabled.
[Pipeline] echo
07:40:50 --- BEGIN LIBRARY STEP: setupCommonPipelineEnvironment ---
[Pipeline] echo
07:40:50 --- BEGIN LIBRARY STEP: prepareDefaultValues ---
[Pipeline] echo
07:40:50 Loading configuration file 'default_pipeline_environment.yml'
[Pipeline] libraryResource
[Pipeline] readYaml
[Pipeline] echo
07:40:50 Loading configuration file 'default_s4_pipeline_environment.yml'
[Pipeline] libraryResource
[Pipeline] readYaml
[Pipeline] echo
07:40:50 --- END LIBRARY STEP: prepareDefaultValues ---
[Pipeline] fileExists
[Pipeline] readYaml
[Pipeline] echo
07:40:50 --- BEGIN LIBRARY STEP: prepareDefaultValues ---
[Pipeline] echo
07:40:50 --- END LIBRARY STEP: prepareDefaultValues ---
[Pipeline] echo
07:40:50 --- END LIBRARY STEP: setupCommonPipelineEnvironment ---
[Pipeline] echo
07:40:51 --- BEGIN LIBRARY STEP: checkDiskSpace.groovy ---
[Pipeline] sh
07:40:51 + df -m /var/jenkins_home
07:40:51 + awk FNR > 1 {print $4}
[Pipeline] sh
07:40:52 + du -md 0 /var/jenkins_home/jobs/projectui/branches/PR-1/builds/18
07:40:52 + awk {print $1}
[Pipeline] echo
07:40:52 --- END LIBRARY STEP: checkDiskSpace.groovy ---
[Pipeline] echo
07:40:52 Download cache for maven and npm activated
[Pipeline] libraryResource
[Pipeline] writeFile
[Pipeline] echo
07:40:52 --- END LIBRARY STEP: initS4SdkPipelineLibrary.groovy ---
[Pipeline] libraryResource
[Pipeline] readYaml
[Pipeline] echo
07:40:52 Stash config: [initS4sdkPipeline:[unstash:[], stashes:[[name:SOURCE, includes:**/*.*, excludes:'pipelines/**, **/.git/**], [name:PIPELINE, includes:'pipelines/**, excludes:'pipelines/.git/**], [name:REPORTS, includes:s4hana_pipeline/reports/**], [name:M2, includes:s4hana_pipeline/maven_local_repo/**], [name:TARGET, includes:**/target/**], [name:NODE_MODULES, includes:node_modules/**]]], build:[unstash:[SOURCE, M2], stashes:[[name:M2, includes:s4hana_pipeline/maven_local_repo/**], [name:TARGET, includes:*.mtar, **/target/**, target/**], [name:NODE_MODULES, includes:**/node_modules/**, node_modules/**], [name:PACKAGE_LOCK, includes:**/package-lock.json, **/npm-shrinkwrap.json]]], unitTests:[unstash:[SOURCE, M2, TARGET], stashes:[[name:REPORTS, merge:true, includes:s4hana_pipeline/reports/**]]], integrationTests:[unstash:[SOURCE, M2, TARGET], stashes:[[name:REPORTS, merge:true, includes:s4hana_pipeline/reports/**]]], staticCodeChecks:[unstash:[SOURCE, TARGET, REPORTS, M2], stashes:[[name:REPORTS, merge:true, includes:s4hana_pipeline/reports/**]]], lint:[unstash:[SOURCE, NODE_MODULES, PACKAGE_LOCK]], checkmarxScan:[unstash:[SOURCE, TARGET, REPORTS, M2], stashes:[]], whitesourceScan:[unstash:[SOURCE, M2, NODE_MODULES], stashes:[]], sourceClearScan:[unstash:[SOURCE, M2, NODE_MODULES], stashes:[]], additionalTools:[unstash:[SOURCE, M2, NODE_MODULES], stashes:[]], fortifyScan:[unstash:[SOURCE, M2], stashes:[]], npmAudit:[unstash:[SOURCE, PACKAGE_LOCK], stashes:[]], frontendUnitTests:[unstash:[SOURCE, NODE_MODULES], stashes:[]], endToEndTests:[unstash:[SOURCE, TARGET, NODE_MODULES], stashes:[]], performanceTests:[unstash:[SOURCE, TARGET], stashes:[[name:REPORTS, merge:true, includes:s4hana_pipeline/reports/**]]], s4SdkQualityChecks:[unstash:[SOURCE, M2, TARGET, REPORTS], stashes:[[name:REPORTS, includes:s4hana_pipeline/reports/**]]], artifactDeployment:[unstash:[SOURCE, TARGET, NODE_MODULES], stashes:[]], productionDeployment:[unstash:[SOURCE, TARGET, NODE_MODULES], stashes:[]]]
[Pipeline] fileExists
[Pipeline] fileExists
[Pipeline] fileExists
[Pipeline] echo
07:40:53 --- BEGIN LIBRARY STEP: errorWhenCurrentBuildResultIsWorseOrEqualTo.groovy ---
[Pipeline] echo
07:40:53 --- END LIBRARY STEP: errorWhenCurrentBuildResultIsWorseOrEqualTo.groovy ---
[Pipeline] fileExists
[Pipeline] readYaml
[Pipeline] echo
07:40:54 nodejs has modules:  projectui
[Pipeline] sh
07:40:54 + git rev-parse HEAD
[Pipeline] fileExists
[Pipeline] fileExists
[Pipeline] fileExists
[Pipeline] fileExists
[Pipeline] fileExists
[Pipeline] echo
07:41:02 --- BEGIN LIBRARY STEP: stashFiles.groovy ---
[Pipeline] stash
07:41:03 Stashed 105 file(s)
[Pipeline] stash
07:41:03 Stashed 0 file(s)
[Pipeline] stash
07:41:03 Stashed 0 file(s)
[Pipeline] stash
07:41:03 Stashed 0 file(s)
[Pipeline] stash
07:41:03 Stashed 1 file(s)
[Pipeline] stash
07:41:03 Stashed 0 file(s)
[Pipeline] deleteDir
[Pipeline] echo
07:41:03 --- END LIBRARY STEP: stashFiles.groovy ---
[Pipeline] echo
07:41:03 Current build result in stage initS4sdkPipeline is SUCCESS.
[Pipeline] echo
07:41:03 Sending telemetry data: [event_type:pipeline_stage, custom3:stage_name, e_3:initS4sdkPipeline, custom4:stage_result, e_4:SUCCESS, custom5:start_time, e_5:1549957247815, custom6:duration, e_6:15979, custom7:project_extensions, e_7:false, custom8:global_extensions, e_8:false, action_name:SAP S/4HANA Cloud SDK, idsite:70aeb424-0d69-0265-c486-b5471b014ba8, idsitesub:pipeline, url:https://github.com/SAP/cloud-s4-sdk-pipeline/tree/master/doc/operations/analytics.md, custom2:project_id_hash, e_2:75174568523be69fb6d03f76d4bd9263f70a5e265d4374c4eca2bc6994a06ea0, custom1:build_url_hash, e_a:317b74bc0b282598de984862589c9b33f4bf1864, custom10:build_number, e_10:19]
[Pipeline] sh
[Pipeline] deleteDir
[Pipeline] }
[Pipeline] // node
[Pipeline] echo
07:41:04 --- END LIBRARY STEP: initS4sdkPipeline.groovy ---
[Pipeline] echo
07:41:05 --- BEGIN LIBRARY STEP: abortOldBuilds.groovy ---
[Pipeline] echo
07:41:05 --- END LIBRARY STEP: abortOldBuilds.groovy ---
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] milestone
07:41:05 Trying to pass milestone 20
[Pipeline] echo
07:41:05 --- BEGIN LIBRARY STEP: build.groovy ---
[Pipeline] node
07:41:05 Running on Jenkins in /var/jenkins_home/workspace/projectui_PR-1@3
[Pipeline] {
[Pipeline] echo
07:41:05 --- BEGIN LIBRARY STEP: unstashFiles.groovy ---
[Pipeline] deleteDir
[Pipeline] echo
07:41:05 Unstashing [SOURCE, M2]
[Pipeline] unstash
[Pipeline] unstash
[Pipeline] echo
07:41:06 --- END LIBRARY STEP: unstashFiles.groovy ---
[Pipeline] fileExists
[Pipeline] fileExists
[Pipeline] withEnv
[Pipeline] {
[Pipeline] echo
07:41:07 --- BEGIN LIBRARY STEP: mtaBuild ---
[Pipeline] echo
07:41:07 --- BEGIN LIBRARY STEP: prepareDefaultValues ---
[Pipeline] echo
07:41:07 --- END LIBRARY STEP: prepareDefaultValues ---
[Pipeline] sh
[Pipeline] echo
07:41:08 --- BEGIN LIBRARY STEP: dockerExecute ---
[Pipeline] echo
07:41:08 --- BEGIN LIBRARY STEP: prepareDefaultValues ---
[Pipeline] echo
07:41:08 --- END LIBRARY STEP: prepareDefaultValues ---
[Pipeline] sh
07:41:09 + docker ps -q
[Pipeline] echo
07:41:09 [INFO][dockerExecute] Running on local environment.
[Pipeline] sh
[Pipeline] sh
[Pipeline] echo
07:41:09 Java home '/docker-java-home' retrieved from environment.
[Pipeline] echo
07:41:09 Verifying Java location '/docker-java-home'.
[Pipeline] sh
07:41:10 + set +x
07:41:10 /docker-java-home exists.
[Pipeline] sh
07:41:10 + set +x
07:41:10 /docker-java-home is a directory.
[Pipeline] sh
07:41:10 + set +x
07:41:10 /docker-java-home is not empty.
[Pipeline] echo
07:41:10 Verification success. Java location '/docker-java-home' exists.
[Pipeline] sh
[Pipeline] sh
[Pipeline] sh
[Pipeline] sh
[Pipeline] echo
07:41:11 Verifying Java '/docker-java-home/bin/java'.
[Pipeline] sh
07:41:12 + set +x
07:41:12 /docker-java-home/bin/java exists.
[Pipeline] sh
07:41:12 + set +x
07:41:12 /docker-java-home/bin/java is a file.
[Pipeline] echo
07:41:12 Verification success. Java '/docker-java-home/bin/java' exists.
[Pipeline] sh
[Pipeline] sh
[Pipeline] sh
[Pipeline] echo
07:41:13 Verifying Java version 1.8.0 or compatible version.
[Pipeline] echo
07:41:13 Verification success. Java version 1.8.0 is installed.
[Pipeline] sh
[Pipeline] echo
07:41:13 Verifying SAP Multitarget Application Archive Builder 'mta.jar'.
[Pipeline] sh
07:41:14 + set +x
07:41:14 mta.jar exists.
[Pipeline] sh
07:41:14 + set +x
07:41:14 mta.jar is a file.
[Pipeline] echo
07:41:14 Verification success. SAP Multitarget Application Archive Builder 'mta.jar' exists.
[Pipeline] sh
[Pipeline] sh
[Pipeline] sh
[Pipeline] echo
07:41:15 Verifying SAP Multitarget Application Archive Builder version 1.0.6 or compatible version.
[Pipeline] sh
[Pipeline] echo
07:41:16 Verification success. SAP Multitarget Application Archive Builder version 1.1.8 is installed.
[Pipeline] fileExists
[Pipeline] echo
07:41:16 [INFO] 'mta.yaml' file found in project sources.
[Pipeline] readYaml
[Pipeline] sh
07:41:16 + date +%Y%m%d%H%M%S
07:41:16 + sed -ie s/${timestamp}/20190212074116/g mta.yaml
[Pipeline] sh
[Pipeline] echo
07:41:16 SAP Multitarget Application Archive Builder file 'mta.jar' retrieved from configuration.
[Pipeline] echo
07:41:17 Using SAP Multitarget Application Archive Builder 'mta.jar'.
[Pipeline] sh
[Pipeline] sh
[Pipeline] echo
07:41:17 [INFO] Executing mta build call: '/docker-java-home/bin/java -jar mta.jar --mtar projectui.mtar --build-target=CF build'.
[Pipeline] sh
07:41:18 SAP Multitarget Application Archive Builder 1.1.8
07:41:18 Module "projectui": invoking npm
07:41:18 ERROR: An unexpected error has occurred; please tell us about it in our Community page: " https://answers.sap.com/tags/73554900100700001351"
[Pipeline] libraryResource
[Pipeline] echo
07:41:18 ----------------------------------------------------------
07:41:18 --- ERROR OCCURRED IN LIBRARY STEP: dockerExecute
07:41:18 ----------------------------------------------------------
07:41:18
07:41:18 FOLLOWING PARAMETERS WERE AVAILABLE TO THIS STEP:
07:41:18 ***
07:41:18 [script:Script1@ee5197a, dockerImage:null, dockerOptions:null]
07:41:18 ***
07:41:18
07:41:18 ERROR WAS:
07:41:18 ***
07:41:18 hudson.AbortException: script returned exit code 1
07:41:18 ***
07:41:18
07:41:18 FURTHER INFORMATION:
07:41:18 * Documentation of library step dockerExecute: https://sap.github.io/jenkins-library/steps/dockerExecute/
07:41:18 * Source code of library step dockerExecute: https://github.com/SAP/jenkins-library/blob/master/vars/dockerExecute.groovy
07:41:18 * Library documentation: https://sap.github.io/jenkins-library/
07:41:18 * Library repository: https://github.com/SAP/jenkins-library
07:41:18
07:41:18 ----------------------------------------------------------
07:41:18 --- END LIBRARY STEP: dockerExecute ---
[Pipeline] libraryResource
[Pipeline] echo
07:41:18 ----------------------------------------------------------
07:41:18 --- ERROR OCCURRED IN LIBRARY STEP: mtaBuild
07:41:18 ----------------------------------------------------------
07:41:18
07:41:18 FOLLOWING PARAMETERS WERE AVAILABLE TO THIS STEP:
07:41:18 ***
07:41:18 [script:Script1@ee5197a]
07:41:18 ***
07:41:18
07:41:18 ERROR WAS:
07:41:18 ***
07:41:18 hudson.AbortException: script returned exit code 1
07:41:18 ***
07:41:18
07:41:18 FURTHER INFORMATION:
07:41:18 * Documentation of library step mtaBuild: https://sap.github.io/jenkins-library/steps/mtaBuild/
07:41:18 * Source code of library step mtaBuild: https://github.com/SAP/jenkins-library/blob/master/vars/mtaBuild.groovy
07:41:18 * Library documentation: https://sap.github.io/jenkins-library/
07:41:18 * Library repository: https://github.com/SAP/jenkins-library
07:41:18
07:41:18 ----------------------------------------------------------
07:41:18 --- END LIBRARY STEP: mtaBuild ---
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] echo
07:41:18 Sending telemetry data: [event_type:pipeline_stage, custom3:stage_name, e_3:build, custom4:stage_result, e_4:SUCCESS, custom5:start_time, e_5:1549957265764, custom6:duration, e_6:13028, custom7:project_extensions, e_7:false, custom8:global_extensions, e_8:false, action_name:SAP S/4HANA Cloud SDK, idsite:70aeb424-0d69-0265-c486-b5471b014ba8, idsitesub:pipeline, url:https://github.com/SAP/cloud-s4-sdk-pipeline/tree/master/doc/operations/analytics.md, custom2:project_id_hash, e_2:75174568523be69fb6d03f76d4bd9263f70a5e265d4374c4eca2bc6994a06ea0, custom1:build_url_hash, e_a:317b74bc0b282598de984862589c9b33f4bf1864, custom10:build_number, e_10:19]
[Pipeline] sh
[Pipeline] deleteDir
[Pipeline] }
[Pipeline] // node
[Pipeline] echo
07:41:19 ----------------------------------------------------------
07:41:19 --- ERROR OCCURRED IN LIBRARY STEP: build
07:41:19 ----------------------------------------------------------
07:41:19
07:41:19 FOLLOWING PARAMETERS WERE AVAILABLE TO THIS STEP:
07:41:19 ***
07:41:19 [:]
07:41:19 ***
07:41:19
07:41:19 ERROR WAS:
07:41:19 ***
07:41:19 hudson.AbortException: script returned exit code 1
07:41:19 ***
07:41:19
07:41:19
[Pipeline] echo
07:41:19 --- END LIBRARY STEP: build.groovy ---
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Artifact Deployment)
Stage "Artifact Deployment" skipped due to earlier failure(s)
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Production Deployment)
Stage "Production Deployment" skipped due to earlier failure(s)
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
07:41:20 Sending telemetry data: [custom11:os_name, e_11:Linux, custom12:os_version, e_12:4.15.0-1032-aws, custom13:swa_schema_version, e_13:1, locale:C.UTF-8, custom7:jenkins_version, e_7:2.150.1, custom9:is_productive, e_9:false, event_type:pipeline, custom3:stage_name, e_3:postAction, custom4:pipeline_result, e_4:FAILURE, custom5:start_time, e_5:1549957239642, custom6:pipeline_duration, e_6:40344, action_name:SAP S/4HANA Cloud SDK, idsite:70aeb424-0d69-0265-c486-b5471b014ba8, idsitesub:pipeline, url:https://github.com/SAP/cloud-s4-sdk-pipeline/tree/master/doc/operations/analytics.md, custom2:project_id_hash, e_2:75174568523be69fb6d03f76d4bd9263f70a5e265d4374c4eca2bc6994a06ea0, custom1:build_url_hash, e_a:317b74bc0b282598de984862589c9b33f4bf1864, custom10:build_number, e_10:19]
[Pipeline] sh
[Pipeline] }
[Pipeline] // script
[Pipeline] script
[Pipeline] {
[Pipeline] echo
07:41:20 Hello World
[Pipeline] echo
07:41:22 Hello World--1
[Pipeline] }
[Pipeline] // script
[Pipeline] deleteDir
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // timestamps
[Pipeline] }
[Pipeline] // timeout
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // load
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline

GitHub has been notified of this commit's build result

ERROR: script returned exit code 1
Finished: FAILURE

screenshot of local build  local build screenshot

A: Your log output says:
[INFO][dockerExecute] Running on local environment.. That means that either Docker is not installed or no Docker image is defined. Thus, it tries to build the mta in the local environment which potentially does not have all requirements installed. (E.g. no nodejs installation.)
Please add the following configuration to your pipeline configuration (pipeline_config.yml) in order to configure the Docker image which should be used:
steps:
  mtaBuild:
    mtaJarLocation: '/opt/sap/mta/lib/mta.jar'
    dockerImage: 'ppiper/mta-archive-builder'

and try again.


text:
Q: AWS Cost Calculation I want to take AWS EC2 instance and opensearch managed service nodes. I was calculating costs but could not see much difference between on demand and all upfront costs.
In all upfront costs, it was also showing monthly costs? WHat does that mean.


text:
Q: One Year Limited Warranty Is the one year limited warranty provided by Apple with a MacBook Pro international?
If I buy the MacBook Pro from US and use it in India, will the limited warranty be applicable in India?

A: I bought my MacBook Air in Hong Kong and I live in Ireland. The condition for the Warranty and AppleCare was that I had to pay for postage to Hong Kong where they would handle it.


text:
Q: Embed a bordered Riemann surface into punctured Riemann surfaces? Let $U$ be a bordered Riemann surface of genus $g$ with $n -1$ punctures and one hole (i.e., the border has one connected component). For any punctured Riemann surface $\Sigma$ of genus $g$ with $n$ punctures, does there necessarily exist an embedding (i.e. an injective holomorphic map) $\Phi: U \to \Sigma$?

A: The answer is no. For $g=0$, the problem is equivalent to the following: is there a univalent function in the unit disk which takes given values at finitely many given points. It is well known that the answer is no: there are many inequalities
relating the points and the values. For example, Theorem 1 on p. 119 of Goluzin's book Geometric theory of functions of a complex variable, Engl. tranls. AMS, 1969
(available on the Internet). Certainly, similar situation prevails for other genera.
The intuitive explanation is this: suppose all your points (punctures) are far away from the hole. And two of them are very close together, while the third is on certain distance from these two. Then this situation (two close together and one
relatively far away must persist no matter how you embed it.


text:
Q: Controlling the size of circuitikz junctions Is there a way to control the size of junction dots / open circles in circuitikz ?
It looks like bipoles/length influences everything including junction dot size; I want to keep the junction dot size the same but decrease bipoles/length and I can't figure out what causes the dot size.

A: Found it! It's nodes width.
From pgfcirc.defines.tex:
\ctikzset{nodes width/.initial=.04}

From pgfcircshapes.tex:
%% Empty terminal

\pgfdeclareshape{ocirc}{
        \anchor{center}{
                \pgfpointorigin
        }
        \anchorborder{
                \pgf@circ@res@left=\pgf@x
                \pgf@circ@res@up=\pgf@y
                \pgfpointborderellipse{\pgfpoint{\pgf@circ@res@left}{\pgf@circ@res@up}
}{\pgfpoint{\pgfkeysvalueof{/tikz/circuitikz/nodes width}*\pgf@circ@Rlen}{\pgfkeysvalueof{/tikz/circuitikz/nodes width}*\pgf@circ@Rlen}}
        }

        \behindforegroundpath{

                \pgfscope
                        \pgfpathcircle{\pgfpointorigin}{\pgfkeysvalueof{/tikz/circuitikz/nodes width}*\pgf@circ@Rlen}
                        \pgfsetcolor{\pgfkeysvalueof{/tikz/circuitikz/color}}
                        \pgfsetfillcolor{white}
                        \pgfusepath{draw,fill}
                \endpgfscope

                }
}


text:
Q: Jenkins ERROR 403 No valid crumb was included in the request - using github authentication Recently I upgraded from a very old jenkins version from 2016 to 2.289.1.  I updated all the plugins as well.  Previously we had it setup with github security.  When we would send jobs, it would be sent with the username and oauth key generated from github, and that's how we would track who sent jobs.
After upgrading, every time I would try to send a job I would get HTTP ERROR 403 No valid crumb was included in the request.  I've tried a lot of different solutions I found online, like checking Enable proxy compatibility under crsf protection, or downloading the crumb plugin.  I even started requesting the crumb and attaching it to the header.  In all cases I was still getting the crumb error.
Now if I disabled the github authentication and changed it to jenkins own user database, and replaced the username and token with a jenkins one (and kept the code to insert the crumb into the header) then the job would successfully get sent to jenkins.  I would rather do it through github since that is how we have it setup, anyone have any suggestions now how to get around the crumb error?
here is just a piece of the code that sends the request
HttpWebRequest crumbRequest = WebRequest.Create(jenkinsCrumbUrl) as HttpWebRequest;
crumbRequest.Method = "GET";
HttpWebResponse crumbResponse = (HttpWebResponse)crumbRequest.GetResponse();
StreamReader responseReader = new StreamReader(crumbResponse.GetResponseStream());
string responseString = responseReader.ReadToEnd();
var crumb = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString);

HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;

request.Method = "POST";
request.ContentType = contentType;
request.UserAgent = userName;
request.CookieContainer = new CookieContainer();
request.ContentLength = formData.Length;
request.PreAuthenticate = true;

byte[] credentialBuffer = new UTF8Encoding().GetBytes(String.Format("{0}:{1}", userName, APIToken));
request.Headers["Authorization"] = String.Format("Basic {0}", Convert.ToBase64String(credentialBuffer));
request.Headers[crumb["crumbRequestField"]] = crumb["crumb"];

using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(formData, 0, formData.Length);
    requestStream.Close();
}
return request.GetResponse() as HttpWebResponse;


text:
Q: Comparing linear mixed-effect models I'm trying to compare a set of four linear mixed-effect models (run in R, lme4::lmer), and, judging by what I've read, there seems to be some debate as to the best way of doing so. I was hoping someone might provide some much needed input.
I started with two models:
m1 <- lmer(IA_DT_PC ~ CONDITION * IA_LABEL + (1 | PARTICIPANT), data2)
m2 <- lmer(IA_DT_PC ~ GROUP * CONDITION * IA_LABEL + (1 | PARTICIPANT), data2)

My usual approach is to use the anova function, so I began by comparing the first two, which showed no difference.
> anova(m1,m2, refit = FALSE)
Data: data2
Models:
object: IA_DT_PC ~ CONDITION * IA_LABEL + (1 | PARTICIPANT)
..1: IA_DT_PC ~ GROUP * CONDITION * IA_LABEL + (1 | PARTICIPANT)
       Df     AIC     BIC logLik deviance Chisq Chi Df Pr(>Chisq)
object  6 -5670.2 -5634.4 2841.1  -5682.2
..1    10 -5638.6 -5578.8 2829.3  -5658.6     0      4          1

So I figured the between-subject factor GROUP wasn't adding to the overall fit of the model. So I put that aside and fitted a third model with another factor of interest:
m3 <- lmer(IA_DT_PC ~ CONDITION * VERSION * IA_LABEL + (1 | PARTICIPANT), data2)

Now, comparing m1 to m3 did reveal a difference, suggesting that m3 is a better fit:
> anova(m1,m3, refit = FALSE)
Data: data2
Models:
object: IA_DT_PC ~ CONDITION * IA_LABEL + (1 | PARTICIPANT)
..1: IA_DT_PC ~ CONDITION * VERSION * IA_LABEL + (1 | PARTICIPANT)
       Df     AIC     BIC logLik deviance  Chisq Chi Df Pr(>Chisq)
object  6 -5670.2 -5634.4 2841.1  -5682.2
..1    10 -5680.1 -5620.3 2850.1  -5700.1 17.882      4   0.001302 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

However, because I'm a fundamentally curious person, I also tried digging that GROUP factor up again, and included it in a fourth model:
m4 <- lmer(IA_DT_PC ~ GROUP * CONDITION * VERSION * IA_LABEL + (1 | PARTICIPANT), data2)

The confusing part (well, to me anyway) is that m4 actually appears to be a better fit than m3 now:
> anova(m3,m4, refit = FALSE)
Data: data2
Models:
object: IA_DT_PC ~ CONDITION * VERSION * IA_LABEL + (1 | PARTICIPANT)
..1: IA_DT_PC ~ GROUP * CONDITION * VERSION * IA_LABEL + (1 | PARTICIPANT)
       Df     AIC     BIC logLik deviance  Chisq Chi Df  Pr(>Chisq)
object 10 -5680.1 -5620.3 2850.1  -5700.1
..1    18 -5711.6 -5604.0 2873.8  -5747.6 47.502      8 0.000000123 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

So, my question is, why did GROUP not explain any additional variance when added to the m1 structure, but it does when added to the m3 structure?
Somewhat related questions:
1) When is it (in)appropriate to allow anova() to refit the models when comparing them?
2) Is there an altogether better way of comparing models that I might try?

A: It probably has to do with your usage of '*'. In your m1 model, you define the following effect: CONDITION * IA_LABEL. It translates to:
Main effects: CONDITION, IA_LABEL.
2-way interactions: CONDITION:IA_LABEL
So, by using '*' you include the two-way interaction and all lower-order effects. In your m2 model, you define the following effect: GROUP * CONDITION * IA_LABEL. It translates to:
Main effects: GROUP, CONDITION, IA_LABEL.
2-way interactions: GROUP:CONDITION, GROUP:IA_LABEL, CONDITION:IA_LABEL
3-way interaction: GROUP:CONDITION:IA_LABEL
So, when comparing m1 to m2, you compare a model that does not include any effect of GROUP to a model that includes the main effect of GROUP and all possible interactions between GROUP and the remaining variables (in addition to the other main effects and interactions).
In your m4 model, you specify the four-way interaction GROUP * CONDITION * VERSION * IA_LABEL, including all lower order effects. It is likely that m4 has a better fit compared to m3 because there is one (or more) interaction that explains variance and involves GROUP and VERSION. This interaction was not specified in the m2 model and may therefore not perform better compared to the m1 model.


text:
Q: using a sequence in sqlj? I'm new to sqlj and try to insert data with an id generated by a sequence. This is my current code:
String pattern = ...;
#sql {INSERT INTO my_table (id, pattern) VALUES (my_seq.nextVal(), :(pattern))};

but I keep getting and ORA-02287 Error.
Do I need to do it differently?

A: Not expert on sqlJ, but in the SQL part you should use my_seq.nextVal, with no ()

A: Omit the parentheses after nextval:
#sql {INSERT INTO my_table (id, pattern) VALUES (my_seq.nextval, :(pattern))};


text:
Q: Bundle install failing on production server I am trying to get a rails app up in production.  I have uploaded it to the server, and ssh'ed into it without a problem. When I try to run: rake db:migrate RAILS_ENV=production, I get the following error:
Could not find rake-10.0.4 in any of the sources
Run `bundle install` to install missing gems.

So, I run bundle install and get the following error:
Gem::Exception: Cannot load gem at [/usr/local/lib/ruby/gems/1.9.1/cache/rake-10.0.4.gem] in /home/root/myapp
An error occurred while installing rake (10.0.4), and Bundler cannot continue.
Make sure that `gem install rake -v '10.0.4'` succeeds before bundling.

From here, I ran gem install rake -v '10.0.4' --no-rdoc --no-ri, and it succeeded:
Yet still, bundle install fails with the same error.  What can I do to fix this?

A: Thanks for all the help guys!
I ended up redeploying after running bundle package, and then ran bundle install --deployment on the server, and now it works.
It looks like I/bundle needed to be more explicit about where to look for the gem files :)

A: Bundler will try to run Rake that is in your gemfile. You need to run bundle exec rake db:migrate RAILS_ENV=production

A: Obviously your installation is faulty. I suggest you re-do it from scratch, and if you'd like you better use rbenv
Please check this answer Install Ruby on Rails on Ubuntu 12.04 LTS

A: my suggestion will you please try. if you are not root user and running this rake commmad may be it will give error. why not you  try to login as root user and then place and navigate to your code. home/root/myapp to var/yourfolder/yourapp then. check which version or ruby you are using ruby -v it should be 1.9 or above and the same for rails which version of rails you are using.


text:
Q: How to subscribe to BOOT_COMPLETED event? I want to subscribe to the BOOT_COMPLETED intent action, which signals the restart of the mobile phone. Once I subscribe I want to schedule some alarms. I have a BroadcastReceiver that listens to the BOOT_COMPLETED action and it gets hit/called if I use android SDK 25. How can I make the code in BroadcastReceiver execute from Android SDK 26 (Oreo) and above ?
When I run the code on sdk 26 I get the error:
system_process W/BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.BOOT_COMPLETED flg=0x400010 }
I have created a Github repo https://github.com/Ferencz8/BootIntent on a simpler case, which shows exactly how on sdk 25 things work and on 26 they don't.
Here is the AndroidManifest.xml part:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".BootReceiver"
            android:exported="false">
            <intent-filter>

                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
                <action android:name="android.intent.action.REBOOT"/>
            </intent-filter>
        </receiver>
</application>

And the BroadcastReceiver:
public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, final Intent intent) {
        Log.d(BootReceiver.class.getSimpleName(), "In Boot Receiver");
        Intent mainActivityIntent = new Intent(context, MainActivity.class);
        context.startActivity(mainActivityIntent);
    }
}

I have tried in the OnReceive method from the BroadcastReceiver to start a ForegroundService like, but with no luck:
@Override
    public void onReceive(final Context context,final  Intent intent) {
        intent.setClass(context, AlarmBootService.class);

        if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        }
        else{
            context.startService(intent);
        }
}

I have also tried adding other intent actions besides the BOOT_COMPLETED:
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="android.intent.action.REBOOT"/>

In order to simulate the BOOT_COMPLETED action I used the command:
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

Also, this is my first question so if you have any feedback on how to describe/articulate better my question please do tell :).


text:
Q: 'If she would have studied hard" I wonder how this sentence sounds. Does it sound absurd or could it be used in some situations?
In other words, is it possible to make a correct sentence with this phrase 'if she would have studied hard'?
PS. Source: my curiosity (I maybe remember someone using this kind of sentence)

A: Many people (Americans, at least), use this construction (would have + Past Participle),
instead of past perfect (had + Past Participle), and with the same meaning.

*

*If she would have studied harder, she could have gotten an A.

*If she had studied harder, she could have gotten an A.
Of course, this is only in writing.
What people would actually say blurs the seeming difference between these two constructions.
Auxiliary verbs are usually contracted; in particular, would is normally contracted to a single final 'd. I.e,

*

*She would never do that ==> She'd never do that.

*He would answer the phone in Swedish ==> He'd answer the phone in
Swedish
Would have is contracted to would've, normally pronounced /wʊdə/,
with the /v/ dropped and only the syllable remaining.

*

*He would have hung up ==> He would've hung up /hiwʊdəhə'ŋəp/

However, would've can also contract the would to /d/, as usual, so further contraction is possible, to

*

*He would've hung up ==> He'd've hung up. /hidəhə'ŋəp/

which leaves only /də/ between he and the verb. Recall that this syllable is intended to be a short form of would have, at least in the mind's ear of the speaker.
And in the example sentence, that'd be

*

*if she would have studied harder ==> if she'd'a studied harder
Notice that, in shortening would have successively to /də/, we have passed right through the standard contraction for the past perfect. I.e,

*

*if she had studied harder ==> if she'd studied harder
so the only pronunciation difference between these two forms is the presence or absence of a reduced schwa (/ə/), which can get swallowed easily in ordinary speech.
Consequently,  many people don't hear any phonetic  difference between these two constructions. They look very different on paper (and there isn't any semantic difference between them), but people can't tell which one others are using, so they confuse them totally, with the usual result.

A: *

*The former implies she had other things to do that seemed more important and/or pleasant at the time. The latter indicates that, in the speaker's opinion, at least, she did not have the ability to study hard.

*It would be better grammatically and stylistically to say "Had she studied hard, [she would have been a celebrated and well-compensated scholar by now].


text:
Q: The use of "of as" A friend of mine asked me this question few days ago:

What acts do you think of as a form of bullying?

If this is in fact grammatically correct, could the of as be replaced with a form of the verb to be?

What acts do you think are a form of bullying?

The use of "of as" is actually new to me. Any explanation would be appreciated.

A: In a comment, Janus Bahs Jacquet wrote:

Of as is not a unit, just two prepositions that happen to end up next to each other. It's a question form of "I think of these acts as a form of bullying". Your alternative version is fine, too, but syntactically different, using a dependent clause.


text:
Q: AngularJS prevent template from rendering based on response from an API In a single page application we're building with angularjs and a Rest API in python, we have an ACL logic in the Rest API that determines if the current logged in user has access to a certain resource or not.
What we are currently doing is to wrap the markup of each "protected" template in a div that contains an ng-if="authorized" attribute where the $scope.authorized variable gets true if the API responds that the current user is authorized to view the content of the template.
With this solution, what the end user experiences, is a quick blank template between the time the API takes to determine if they are authorized to access the resource and the time it takes to redirect them to a dashboard page (a page that all kinds of users have access to) along with a message that tells them that they are not authorized to access that particular resource.
Of course, our concern is the time that the blank template is displayed to the end user before the application takes them to the dashboard page.
Is there something we can do in AngularJS to avoid that span time when the blank template is displayed to the end user and instead make them keep in the current page and only go to the page they requested only if the API resolved that they have access to it?

A: Do you have to use ngRoute? ui-router has two excellent tools that you could use either separately or together to solve this:

*

*It has a $stateChangeStart event that gets fired before a state transition occurs, with all information about the previous/next states. You can stop state transitions here. For example, I use something like this to send auth-required accesses to a login experience:
$stateProvider.state('auth-required-state', {
    url: '^/auth-required-state',
    templateUrl: '/views/view/auth-required-state.html',
    controller: 'AuthRequiredStateController',

    // NOTE: You have access to this entire block in $stateChangeStart, so you can
    // define your own attributes that your own code looks at
    allowAnonymous: false
});

and in $stateChangeStart:
// Handle some checking that needs to be performed
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    // If we aren't logged in and we need to be, do that
    if (!$rootScope.currentUser.loggedIn && !toState.allowAnonymous) {
        $state.go('login');
        e.preventDefault();
    }
});

*It has a resolve operator that you can use to lazy-load things like if you need a data block from a REST service, not just a template. For another use-case I had, I only wanted to go to the target screen if the user had access to that data - the template was always available because you could access some records but not others. You can do something like this:
var ShowDataControllerConfig = function($stateProvider) {
    var getDataBlock = function($stateParams, myDataManager) {
        return myDataManager.getDataBlockAndReturnAPromise($stateParams.data_id);
    };

    // Tolerate minification - you can't use the array trick in state definitions
    getGroupEntry.$inject = ['$stateParams', 'myDataManager'];

    $stateProvider.state('show-data', {
        url: '^/show-data/{data_id}',
        templateUrl: '/views/view/show-data.html',
        controller: 'ShowDataRoomController',
        resolve: {
            dataBlock: getDataBlock
        }
    });
};

ShowDataControllerConfig.$inject = ['$stateProvider'];

var ShowDataController = function(dataBlock) {
    // dataBlock contains our data - but unlike ngRoute, we never even get here if
    // it couldn't be loaded. You can do error handling in $stateChangeError.
};

ShowDataController.$inject = ['dataBlock'];

angular
    .module('myApp.controllers.showData', [])
    .config(ShowDataControllerConfig)
    .controller('ShowDataController', ShowDataController);


text: Q: How to create multiple filters params using react-router-dom I have to create this type of filters https://www.vroom.com/catalog/all-years/acura_ilx,bmw/?price_min=20000&price_max=30000&miles_max=20000 in my website any suggestions how to do with react-router-dom params and query strings but the issue is when I set the optional params in the Route path or URL it will replace the previous filters i have many filters in my website


text:
Q: React Native - Separate View and Logic Is separate view and logic (like java class and xml in Android) in React Native is best way to increase app performance? Any reference for this guys?

A: In terms of app performance it wont really matter because in the end it all gets combined into a single JS bundle file. But separating render and business logic is always useful. It lets you rewrite business logic without having to navigate render logic when you want to make a change and also helps reuse business logic elsewhere in your app if you need to.
A simple example is something we evaluated at work, we have a react native application and a react website. A lot of our business logic of API handling data parsing and storage and redux handling was similar if not exactly the same on both platforms. What we realised is that if we write all the business logic separately we could simply write it once and use it on both platforms and only our render logic could change. Now it is more complicated than my explanation of course but it is possible.
Hope this helps.


text:
Q: Is it possible to create Site Collection such that URL should not have "/sites" in SharePoint foundation 2010? I want to create Site Collection such that Site collection should not contain "/sites" in its URL(Except root Site Collection) in SharePoint Foundation 2010.
Is it possible to do it?

A: I think that you could look at the managed paths

*

*Open Sharepoint Central Administration -> Application Managment -> Manage web applications

*Select your web application

*Click Managed Paths button on the ribbon

You will see that there are at least two path:

*

*Root (Explicit inclusion)

*sites (Wildcard inclusion)

Explicit inclusion means that you can create only one site collection with this path. Wildcard inclusion means that you can create so many sites as you wish.
if you would not want to use \sites, you can add you own path. After this you can select this path on site collection creation page.


text:
Q: Missing parameter error while creating script-tag shopify I'm trying to create a scripttag using POST and it's giving me this error: { errors: { script_tag: 'Required parameter missing or invalid' } }
Below is the code for file server.js. and the scripttag.js file is in the public folder.
I have tried to use the function without the "display_scope" parameter and also with process.env.host instead of https:///21c3ed9616a8.ngrok.io, but nothing seems to work.
require('isomorphic-fetch');
const dotenv = require('dotenv');
const Koa = require('koa');
const next = require('next');
const { default: createShopifyAuth } = require('@shopify/koa-shopify-auth');
const { verifyRequest } = require('@shopify/koa-shopify-auth');
const session = require('koa-session');
const fetch = require('node-fetch');

//const Cryptr = require('cryptr');

dotenv.config();
const {default: graphQLProxy} = require('@shopify/koa-shopify-graphql-proxy');
const {ApiVersion} = require('@shopify/koa-shopify-graphql-proxy');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const { SHOPIFY_API_SECRET_KEY, SHOPIFY_API_KEY } = process.env;

app.prepare().then(() => {
  const server = new Koa();
  server.use(session({ secure: true, sameSite: 'none' }, server));
  server.keys = [SHOPIFY_API_SECRET_KEY];
  server.use(graphQLProxy({version: ApiVersion.October20}));
  server.use(
    createShopifyAuth({
      apiKey: SHOPIFY_API_KEY,
      secret: SHOPIFY_API_SECRET_KEY,
      scopes: ['read_products', 'write_products', 'write_script_tags', 'read_script_tags'],
      afterAuth(ctx) {
        const { shop, accessToken } = ctx.session;
        console.log(shop);
        console.log(accessToken);
        ctx.cookies.set('shopOrigin', shop, {
          httpOnly: false,
          secure: true,
          sameSite: 'none'
      })

  fetch(`https://${shop}/admin/api/2021-01/script_tags.json`, {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      "X-Shopify-Access-Token": accessToken,
    },
    body: JSON.stringify(`{"script_tag": {
      "event": "onload",
      "src": "https://21c3ed9616a8.ngrok.io/public/scripttag.js",
      "display_scope": "all"
    }}`)
  }).then(async response => {
    const data = await response.json();
    console.log(data);
    // check for error response
});
//  const confirmationUrl = responseJson.data.scriptTagCreate.scriptTag;
   console.log(`hi`);

        ctx.redirect('/');
      },
    }),
  );

  server.use(verifyRequest());
  server.use(async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
    ctx.res.statusCode = 200;
    return
  });

  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});


text:
Q: Image handling for different sizes of iPhone and iPad for universal app I am new in iOS
my question is we can take different sizes of images for app icon that support iPhone and iPad pick that images default as per screen resolutions.
same thing how to apply for other images in app. also is it necessary take every image with different sizes or resolutions?
if it is necessary then what is the best way for that?
appreciate for help.

A: *

*For Other Images:
Let's assume our image is supposed to be called "name". We need to supply four image resources. The iPhone resources are supposed to have the ~iphone suffix and accordingly the iPad resources need the ~ipad suffix and the @2x for the retina display is in between the name and the suffix. So this is what we get:
•   name~iphone.png
•   name@2x~iphone.png
•   name~ipad.png
•   name@2x~ipad.png
•   name-568h@2x~iphone.png (iPhone 5)

It is important that the suffix is all lowercase. With this naming convention there is no need to do that any more because
[UIImage imageNamed:@"name.png"];

handles the loading of all different image sizes.
For more info see this & this.

*

*For App Icon:
You should use Asset Catalog.
For more info see Link1, Link2 & Link3

*

*For Lunch Images:
see this.


text:
Q: aiogram + APScheduler user timezone input problems I have sched = AsyncIOScheduler() right after imports
Then in registration process where user passing geolocation I have this
lat = message.location.latitude
lon = message.location.longitude
await state.update_data(lat=lat)
await state.update_data(lon=lon)
tzwhere_ = tzwhere.tzwhere()
timezone_str = tzwhere_.tzNameAt(lat, lon)
print(timezone_str)  # Europe/Moscow
global sched
sched = AsyncIOScheduler(timezone=timezone_str)

Global is a bad practice and it's not working. Notifications (jobs from apscheduler) was doesn't sended. So, how can user pass timezone into apscheduler?


text:
Q: why git returns this error message: "error: branch '.*' not found." I am trying to delete al merged branch, but I dont understand why I got this error message:
prompt> (master) $ git b
  4.0
  4.1
  4.2
  4.3
  4.4
* master
prompt> (master) $ git b --merged | grep -v '*' | xargs git branch -d
error: branch '4.0' not found.
error: branch '4.1' not found.
error: branch '4.2' not found.
error: branch '4.3' not found.
error: branch '4.4' not found.
prompt> (master) $

edit
I've problems just because I've this configuration:
#~/.gitconfig
[alias]
    b = branch --color

This means that my real command is git branch --color --merged | grep -v '*' | xargs git branch -d

A: git b --merged | grep -v '*' | xargs git branch -d

Here you are trying of search the branches and then you are trying to show the deleted branches?
so deleted branches are not found on  xargs git branch -d
Updated :
This worked fine for me.
git branch --merged | grep -v '*' | xargs git branch -d

Deleted branch b_01 (was b62ecb1).
Deleted branch b_02 (was b62ecb1).


text:
Q: Google Cloud Platform swagger openapi config yaml file isn't properly rejecting requests that don't contain my api key in the header I have this config file for my Google Cloud Platform API Gateway endpoint:
swagger: '2.0'
info:
  title: api-1
  description: API Gateway First for Testing
  version: 1.0.0
securityDefinitions:
  api_key_header:
    type: apiKey
    name: key
    in: header
schemes:
  - https
produces:
  - application/json
paths:
  /endpoint1:
    post:
      summary: Simple echo service
      operationId: echo-1
      x-google-backend:
        address: https://<CLOUD FUNCTION GEN 2 NAME>-<MORE IDENTIFYING INFO>-uc.a.run.app
      security:
        - api_key_header: []
      responses:
        '200':
          description: OK

As you can see, I'm trying to require an API key in order for my server to call the API safely. In my opinion, an API key is necessary for security to prevent someone from figuring out my endpoint and spaming the GCP function.
I created an API key to use for this API endpoint (I censored a lot of data for privacy reasons):

I tried to call the endpoint in Postman like this:
curl --location --request POST 'https://<API CALLABLE ENDPOINT>.uc.gateway.dev/endpoint1' \
--header 'X-goog-api-key: <MY API KEY HERE>' \
--header 'Content-Type: application/json; charset=utf-8' \
--data-raw '{
    "name": "Test1"
}'

The problem is that the Postman request works... always lol. No matter what incorrect API key I use for the header...
I noticed that there is no place where I'm directly referencing my API key name. I'm not sure where I'd put this. How do I alter this API Gateway to properly reject requests that do not contain the correct API key?

A: All available formats are specified on this documentation.
When requesting Api Key through the header, you have to match a specific name which is "x-api-key".
So for your openapi file, it gives the following securityDefinitions:
securityDefinitions:
  api_key_header:
    type: "apiKey"
    name: "x-api-key"
    in: "header"

And the curl request should have this header then:
--header 'x-api-key: <MY API KEY HERE>'


text:
Q: Filling polygon with graphic file in QGIS What I want to do is to fill a polygon (country) with a graphic file in any format (*.jpg, .bmp, .png).
It should look like this:

I'm aware that GIS soft is not proper for such an operation but maybe is there any option to do it only in QGIS.

A: Using a gradient, you can obtain this:

You have to use two stops at the border between colours, one for each colour, to make sure the result is neat.
SVG would in any case be the way to go for any flag with more than straight lines!

A: Use the "raster image fill" style on the polygon layer. This fill style allows drawing a polygon using a PNG/JPG/BMP/... etc.

A: This can be done using Python by creating image patches and clipping images using the patches. Needs Python libraries like shapely, cartopy and GeoPandas.
here


text:
Q: Chai http attach sets up content type multipart-formdata I want to pass the file as binary to one of my functions which i want to write the test around using chai http, below is the code:
              chai.request('http://localhost:8085')
                .post('/myAPI/' + req.params.id + '/logo')
                .attach('image', fs.readFileSync(__dirname + '/resources/IMG_86425.jpg'), 'IMG_86425.jpg')
                .set('Content-Type','image/jpeg')
                .end((err, res) => {
                    should.equal(err, null);
                    res.status.should.equal(200);
                    res.should.be.json;
                    done();
                });

Problem is that attach() inherently seem to update the content type to multipart form data in spite of me trying to over ride it with image/jpeg.
Is there something we can do to override this behaviour of attach() or is there any other way i can post binary data to my function.
Thanks

A: attach is meant to work for multi part form data, for sending file as binary i used:
.send(fs.readFileSync(__dirname + '/resources/IMG_86425.jpg'))
                .set('Content-Type','image/jpeg')

Solves the problem...


text:
Q: unable to free gpu memory after loading spacy model Why does SpaCy keep GPU memory even after I delete the model? First I thought I'm facing same problem as this question but then I realized even Cupy doesn't mark the memory as being free.
import spacy
import cupy as cp
import time
import gc

def pool_stats(mempool):
    print('used:',mempool.used_bytes(),'bytes')
    print('total:',mempool.total_bytes(),'bytes\n')

pool = cp.cuda.MemoryPool(cp.cuda.memory.malloc_managed) # get unified pool
cp.cuda.set_allocator(pool.malloc) # set unified pool as default allocator

spacy.prefer_gpu()
nlp = spacy.load('/tmp/nlp')
pool_stats(pool)

# used: 2716626944 bytes
# total: 2719709696 bytes

del nlp
time.sleep(3)
gc.collect()
pool_stats(pool)

# used: 2700994560 bytes
# total: 2719709696 bytes


text:
Q: SIGABRT Error during runtime (c++) This is the skyscraper floors problem from spoj. I m getting SIGABRT when I run the code.Link for the problem is http://www.spoj.com/problems/SCRAPER/. When I run this code on my PC, it runs without any error but spoj's online judge shows SIGABRT error.
#include <iostream>
#include <vector>
using namespace std;
struct floor
{
    unsigned int floornum;
    bool calldone;
    vector <floor*> connection;
    floor()
    {
        floornum=0;
        calldone=0;
    }

};
struct elevator
{
    unsigned int x,y;
    elevator()
    {
        x=y=0;
    }
};
struct skyscrapper
{
    unsigned int f,e,a,b;
    vector <elevator> ele;

    vector <floor*> flooraddress; //this is a spoj problem

    void read()
    {
        cin>>f>>e>>a>>b;

        elevator *temp;
        for(unsigned int i=0;i<e;i++)
        {
            temp=new elevator;
            cin>>(*temp).x>>(*temp).y;
            ele.push_back(*temp);
        }
        for (unsigned int i=0;i<f;i++)
        {
            floor* tempp=new floor;
            (*tempp).floornum=i;
            flooraddress.push_back(tempp);

        }
    }
    void allotaddress()
    {

        unsigned int j,k;
        for(unsigned int i=0;i<ele.size();i++)
        {
             j=ele[i].y;
             k=ele[i].x;
            while(j<f)
            {

                if(j!=ele[i].y)
                {
                (*(flooraddress[j])).connection.push_back(flooraddress[j-k]);

                (*(flooraddress[j-k])).connection.push_back(flooraddress[j]);
                }
                j=j+k;
            }
        }
    }

};
bool flag;

bool traverse(floor* m,int destination)
    {
    if((*m).calldone==1)
    {
        return 0;
    }
    (*m).calldone=1;
        if((*m).floornum==destination)
        return 1;
        if((*m).connection.empty())
        return 0;

        for(int i=0;i<(*m).connection.size();i++)
        {
             flag=traverse(((*m).connection[i]),destination);
            if(flag==1)
            return flag;
        }
        return 0;
    }

int main()
{
    int n;
    cin>>n;
    skyscrapper iit[n];
    bool ans[n];
    for(int i=0;i<n;i++)
    {
    iit[i].read();
    iit[i].allotaddress();
    ans[i]=traverse(iit[i].flooraddress[iit[i].a],iit[i].b);

}
for(int i=0;i<n;i++)
{
    if(ans[i]==1)
    cout<<"It is possible to move the furniture."<<endl;
    else
    cout<<"The furniture cannot be moved."<<endl;
}
    return 0;
}


text:
Q: How to detect if user clicked on an image on a map in Android? I have a map in my app and that has circles plotted on them, like seen in the image, three png images A, B and C.

I want to highlight one of these images, when the user precisely intends to tap on them to do some action pertaining to them.
In order to achieve this,I am using a very crude method
            for(int i = 0; i < vectorPts.size(); i ++){
                dest_location.setLatitude(vectorPts.get(i).x);
                dest_location.setLongitude(vectorPts.get(i).y);
                double distance = (double) mylocation.distanceTo(dest_location);
                distanceCollect.add(distance);
                 int minIndex = distanceCollect.indexOf(Collections.min(distanceCollect));
                 System.out.println("The value >> " + minIndex + DSS.activeRoute);
                 indexUnderEdit = minIndex;
            }

The Vector vectorPts of points has all the points coordinates. I am using the distanceTo method to find the distance between the click point and the location of the images. The least distance between the click point and the actual image location means the user intended to click that image is my assumption. But this is a weak apporach, because any clicks any where on the map (far from any images) will also be considered and the shortest distance will be selected. Can you suggest me an alternate way to find on which specific image the user clicked.
@Override
    public void drawRoute(Canvas canvas,String routeName,MapActivity mact) {
        // TODO Auto-generated method stub
        if((routeName == null || (routeName.equals(PROJ.currentRoute.activeRouteName)))){
        if (cpts.size() > 0)
       {
           if (this.wktType == WKTType.ePolyLine || this.wktType == WKTType.ePolyLineM)
           {
            if ( mPath != null)
                canvas.drawPath(mPath, mPen);
           }

           // draw point icons
           Resources Res = PROJ.getInstance().getResources();
           int i = 0;
           for(; i < cpts.size(); i++)
           {
            if(i == 0)
            {
                // Draw start point //
                if(this.angleRecieved >= 0){
                    Bitmap img = BitmapFactory.decodeResource(Res,  R.drawable.startpoint);
                    canvas.drawBitmap( img,  cpts.get(i).x - img.getWidth()+2, cpts.get(i).y - (img.getHeight()/2) , null);
                }
                else{
                    Bitmap img = BitmapFactory.decodeResource(Res, R.drawable.startpoint_inv);
                    canvas.drawBitmap( img,  cpts.get(i).x-3 , cpts.get(i).y - (img.getHeight()/2), null);
                }
            }
            else if((i == cpts.size() - 1)&&(bIsFinished == true))
            {
                // Draw end point
                if(this.angleRecievedFinish >= 0){
                    Bitmap img = BitmapFactory.decodeResource(Res,R.drawable.finishpoint);
                    canvas.drawBitmap( img,  cpts.get(i).x - img.getWidth()+2, cpts.get(i).y - (img.getHeight()/2), null);
                    }
                    else{
                    Bitmap img = BitmapFactory.decodeResource(Res, R.drawable.finishpoint_inv);
                    canvas.drawBitmap( img,  cpts.get(i).x-3 , cpts.get(i).y - (img.getHeight()/2), null);
                    }

                if(!bIsSaved){
                    Intent intent = new Intent();
                    intent.setAction(Constants.CUSTOM_NEWMESSAGE_INTENT);
                    intent.putExtra(Constants.EVENT_STRING, Constants.mapEvents.ROUTE_FINISHED);
                    PROJ.getCurrentApplicationContext().sendBroadcast(intent);
                    bIsSaved = true;
                }
            }
            else
            //Draw intermediate points from 1 to 10
            {
                if (i ==1){
                    this.forFirstIteration = this.angleRecieved;
                }
                if(i == 10){
                    this.lastNotifier = true;
                }
                int wpResId = getWPResourceId(i);
                Bitmap img = BitmapFactory.decodeResource(Res, wpResId);
                canvas.drawBitmap( img,  cpts.get(i).x - img.getWidth()/2, cpts.get(i).y -  img.getWidth()/2, null);
            }

           }
       }

    }
}


text:
Q: Programmatically create a user in Cognito with email and password (permanent password) I currently have some code that creates a new user with temporary password. I get an email with a temporary password to my account, but instead I want to get a verification code. to confirm my email.
here is the code:
  public static void registerUser(String email) {
    String userPoolId = "eu-central-1_xxx";
    AWSCognitoIdentityProvider cognitoClient = setUpCognitoClient();

    String password = "123456789";

    try {
      AdminCreateUserRequest userRequest =
              new AdminCreateUserRequest().withUserPoolId(userPoolId).withUsername(email);

      cognitoClient.adminCreateUser(userRequest);

      AdminSetUserPasswordRequest adminSetUserPasswordRequest =
              new AdminSetUserPasswordRequest().withUsername(email)
                      .withUserPoolId(userPoolId).withPassword(password).withPermanent(true);

      cognitoClient.adminSetUserPassword(adminSetUserPasswordRequest);
    } catch (AWSCognitoIdentityProviderException e) {
      System.out.println(e.getErrorMessage());
    } catch (Exception e) {
      System.out.println(e);
    }

  }

Seems like .withPermanent(true) doesn't work.
Also currently I am creating a user with one call and setting the password (AdminSetUserPasswordRequest()) with another. Is there a simpler way of doing it?

A: I was surprised how long it took me to actually find a solution to something quite trivial as creating a user without a temporary password.
public static void signUpUser(String email, String password) {
    AWSCognitoIdentityProvider cognitoClient = setUpCognitoClient();
    try {
      SignUpRequest signUpRequest = new SignUpRequest().withUsername(email).withPassword(password).withClientId("xxx");
      cognitoClient.signUp(signUpRequest);
    } catch (AWSCognitoIdentityProviderException e) {
      System.out.println(e.getErrorMessage());
    } catch (Exception e) {
      System.out.println(e);
    }
 }

So the difference is stead instead of .adminCreateUser I'm using .signUp.
In this case you will need your clientId (which is not your pool id!) - .withClientId("xxx").
Tip: switch to the old view of Cognito console to find the client id faster - if will be under App Clients tab on the left side menu.
After sign up the user will be not confirmed and not verified and will receive an email with the code to verify email (not temporary password).
btw, my verification email landed in spam - so look there if you got no email.


text:
Q: Draw on a PDF using Swift on macOS My goal is to write text on a PDF, like an annotation.
I achieved it transforming the PDFPage to a NSImage, I drew on the NSImage then I saved the PDF formed by the images.
let image = NSImage(size: pageImage.size)
image.lockFocus()

let rect: NSRect = NSRect(x: 50, y: 50, width: 60, height: 20)
"Write it on the page!".draw(in: rect, withAttributes: someAttributes)

image.unlockFocus()

let out = PDFPage(image: image)

The problem is obviously that out (the new page of the output PDF) is a PDFPage of images and not a regular one. So the output PDF is very big in size and you can't copy and paste anything on it. It's just a sequence of images.
My question is if there's a way to add simple text on a PDF page programmatically without using NSImage. Any idea?
Note: There's this class in iOS programming UIGraphicsBeginPDFPageWithInfo which could be very helpful in my case. But I can't find the similar class for macOS development.

A: You can create a PDF graphics context on macOS and draw a PDFPage into it. Then you can draw more objects into the context using either Core Graphics or AppKit graphics.
Here's a test PDF I created by printing your question:

And here's the result from drawing that page into a PDF context, then drawing more text on top of it:

Here's the code I wrote to transform the first PDF into the second PDF:
import Cocoa
import Quartz

let inUrl: URL = URL(fileURLWithPath: "/Users/mayoff/Desktop/test.pdf")
let outUrl: CFURL = URL(fileURLWithPath: "/Users/mayoff/Desktop/testout.pdf") as CFURL

let doc: PDFDocument = PDFDocument(url: inUrl)!
let page: PDFPage = doc.page(at: 0)!
var mediaBox: CGRect = page.bounds(for: .mediaBox)

let gc = CGContext(outUrl, mediaBox: &mediaBox, nil)!
let nsgc = NSGraphicsContext(cgContext: gc, flipped: false)
NSGraphicsContext.current = nsgc
gc.beginPDFPage(nil); do {
    page.draw(with: .mediaBox, to: gc)

    let style = NSMutableParagraphStyle()
    style.alignment = .center

    let richText = NSAttributedString(string: "Hello, world!", attributes: [
        NSFontAttributeName: NSFont.systemFont(ofSize: 64),
        NSForegroundColorAttributeName: NSColor.red,
        NSParagraphStyleAttributeName: style
        ])

    let richTextBounds = richText.size()
    let point = CGPoint(x: mediaBox.midX - richTextBounds.width / 2, y: mediaBox.midY - richTextBounds.height / 2)
    gc.saveGState(); do {
        gc.translateBy(x: point.x, y: point.y)
        gc.rotate(by: .pi / 5)
        richText.draw(at: .zero)
    }; gc.restoreGState()

}; gc.endPDFPage()
NSGraphicsContext.current = nil
gc.closePDF()


text:
Q: How does one use a PIP installed package from GitHub in Command Prompt? I am trying to use the NTS Radio downloader (https://github.com/everdrone/nts) that is available on GitHub.
I have PIP installed all the requirements and the downloader itself. So now it's a matter of using the program to download these free radio shows.
To the best of my knowledge, the author of the program mentions one would have to type "nts" on a line in the command prompt with a valid link and press enter for the program to work. In other words, the act of writing "nts" will execute or import the program for the user to enter whatever it is one wants.
However, when I enter "nts" on the command prompt, I get the message that "nts" "is not recognized as an internal or external command, operable program or batch file." So my question is, what should I enter in the command prompt so that it recalls, imports, or executes the downloader before or in addition to writing "nts" so I can make use of it?
Thank you!

A: The correct syntax to install from a Github repository is:
pip install "git+https://github.com/everdrone/nts"

A: you can install git on your computer. by this you can clone the repository and install it.

*

*go to the repository page on github and press on the button code. Copy the url

*go to your command line and type: git clone [copied url]

*type: cd [name of cloned repository]

*type: pip install .
here is a guide if you don't understand the git clone function or want to learn more about it
this should do it!


text:
Q: Firebase security - updating Firestore ddbb I've got 2 collections: Users and Recipes (1:N)
Recipes have likes which haves users.uid: likes: ['id1', 'id2' ... ]
Knowing this, how can I push just my id and avoid pushing other user ids?

A: If you want to add items to an array in Firestore, you have to read the document, set the contents of the array to whatever you want, then write the entire array back to the document.  There is no push operation on an array field.


text:
Q: Having problems using Pace.js with Flask templates I have a html page that is return by Flask templates, the loading takes 2 minutes, so I tried to use Pace.js to implement a progress bar.
here is my project structure:
project
   -static(folder)
        -js(folder)
             -pace.js
        -css(folder)
             -other.css
             -dataurl.css
   -templates(folder)
        -index.html
   -run.py(file)

index.html
    <!doctype html>

    <title>Popular Flickr Camera</title>

Yes, this is a bit weird, but some browsers don't understand the


text:
Q: Uncaught TypeError: Cannot read property 'arr' of undefined Hello I'm trying to load data from a row in a .csv file on P5JS and I keep getting the error message Uncaught TypeError: Cannot read property 'arr' of undefined. Does anyone know why I may be getting this? I have check to make sure there is nothing wrong with my .csv file.
 var table;
var travel = [];
function preload() {
  table = loadTable("data/travel.csv", "csv", "header");
}
function setup() {
  createCanvas(400,400);
  textSize(24);
  travel = table.getRow(1).arr;
}

function draw(){
  background(255);
  translate(0,height/1);

  for(var i = 1; i < travel.length; i++){
    translate(25,0);
    push();
    rect(0,0,20,travel[i] * 5.0);
  }
}

A: I ran your script with my own csv file and it worked as expected. So, I suspect the problem is in your file. You should start by trying the same code with a different csv file (grabbed from the internet or wherever).
However, I did some searching around and have found a couple of issues noted with load--() P5 functions and the preload() function. If you're still having no luck with this after replacing the csv file, I would try rewriting the script with a callback function rather than using the preload() function. Hope this helps.


text:
Q: Stacked ybar plot creates additional empty y-entries I have this code:
\documentclass{scrartcl}

\usepackage{pgfplots}
\pgfplotsset{
  compat=1.16,
  table/col sep=comma}

\usepackage{filecontents}
\begin{filecontents*}{data.csv}
Type, fillA, fillC, preAllocA, preAllocC
off, 10, 20, 0, 0
tree, 4, 5, 6, 4
computed, 6, 5, 4, 8
\end{filecontents*}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[ybar stacked,
    symbolic x coords={off, tree, computed},
    x tick label style={rotate=45,anchor=east}]
    \legend{FillA, FillC, preAllocA, preAllocC}

    \addplot+ table[y=fillA]{data.csv};
    \addplot+ table[y=fillC]{data.csv};
    \addplot+ table[y=preAllocA]{data.csv};
    \addplot+ table[y=preAllocC]{data.csv};
  \end{axis}
\end{tikzpicture}

\end{document}

The code basically works, but creates an extra category (y-entry) for tree and computed, as can be seen here:

Why is this? How can I prevent it?
One more small question: Is there a way to get rid of the symbolic x coords and have pgfplots take the coords from the first column of the file?
Thanks Again!

A: The perhaps simplest way to prevent pgfplots from adding more ticks is to add xtick=data. See e.g. the examples on p. 97 of the manual.
\documentclass{scrartcl}

\usepackage{pgfplots}
\pgfplotsset{
  compat=1.16,
  table/col sep=comma}

\usepackage{filecontents}
\begin{filecontents*}{data.csv}
Type, fillA, fillC, preAllocA, preAllocC
off, 10, 20, 0, 0
tree, 4, 5, 6, 4
computed, 6, 5, 4, 8
\end{filecontents*}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[ybar stacked,
    symbolic x coords={off, tree, computed},
    xtick=data,
    x tick label style={rotate=45,anchor=east}]
    \legend{FillA, FillC, preAllocA, preAllocC}

    \addplot table[y=fillA]{data.csv};
    \addplot+ table[y=fillC]{data.csv};
    \addplot+ table[y=preAllocA]{data.csv};
    \addplot+ table[y=preAllocC]{data.csv};
  \end{axis}
\end{tikzpicture}
\end{document}

A: Answering also the last part, you can set xtick={0,1,2} (I first tried xtick distance=1 which would be better, but that didn't quite work, at least not on Overleaf), and then add xticklabels from table={data.csv}{Type} to get the ticklabels from the file. Finally, in the plots use x expr to set the x-coordinate, e.g. \addplot+ table[x expr=\coordindex, y=fillA]{data.csv};.

\documentclass{scrartcl}

\usepackage{pgfplots}
\pgfplotsset{
  compat=1.14,% overleaf was still on 1.14, so I changed the compat-setting
  table/col sep=comma
}

\usepackage{filecontents}
\begin{filecontents*}{data.csv}
Type, fillA, fillC, preAllocA, preAllocC
off, 10, 20, 0, 0
tree, 4, 5, 6, 4
computed, 6, 5, 4, 8
\end{filecontents*}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    ybar stacked,
    xtick={0,1,2}, % set explicit tick positions
    xticklabels from table={data.csv}{Type}, % get ticklabels from Type column
    x tick label style={rotate=45,anchor=north east}, % change east to north east
    % just a quick suggestion for the legend layout
    legend columns=2,
    legend cell align=left,
    legend transposed
    ]
    \legend{FillA, FillC, preAllocA, preAllocC}

    % \coordindex corresponds to row number in table, counting from 0
    \addplot+ table[x expr=\coordindex, y=fillA]{data.csv};
    \addplot+ table[x expr=\coordindex, y=fillC]{data.csv};
    \addplot+ table[x expr=\coordindex, y=preAllocA]{data.csv};
    \addplot+ table[x expr=\coordindex, y=preAllocC]{data.csv};
  \end{axis}
\end{tikzpicture}

\end{document}


text:
Q: How to specify a integer value using % in print statement in python? Please fix this code, it is giving an error-
print("\nANSWER THE QUESTIONS BELOW-\n")
name=input("What is your name: ")
age=int(input("What is your age: "))
gender=input("What is your gender: ")
name = name.upper()
print("\nYour name is %s, your age is %d, and you are a %s" %name %age %gender)
print("\n Thank You!!")

A: You supply a single tuple of values, rather than repeating the % operator.
print("\nYour name is %s, your age is %d, and you are a %s" % (name, age , gender))

If you really wanted to chain the operators, each one would have to return a string suitable as an argument for the next. This involves escaping a lot of %s.
 name = "Bob"
 age = 20
 gender = "male"
 print("\nYour name is %s, your age is %%d, and you are a %%%%s" %name %age %gender)

Each operation replaces %% with %, so

*

*The first operation, "..." % name, produces
"\nYour name is bob, your age is %d, and you are a %%s"

*The second operation, "..." % age, produces
"\nYour name is bob, your age is 10, and you are a %s"

The final operation `"..." % gender produces the expected string
    "\nYour name is bob, your age is 10, and you are a male"

A: You can replace your print statement with any of the following:
print("\nYour name is %s, your age is %d, and you are a %s" % (name, age, gender))

print("\nYour name is {}, your age is {}, and you are a {}".format(name, age, gender))

print("\nYour name is {name}, your age is {age}, and you are a {gender}".format(name=name, age=age, gender=gender))

print(f"\nYour name is {name}, your age is {age}, and you are a {gender}")

A: Use a tuple:
print("\nYour name is %s, your age is %d, and you are a %s" % (name, age , gender))

Or, with str.format:
print("\nYour name is {}, your age is {}, and you are a {}".format(name, age, gender))

Or, with an f-string:
print(f"\nYour name is {name}, your age is {age}, and you are a {gender}")


text:
Q: Adjust arrow position to match the middle of the referencing element I have two elements, a reference element, illustrated by a black, rounded button, and a wider component, that resembles a popover, with a pointer. Unlike most popovers on the internet, I decided to go with relative positioning, because I want it to continue occupying the space.
The problem is that, by using react-popper, it seems like it can't handle the positioning too well. If you take a look at the Sandbox sample below, the arrow is not pointing towards the middle of the rounded button.
The components code, nothing special, just made this to illustrate my big problem. Here's the button, pretty basic.
import { forwardRef } from "react";

export const RoundedBtn = forwardRef(({ children }, ref) => {
  return (
    <button className="btn" ref={ref}>
      {children}
    </button>
  );
});

And the Popover
import { forwardRef } from "react";

export const Popover = forwardRef(
  ({ title, footer, popoverProps, children }, ref) => {
    const { popperStyles, arrowStyles } = popoverProps;

    return (

        {title && {title}}
        {children}
        {footer && {footer}}

    );
  }
);

Forwarded refs in both components, in Popover I'm using the popper styles to apply it to the arrow (I haven't done so to the Popover container, because it applies position: absolute to it and I don't want it).
In App.js, again, simple:

export default function App() {
  const [refEl, setRefEl] = useState(null);
  const [popOverRef, setPopoverRef] = useState(null);

  const {
    styles: { popper, arrow }
  } = usePopper(refEl, popOverRef, {
    placement: "top"
  });

  const popoverProps = {
    popperStyles: popper,
    arrowStyles: arrow
  };

  return (

      <RoundedBtn ref={setRefEl}>+</RoundedBtn>
      <Popover
        popoverProps={popoverProps}
        ref={setPopoverRef}
        title={title}
        footer={footer}
      >
        {content}
      </Popover>

  );
}

Just using usePopper hook and setting its needed refs.
But, please see this live because it's not aligned correctly.
https://codesandbox.io/s/frosty-tess-jtz61e
Can you instruct me what steps to take in order to fix this? It shouldn't matter the technique we use to move the ref and popper elements, we can use align-items: center (which oddly seems to work fine with the arrow), or align-items: flex-end, the arrow should still be pointing at the referencing element, or very approximately.
Please help, I would very much appreciate it, it's been driving me insane.

A: pass this CSS property for the second popover
transform: translate(8px, 0px);