javascript – Wait 5 seconds before executing next line

javascript – Wait 5 seconds before executing next line

javascript – Wait 5 seconds before executing next line

You have to put your code in the callback function you supply to setTimeout:

function stateChange(newState) {
    setTimeout(function () {
        if (newState == -1) {
            alert(VIDEO HAS STOPPED);
        }
    }, 5000);
}

Any other code will execute immediately.

Heres a solution using the new async/await syntax.

Be sure to check browser support as this is a language feature introduced with ECMAScript 6.

Utility function:

const delay = ms => new Promise(res => setTimeout(res, ms));

Usage:

const yourFunction = async () => {
  await delay(5000);
  console.log(Waited 5s);

  await delay(5000);
  console.log(Waited an additional 5s);
};

The advantage of this approach is that it makes your code look and behave like synchronous code.

javascript – Wait 5 seconds before executing next line

You really shouldnt be doing this, the correct use of timeout is the right tool for the OPs problem and any other occasion where you just want to run something after a period of time. Joseph Silber has demonstrated that well in his answer. However, if in some non-production case you really want to hang the main thread for a period of time, this will do it.

function wait(ms){
   var start = new Date().getTime();
   var end = start;
   while(end < start + ms) {
     end = new Date().getTime();
  }
}

With execution in the form:

console.log(before);
wait(7000);  //7 seconds in milliseconds
console.log(after);

Ive arrived here because I was building a simple test case for sequencing a mix of asynchronous operations around long-running blocking operations (i.e. expensive DOM manipulation) and this is my simulated blocking operation. It suits that job fine, so I thought I post it for anyone else who arrives here with a similar use case. Even so, its creating a Date() object in a while loop, which might very overwhelm the GC if it runs long enough. But I cant emphasize enough, this is only suitable for testing, for building any actual functionality you should refer to Joseph Silbers answer.

Related posts on java script   :

python – Token error: EOF in multi-line statement

python – Token error: EOF in multi-line statement

python – Token error: EOF in multi-line statement

Your first line in choices variable doesnt have an apostrophe () at the end.

Not a direct answer to the original question, but since online searching brought me here… I got this error for another reason: a stray parenthesis! But it came from flake8. Heres a snippet of code to reproduce it:

n

import socketnnndef all_good(name):n    name_line = fName: {name})n    print(name_line)n

n

I saved this into a file called error.py. Now if I run flake8 on it:

n

$ flake8 error.py nerror.py:1:1: E902 TokenError: EOF in multi-line statementn

n

Which is rather puzzling as there is no multi-line statement anywhere! Eventually I found the bug, but the moral of the story is that Id have found it much quicker if I had run it through the python interpreter:

n

$ python3 error.py n  File error.py, line 5n    name_line = fName: {name})n                               ^nSyntaxError: unmatched )n

n

Fix it:

n

import socketnnndef all_good(name):n    name_line = fName: {name}n    print(name_line)n

n

And now flake8 will actually do its job:

n

$ flake8 error.py nerror.py:1:1: F401 socket imported but unusedn

n

Its obvious, but remember: check the code with python3 first, then run it through linters or other checkers.

python – Token error: EOF in multi-line statement

Youre missing the closing quote on the Fortune-Telling line.

n

That is easy to find because that is where the syntax highlighting becomes different.

Related posts on Python :

c++ – How to convert integer to double implicitly?

c++ – How to convert integer to double implicitly?

c++ – How to convert integer to double implicitly?

You can multiply by 1.0:

int a{5}, b{2}, c{9};
double d = 1.0 * a / b + 1.0 * c;

And when you work with sums you can add to 0.0:

double d = 0.0 + a - b + c;

Most compilers perform optimization such that the meaningless operation is not evaluated. Only type conversion is done.


Remember that you only need to cast the first member in each division/multiply group. Do so in any manner that seems reasonable. And simple addition/substraction (with no other type multipliers/divisors) is casted too. Compilers guarantee casting. So your example:

double d = (double)a / (double)b + (double)c;

Really may be rewritten like this:

double d = (double)a / b + c;
double d = 1.0 * a / b + c;
double d = static_cast<double>(a) / b + c;

Some more examples:

double d = (double)a / b + (double)c / d + e;
double d = 1.0 * a / b + 1.0 * c / d + e;
double d = static_cast<double>(a) / b + static_cast<double>(c) / d + e;

Is there a better solution?

Yes. Express intent through functions.

Marvel as the optimiser emits perfectly efficient assembler. Enjoy the accolades of your colleagues who gaze in wonder at your awesomely readable and maintainable code:

#include <iostream>

auto a_over_b_plus_c(double a, double b, double c)
{
  double d = a / b + c;
  return d;
}

int main()
{
  int a = 5, b = 2, c = 9;

  std::cout << a_over_b_plus_c(a, b, c) << std::endl;
}

For fun, heres a solution based on tuples & lambdas:

#include <iostream>
#include <tuple>

template<class T, class...Args> 
auto to(Args&&...args)
{
  return std::make_tuple(T(std::forward<Args>(args))...);
}

int main()
{
  int a = 5, b = 2, c = 9;

  auto calc = [](auto&& vals) {
    auto& a = std::get<0>(vals);
    auto& b = std::get<1>(vals);
    auto& c = std::get<2>(vals);

    return a / b + c;
  };

  auto result = calc(to<double>(a, b, c));

  std::cout << result << std::endl;
}

… and something perhaps more readable…

#include <iostream>
#include <tuple>
#include <complex>

template<class T, class F, class...Args> 
auto with(F f, Args&&...args)
{
  return f(T(std::forward<Args>(args))...);
}



int main()
{
  int a = 5, b = 2, c = 9;

  auto calc = [](auto&& a, auto&& b, auto&& c) {

    return a / b + c;
  };

  auto result = with<double>(calc, a, b, c);
  auto result2 = with<float>(calc, a, b, c);
  auto result3 = with<std::complex<double>>(calc, a, b, c);
  auto result4 = with<std::complex<float>>(calc, a, b, c);

  std::cout << result << std::endl;
  std::cout << result2 << std::endl;
  std::cout << result3 << std::endl;
}

c++ – How to convert integer to double implicitly?

This works but all you need is a single 1.0* in front of a

int a{5},b{2},c{9};
double d = (double)a / (double)b + (double)c;

int a{5},b{2},c{9};
double d = 1.0*a / b + c;

The rules of precedence and implicit conversion will cause all the variables to be converted to doubles.

One thing to be careful of is grouped variables which will need to have their own 1.0* or 0.0+ as appropriate:

int a{5},b{2},c{9};
double d = a / (0.0 + b + c);

int a{5},b{2},c{9};
double d = a / (1.0 * b * c);

Alternately, one use use a static cast on the associated variable. I prefer the smaller version as the 1.0* or 0.0+ both scream out implicit conversion to doubles.

int a{5},b{2},c{9};
double d = a / (static_cast<double>(b) * c);

Related posts on C++  :

linux – Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

linux – Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

linux – Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

You can try out this:

systemctl start docker

It worked fine for me.

P.S.: after if there is commands that you cant do without sudo, try this:

gpasswd -a $USER docker

Just Run

sudo dockerd

dockerd is the daemon service for docker containers, because it is not running in background were not able to take any actions related to the service, which needs be restarted.

linux – Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

You can get this error if docker doesnt shut down cleanly. The following answer is for the docker snap package.

Run snap logs docker and look for the following:

Error starting daemon: pid file found, ensure docker is not running or delete /var/snap/docker/179/run/docker.pid

Deleting that file and restarting docker worked for me.

rm /var/snap/docker/<your-version-number>/run/docker.pid
snap stop docker
snap start docker

Make sure to replace ‍‍‍‍<your-version-number>‍ with the appropriate version number.

Related posts on Linux   :

python – Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

python – Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

python – Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

The or and and python statements require truth-values. For pandas these are considered ambiguous so you should use bitwise | (or) or & (and) operations:

result = result[(result[var]>0.25) | (result[var]<-0.25)]

These are overloaded for these kind of datastructures to yield the element-wise or (or and).


Just to add some more explanation to this statement:

The exception is thrown when you want to get the bool of a pandas.Series:

>>> import pandas as pd
>>> x = pd.Series([1])
>>> bool(x)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

What you hit was a place where the operator implicitly converted the operands to bool (you used or but it also happens for and, if and while):

>>> x or x
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> x and x
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> if x:
...     print(fun)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> while x:
...     print(fun)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Besides these 4 statements there are several python functions that hide some bool calls (like any, all, filter, …) these are normally not problematic with pandas.Series but for completeness I wanted to mention these.


In your case the exception isnt really helpful, because it doesnt mention the right alternatives. For and and or you can use (if you want element-wise comparisons):

  • numpy.logical_or:
    >>> import numpy as np
    >>> np.logical_or(x, y)
    

    or simply the | operator:

    >>> x | y
    
  • numpy.logical_and:
    >>> np.logical_and(x, y)
    

    or simply the & operator:

    >>> x & y
    

If youre using the operators then make sure you set your parenthesis correctly because of the operator precedence.

There are several logical numpy functions which should work on pandas.Series.


The alternatives mentioned in the Exception are more suited if you encountered it when doing if or while. Ill shortly explain each of these:

  • If you want to check if your Series is empty:
    >>> x = pd.Series([])
    >>> x.empty
    True
    >>> x = pd.Series([1])
    >>> x.empty
    False
    

    Python normally interprets the length of containers (like list, tuple, …) as truth-value if it has no explicit boolean interpretation. So if you want the python-like check, you could do: if x.size or if not x.empty instead of if x.

  • If your Series contains one and only one boolean value:
    >>> x = pd.Series([100])
    >>> (x > 50).bool()
    True
    >>> (x < 50).bool()
    False
    
  • If you want to check the first and only item of your Series (like .bool() but works even for not boolean contents):
    >>> x = pd.Series([100])
    >>> x.item()
    100
    
  • If you want to check if all or any item is not-zero, not-empty or not-False:
    >>> x = pd.Series([0, 1, 2])
    >>> x.all()   # because one element is zero
    False
    >>> x.any()   # because one (or more) elements are non-zero
    True
    

Well pandas use bitwise & | and each condition should be wrapped in a ()

For example following works

data_query = data[(data[year] >= 2005) & (data[year] <= 2010)]

But the same query without proper brackets does not

data_query = data[(data[year] >= 2005 & data[year] <= 2010)]

python – Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

For boolean logic, use & and |.

np.random.seed(0)
df = pd.DataFrame(np.random.randn(5,3), columns=list(ABC))

>>> df
          A         B         C
0  1.764052  0.400157  0.978738
1  2.240893  1.867558 -0.977278
2  0.950088 -0.151357 -0.103219
3  0.410599  0.144044  1.454274
4  0.761038  0.121675  0.443863

>>> df.loc[(df.C > 0.25) | (df.C < -0.25)]
          A         B         C
0  1.764052  0.400157  0.978738
1  2.240893  1.867558 -0.977278
3  0.410599  0.144044  1.454274
4  0.761038  0.121675  0.443863

To see what is happening, you get a column of booleans for each comparison, e.g.

df.C > 0.25
0     True
1    False
2    False
3     True
4     True
Name: C, dtype: bool

When you have multiple criteria, you will get multiple columns returned. This is why the join logic is ambiguous. Using and or or treats each column separately, so you first need to reduce that column to a single boolean value. For example, to see if any value or all values in each of the columns is True.

# Any value in either column is True?
(df.C > 0.25).any() or (df.C < -0.25).any()
True

# All values in either column is True?
(df.C > 0.25).all() or (df.C < -0.25).all()
False

One convoluted way to achieve the same thing is to zip all of these columns together, and perform the appropriate logic.

>>> df[[any([a, b]) for a, b in zip(df.C > 0.25, df.C < -0.25)]]
          A         B         C
0  1.764052  0.400157  0.978738
1  2.240893  1.867558 -0.977278
3  0.410599  0.144044  1.454274
4  0.761038  0.121675  0.443863

For more details, refer to Boolean Indexing in the docs.

Related posts on python  :

bash – Github permission denied: ssh add agent has no identities

bash – Github permission denied: ssh add agent has no identities

bash – Github permission denied: ssh add agent has no identities

Full details in this answer.

In summary, when ssh-add -l returns “The agent has no identities”, it means that keys used by ssh (stored in files such as ~/.ssh/id_rsa, ~/.ssh/id_dsa, etc.) are either missing, they are not known to ssh-agent, which is the authentication agent, or that their permissions are set incorrectly (for example, world writable).

If your keys are missing or if you have not generated any, use ssh-keygen -t rsa, then ssh-add to add them.

If keys exist but are not known to ssh-agent (like if they are in a non-standard folder), use ssh-add /path/to/my-non-standard-ssh-folder/id_rsa to add them.

See this answer if you are having trouble with ssh-add or ssh-agent.

try this:

ssh-add ~/.ssh/id_rsa

worked for me

bash – Github permission denied: ssh add agent has no identities

THE 2019 ANSWER for macOS Sierra & High Sierra & Catalina:

PS: most of the other answers will have you to create a new ssh key … but you dont need to do that 🙂

As described in detail on https://openradar.appspot.com/27348363, macOS/OS X till Yosemite used to remember SSH keys added by command ssh-add -K <key>

So here are the 4 steps i had to take in order for it to work:

1: ssh-add ~/.ssh/PATH_TO_YOUR_SSH_PRIVATE_KEY (e.g. ~/.ssh/id_rsa)

2: Add the following in ~/.ssh/config

Host * 
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile PATH_TO_YOUR_SSH_PRIVATE_KEY (e.g. ~/.ssh/id_rsa)

3: make sure to remove any gitconfig entry that use osxkeychain helper:

 https://github.com/gregory/dotfiles/commit/e38000527fb1a82b577f2dcf685aeefd3b78a609#diff-6cb0f77b38346e0fed47293bdc6430c6L48

4: restart your terminal for it to take effect.

Related posts on Bash  :

Python Turtle Opacity?

Python Turtle Opacity?

Python Turtle Opacity?

Its not possible to do that, but you could define your colors, and then a light equivalent, and use those.

Red = (255,0,0,0)
LRed = (100,0,0)

I think that would achieve similar effects. You could then just use a lighter color when you want it semi-transparent.

This python turtle example fades out the text while keeping the original turtle stamps unmodified:

import turtle
import time

alex = turtle.Turtle()
alex_text = turtle.Turtle()
alex_text.goto(alex.position()[0], alex.position()[1])

alex_text.pencolor((0, 0, 0))       #black
alex_text.write(hello)
time.sleep(1)
alex_text.clear()

alex_text.pencolor((.1, .1, .1))       #dark grey
alex_text.write(hello)
time.sleep(1)

alex_text.pencolor((.5, .5, .5))       #Grey
alex_text.write(hello)
time.sleep(1)

alex_text.pencolor((.8, .8, .8))       #Light grey
alex_text.write(hello)
time.sleep(1)

alex_text.pencolor((1, 1, 1))          #white
alex_text.write(hello)
time.sleep(1)

alex_text.clear()                      #gone
time.sleep(1)

The text simulates an opacity increase to maximum. Alexs stamps are unmodified.

Python Turtle Opacity?

You can by doing

import turtle
turtle = turtle.Turtle()
r = 100
g = 100
b = 100
a = 0.5
turtle.color(r,g,b,a)

(well, maybe it only works for repl.it)

Related posts on Python  :

build context for docker image very large

build context for docker image very large

build context for docker image very large

The Docker client sends the entire build context to the Docker daemon. That build context (by default) is the entire directory the Dockerfile is in (so, the entire rpms tree).

You can setup a .dockerignore file to get Docker to ignore some files. You might want to experiment with it.

Alternatively, you can move your rpms folder one directory level above your Dockerfile, and only symlink test.rpm into the Dockerfiles directory.


You’ll often want to add the .git folder to the .dockerignore which was the cause of a 150MB -> 5GB difference for some users in the comments here.

Update 2019

Starting from Docker v18.06 there is an option to use a new image builder called Build Kit.

Its pre-bundled with the Docker, no need to install anything. Its backward compatible with the Dockerfile syntax, no need to change the Dockerfile.

Legacy Docker Build vs New Docker BuildKit

Here is an example of building an image with a huge unused file in the build directory:

Legacy Docker Build:

$ time docker image build --no-cache .
Sending build context to Docker daemon  4.315GB
[...]
Successfully built c9ec5d33e12e

real    0m51.035s
user    0m7.189s
sys 0m10.712s

New Docker BuildKit:

$ time DOCKER_BUILDKIT=1 docker image build --no-cache .
[+] Building 0.1s (5/5) FINISHED                                                
 => [internal] load build definition from Dockerfile                       0.0s
 => => transferring dockerfile: 37B                                        0.0s
 => [internal] load .dockerignore                                          0.0s
 => => transferring context: 2B                                            0.0s
[...]
 => => writing image sha256:ba5bca3a525ac97573b2e1d3cb936ad50cf8129eedfa9  0.0s

real    0m0.166s
user    0m0.034s
sys 0m0.026s

The only change is the DOCKER_BUILDKIT=1 environment variable, the difference in time is huge.

.dockerignore File

Please note, that the .dockerignore file is still valid and useful. Some Dockerfile commands like COPY . . will still take into account the .dockerignore rules. But the side files in the build directory (not referenced in the Dockerfile) are not getting copied anymore as a build context by the BuildKit.

build context for docker image very large

I fixed it by moving my Dockerfile and docker-compose.yml into a subfolder and it worked great. Apparently docker sends the current folder to the daemon and my folder was 9 gigs.

Related  posts on Large  :

django rest framework – What is @csrf_exempt

django rest framework – What is @csrf_exempt

django rest framework – What is @csrf_exempt

Normally when you make a request via a form you want the form being submitted to your view to originate from your website and not come from some other domain. To ensure that this happens, you can put a csrf token in your form for your view to recognize. If you add @csrf_exempt to the top of your view, then you are basically telling the view that it doesnt need the token. This is a security exemption that you should take seriously.

The decorator marks a view as being exempt from the protection ensured by the middleware. Example:

n

from django.http import HttpResponsenfrom django.views.decorators.csrf import [email protected]_exemptndef my_view(request):n    return HttpResponse(Hello world)n

django rest framework – What is @csrf_exempt

You should not have to use this unless you know exactly why. A good exemple where it is used is to build a webhook, that will recieve informations from another site via a POST request. You then must be able to receive data even if it has no csrf token, but will be replaced by another system of security. For exemple, if you use stripe for the subscriptions of your clients, you need to know if a client unsuscribed his account. The webhook will be the way to inform your site, and then cut the access to your service for the unsuscribed client.

Related posts on frame work  :

javascript – Cannot Load m3u8: no EXTm3u delimiter JWPlayer Error

javascript – Cannot Load m3u8: no EXTm3u delimiter JWPlayer Error

javascript – Cannot Load m3u8: no EXTm3u delimiter JWPlayer Error

I had the same error. It was caused by wrong file extension.nThis was my code:

n

var playerInstance = jwplayer(test-jwplayer-adaptive);n    playerInstance.setup({n        type: hls,n        file: http://example.com/adaptive-1.mp4, //A link to the HLS manifestn        mediaid: xxxxYYYY // MediaID generated by our platform in order to take advantage of our analyticsn    });n

n

The fix was changing .mp4 to .m3u8 file format.

javascript – Cannot Load m3u8: no EXTm3u delimiter JWPlayer Error

Related posts on java script  :