text:
Q: Trying to run a test suite but Jenkins not pulling down the latest code I am running a test suite using Jenkins and I have configured a job to do that. I have a pipeline script that is doing all the steps, but it seems that with the latest release on LIVE by adding a new button on the LIVE, my tests run a version of the code that does not have that button and it seems that it's not pulling the latest code. What am I doing wrong in the script?
I have tried in pulling down the latest code from Bitbucket, but with no success and building the branch by doing 'docker-compose build --build-arg BRANCH=${branch} apache'
node {
   stage('Pull latest Docker repo') {
      git credentialsId: 'xyz',
          url: 'git@bitbucket.org:domain/myportal-docker.git'
   }
   stage('Install app') {
      sh 'docker-compose down'
      sh 'docker-compose build --no-cache mysql'
      if (params.buildapp == true){
        sh 'docker-compose build --build-arg BRANCH=${branch} apache'
      }
      sh 'docker-compose up -d'
   }
   stage('Set up Selenium') {
      try {
        sh 'docker rm selenium -f'
      }
      catch(exc) {
        echo 'No selenium container running'
      }
      sh 'docker pull selenium/standalone-chrome'
      sh 'docker run -d -p 4444:4444 --name=selenium --net=host -v /dev/shm:/dev/shm selenium/standalone-chrome:3.141.59-dubnium'
   }
   stage('Load tests') {
      dir("../") {}
      git credentialsId: 'xyz',
          url: 'git@bitbucket.org:domain/my-tests.git'
   }
   stage('Run tests') {
      sh 'composer install'
      sh 'vendor/bin/codecept --debug run --steps tests/jenkins'
   }
}

Tests are running fine, but somehow they don't run on the latest code, they run against the master branch but it does not have the latest code.
Also I have an On demand job that I want to try and mess around with it once have some info maybe from some of you with this.

A: params.buildapp is false so it isn't building the apache container. The code only gets pulled from your repo when this container gets built.

A: probably has to do with your Dockerfile
you need to make sure you close your file with ADD ./yourcodefolder

A: @teddym6 now it looks like this, my Dockerfile:
FROM webdevops/php-apache:7.1
ARG WWW_ROOT
ARG APP_DIR
ARG APP_ROOT=${WWW_ROOT}/${APP_DIR}
ARG BRANCH
ENV WEB_DOCUMENT_ROOT=${APP_ROOT}/htdocs
RUN mkdir /root/.ssh/
ADD ./.ssh/ /root/.ssh/
RUN chmod -R 0600 /root/.ssh/*
RUN echo "Using branch ${BRANCH} for code"
RUN git clone --branch ${BRANCH} --depth 1 git@bitbucket.org:domain/myportal-docker.git ${APP_ROOT}
WORKDIR ${APP_ROOT}
RUN mkdir -p runtime htdocs/assets
RUN chmod -R a+w runtime htdocs/assets
WORKDIR /usr/src/app
COPY app/local.php ${APP_ROOT}/config/local.php
ADD . /usr/src/app
WORKDIR /usr/src/app

A: back to this as it's giving me a headache, so the console output looks like this:
  Started by timer
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/jobs/Autotest/workspace
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Pull latest Docker repo)
[Pipeline] git
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url git@bitbucket.org:domain/myportal-docker.git
 # timeout=10
Fetching upstream changes from git@bitbucket.org:domain/myportal-docker.git
 > git --version # timeout=10
using GIT_SSH to set credentials Jenkins Portal Tests Repo
 > git fetch --tags --progress git@bitbucket.org:domain/myportal-docker.git +refs/heads/*:refs/remotes/origin/*
 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision 20cdc207dc87e736983d6b28b5a81853c7c37f70 (refs/remotes/origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 20cdc207dc87e736983d6b28b5a81853c7c37f70
 > git branch -a -v --no-abbrev # timeout=10
 > git branch -D master # timeout=10
 > git checkout -b master 20cdc207dc87e736983d6b28b5a81853c7c37f70
Commit message: "Got rid of the WORKDIR"
 > git rev-list --no-walk 20cdc207dc87e736983d6b28b5a81853c7c37f70 # timeout=10
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Install app)
[Pipeline] sh
[workspace] Running shell script
+ docker-compose down
Stopping workspace_apache_1 ...
Stopping workspace_mysql_1  ...
[2A[2K
Stopping workspace_apache_1 ... [32mdone[0m
[2B[1A[2K
Stopping workspace_mysql_1  ... [32mdone[0m
[1BRemoving workspace_apache_1 ...
Removing workspace_mysql_1  ...
[1A[2K
Removing workspace_mysql_1  ... [32mdone[0m
[1B[2A[2K
Removing workspace_apache_1 ... [32mdone[0m
[2BRemoving network workspace_frontend
Removing network workspace_backend
[Pipeline] sh
[workspace] Running shell script
+ docker-compose build --no-cache mysql
Building mysql
Step 1/2 : FROM mysql:5.7.24
 ---> ba7a93aae2a8
Step 2/2 : ADD mysql.cnf /etc/mysql/mysql.conf.d/mysql.cnf
 ---> cd3843490228
Successfully built cd3843490228
Successfully tagged workspace_mysql:latest
[Pipeline] echo
Will deploy from feature/docker-enablement
[Pipeline] echo
BuildApp Param false
[Pipeline] sh
[workspace] Running shell script
+ docker-compose up -d
Creating network "workspace_frontend" with the default driver
Creating network "workspace_backend" with the default driver
Creating workspace_mysql_1 ...
Creating workspace_mysql_1
[1A[2K
Creating workspace_mysql_1 ... [32mdone[0m
[1BCreating workspace_apache_1 ...
Creating workspace_apache_1
[1A[2K
Creating workspace_apache_1 ... [32mdone[0m
[1B[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Set up Selenium)
[Pipeline] sh
[workspace] Running shell script
+ docker rm selenium -f
selenium
[Pipeline] sh
[workspace] Running shell script
+ docker pull selenium/standalone-chrome
Using default tag: latest
latest: Pulling from selenium/standalone-chrome
Digest: sha256:c478febf26729b7cc27e2fac7d10fa79cf2519b5ab83f9cf82705248258b6495
Status: Image is up to date for selenium/standalone-chrome:latest
[Pipeline] sh
[workspace] Running shell script
+ docker run -d -p 4444:4444 --name=selenium --net=host -v /dev/shm:/dev/shm selenium/standalone-chrome:3.141.59-dubnium
WARNING: Published ports are discarded when using host network mode
952481c15140f1b9fe797cbee495268d7fd191c4ec07194297e19b27109f829a
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Load tests)
[Pipeline] dir
Running in /var/lib/jenkins/jobs/Autotest
[Pipeline] {
[Pipeline] }
[Pipeline] // dir
[Pipeline] git
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url git@bitbucket.org:domain/myportal-docker.git
 # timeout=10
Fetching upstream changes from git@bitbucket.org:domain/myportal-docker.git
 > git --version # timeout=10
using GIT_SSH to set credentials Jenkins Portal Tests Repo
 > git fetch --tags --progress git@bitbucket.org:domain/myportal-docker.git +refs/heads/*:refs/remotes/origin/*
 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision a5ddc6742c13e3b8c37e7ebda625fd8d89b1386a (refs/remotes/origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f a5ddc6742c13e3b8c37e7ebda625fd8d89b1386a
 > git branch -a -v --no-abbrev # timeout=10
 > git branch -D master # timeout=10
 > git checkout -b master a5ddc6742c13e3b8c37e7ebda625fd8d89b1386a
Commit message: "Commented out the forum request button test"
 > git rev-list --no-walk a5ddc6742c13e3b8c37e7ebda625fd8d89b1386a # timeout=10
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Run tests)
[Pipeline] sh
[workspace] Running shell script
+ composer install
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Generating autoload files
[Pipeline] sh
[workspace] Running shell script
+ vendor/bin/codecept --debug run --steps tests/jenkins
Codeception PHP Testing Framework v2.5.2
Powered by PHPUnit 6.5.13 by Sebastian Bergmann and contributors.
Running with seed:

After all of the above, the tests run normally, but as this thread says, not on the latest code.


text:
Q: Loop through specific columns in dataframe I have a dataframe that I'm trying to loop through, printing out the values from each dataframe... I'm new to R and am more familiar with python and javascript so I'm gonna pseudo-code what I'm trying to say here:
df <- read.table(text="
              a     b    c    d     e      f       g
              1     5    6    7     3      4       7
              3     2    8    4     1      9       4
              6     5    2    5     4      6       1
         ",header=TRUE,stringsAsFactors = FALSE)

my javascript mentality...(I only want to select from columns 4 and on):
for (i = 3; i < df.length; i++) {
     console.log(i)
}

and it would return to me
              d     e      f       g
              7     3      4       7
              4     1      9       4
              5     4      6       1

to understand this better, I'm making a dashboard where when I hover over certain data points only values from certain columns are being displayed in a tooltip, which is why i still need to keep the original dataframe without shortening it, yet write an algorithm that will return values from specific columns in the dataframe just for the tooltip

A: Here are two different ways two subset a dataframe:
# by column numbers
df[, 4:7]

# by column names
names <- c("d", "e", "f", "g")
df[names]

A: Try this: df[,c(3,4,5,6)]
And check out this link: https://dzone.com/articles/learn-r-how-extract-rows
I'm not sure if this is what you are asking.

A: You can run a loop over with a conditional to loop:
for (column in dataFrame) {
if(column %% 2 == 0){
for (entry in rawdata[,column]) {
#run your code here, it will impact ever second column
  }
 }
}

Change the 0 to a 1 in order to do it for every odd column.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Missing } inserted when using newenvironment \begin{block}{Command} \newcolumntype{R}{>{\raggedleft\arraybackslash}X}
    \begin{tabularx}{\textwidth}{*{2}{@{}l}@{}R}
        1 & 2 & 3
    \end{tabularx}
\end{block}

Since this is a bit cumbersome, I want to use \newenvironment to make things easier.
\documentclass[10pt]{beamer}

\usepackage{tabularx}

\newenvironment{Command}[1]
{\begin{block}{Command}%
    \newcolumntype{R}{>{\raggedleft\arraybackslash}X}%
    \begin{tabularx}{\textwidth}{*{#1}{@{}l}@{}R}%
}{  \end{tabularx}%
\end{block}}

\begin{document}

% THIS IS CORRECT
% \begin{block}{Command} \newcolumntype{R}{>{\raggedleft\arraybackslash}X}
%     \begin{tabularx}{\textwidth}{*{2}{@{}l}@{}R}
%         1 & 2 & 3
%     \end{tabularx}
% \end{block}

% THIS IS INCORRECT
\begin{Command}{2}
        1 & 2 & 3
\end{Command}

\end{document}

This is what I've tried, but it doesn't work, and the error message is
! Missing } inserted.
<inserted text>
}
l.nn        \end{tabularx}

EDITED
According to the thread @TeXnician mentioned, I tried
\newenvironment{Command}[1]
{   \newcolumntype{R}{>{\raggedleft\arraybackslash}X}%
    \tabularx{\textwidth}{#1}%
}{  \endtabularx}

and it does work. However, if \begin{block}\end{block} are added, the warning pops up:
! Undefined control sequence.
\endbeamercolorbox ->\ifdim \beamer@colbox@sep
                                               =0pt\else \vskip \beamer@colb...
l.nn ^^I\end{block}

A: You can try with the environ package:
\documentclass[10pt]{beamer}
\usetheme{warsaw}
\usepackage{tabularx}
\newcolumntype{R}{>{\raggedleft\arraybackslash}X}
\usepackage{environ}

\NewEnviron{Command}[1]
{\begin{block}{command} %
    \begin{tabularx}{\textwidth}{*{#1}{@{}l}@{}R}%
    \BODY
    \end{tabularx}
 \end{block}
}

\begin{document}

\begin{frame}

\begin{Command}{2}
     1 & 2 & 3 \\
     abc & abc & abc
\end{Command}

\end{frame}

\end{document}

Update 3/2019:
It also works with the new xparse version and its new b-type argument:
\documentclass[10pt]{beamer}
\usetheme{warsaw}
\usepackage{tabularx}
\newcolumntype{R}{>{\raggedleft\arraybackslash}X}

\usepackage{xparse}
\NewDocumentEnvironment{Command}{m b}
{\begin{block}{command} %
    \begin{tabularx}{\textwidth}{*{#1}{@{}l}@{}R}%
    #2
    \end{tabularx}
 \end{block}
}

\begin{document}

\begin{frame}

\begin{Command}{2}
     1 & 2 & 3 \\
     abc & abc & abc
\end{Command}

\end{frame}

\end{document}


text:
Q: How to "session.getAttribute" when using @SessionAttributes I know the "pet" object below is stored to session by using @SessionAttributes, but can I use session.getAttribute ? (such as ..  Pet pet = (Pet)session.getAttribute("pet")). I am not sure why I do not need a "Session Key". (We have to define the key when using session.setAttribute("id", id))
    @Controller
    @RequestMapping("/editPet.do")
    @SessionAttributes("pet")
    public class EditPetFormController {

        @Autowired
        private final Clinic clinic;

        @RequestMapping(method = RequestMethod.GET)
        public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
            Pet pet = this.clinic.loadPet(petId);
            model.addAttribute("pet", pet);
            return "petForm";
        }

A: Session attributes configured via @SessionAttributes are intended to be accessed as model attributes rather than by calling methods of Session directly, therefore their names are generated from the model attribute names automatically.
By default, session attribute name is the same as the model attribute name, so you can access it as session.getAttribute("pet") (see DefaultSessionAttributeStore).


text:
Q: Undefined method for nil I'm trying to finish the codecademy ruby on rails track. I'm getting this error:
Showing /home/ccuser/workspace/learn-rails_innovation-cloud/innovation
cloud/app/views/signups/new.html.erb where line #41 raised:

undefined method `content' for #<Signup id: nil, email: nil, created_at: nil,        updated_at: nil>
Extracted source (around line #41):

      <%= form_for(@signup) do |f| %>

            <%= f.label :message %>

            <%= f.text_area :content %>

            <%= f.submit "Create" %>

Here's my controller:
        class SignupsController < ApplicationController

            def new
                @signup = Signup.new
            end

        end

And finally my migration file:
class CreateSignups < ActiveRecord::Migration
              def change
                create_table :signups do |t|
                  t.text :email
                  t.timestamps
                end
              end
end

Any insight is appreciated to understand what I'm doing wrong.

A: content field is missing in your signups table. Please add using migration.

A: Your form code should look like:
<%= form_for(@signup) do |f| %>

        <%= f.label :email %>

        <%= f.text_field :email %>

<%= f.submit "Create" %>

And it should work now.


text:
Q: How to get the difference between next and previous row in an R time series? I have a quite large time series comprising around 14k observations of 4 variables (date, x, y, z).
How can I, (contrary to the function diff( df$vector, lag = 1) which computes the difference between the current value (t) and the previous one (t-1)),   calculate for each value the difference between the next value (t+1) and the previous value (t-1)?

A: So, to understand the request... Generate some data:
set.seed(11)
a = sample(1:10, 10)

Data is given as:
3  1  5  9  7  8  6  4  2 10

Need T+1 vs. T-1:
T = 0 => No computation
T = 1 => 5 - 3 = 2
T = 2 => 9 - 1 = 8
...
T = 9 => 10 - 4 = 6
T = 10 => No computation

With that being established...
#' Future Difference
#'
#' Obtain the lagged difference between X[t+1+lag] - X[t-1-lag]
#' @param x   A \code{vec}
#' @param lag A \code{integer} indicating the lag
#' @return A \code{vec} with differences taken at T+lag v. T-lag
#' @examples
#' set.seed(11)
#' a = sample(1:10, 12)
#' fdiff(a)
fdiff = function(x, lag = 1){
  # Number of obs
  n = length(x)

  # Trigger error to prevent subset
  if(n < 2+lag){stop("`x` must be greater than `2+lag`")}

  # X_(T+1) - X_(T-1)
  x[(2+lag):n] - x[1:(n-lag-1)]
}

Calling it on a gives:
fdiff(a)

2  8  2 -1 -1 -4 -4  6

A: If I understand your question correctly, all you want is to set lag = 2.

A: What you are looking for is diff of 2 ! (You should use diff not lag as suggested by @Kake_Fisk.) Using the data from the accepted answer from @Coatless:
set.seed(11)
a = sample(1:10, 10)
diff(a,2)

gives:
[1]  2  8  2 -1 -1 -4 -4  6

edit after comment from OP:
If I understand your comment correctly your accepted answer from @coatless does not give you what you were asking for. You are looking for a series which gives you the previous and next differences of each element to it's neighbours. So the length of this series has to be 2 times minus 2 ( as the first element has no previous value and the last one no next value ) of the original series.
One possible solution might be:
set.seed(11)
a = sample(1:10, 10)
a
[1]  3  1  5  9  7  8  6  4  2 10

prev <- a[1:(length(a)-1)] - a[2:length(a)] # series of previous values
nxt <- -1 * prev # series of next values

nextPrevValues <- rep(0,2 * (length(a)-1))
for(i in 1:length(a)-1){
  nextPrevValues[2*i-1] <- nxt[i]
  nextPrevValues[2*i] <- prev[i]
}

Starting with the difference from the first element to the next you get the previous and next differences for each element. The last element only has a previous value.
nextPrevValues
 [1] -2  2  4 -4  4 -4 -2  2  1 -1 -2  2 -2  2 -2  2  8 -8


text:
Q: ask user to reenter input if there is an error in python I am working on a program in python to convert from any number base to any number base. My code is as follows
num = raw_input("Please enter a number: ")
base = int(raw_input("Please enter the base that your number is in: "))
convers = int(raw_input("Please enter the base that you would like to convert to: "))
if (64 < convert < 2 or 64 < base < 2):
    print "Error! Base must be between 2 and 32."
    sys.exit()
symtodig = {
    '0': 0,
    '1': 1,
    '2': 2,
    '3': 3,
    '4': 4,
    '5': 5,
    '6': 6,
    '7': 7,
    '8': 8,
    '9': 9,
    'A': 10,
    'B': 11,
    'C': 12,
    'D': 13,
    'E': 14,
    'F': 15,
    'G': 16,
    'H': 17,
    'I': 18,
    'J': 19,
    'K': 20,
    'L': 21,
    'M': 22,
    'N': 23,
    'O': 24,
    'P': 25,
    'Q': 26,
    'R': 27,
    'S': 28,
    'T': 29,
    'U': 30,
    'V': 31,
    'W': 32,
    'X': 33,
    'Y': 34,
    'Z': 35,
    'a': 36,
    'b': 37,
    'c': 38,
    'd': 39,
    'e': 40,
    'f': 41,
    'g': 42,
    'h': 43,
    'i': 44,
    'j': 45,
    'k': 46,
    'l': 47,
    'm': 48,
    'n': 49,
    'o': 50,
    'p': 51,
    'q': 52,
    'r': 53,
    's': 54,
    't': 55,
    'u': 56,
    'v': 57,
    'w': 58,
    'x': 59,
    'y': 60,
    'z': 61,
    '!': 62,
    '"': 63,
    '#': 64,
    '$': 65,
    '%': 66,
    '&': 67,
    "'": 68,
    '(': 69,
    ')': 70,
    '*': 71,
    '+': 72,
    ',': 73,
    '-': 74,
    '.': 75,
    '/': 76,
    ':': 77,
    ';': 78,
    '<': 79,
    '=': 80,
    '>': 81,
    '?': 82,
    '@': 83,
    '[': 84,
    '\\': 85,
    ']': 86,
    '^': 87,
    '_': 88,
    '`': 89,
    '{': 90,
    '|': 91,
    '}': 92,
    '~': 93}

digits = 0
for character in num:
assert character in symtodig, 'Found unknown character!'
value = symtodig[character]
assert value < base, 'Found digit outside base!'
digits *= base
digits += value

digtosym = dict(map(reversed, symtodig.items()))

array = []
    while digits:
    digits, value = divmod(digits, convers)
    array.append(digtosym[value])
answer = ''.join(reversed(array))

print "Your number in base", base, "is: ", answer

my code works great, but instead of using
if (64 < convert < 2 or 64 < base < 2):
print "Error! Base must be between 2 and 32."
sys.exit()

id like to take them back to the input for the base variable instead of exiting the program.
I am new to python and have no clue how to do something like this. please help.

A: while True:
    try:
        convert = int(raw_input('Convert: '))
        base = int(raw_input('Base: '))
        if (64 < convert < 2 or 64 < base < 2):
            print "Error! Base must be between 2 and 32."
            continue
        break
    except Exception, e:
        print '>> Error: %s' % e

A: The general template:
while True:
    # get user input
    # ...
    if valid_input():
        break

For example:
def get_int(prompt, lo=None, hi=None):
    while True:
        try:
            n = int(raw_input(prompt))
        except ValueError:
            print("expected integer")
        else: # got integer, check range
            if ((lo is None or n >= lo) and
                (hi is None or n <= hi)):
                break # valid
            print("integer is not in range")
    return n

A: An easy way out would be to simply add a loop at the beginning of the selection: it escapes in case of a valid choice and iterates while it is incorrect (instead of sys.exit(), which is I believe you want to avoid).
The first part could be:
selected = False
while not selected:
    num = raw_input("Please enter a number: ")
    base = int(raw_input("Please enter the base that your number is in: "))
    convert = int(raw_input("Please enter the base that you would like to convert to: "))
    if (64 < convert or convert < 2 or 64 < base or base < 2):
        print "Error! Base must be between 2 and 32."

    else:
        selected = True

In addition, please note that I changed the condition to:
if (64 < convert or convert < 2 or 64 < base or base < 2):


text:
Q: Wordpress mobile homepage lost formatting during server migration I recently migrated my wordpress theme to blog.nearlynewlywed.com.  The site renders fine on desktop, however, the homepage on mobile has lost all formatting.  Just the homepage.  Interior pages on mobile are fine.
It looks like the site is displaying a mobile theme template but I'm not sure and honestly I can't figure out how to identify the cause.

A: Probably you are using some conditionals to select the correct style sheets, and some of them could be missing or pointing to a wrong url.
Use firebug and in the "Net" tab check if something is missing or giving any error.


text:
Q: Implementing OAuth in asp.net error with context.RunClaimsAction(user) I am trying to implement oauth in asp.net 3.0, and I understand there were some changes as regards to changes to the Newtonsoft.Json types replaced in Microsoft.AspNetCore.Authentication APIs link here
It does not accept a JObject of the user's claims and throws an error when you try to pass a JObject as a parameter to the RunClaimActions(user) and does not throw an error when you run the method without passing the user JObject parameter in the method. The result is that it does not return the User claims to the view. Has anyone faced this problem yet ? Is there a way to convert a newtonsoft JObject to a JsonElement.
options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
                options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
                options.ClaimActions.MapJsonKey("urn:github:login", "login");
                options.ClaimActions.MapJsonKey("urn:github:url", "html_url");
                options.ClaimActions.MapJsonKey("urn:github:avatar", "avatar_url");

                options.Events = new OAuthEvents
                {
                    OnCreatingTicket = async context =>
                    {
                        var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

                        var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
                        response.EnsureSuccessStatusCode();

                        var user = JObject.Parse(await response.Content.ReadAsStringAsync());
                        context.RunClaimActions(user);

                    }

                };
            });

A: After some reading, I solved the issue by using the JsonDocument for parsing the claims and passing the root document to the RunClaimActions method.
    options.Events = new OAuthEvents
                {
                    OnCreatingTicket = async context =>
                    {
                        var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

                        var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
                        response.EnsureSuccessStatusCode();

                        var user = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
                        context.RunClaimActions(user.RootElement);

                    }


text:
Q: php - How to exec in background multiple bash command I'm trying to run in background two bash command using exec function.
 $action[] = "/path/script1 par1 > log1 2>&1";
 ...
 $action[] = "/path/script2 par2 > log2 2>&1";
 ...
 $cmd = "( " .implode(' && ',$action). " ) &";
 exec($cmd);

script1 and script2 are bash scripts.
Scripts are properly executed and their output is correctly saved in their log files, but my application hangs. It seems that last & doesn't work.
I have already tried:
 $cmd = "bash -c \"" .implode(' && ',$action). "\" &";

If I run a single command, it works in background.
I captured $cmd and if I run:
 ( /path/script1 par1 > log1 2>&1 && /path/script2 par2 > log2 2>&1 ) &

from command line, it works in background.
I'm using Apache/2.0.52 and PHP/5.2.0 on Red Hat Enterprise Linux AS release 3 (Taroon Update 2)

A: The answer is hidden in the PHP exec documentation:

If a program is started with this function, in order for it to
  continue running in the background, the output of the program must be
  redirected to a file or another output stream. Failing to do so will
  cause PHP to hang until the execution of the program ends.

Add a redirection to the top level of your command line:
exec( "bash -c \"( ./script1 par1 > log1 2>&1 && ./script2 par2 > log2 2>&1 ) \" >/dev/null 2>&1 & " );

and without bash -c:
exec( "( ./script1 par1 > log1 2>&1 && ./script2 par2 > log2 2>&1 ) >/dev/null 2>&1 & " );

Tested with PHP 5.3.3-7 (command line invocation): Program hangs before adding the redirect operators, and terminates afterwards.


text:
Q: Converting Ubuntu Legacy with Windows installed I made a Bootable USB with Rufus, but my Ubuntu boot is on UEFI while my Windows is on Legacy. How do I convert my Ubuntu to Legacy? I don't have Separate/boot/efi partition, as seen on boot repair. I'm currently running a live USB

A: Several options

*

*Convert Windows to UEFI boot (GPT) in command  prompt (search cmd in taskbar -> right click run as admin -> type in using mbr2gpt.exe /convert /allowfullOS in Windows ,  make sure you switch your bios settings to  uefi boot! , othewise it wont boot (may need to select windows efi boot on efi partition  driveletterwitharound100mbspace:/EFI/Microsoft/Boot/bootmgfw.efi)

*Reinstall grub(on linux) on mbr  (legacy) to enable dual boot windows + linux , note  you will loose windows boot loader .
**Highly recommend having a live linux live usb + windows usb installer (make one now) just incase it goes pear shaped.


text:
Q: The request was missing an Authentication Key. Please, refer to section "Authentication" with IHttpClientFactory I'm trying to send an HTTP request from .NET Core 3.1 REST API to another API but below Exception keep appeared Although I'm already added the Authentication Key :
The request was missing an Authentication Key. Please, refer to section "Authentication"
here is my code :
public class AppService
    {

        private readonly IHttpClientFactory _clientFactory;
        string key = "key=llllll ......";
        string webAPIKey = "......";
        string Id = "......";

        public AppService(IHttpClientFactory clientFactory) {
            _clientFactory = clientFactory;

        }

public async Task<string> sendBroadCastNotification()
        {
            Data _data = new Data();
            _data.title = "test data Ttile";
            _data.detail = "test data detail";
            Notification _notification = new Notification();
            _notification.title = "test notification Ttile";
            _notification.body = "test notification body";

            MyNotification NotifcationData = new MyNotification {
            data=_data,
            notification=_notification,
            to= "/topics/all"
            };

            try {

            var client = _clientFactory.CreateClient();

            client.DefaultRequestHeaders.Add("project_id", Id );
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", key);

                StringContent bodyOfRequest = new StringContent(System.Text.Json.JsonSerializer.Serialize(NotifcationData ), Encoding.UTF8, "application/json");

            using var httpResponse =
          await client.PostAsync("https://.......", bodyOfRequest);

                var result = httpResponse.Content.ReadAsStringAsync().Result;

                return result;
            }
            catch (Exception ex)
            {
                throw new System.ArgumentException(ex.Message.ToString(), "original");

            }
            //return null;

        }

}

A: I found the answer here in this link:
I add the key by using the below line:
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", key);

the below way that I was trying to add the authorization header wasn't understandable as an authorization header :
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", key);


text:
Q: Logging requests on high traffic websites I wonder how high traffic websites handle traffic logging, for example a website like myspace.com receives a lot of hits, I can imagine it would take a lot of space to log all those requests, so, do they log every single request or how do they handle this?

A: If you view source on a MySpace page, you get the answer:
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-6293770-1");
pageTracker._setDomainName(".myspace.com");
pageTracker._setSampleRate("1"); //sets sampling rate to 1 percent
pageTracker._trackPageview();
</script>

That script means they're using Google Analytics.
They can't just gauge traffic using IIS logs because they may sell ads to third parties, and third parties won't take your word for how much traffic you get.  They want independent numbers from a separate company, and that's where Google Analytics comes in.
Just for future reference - whenever you've got a question about how a web site is doing something, try viewing the source.  You'd be amazed at what you can find there in plain view.

A: We had a similar issue with out Intranet which is used by hundreds of people. The disk activity was huge and performance was being hurt.
The short answer is Asynchronous non-blocking logging.

A: probably like google analytics.
Use Javascript to load a page on a difference server, etc.

A: Don't how they track it since I don't work there. I am pretty sure that they have enough storage to record every little thing about their user if they wanted.
If I were them, I would use AwStats if I just wanted to know basic stuff about my users.
It is more likely that they have developed their own scripts for tracking their users. Stuff they would log
-ip_address
-referrer
-time
-browser
-OS
and so on. Then a script to see different data about the user varying by day, weeks, or months. As brulak said, something along the line of Analytics, but since they have access to actual database, they can learn much more about their users.

A: ZXTM traffic shaping and logging, speaking from experience here

A: I'd be extremely surprised if they didn't log every single request, yes, and operations with particularly high traffic volumes usually roll their own log-management solutions against the raw server logs, in some form or other -- sometimes as simple batch-type processes, sometimes as complete subsystems.
One company I worked for, back in the dot-com heyday, got upwards of twenty million pageviews a day; for that site (actually a set of them, running across a few dozen machines in all, as I recall), our ops team wrote a quite sophisticated, clustered solution in C that parsed, translated (into relational storage), compressed and distributed the logs daily.  Log files, especially verbose ones, pile up fast, and the commercial solutions available at the time just couldn't cut it.

A: If by logging you mean for collecting server related information (request and response times, db and cpu usage per request etc) I think they sample only the 10% or 1% of the traffic. That gives the same results (provide developers with auditing information) without filling in the disks or slowing the site down.


text:
Q: Python requests 0.x code port to 2.x I had a really simple piece of code working with Python requests 0.x but when I updated to 2.x it no longer works.
The code would return me the color contained within 'field1':
import time
import requests

# Read the thingspeak feed to get the current colour
while True:
    cheerlights = requests.get('http://api.thingspeak.com/channels/1417/field/1/last.json').json['field1']
    print(cheerlights)
time.sleep(16)

When I run this not I get this error:
Traceback (most recent call last):
  File "cheelightsJsonHELP.py", line 7, in
    cheerlights = requests.get('http://api.thingspeak.com/channels/1417/field/1/last.json').json['field1']
TypeError: 'instancemethod' object has no attribute 'getitem'
I have read the documentation on migrating from 0.x to 2.x but unfortunately this is not a strong area of mine, can anybody help?

A: response.json() is now a method, where in the past it was a property; add () to call it:
response = requests.get('http://api.thingspeak.com/channels/1417/field/1/last.json')
cheerlights = response.json()['field1']

Demo:
>>> import requests
>>> response = requests.get('http://api.thingspeak.com/channels/1417/field/1/last.json')
>>> response.json()['field1']
'orange'


text:
Q: Call to a member function success() on a non-object I have tried many times this error in different ways also tried one sollution from: CakePHP: Call to a member function setFlash() on a non-object url ... But this solution is also not working in my project.
Cant recognize whats the error. !!!
Here is my User.php model
class User extends AppModel {

public $helpers = array('Html','Form');
public $components = array('Email','Flash','Session');

 public function send_mail($useremail){

    $Email = new CakeEmail('gmail');

    $Email->emailFormat('html')
          ->from('abc@xyz.com')
          ->to($useremail)
          ->subject('User subject');
    if($Email->send("123")){
        $this->Flash->success(__('Mail Sent')); // **this line cause error**
    }else{
        $this->Session->setFlash('Problem during sending email');
    }
}
}

A: As the documentation suggest, FlashComponent provides two ways to set flash messages: its __call()magic method and its
set() method. To furnish your application with verbosity, FlashComponent's __call() magic method allows you use a method name that maps to an element located under the src/Template/Element/Flash directory. By convention, camelcased methods will map to the lowercased and underscored element name:

// Uses src/Template/Element/Flash/success.ctp

$this->Flash->success('This was successful');

// Uses src/Template/Element/Flash/great_success.ctp

$this->Flash->greatSuccess('This was greatly successful');

Alternatively, to set a plain-text message without rendering an element, you can use the set() method:
$this->Flash->set('This is a message');

And hence, you need to change it by typing
 $this->Flash->success('Mail sent');


text:
Q: Magento doesn't appear any default email template I'm trying to create a transactional email in magento 1.7, but when I try to add a new template the default template select is empty and I can't continue creating it.

A: The problem comes from the fact that no email is set in the database and you can wether get the data from a clean installation or set it by yourself througth the admin : System > configuration > transactionnal emails.
I would advise you the second solution that is in my opinion safier and permits to define the email as you wish with the design you want to use.
If you do not have any default template in your selectbox, you can check under the app / locale / yourlanguage / template / email if you do not have anything, you should have under the en_US folder. You can copy and adapt. If you have nothing under these two folder, you can get it from a basic installation.


text:
Q: How to filter out daytime image of LANDSAT 8 using google earth engine? I saw an answer here saying that we should sort by 'system:time_start' but shouldn't that refer to the date (like 2015-05-01) instead of hour of the day? I also tried something like ee.Filter.calendarRange(7, 15, 'hour') but it didn't seem to work.

A: About using ee.Filter.calendarRange() - you might have expected that images in certain location will be coming at different hours. In many areas, it's not a case. Also,ee.Filter.calendarRange() is way to go (you should avoid using .sort as suggested in other example for many reasons).
In the example below all the images for given locations were taken between ~10:38-10:41.
I've added an example of using ee.Filter.calendarRange(), showing that it does what it is expected to do.
var l8 = ee.ImageCollection("LANDSAT/LC08/C02/T1_L2"),
    geometry = /* color: #d63000 */ee.Geometry.Point([-1.6843750000000135, 31.62971723875741]);

var ic = l8.filterBounds(geometry)

print("Size of filtered image collection", ic.size())

// What time of the day images were taken?
print("SCENE_CENTER_TIME histogram", ic.aggregate_histogram("SCENE_CENTER_TIME"))

print("Filter includes 10am", ic.filter(ee.Filter.calendarRange(10,17,"hour")).size())
print("Filter excludes 10am", ic.filter(ee.Filter.calendarRange(11,17,"hour")).size())

Here is the link to the example:
https://code.earthengine.google.com/005c8c3616ee0371b6cdf9597d91f095
Next time include an example script illustrating what didn't work for you.
I hope, it helps. Good luck with your analysis!


text:
Q: I have created A new sample REST Api to GET method, Giving Consumer is not authorized to access the resource error As I have created a New sample REST Api Call to method GET please look below details
etc/webapi.xml
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route url="/V1/hello/name/:name" method="GET">
        <service class="Magestore\Magento\Api\HelloInterface" method="name"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magestore\Magento\Api\HelloInterface"
                type="Magestore\Magento\Model\Hello" />
</config>

Api/HelloInterface
<?php
namespace Magestore\Magento\Api;

interface HelloInterface
{
    /**
     * Returns greeting message to user
     *
     * @api
     * @param string $name Users name.
     * @return string Greeting message with users name.
     */
    public function name($name);
}

Model/Hello.php
<?php
namespace Magestore\Magento\Model;
use Magestore\Magento\Api\HelloInterface;

class Hello implements HelloInterface
{
    /**
     * Returns greeting message to user
     *
     * @api
     * @param string $name Users name.
     * @return string Greeting message with users name.
     */
    public function name($name) {
        return "Hello, " . $name;
    }
}

As you can see the below image giving me the consumer is not authorized to access the resource as, the resource type is anonmoys.

Please can anyone help me to solve these,or else give me idea to resolve this.
Advance thanks.

A: You can try it:
etc/webapi.xml
<?xml version="1.0"?>
 <routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
  <route url="/V1/hello/name" method="GET">
    <service class="Magestore\Magento\Api\HelloInterface" method="name"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
   </route>
</routes>

then use api url like:
www.example.com/rest/V1/hello/name/?name=test

Hope this help you.

A: Remove Auth from header it is not needed.
Please flush cache using below command
php bin/magento cache:flush

It is working for me please check below


text:
Q: Convexity of a function with discrete parameters Let $k\in\mathbb N_{>0}$, $n_1,\dots,n_k\in\mathbb N_{>0}$ and $N=\sum_{i=1}^kn_i$.
I would like to know if the following function is convex:
$$
r_{\alpha,\theta}(Z) = \overbrace{\sum_{i=1}^{n-1}\ln(\alpha+i)}^\beta - \overbrace{\sum_{i=1}^{k-1}\ln(\alpha+i\theta)}^{\gamma(k)} - \overbrace{\sum_{c=1}^k\sum_{i=1}^{n_c-1}\ln(i-\theta)}^{\delta(Z)}.
$$
where $\alpha$ and $\theta$ are constants.
I am not sure how I can do this.
At first, I was thinking about relaxing the discreteness of $k$ and $n_i$ but it just doesn't make sense.


text:
Q: Multiply word search I have made a simple search engine that can search my database. It works this way: you check the word you want to search for in a checkbox. Result are sent using a form. The issue is that it only searches for the last word checked. This mean do I check 3 words it's only showing results for the last word checked. Here is my form:
<form method="POST" action="<?=$_SERVER["PHP_SELF"]?>">

Search for:

Books: <input type="checkbox" name='search' value="Books">
Movies: <input type="checkbox" name='search' value="Movies">
Outdoor: <input type="checkbox" name='search' value="Outdoor">
Indoor: <input type="checkbox" name='search' value="Indoor">

<input type='submit'  value='Search'>

</form>

This is my codes that generate the result:
    <?php
if(isset($_POST['search']))
{
  $connx = mysql_connect('localhost', 'USER', 'PASSWORD') or die("connx");
  $db = mysql_select_db('DB_NAME') or die(mysql_error());

  # convert to upper case, trim it, and replace spaces with "|":
  $search = (ini_get('magic_quotes_gpc')) ? stripslashes($_POST['search']) :
            $_POST['search'];
  $search = mysql_real_escape_string($search);
  $search = strtoupper(preg_replace('/\s+/', '|', trim($_POST['search'])));

  # create a MySQL REGEXP for the search:
  $regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";
  $query = "SELECT * FROM `galleries` WHERE UPPER(`keywords1`) $regexp OR ".
           "`keywords2` $regexp";
  $result = mysql_query($query) or die($query . " - " . mysql_error());

echo "
\n";
while($row = mysql_fetch_assoc($result))

{
    echo "
";
    echo "	";
    echo "{$row['name']}	";
    echo "{$row['date']}	";
    echo "View	";
    echo "
\n";
  }
}
?>

Can someone help me telling me how do I get the search engine to search and/or show more than 1 word searched result?

A: You have input fields with same name therefore you are getting the last one you need to make the array for search fields like name="search[]" and the loop through your query against the array values
Books: <input type="checkbox" name='search[]' value="Books">
Movies: <input type="checkbox" name='search[]' value="Movies">
Outdoor: <input type="checkbox" name='search[]' value="Outdoor">
Indoor: <input type="checkbox" name='search[]' value="Indoor">

something like this
$regexp ="";
$searharray =$_POST['search'];
$count=count($searharray);
$index=1;
foreach($searharray as $s){

$s = (ini_get('magic_quotes_gpc')) ? stripslashes($s) :$s;
$s= mysql_real_escape_string($s);
$s = strtoupper(preg_replace('/\s+/', '|', trim($s)));

$regexp .= " UPPER(`keywords1`) REGEXP '[[:<:]](".$s.")[[:>:]]'  OR  `keywords2` REGEXP '[[:<:]](".$s.")[[:>:]]'";
if($index<$count){
  $regexp .=" OR ";
 }
 $index++
}

 $query = "SELECT * FROM `galleries` WHERE $regexp";

A: Problem fixed! I replaced the 2 lines:
$search = mysql_real_escape_string($search);
  $search = strtoupper(preg_replace('/\s+/', '|', ($_POST['search'])));
With:
  $search = implode( '|', $_POST['search'] );
And now its working - just if anyone else should need the info :)


text:
Q: Maven and native library files I have a library that gets used in a mavenized java projects. The library is composed of two parts: a jar that exposes the API, and 3 dlls (native lib). There is a piece of code in the jar that loads the dlls, so the directory where the dlls are located has to be in the PATH environment variable.
Adding the jar to my project was easy. The way I have the dll set up is each developer downloads the dlls into a directory then adds the path-to-dlls to the PATH environment variable.
Ideally I'd like there to be as little set-up possible when a new developer downloads the project. Is there a better way to set the dlls up (without the overhead of downloading them separate from the project, and adding the directory to PATH)?

A: If you can change the loading code of the library: Include the DLLs in your jar/classpath.  Then copy the DLL files to the local file system.  Load from there.  The following assumes library is on the classpath.
public void loadLibrary(String library) throws IOException {
    InputStream source = getClass().getResourceAsStream(library);
    File tempFile = File.createTempFile("javatmp", ".dll");
    FileOutputStream dest = new FileOutputStream(tempFile);
    try {
        IOUtils.copy(source, dest)
    }
    finally {
        dest.close();
        source.close();
    }
    System.load(tempFile.getAbsolutePath());
    tempFile.delete();
}

If you can't change how the library loads DLLs, then you could modify the PATH (using JNA) and copy the DLLs to that location.  The following assumes library is on the root of the classpath.
public void exposeLibrary(String library, File tempDir) throws IOException {
    InputStream source = getClass().getResourceAsStream(library);
    File tempFile = new File(tempDir, library);
    FileOutputStream dest = new FileOutputStream(tempFile);
    try {
        IOUtil.copy(source, dest)
    }
    finally {
        dest.close();
        source.close();
    }
    WinLibc.INSTANCE._putenv("PATH=" +
        System.getenv().get("PATH") + File.pathSeparator + tempDir.getAbsolutePath());

    // After this point System.loadLibrary(library) will load the DLL.
}

public interface WinLibC extends Library {
  static WinLibC INSTANCE = Native.loadLibrary("msvcrt", WinLibC.class);

  public int _putenv(String name);
}

Note: I didn't test any of this. The 2nd solution won't work for Linux (but could with a few changes.)


text:
Q: UIBarButtonSystemItemPageCurl in iOS 5 beta missing In my latest release application, everything looks good on iOS4+, but not on iOS5 Beta.
The only thing that is wrong is that the UIBarButtonSystemItemPageCurl is not shown on iOS5 devices. It shows an empty UIBarButtonItem with style Plain.
It looks good in IB in XCode 4.1, will test on my work computer as well on the BETA XCode tomorrow.
Does anyone know why this happens, or is this a bug in iOS5 beta?
EDIT
The question: If someone else found this too, how can I fix it (the correct way!)?

A: I'm still getting this issue with iOS 5.0 (non-beta). It looks like someone created their own page curl button here:
http://blog.shuningbian.net/2011/01/ios-toolbar-pagecurl-icon.html
Alternatively you can try using this tool to extract the icon from UIKit on a version 4 device:
https://github.com/0xced/UIKit-Artwork-Extractor

A: UIBarButtonSystemItemPageCurl can only be used in toolbars, at the bottom of the screen. Else the button is simply not displayed, like in a navigation bar.


text:
Q: Passing variable as argument I have a python script sms.py and it takes two args:
1) a mobile number
2) a random number
The random number is generated by:
myrandnumber=expr '(' $RANDOM '*' 30  / 32767 ')' + 1
My sh script looks like this:
myrandnumber=`expr '(' $RANDOM '*' 30  / 32767 ')' + 1`

cd /home/janu/programs/

output_filename=output/output-`date +%Y%m%d-%H.%M.%S`.txt
python sms.py -mob 917204785003 --key $myrandnumber > $output_filename

I am not able to get the '$myrandnumber' value.

A: If you made the sms.py script you are beter of using the random lib in the python code:
   import random
   key = random.randint(1,3000) # 1 to 3000 inclusive


text:
Q: Issue when fetch image from gallery Currently, I am using below code to fetch an image from gallery
 Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 galleryIntent.setType("image/*");
 startActivityForResult(galleryIntent, Constants.SELECT_GALLERY);

But the issue is that its also showing GIF file, when open gallery, I want only image files, I have also tried this
galleryIntent.setType("image/jpeg, image/png");

But the result is same. How could I achieve this?

A: Solution:
This solution is from my own project usage:
String[] mimeTypes = {"image/jpeg", "image/png"};
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT)
    .setType("image/*")
    .putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);

then startActivityForResult(galleryIntent, Constants.SELECT_GALLERY);
The Intent.ACTION_GET_CONTENT and image/* asks android to get anything that can open it, i.e. gallery, and the Intent.EXTRA_MIME_TYPES retruns those intent only those MIME types to be selectable.
This will help.


text:
Q: jQuery div animate from left to right and comes back after pause I'm trying to slide a div from the left to the right side when the 'submit' button is clicked. After a little pause, the div would automatically slides back to it's original position. Currently it goes to the right side but it isn't coming back to the left corner.
CSS
#mainform{
    position: absolute;
    display: block;
    padding-top:20px;
    font-family: 'Fauna One', serif;
}

HTML

        <form id="form">

Contact Form

           <input type="button" id="submit" value="Send Message"/>
        </form>

JS
  $(document).ready(function() {
            $('#submit').click(function(e) {
                reslide();

                function reslide() {
                    $('#mainform').delay().animate({width: '510px', left: '1050'}, 600).delay(5000).animate({width: '510px', right: '1000px'}, 200, function() {
                        setTimeout(reslide, 3000);
                    });
                }
                $('.hello').fadeIn(1500);
                $("Successfully send").appendTo(".hello");
                $('.hello').fadeOut(2500);
            });
});

A: When you give feedback to the user after/before submiting, try to use CSS3 Transform instead of actually moving/resizing the object.
function slide($obj) { // jQuery object of element
    $obj.css("transform", "translateX (50px)");
    setTimeout(function(){
      $obj.css("transform", "none");
    }, 5000);
}

To make it smooth (real animation) apply CSS3 Transition property.

Or you can shorten, if you're sure everything'd go smoothly.
function slide($obj) { // jQuery object of element
    $obj.animate("transform", "translateX (50px)")
         .delay(600).
         .animate("transform", "translateX (0px)");
}

PS; in my expirience jQuery.delay(); wasn't always working with queueing animations, i'm not entirely sure why. As a matter of fact, this happened only sometimes. Sometimes tought it wasn't working
// not working
$("smth").animate({"rule":"val"}).delay(500).animate("rule":"val");

// working
$("smth").animate({"rule":"val"})
setTimeout(function(){
   $("smth").animate({"rule":"val"})
}, 1000);

A: The reason it's not working is that, while you add right to the element, you also keep left with its original value, thus the element will not "come back". Add left: '', to the 2nd animate function and you should be good to go:
function reslide() {
    $('#mainform').delay().animate({
        width: '510px',
        left: '1050'
    }, 600).delay(5000).animate({
        width: '510px',
        left: '',
        right: '1000px'
    }, 200, function () {
        setTimeout(reslide, 3000);
    });
}

Here is a fiddle you can play with: http://jsfiddle.net/bv8dwaq2/


text:
Q: CSS files and pictures dosen't show on localhost I made a website, I threw it on hosting and I have a problem. Well, on the hosting, photos and .css files work normally and load normally, but not on localhost.
I noticed that the problem is the path to which he gives to photos or .css files
For example that looks for some image:

And this way works on hosting, but it does not work on localhost. However, when I remove 'public' from the path, it works the other way around. At localhost works and not on hosting.
I have 2 .htaccess files, first on root folder:
<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteRule ^(.*)$ public/ [L]
</IfModule>

And second.. in public folder:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

What can I change to make the tracks work in both sides?

A: Are you using Laravel framework? the syntax looks like a blade template syntax. If yes then you might want to use the asset helper function like so:

Here's the documentation  link


text:
Q: Show that the congruence $x^2 \equiv a \pmod {2^e}$, where $e$ is an integer, $e \geq 3$, has either no solutions or exactly 4 incomgruent solutions. Let $a$ be an odd integer. Show that the congruence $x^2 \equiv a \pmod {2^e}$, where $e$ is an integer, $e \geq 3$, has either no solutions or exactly 4 incongruent solutions.

A: If $x^2\equiv a\pmod{2^e}$ the also $x^2\equiv a\pmod{8}$. A square is odd iff the number itself is odd, and the square of an odd number is always $\equiv1\pmod 8$. Therefore, there is no solution if $a\not\equiv 1\pmod 8$. On the other hand, if $a\equiv 1\pmod 8$ there are exactly four solutions. This can be shown by induction on $e$. Indeed, if $e=3$, then $1,3,5,7\bmod 8$ are the four soulutions. Assume we have exactly four soulutions $x_1, x_2, x_3, x_4$ modulo $2^e$. Then there are at most eight solutions modulo $2^{e+1}$, namely $x_1, x_2, x_3, x_4, x_1+2^e, x_2+2^e, x_3+2^e, x_4+2^e$. But $$(x_i+2^e)^2=x_i^2+2^{e+1}x_i+2^{2e}\equiv x_i^2+2^{e+1}\pmod{2^{e+1}}$$
because $x_i$ is odd, so that of each pair $x_i, x_i+2^e$ there is at most one solution modulo $2^{e+1}$. On the other hand, $x_i^2\equiv a\pmod {2^e}$ implies that $x_i^2\equiv a\pmod {2^{e+1}}$ or $x_i^2\equiv a+2^e\pmod {2^{e+1}}$ so that eihter $x_i$ or $x_i+e^2$ gives us a solution modulo $2^{e+1}$.


text:
Q: New levels not available? New levels are showing ready to build. But when I try to build them, I get told there are none available. I'm using iOS version. Anyone else having this issue. Thanks.

A: Keep trying.  I was able to get several of them about an hour ago on Windows Phone.

A: While there are new levels to build, (One Residential, one Recreational, and 2 Imperial) there are others which are still locked.
I guess we just wait.
I'm on Android.
Note if you choose the option to "Choose specific level", it will show you all the unlocked levels available


text:
Q: How to use ArcGIS Server JavaScript API inside a  tag? I need to embed an ArcGIS Server JavaScript API (version 4) map in a client's Content Management System. For reasons unknown to me, the CMS developers said this results in the map's entire DOM being placed inside a <form> tag.
Doing so prevents the map from loading and displaying, although the JS appears to run correctly.
I've put together a simple demonstration at https://codepen.io/slead/pen/QWWedvd - if you comment/uncomment the <form> tag you can see that placing the map inside the form results in the map not displaying, even though the console logs show that the JS has run.

  <form>

  </form>

// JavaScript
require(["esri/Map", "esri/views/MapView"], function(Map, MapView) {
  console.log("Before");
  var map = new Map({basemap: "streets"});
  var view = new MapView({
    container: "viewDiv",
    map: map,
    zoom: 4,
    center: [15, 65]
  });
  console.log("After");
});

How can I enable the map functionality when the map's elements are located inside a <form>?

A: Actually after all that, this problem was simpler than expected. Giving the form the appropriate CSS seems to solve the problem:
#viewDiv, #frmMap {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}

<form id="frmMap">

</form>


text:
Q: implicit Akka system in Scala trait How can I make my ActorSystem available in ServiceA and ServiceB, this is the code im trying to get get working. It compile but i get a null pointer exception for the implicit system in Tcp.

Why do I get a nullpointer exception and what can i change to get my
  system into my trait services? Why does it compile?

trait ServiceA {
  implicit val system: ActorSystem
}

trait ServiceB {
  implicit val system: ActorSystem
  Tcp().outgo... // Code compile but i get nullpointer exception
}

object Main extends App with ServiceA with ServiceB {
  override implicit val system: ActorSystem = ActorSystem("MySys")
}

A: Constructors of SystemA and SystemB (which uses system) are executed before constructor of Main which includes initialization of system. Use implicit lazy val system = ... in Main (it is allowed to implement an abstract val in this way) and this problem should be fixed.

A: As an addition to answer
by  @alexei_romanov .
What do you want to achieve by placing Tcp... call in a trait body without assigning it to val or def? It is now just an action which is executed at some moment during initialization of Main. It can leat to undefined behavior since it is an action on not yet initialized object.

A: This is caused by the trait initialization order, and it is indeed unfortunate that the type system cannot defend against this.
One option to resolve this is to put the ActorSystem initialization into its own trait and make sure that one gets mixed in first, so:
trait ServiceA {
  implicit val system: ActorSystem
}

trait ServiceB {
  implicit val system: ActorSystem
  Tcp().outgo... // Code compile but i get nullpointer exception
}

trait ActorSystemInitialization {
  val system: ActorSystem = ActorSystem("MySys")
}

object Main extends App with ActorSystemInitialization with ServiceA with ServiceB {

}


text:
Q: Racket: Difference between `range` and `in-range` There are two possibilities to generate a sequence of numbers to be iterated in a for loop in Racket:
(for ([i (range 1 5)])
    (display i))

and
(for ([i (in-range 1 5)])
    (display i))

range and in-range both work and seem to be equivalent, but https://docs.racket-lang.org/reference/sequences.html says:

"An in-range application can provide better performance for number
iteration when it appears directly in a for clause."

Does this also hold true in comparison to range?

A: Yes, range is equally performant as in-range when it syntactically appears directly in for clauses. In fact, range is simply transformed to in-range in that case.
Note that while it's true that range and in-range are functionally equivalent when they appear in for clauses, they are not functionally equivalent in general.
> (range 5)
'(0 1 2 3 4)
> (in-range 5)
#<stream>


text:
Q: custom .desktop entry to launch Minecraft not working I have made a Minecraft.desktop file in ~/.local/share/applications/ that reads as follows:
[Desktop Entry]
Name=Minecraft
Comment=Play this game in OpenJDK Java 7 Runtime
Exec=minecraft
Terminal=false
Icon=minecraft
Type=Application
Categories=Game;

and my "minecraft" script reads:
java -jar ~/Desktop/Minecraft.jar

I can enter java -jar ~/Desktop/Minecraft.jar into the teminal and minecraft will start.  I can also enter minecraft into the terminal and the script will run and the game will start.  However, the icon will not actually appear to do anything when I click it with this configuration.  I tried first with the Exec line as Exec=java -jar ~/Desktop/Minecraft.jar, but that didn't work, so I tried the script.   I just don't know why nothing seems to happen when I use the launcher icon??
any thought on this issue? thanks!

A: I have found the solution to my problem after a little more experimenting:
I needed the script in a default PATH area, because it seems that .bashrc does not run before the .desktop Exec occurs.  So what this means is that instead of having my minecraft script in my ~/Desktop/scripts folder (which is added to my path in .bashrc), I placed the script in /usr/local/sbin.
So I hope this might help anyone else wanting to make an awesome Minecraft icon!

A: Go to the path where ever you have created this .desktop file open terminal to that path and type
 sudo desktop-file-install Minecraft.desktop

This will add entry to the launcher.Find it use it .


text:
Q: HTML5 video embedding I am trying to embed HTML5 video in bootstrap 2.2.2 based design but it is not working on Firefox, however it is working fine with chrome but on firefox it says No video with supported format and MIME type found.
I have tried adding these to .htaccess file and uploaded this to my root directory but this didn't helped either.

*

*AddType video/mp4  mp4 m4v

*AddType audio/mp4  m4a

*AddType video/ogg ogv

*AddType audio/ogg  ogg oga

*AddType video/webm webm

I have also converted videos into different html supported format and tried to add but no luck.
This is the page where I am adding videos and you can see the source
Note: I went to through previous questions on stackoverflow but no luck there and I do not have apache config files to allow video style as I am on shared hosting.

A: You could try this: http://mediaelementjs.com/
Seems to have good reviews.

A: First of all, both your webm and ogg files are throwing a 404 error - file not found.
secondly, in your question you have the right mime type, but in the code you are using
video/ogv

which is incorrect. it should be
video/ogg

EDIT
Furthermore, you should not be using the same id on the elements id="video" rather e.g. id="video1".
However these are not the real problem you are facing. If you have indeed uploaded the files,  if it won't play, firefox will still try to download it. My intuition tells me it is something to do with your htaccess...
The reason why I say this is because I discovered that the server is doing some wacky redirection, and this is a valid address that enables the browser to download the mp4:
http://ritzcarltonmiamibeach.com/ritzcarltonmiamibeach.com/videos/aerial.mp4

Why don't you post your entire htaccess?

A: I agree with denjello that your server might be doing some strange redirection. However, this does not seem to be a problem for the mp4 files, which I was able to access directly from the browser, even with the strange redirection.
So it's likely that webm videos are disabled from another place. It will be difficult to find out exactly what is going on since, as you say, you have no access to the apache config files. Have you asked your hosting company about this?
I know this is not the optimal solution, but you can consider loading the videos from another server. I would recommend that you try this at least for testing purposes to rule out other sources of errors.


text:
Q: how to display single product do_action in shop Page in Woocommerce Is there any method available to display single product woocommerce_before_single_product_summary action woocommerce shop page

A: Yes. There are a couple ways to do this, depending on what you're actually trying to achieve:

*

*You can override the WooCommerce shop page template (archive-product.php) in your theme (or hopefully child theme) to do the woocommerce_before_single_product_summary action

*You can add the functionality you're looking for that's currently hooked into the woocommerce_before_single_product_summary action to an action that fires on the Shop page

*You can create a function that will do the woocommerce_before_single_product_summary action, and hook that into an action on the Shop page (similar to option 1, but doesn't override the Shop template - in theory, preventing more work in future if/when WooCommerce updates their templates)
How to do it

*

*Create a folder in your theme/child theme called woocommerce and copy plugins/woocommerce/templates/content-product.php to it and figure out where you want to put the woocommerce_before_single_product_summary action. Making sure you're within the <?php ?> tags, pop this is where you want: do_action( 'woocommerce_before_single_product_summary' );

*Find the specific function that does what you're looking for, and add it to an action that's already firing on the Shop page. In the functions.php file of your theme/child theme, (please use a child theme), add this within the <?php ?> tags:

    add_action( 'woocommerce_before_shop_loop_item', 'specific_function_you_want' );

where 'woocommerce_before_shop_loop_item' is the first action that fires on the Shop page (you can swap out for another action in content-product.php depending on where you want to put the functionality, and 'specific_function_you_want' is the name of the function currently hooked into the woocommerce_before_single_product_summary action that you're looking to replicate.

*Again, within the <?php ?> tags in your functions.php file add the following:

add_action( 'woocommerce_before_shop_loop_item', 'do_before_product_summary');

function do_before_product_summary() {

    do_action('woocommerce_before_single_product_summary');

}

Pros/Cons

*

*Easiest and fastest way to do what the question asks; however: note that by default, woocommerce_before_single_product_summary only does two things: display the product image & say if the item is on sale. Both of these are already being shown on the Shop page. Since this method just does the woocommerce_before_single_product_summary action, you'll most likely have duplicated content on the Shop page. Probably not the best way to go about this.

*Gives you the most granularity. I'm making the assumption that you're probably looking to get some specific functionality that is currently hooked to the woocommerce_before_single_product_summary action, and do that on the Shop page. If that is the case, this method will allow you do that, without having to worry about any other functionality that's attached to the woocommerce_before_single_product_summary action (like duplicated product image as mentioned in method 1). However, you will need to find out where that specific functionality is coming from, which will require a bit of digging.

*Doesn't require the digging required in method 2, but as with method 1, will do everything that's hooked into the woocommerce_before_single_product_summary action. The big benefit to using this over method 1 is that when/if WooCommerce updates their templates in the future (as they do from time to time), you won't need to worry about keeping your template override up to date with theirs. This isn't always a big deal, but it is something to keep in mind.


text:
Q: How to access firebase (JS web client API) exported types? I've just started using Typescript, so I went to look for Firebase types over on @types/firebase.
https://www.npmjs.com/package/@types/firebase

So it seems that the Firebase API ships with types.
But how can I access, if I need to declare them at some point?
For example:
Let's say I want to declare this config object as a "Firebase App Config Object" (don't know how it would be called, though).
const config: THE_FIREBASE_CONFIG_TYPE = {       // <--- WHAT SHOULD I PUT AS THE_FIREBASE_CONFIG_TYPE ?
  apiKey: process.env.FIREBASE_APP_API_KEY,
  authDomain: process.env.FIREBASE_APP_AUTH_DOMAIN,
  databaseURL: process.env.FIREBASE_APP_DATABASE_URL,
  projectId: process.env.FIREBASE_APP_PROJECT_ID,
  storageBucket: process.env.FIREBASE_APP_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_APP_MESSAGING_SENDER_ID,
  appId: process.env.FIREBASE_APP_ID,
};

What documentation should I refer to in order to find out which types to use?

A: I usually look up the types in the reference documentation.
From looking at the reference documentation for initializeApp, there is no specific type for this config object:

initializeApp

initializeApp ( options :  Object ,  name ? :  string ) : App

Creates and initializes a Firebase app instance.

So it looks like you should declare it as Object, as there is no more specific type for the config.


text:
Q: when resizing a image set only resizing one image When I was trying to resize an image set, it was only resizing the first image.How to resize all images? This is my code:
import numpy as np
import os
import cv2
pic_num = 1
img = cv2.imread("E:\ele/"+str(pic_num)+'.jpg',cv2.IMREAD_GRAYSCALE)
resized_image = cv2.resize(img,(100,100))
cv2.imwrite("E:\eye/"+str(pic_num)+'.jpg',resized_image)
pic_num += 1

A: If you are just looping through files and change it, and don't worried about time.
then you can just use for loop in python
For example you have pics from 1 too 100
Then you can just do following:
import numpy as np
import os
import cv2

for pic_num in range(1,100):
    img = cv2.imread("E:\ele/"+str(pic_num)+'.jpg',cv2.IMREAD_GRAYSCALE)
    resized_image = cv2.resize(img,(100,100))
    cv2.imwrite("E:\eye/"+str(pic_num)+'.jpg',resized_image)


text:
Q: Google App Script to rename a downloaded file please assist.
I have a Google App Script that downloads an Excel file from the internet into my Google Drive. This is working. Thereafter the file needs to be renamed, this I'm struggling with.
Downloading of file working. Struggling with renaming...
function SaveToGoogleDrive()

  var folderID = 'foldername';  // put id of the Google Drive folder
  var folder = DriveApp.getFolderById(folderID) // get the folder
  var file = UrlFetchApp.fetch("thewebsite");
  folder.createFile(file);
  //file.remame("NewDownloadedFile); // help?
}

A: Try this:
function SaveToGoogleDrive()
  var folder = DriveApp.getFolderById('folderID');
  var fileblob = UrlFetchApp.fetch("thewebsite").getBlob();
  var file=folder.createFile(fileblob);
  file.setName('NewDownLoadFile');
}


text:
Q: Probability and combinatorics problems - picking balls and choosing postcards I am sorry for bothering you with such a trivial and easy question (in comparison to the others asked here) but I have no idea where else I could ask. These are two problems I have to solve and I just need you to check if my solution is correct.
First: I have 10 red balls and 3 blue balls. What is the probability of picking 1 red ball and 3 blue balls?
My solution: 10/13 . 3/12 . 2/11 . 1/10 = 1/286
Or should it be 10/13 . 3/12 . 3/11 . 3/10 = 9/572?
Second: They have 16 different postcards in the shop. How many possibilities do we have if we want to choose 6 different ones?
My solution: 16 . 15 . 14 . 13 . 12 . 11 = 5765760
Thanks in advance for checking my solutions

A: Your method for the first problem is the probability of selecting a red, followed by $3$ blues, sequentially. We have to take into account all the different ways to arrange $3$ blues and $1$ red. Note that this is a hypergeometric random variable, giving probability
$$\frac{{10 \choose 1}{3 \choose 3}}{{13 \choose 4}}\approx 0.014$$
For the second problem, your solution would be correct if ordering mattered, but it does not. Getting $123456$ is considered the same as $654321$. We have
$${16\choose6}=8008$$

A: Both your solutions are incorrect.  Let me start with the second.
You are overlooking the fact that the order in which you choose the postcards is irrelevant.  Picking ABCDEF is the same as picking CDEBFA.  Since there are $6!=720$ ways to arrange any set of six postcards in order, you have counted each set $720$ times.  Divide your solution by $720$ to get the right answer.
In the first problem, you are imposing an order, assuming that we pick the red ball first, then the blues balls.  Perhaps you interpret the question to mean that, but I'm sure it's not what is intended.  There are only $10$
ways to pick the balls, because you must pick all $3$ blue balls, but you can pick any one of the $10$ red ones.  You must divide this by the number of ways to pick $4$ balls from $13$.  This is just like the postcard problem:$$\frac{13\cdot 12\cdot 11\cdot 10}{4\cdot 3\cdot 2 \cdot 1} $$ so we get $$\frac{10\cdot 24}{13\cdot 12\cdot 11\cdot 10}$$


text:
Q: Psycopg2 + Python 2 Unicode decode error with cursor.mogrify I have a database, called test with only one column, being a character varying column of the name some_data. The database has the encoding UTF8 with collation de_DE.utf8.
The connection to this databases is established after the unicode type is registered like:
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)

and I establish the connection
C_test = psycopg.connect(myhost [...])

and open a cursor on the connections
cur_test = C_test.cursor()

I insert my data as unicode strings in test, so when I do:
cur_prod.execute("INSERT INTO test some_data VALUES ("+u'ö'+");")

the table is expected to hold the unicode u'ö' as a 'UTF8' string "\xc3\xb6".
When I select that inserted value, the UNICODE extension guarantees to get me unicode back, and indeed when I select and print the value, I get '\xf6', the unicode for 'ö'. If I use mogrify on the cursor, like:
cur_test.mogrify(u'%s',(u'ö',))

I get a string like "'\xc3\xb6'", which I cannot insert due to a UnicodeDecode error. Long story short: Can I use mogrify together with the unicode extension registered, or should I do my string concatenation without mogrify?

A: Yes, if you register the unicode adapter mogrify will use it.


text:
Q: MongooseError: Operation `devices.insertOne()` buffering timed out after 10000ms I'm trying to run automation test in node.js but I got the above error.
Its not a connection problem, because a minute before it I tried to create user in mongodb using mongoose and secceed.
Do you have any idea?
My test is:

it('should be error in createing users with the same id', async () => {
    const error = Device.create([{userId:'9573468'}, {userId:'9573468'}])
    return expect(!!error).toBe(true)
})

The other fields in user model are not required.


text:
Q: NodeJS cannot find module I have entities directory that store user.js file like this:
"use strict";

class User {}

module.exports = User;

and in my index.js:
var User = require("./entities/User")

but I got an error

Error: Cannot find module './entities/User'
      at Function.Module._resolveFilename (module.js:470:15)
      at Function.Module._load (module.js:418:25)
      at Module.require (module.js:498:17)
      at require (internal/module.js:20:19)
      at Socket.socket.on (/home/etours/capstone-etours/index.js:154:21)
      at emitTwo (events.js:106:13)
      at Socket.emit (events.js:194:7)
      at /home/etours/capstone-etours/node_modules/socket.io/lib/socket.js:503:12
      at _combinedTickCallback (internal/process/next_tick.js:73:7)
      at process._tickCallback (internal/process/next_tick.js:104:9)

A: The require function it's case sensitive so you have to write the path exactly how you created.
if you use the U lowercase it's gonna work :D

A: You should try this code:
user.js
var User = function() {};
module.exports = User;

var User = class User {
};

module.exports.User = User;

index.js
var User = require("./user");
console.log(User);

A: You can also try below code:
user.js:
var User={};
module.exports = User;

var User = class User {
};

module.exports.User = User;

index.js:
var User = require("./user");
console.log(User);


text:
Q: How do I create a thread dump of a Java Web Start application Is it possible to get a thread dump of a Java Web Start application? And if so, how?
It would be nice if there were a simple solution, which would enable a non-developer (customer) to create a thread dump. Alternatively, is it possible to create a thread dump programmatically?
In the Java Web Start Console I can get a list of threads by pressing 't' but stacktraces are not included.
If answers require certain java versions, please say so.

A: In the console, press V rather than T:
t:   dump thread list
v:   dump thread stack

This works under JDK6. Don't know about others.
Alternative, under JDK5 (and possibly earlier) you can send a full stack trace of all threads to standard out:
Under Windows: type ctrl-break in the Java console.
Under Unix: kill -3 <java_process_id>
(e.g. kill -3 5555). This will NOT kill your app.
One other thing: As others say, you can get the stacks programatically via the Thread class but watch out for Thread.getAllStackTraces() prior to JDK6 as there's a memory leak.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434648
Regards,
scotty

A: Try
StackTraceElement[] stack = Thread.currentThread().getStackTrace();

Then you can iterate over the collection to show the top x stack elements you're interested in.

A: Recent JDKs (sadly not JREs) include tools like jstack which does such things.  JVMs from version 5 include JMX extensions to get thread dumps, memory statistics, and much more.  All java applications, including web start applications, have this functionality available.
You would either need to have the JDK installed or to write a JMX client that does the same thing.  Take a look at http://java.sun.com/javase/6/docs/technotes/guides/management/ to get more information.

A: Since 1.5 you can use Thread.getAllStackTraces() to get a Map to iterate over.
The ideal output would be that produced from Ctrl-\ (or Ctrl-Break or similar), but there doesn't seem to be a documented way of producing this. If you are willing to limit yourself to sun's JVM (or use reflection I suppose) you could have a dig around the sun.* packages and see if anything interesting shows up.

A: Since Java 5 you have the getStackTrace() method of Thread class. For prior versions you can do:
Thread.currentThread().dumpStack();

This will print the stack trace to System.out


text:
Q: Semi-periodic Interpolation I have a set of data, e.g. damped waves in a finite box of size L, so that the data is periodic in space but not time. At a particular instant in time, i.e. taking a cross section of data at a particular time, which I'll call dataSlice, I can create an interpolating function
intFn = Interpolation[dataSlice, InterpolationOrder -> 1, PeriodicInterpolation -> True]
and I don't run into trouble. However, if I attempt a periodic interpolation on the whole data set, it fails
intFn = Interpolation[dataSlice, InterpolationOrder -> 1, PeriodicInterpolation -> True]
(*In dimension 1 the data at the endpoints of the fundamental period are not equal*)
That makes sense, of course. For my data, it would make sense to do a semi-periodic interpolation. Does such a function exist? I would like it to function like
intFn = Interpolation[dataSlice, InterpolationOrder -> 1, PeriodicInterpolation -> {False,True,True,True}]
so the first (time) dimension would be non-periodic, and the spatial dimension is periodic.

A: If the data are equidistant in the two dimensions and if the InterpolationOrder is 1, BSplineFunction can be used equivalently.
The advantage is that BSplineFunctionis able to manage partially periodic domain.
n = 10;
dataSlice = N[Sin /@ Range[0, 2 Pi (1 - 1/n), 2 Pi/n] ]
data = Table[Exp[-2 i]  dataSlice, {i, 0.2, 1, 0.1}];
f = BSplineFunction[data, 2, SplineDegree -> 1,
  SplineClosed -> {False, True}]
Plot3D[f[t, x], {x, 0, 2}, {t, 0, 2}]

The domain of the basic pattern is [0,1]X[0,1] and the samples are equidistant in both dimensions of this domain.
I don't know if it works for Interpolation order >1 (I would guess : No).


text:
Q: Multiple errors when adding tracks to playlist using Spotipy I am trying to add tracks to one of my Spotify playlists, and I'm pretty sure I have all of the code exactly right as described in the Spotipy documentation:
username = '*myusername*'
scope = 'playlist-modify-public'

playlist_id = '*myplaylistid*'
track_ids = *array of track ids*

token = util.prompt_for_user_token(username,
                           scope,
                           client_id='*myclientid*',
                           client_secret='*mysecretclientid*',
                           redirect_uri='http://localhost:8888/callback/')
spotify = spotipy.Spotify(auth=token)

results = spotify.user_playlist_add_tracks(username, playlist_id, track_ids)

However, these are the following errors two errors that I receive no matter what I try:
HTTPError: 400 Client Error: Bad Request for url: https://api.spotify.com/v1/users/*myusername*/playlists/*myplaylist*/tracks

During handling of the above exception, another exception occurred:

SpotifyException: http status: 400, code:-1 - https://api.spotify.com/v1/users/*myusername*/playlists/*myplaylist*/tracks:
 Invalid track uri: spotify:track:*trackid*

It specifies Invalid track uri, however for each of the tracks in my list I have tested by searching the uri in Spotify and it is indeed valid.
Solutions I have tried to no avail:
1. Changing between ID and URIs for both playlists and track list
2. Authenticating using OAuth
3. Using different playlists and tracks
4. Using different redirect_uri
5 example track URIs for reference:
spotify:track:1rdHsnsGmleo6MRctkkFmm?si=7R0IKQ9xTgiwfLAJO7eFCw
spotify:track:70CMnzQ3FjMmUk5NPdQJBe?si=qL_WwgWVRTaSZ2oOBg2eCA
spotify:track:6bbx7nYlixYuElKMbYCzMm?si=Wu64S-obRaOOh3mFP3zWwA
spotify:track:6DZNQKNUskiWVSXs3cQPk3?si=SIW3hBU1SiWd_h1gpXwijg
spotify:track:2FMPIU8FdP9kCi5kUCSGnE?si=jtJOkQhsSF6GoD3otgtV3A

Would appreciate any help!! Thank you

A: The track URIs should not contain ?si= but only what's before that. See https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids
You can fix your code to only keep the first part:
track_uris = [uri.split("?si=")[0] for uri in track_uris]


text:
Q: Steps to detect and track droplets in a video using OpenCV C++ I am currently doing a project where I need to locate ink drops in a video, perform measurements such as volume estimation, velocity, and distance travelled before it becomes spherical.
Firstly, I would like to know whether I am along the right tracks in tackling this project. At the moment I have:
1.) Converted the original image to grayscale
2.) Applied Gaussian Blur then Canny edge detection (Click here for image)
3.) Located the white pixels using findNonZero() then calculated the sum of blocks of rows and the block with the highest concentration of white pixels and all the rows above it are cropped out). This removes the print heads in the image so the ROI is only the droplets below it.
4.) Used the findContours to find the contours. (Click here for image)
The above 4 steps are what I have done so far. Are the following steps below what I should do next?

*

*Dilate the binary image first after cropping and before finding contours to ensure the contours will be closed and not open?

*Maybe ignore the ones that are very open? (Any tips on how to actually do this?)

*floodFill() every closed circles

*Find the each contours' area using contourArea() (Can I then estimate the volume of the drop after this step with a few assumptions like its shape, pixel to volume ratio, etc?)

*Find the centre of each contour and save it to an array so I can compare it to the centre of the same drop in the next frame. Once I know distance travelled of the centre of the droplet and the frame rate of the video I should be able to estimate velocity.

I am also unsure of how I can give a drop an ID so I can be sure I am tracking it properly and know when a new drop has entered the ROI.
Any help would be greatly appreciated, Thank You.

A: I think that your idea is good and can be quite easily extended to something that will satisfy you.
For clarification i will call red ROI from your image "redROI".

*

*Find all droplets in redROI. Remember positions and IDs.

*For each droplet position from previous step create a ROI similar to yellow rectangle:
For each rectangle check whether there is a droplet inside it.
If yes - probably it's the droplet from the previous frame, so the one you are looking for.
If no - you may try to search again in a little bit bigger rectangle or assume that the darkset point of this ROI is you droplet. If ROI is near bottom of redROI probably the droplet is gone - forget about it.

Note few things:
-size of the rectangle depends on how fast droplets move and whether they can move only vertical or diagonal (wind can change direction of move) too.
-before searching for droplets, check whether all rectangles are disjoint (the don't have any common area -> (Rect1 & Rect2).area() == 0 for each pair of rectangles).
-before searching for droplets in ROI make sure this ROI is inside redROI. So just use this code: roi = roi & redROI;
After finding new positions of every old droplet, search for droplets in whole redROI, so you won't miss any new droplet.
Let me know if you don't understand some part of this idea - i will try to explain it better.

Maybe ignore the ones that are very open? (Any tips on how to actually
  do this?)

I'm not sure about it, so check it. Try to use CV_RETR_LIST as the third parameter of findContours and check the distance between first and the last point from returned (by findContours) contour - if the distance is big than the contour is open, if no - it is closed.

floodFill() every closed circles

You can just use drawContours and set thickness parameter to -1 - simpler and faster solution.

edit:
You can try to use optical flow as well - it's already implemented in openCV, here you can read nice tutorial about that: http://robotics.stanford.edu/~dstavens/cs223b/ (start from  .pdf files)


text:
Q: Dolphin FIle Manager on Windows - Dark Theme I am using Dolphin File Manger for obvious reasons (tabs, split views, remembers what's open, filters, functioning searches and tons others) on Windows and to this date I haven't been able to force it to use dark theme.
Since it's a KDE application (and in turn Qt), it's 100% possible to make it dark and it should be also pretty easy. I use Dolphin on Windows as "portable".
dolphin.exe --help-all

...contains also a list of Qt options, including --platformtheme <theme> option, which I would assume could be used to load a qss style sheet, so I downloaded Dark Monokai and run dolphin as:
dolphin.exe --platformtheme C:\Users\myhome\Downloads\DarkMonokai.qss

...but still no luck, Dolphin is "white". My assumption might be wrong and I couldn't find any documentation for this option.
Any ideas, please?


text:
Q: How to pass in variables with a redirect? So I have a signup on my base.html, then the form redirects to a signup page.
def signIn(request):
    if request.user.is_authenticated():
        context = {
            "extendVar":"baseLoggedIn.html",
        }
        return HttpResponseRedirect("out")
    if request.user.is_authenticated()==False:
        # form=SignUpForm(request.POST or None)
        if request.method=="POST":

            email=request.POST.get('email','')
            password = request.POST.get('password','')

            user = auth.authenticate(username=email,password=password)

            print(email)
            print(password)
            print(user)
            if user is not None:
                print("notNone")
                auth.login(request,user)
                return HttpResponseRedirect("out")
            else:
                print("None quàlol")
                context={
                    "failure":"Password and e-mail did not match",
                }
                return HttpResponseRedirect("out") #redirects to base.html
        context = {
            "extendVar":"baseNotLoggedIn.html",
        }
    return render(request, "base.html",context)

the only problem is, when I do this, it redirects to the home page, but the home page doesn't have any errors, and I can't figure out a way to display the error that the password + email did not match, since i'm redirecting.

A: You need to pass your message as part of context, and your HttpResponseRedirect does not take any context as a parameter, so you need to return render(request, "base.html", context) instead of HttpResponseRedirect. Then you can access the "failure" key from context.
Also, keep your code clean!
def sign_in(request):
    if request.user.is_authenticated():
        context = {
            "extendVar":"baseLoggedIn.html",
        }
        return HttpResponseRedirect("out")
    else:
        if request.method == "POST":
            form = SignUpForm(request.POST)
            if form.is_valid():
                email = form.cleaned_data['email']
                password = form.cleaned_data['password']

                user = auth.authenticate(username=email, password=password)

                print(email)
                print(password)
                print(user)
                if user:
                    print("notNone")
                    auth.login(request, user)
                    return HttpResponseRedirect("out")
                else:
                    print("None quàlol")
                    context={
                        "failure":"Password and e-mail did not match",
                    }
                    return render(request, "base.html", context)
            else:  # form invalid, pass as variable back to user with form errors
                return render(request, "base.html", {'form': form}
        context = {
            "extendVar":"baseNotLoggedIn.html",
        }
    return render(request, "base.html",context)


text:
Q: How can I open jupyter notebooks with Anaconda? When I open Anaconda, and open jupyter notebook, it just tells me to open it using a path directory or copy/paste an url into my browser. Is it supposed to be like that? I was expecting it would open a regular window...
Besides, it is difficult to copy and paste from the command prompt without copying the whole text in the entire window and then pasting into notepad and then selecting the url that I want. Any tips how I should most easily use jupyter notebooks? kaggle? ibm cloud? thanks!

A: Jupyter is designed to open in your browser as localhost.
Here is the URL you should copy (it doesn't change): http://localhost:8888/tree
I recommend to use Spyder rather than Jupyter if you are beginner, it opens window for itself as it has the option to show snippets of your code (can be allowed from options).

*

*Kaggle is a community to search for a proper dataset that you want to work on with your model.


text:
Q: Typecasting generic object in NSUserDefault I have an array stored in NSUserDefaults as an object.
var defaults = NSUserDefaults.standardUserDefaults()
var details = [1,2,3]
defaults.setObject(details, forKey: "testing_array")

// this is wrong
var percentArray : Array? = defaults.objectForKey("testing_array") as Array

How do I retrieve and use it as an array? If I set it as anyObject, I cannot use it as an array later on.

A: Instead of:
var percentArray : Array? = defaults.objectForKey("testing_array") as Array

Write:
var percentArray : Array<Int>? = defaults.objectForKey("testing_array") as? Array<Int>

Because when casting to array, you need to specify it's generic type also.
EDIT:
Based on matt's comment. You can also use:
var percentArray  = defaults.objectForKey("testing_array") as [Int]

A: The result from objectForKey will be castable as an array of AnyObject, aka [AnyObject]?
You can't cast it as Array, since that's a generic and you can only cast to a specific class.
As Midhun points out, in this specific case, you actually have an array of Int, so you can use the more specific [Int]?
For even more safety use the if let construct to validate the casting:
if let percentArray = defaults.objectForKey("testing_array") as? [Int] {
    println(percentArray)
}

A: If you know for a fact that it is an array of Int, simply explain to Swift that it's an array of Int (by casting):
var percentArray = defaults.objectForKey("testing_array") as [Int]


text:
Q: Strange error on click on Button (Swift Xcode) I'm a newest Swift programmer. I'm building a simple app to iOS system.
I have a strange error when I try to click on one button of my application.
This is the first View:

If I try yo click on "Kit Button", I have this error but I don't know I can I fix it:

A: You can debug by following steps:

*

*Go to breakpoint navigator

*Click on '+' button in bottom left

*Click on exception breakpoint

*Select All exceptions

Run application again with debug mode active , you can see on which line code breaks.


text:
Q: How to create a variable parameter in NetLogo? I am new in NetLogo and I have a question, if anyone can help me I would appreciate it :)
I have a 90x90 world. Each patch in the world has a resource value (resource variable that has the smallest value from 10000 to infinity, integers). In the world I have 60 turtles.
I would like every tick to have a parameter that affects the world as a whole. A value drawn from 0 to 1 that will be multiplied in the resource variable
And I would like to compute that:
the resource of the turtles is = the value of the patch * (the parameter that affects the whole world) - its metabolism

But, I'm not able to implement some details above.
I tried to remove the file in .txt. But, I don't know how to do that. For example assigning a value to each patch. Sorry...
globals [ edge-size ]
turtles-own [ metabolism resource-turtle ]
patches-own [ resources ]

to setup
 ca
  reset-ticks
  set edge-size 90
  set-patch-size 12
  ask n-of 60 patches  [sprout 1 [ setup-turtles ] ]
  setup-patches
end

to setup-patches
  file-open "resource.txt"
  foreach sort patches [ p ->
    ask p [
      set resources file-read
    ]
  ]
  file-close
end

to setup-turtles
  set metabolism 4
  set resource-turtle [ resources ] of patch-here
end

to go
  ask turtles [
    right random 360
    fd 1
    turtle-eat
    reproduction
    if ticks <= 10 [ die ]
  ]
  parameter-world

  tick
end

to turtle-eat
 set resource-turtle (resources - metabolism )   ;; Here it doesn't do exactly what I want it to do: the resource of the turtles is = the value of the patch * (the parameter that affects the whole world) - its metabolism
end

to reproduction
  if (resource-turtle > 5) [
    hatch 1
  ]
end

to parameter-world ;; And the probability parameter leaves the patch with fractional values... Is this the best way to implement this probability?
  ask patches [
      let prob random-float 2
     set resources resources * prob
   ]
end

Thanks in advance

A: In order to have the same value for all patches, you must define a global variable, for example resource-availability:
globals [resource-availability]

Each simulation set, the resource-availability will be set to a random value between 0 and 1:
to set-resource-availability
 set resource-availability random-float 1
end

Because you want the turtles to not have fractional values as resource-turtle, you must round resources * resource-availability in someway, using ceiling, floor or round.
In the following example, I used ceiling:
globals [resource-availability]
turtles-own [ metabolism resource-turtle ]
patches-own [ resources ]

to setup
 ca
  reset-ticks
  ask n-of 2 patches  [sprout 1 [ setup-turtles ] ]
  setup-patches
end

to setup-patches
  ask patches
  [
    set resources random 50 + 50
  ]
end

to setup-turtles
  set metabolism 4
  set resource-turtle [ resources ] of patch-here
end

to go
  set-resource-availability
  ask turtles
  [
    turtle-eat
  ]
  tick
end

to turtle-eat
 set resource-turtle (ceiling(resources * resource-availability) - metabolism )
end

to set-resource-availability
 set resource-availability random-float 1
end


text:
Q: WebGL - looking for a way to save json model to vrml format Basically I have a model(created dynamically using some inputs) on webgl in the form of array of vertices and an array of indices(indicating the surface to be drawn using the vertices from array of vertices). An array of colors of the vertices.
I need to save this in vrml format for 3D printing. How can I achieve this?

A: Convert the list of vertices and list of indices into a simple mesh format like OFF or PLY. And then use MeshLab to load the mesh and export it to VRML.
If what you are looking for is a way to automate the conversion to VRML from the same kind of input, then you can probably write the converter yourself by inspecting how a simple box mesh is exported to VRML by MeshLab: the VRML file still contains a list of vertices and a list of indices (among other things). You could also rely on the C++ library VCGLIB (the library used by MeshLab), although given how simple the VRML exporter is, it is unlikely to be worth doing it.
Finally, since this mesh is to be used for 3D printing, you may have other requirements (do hole-filling for instance) than the export format. In which case, VCGLIB may actually come in handy to apply mesh processing operations.


text:
Q: LSTM only train once using keras I'm trying to train a LSTM model to predict the temperature.but the model only got trained in first epochs.
I got the usage and temperature of cpu from a server in about twenty hours as the dataset.I want to predict the temperature of cpu after 10m by using 10m's data before.so I reshape my dataset to (1301,10,2) as I have 1301 samples,10m timesteps and 2 features, then I divide it to 1201 and 100 as the train dataset and the validation dataset.
I check the dataset manually,so it should be right.
I creat the LSTM model as below
    model = Sequential()
    model.add(LSTM(10, activation="relu", input_shape=(train_x.shape[1], train_x.shape[2]),return_sequences=True))
    model.add(Flatten())
    model.add(Dense(1, activation="softmax"))
    model.compile(loss='mean_absolute_error', optimizer='RMSprop')

and try to fit it
    model.fit(train_x, train_y, epochs=50, batch_size=32, validation_data=(test_x, test_y), verbose=2)

I got the log like this:
Epoch 1/50
 - 1s - loss: 0.8016 - val_loss: 0.8147
Epoch 2/50
 - 0s - loss: 0.8016 - val_loss: 0.8147
Epoch 3/50
 - 0s - loss: 0.8016 - val_loss: 0.8147
Epoch 4/50
 - 0s - loss: 0.8016 - val_loss: 0.8147
Epoch 5/50
 - 0s - loss: 0.8016 - val_loss: 0.8147
Epoch 6/50
 - 0s - loss: 0.8016 - val_loss: 0.8147
Epoch 7/50
 - 0s - loss: 0.8016 - val_loss: 0.8147
Epoch 8/50
 - 0s - loss: 0.8016 - val_loss: 0.8147
Epoch 9/50
 - 0s - loss: 0.8016 - val_loss: 0.8147

The trainning time of each epoch is 0 expect the first epoch,and the loss never decrease.I tried changing the number of LSTM cells,loss function and optimizer,but it still don't work.

A: Changing the activation function of last layer from softmax to sigmoid make the model works.Thanks to @giser_yugang @Ashwin Geet D'Sa