text:
Q: Run Template on the Cloud Dataflow service I'm trying to running a local template I developed in Google DataFlow.
The problem is when I run it in Google Cloud Shell with:
python -m dataflow.py --project poc-cloud-209212 --temp_location gs://<...>

I got this error
/usr/bin/python: No module named apache_beam

So I tried with a simpler example: the wordcount
Like Google said, I execute:
python -m wordcount --input gs://dataflow-samples/shakespeare/kinglear.txt --output gs://<...> --runner DataflowRunner --project <project> --temp_location gs://<...>

And I got this error:
/usr/bin/python: No module named past.builtins

If I execute without .py:
 python -m wordcount --input gs://dataflow-samples/shakespeare/kinglear.txt --output gs://<...> --runner DataflowRunner --project <project> --temp_location gs://<...>

Again, the same error, but with "more" informatión
Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/home/<...>/wordcount.py", line 26, in <module>
    from past.builtins import unicode
ImportError: No module named past.builtins

What is happening? How can I run those templates in Google Cloud Dataflow?
Do i need to set up the environment in Google Cloud like I did in local or is done by default?

A: Finally I did it.
This is how:
Install virtualenv with python 2.7 in Google Cloud(3.5 was installed by default and Dataflow can not use python3)
 virtualenv env --python=python2

After activate this virtualenv you can run in it


text:
Q: Stacking Cards in react native Currently I am learning react native and I have some problem while I am making stack of the cards.
Here is my code:
constructor(props) {
    super(props);
    const position = new Animated.ValueXY();
    const panResponder = new PanResponder.create({
        onStartShouldSetPanResponder: () => true,
        onPanResponderMove: (event, gesture) => {
            position.setValue({ x: gesture.dx, y: gesture.dy })
        },
    });
    this.state = { panResponder, position, index: 0 };
}

renderCards() {
    if(this.state.index >= this.props.data.length) {
        return this.props.renderNoMoreCard();
    }

    return this.props.data.map((item, i) => {
        if( i < this.state.index) { return null}

        if(i === this.state.index) {
            return (
            <Animated.View
            key={item.id}
            style={[ styles.cardStyle, this.getCardStyle()]}
            {...this.state.panResponder.panHandlers}
        >
        {this.props.renderCard(item)}
        </Animated.View>
            );
        }

        return (
            <Animated.View key={item.id} style={styles.cardStyle}>
            {this.props.renderCard(item)}
            </Animated.View>
        );
    }).reverse();
}
render() {

    return(
        <View>
        {this.renderCards()}
        </View>
    );
}
}

const styles = {
    cardStyle: {
    position: 'absolute',
    width: SCREEN_WIDTH,
    top: 0,
}
};

export default Deck;

The title card 2 is showing instead of card 1 but when I swipe the card. Card 1 is removed from view and title is changed to 3.

A: The mistake was that while using PanResponder which is use to  reconciles several touches into a single gesture. So,
I was declaring  a object const panResponder = new PanResponder.create
but the code should be
const panResponder = PanResponder.create and by Removing this single word "new"  it worked!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get only id from url I have thousands of urls which have ids i want to get only ids from url for example
This is my array
Array
(
    [0] => http://www.videoweed.es/file/f62f2bc536bad
    [1] => http://www.movshare.net/video/5966fcb2605b9
    [2] => http://www.nowvideo.sx/video/524aaacbd6614
    [3] => http://vodlocker.com/pbz4sr6elxmo
)

I want ids from above links
f62f2bc536bad
5966fcb2605b9
524aaacbd6614
pbz4sr6elxmo
I have use parse_url function but its return me path which include all things after slash(/) like /file/pbz4sr6elxmo
<?php
foreach($alllinks as $url){
  $parse = parse_url($url);
  echo $parse['path'];
}
?>

Output

/pbz4sr6elxmo
/video/5966fcb2605b9
/file/f62f2bc536bad
/video/524aaacbd6614

A: You can try with explode -
$alllinks = array
(
    'http://www.videoweed.es/file/f62f2bc536bad',
    'http://www.movshare.net/video/5966fcb2605b9',
    'http://www.nowvideo.sx/video/524aaacbd6614',
    'http://vodlocker.com/pbz4sr6elxmo'
);

foreach($alllinks as $url){
  $temp = explode('/', $url);
  echo $temp[count($temp) - 1].'
';
}

Output
f62f2bc536bad
5966fcb2605b9
524aaacbd6614
pbz4sr6elxmo

This will only help if the the url structure is same, i.e. the last part is the id

A: If the URLs always ends with the id you can simply do
$url = 'http://www.videoweed.es/file/f62f2bc536bad';
$url_split = explode('/', $url);
$code = $url_split[count($url_split) - 1];

A: Try this:
$alllinks = array(
    'http://www.videoweed.es/file/f62f2bc536bad',
    'http://www.movshare.net/video/5966fcb2605b9',
    'http://www.nowvideo.sx/video/524aaacbd6614',
    'http://vodlocker.com/pbz4sr6elxmo'
);

foreach($alllinks as $url){
  $parts = explode('/', $url);
  echo end($parts).'
';
}


text:
Q: Extract chisel in alpine docker I want to install [chisel][1] in my docker under usr/local/bin and try with the following and I got error
RUN curl -L https://github.com/jpillora/chisel/releases/download/1.3.1/chisel_linux_amd64.gz | gzip -d - > /usr/local/bin && \

the error is :
/bin/sh: can't create /usr/local/bin: Is a directory
curl: (23) Failed writing body (0 != 16360)

but it's dir.... , any idea how to add it to to my image ?
im using docker alpine:3.10.1
I've also tried this
RUN curl -sSL https://github.com/jpillora/chisel/releases/download/1.3.1/chisel_linux_amd64.gz | gzip -d - > /usr/local/bin/chisel && \
    chmod +x /usr/local/bin/chisel

and got error:
/bin/sh: can't create /usr/local/bin/chisel: Permission denied
curl: (23) Failed writing body (0 != 16360)

```

https://github.com/jpillora/chisel

  [1]: https://github.com/jpillora/chisel

A: you can use this:
FROM alpine
RUN apk update && apk add --no-cache wget
RUN cd  /usr/local/bin && wget  https://github.com/jpillora/chisel/releases/download/1.3.1/chisel_linux_amd64.gz && gzip -d chisel_linux_amd64.gz
RUN mv /usr/local/bin/chisel_linux_amd64 /usr/local/bin/chisel && chmod +x /usr/local/bin/chisel
RUN chisel -v

result:
ls /usr/local/bin/
chisel

A: You can use below using curl
FROM alpine:3.10.1
RUN apk update && apk add --no-cache curl
RUN curl -sSL https://github.com/jpillora/chisel/releases/download/1.3.1/chisel_linux_amd64.gz | gzip -d - > /usr/local/bin/chisel && chmod +x /usr/local/bin/chisel

Container Output:


text:
Q: How to make auto-sizing boxes in images for text to remain same font size in Python with Wand I'm utilizing Wand in python in order to create an image that iterates over itself so that it can create black-bordered boxes that populate with text. Here is my current code:
import re
from unicodedata import normalize

from docx import Document
from wand.image import Image
from wand.drawing import Drawing
from wand.font import Font

doc = Document("P.docx")
docText = []
for para in doc.paragraphs:
    docText.append(para.text)
fullText = "\n".join(docText)

ct = 242

def get(source, begin, end):
    try:
        start = source.index(len(begin)) + len(begin)
        finish = source.index(len(end), len(start))
        return source[start:finish]
    except ValueError:
        return ""

def capitalize(string):
    cap = ("".join(j[0].upper() + j[1:]) for j in string)
    return cap

def find_matches(text):
    return capitalize(
        [
            m
            for m in re.findall(
                r"^[^0-9]\s+([^.;]+\s*)+[.;]+", normalize("NFKD", text), re.MULTILINE
            )
        ]
    )

with Image(width=400, height=1000, pseudo='xc:white') as canvas:
    left, top, width, height = 2, 2, 395, 131
    for match in find_matches(text=fullText):
        ct += 1
        with Drawing() as context:
            context.fill_color = 'black'
            context.rectangle(left=left, top=top, width=width, height=height)
            context.fill_color = 'white'
            context.rectangle(left=(left+2), top=(top+2), width=(width-4), height=(height-4))
            canvas.font = Font('/System/Library/Fonts/timesnewroman.ttf')
            context(canvas)
            canvas.caption(match + '\n' + str(ct), left=(left+5), top=top, width=(width-10), height=height,
                           gravity='center')
        top += 135
    canvas.crop(bottom=top)
    canvas.save(filename='patdrawTest.png')

With this code, I'm able to produce the following output:

The problem with this is obviously the lack of uniformity when it comes to font size. The following is what my output is supposed to look like (ignoring the text within the boxes):

The only thing that I'm concerned with is making sure that all the text is the same font size (size 12 is great), with those bordered boxes resizing to the text. Thanks for any help!
EDIT
From the provided answer, here is my current code:
import re
from unicodedata import normalize

from docx import Document
from wand.image import Image
from wand.drawing import Drawing

doc = Document("P.docx")
docText = []
for para in doc.paragraphs:
    docText.append(para.text)
fullText = "\n".join(docText)

ct = 242

def get(source, begin, end):
    try:
        start = source.index(len(begin)) + len(begin)
        finish = source.index(len(end), len(start))
        return source[start:finish]
    except ValueError:
        return ""

def capitalize(string):
    cap = ("".join(j[0].upper() + j[1:]) for j in string)
    return cap

def find_matches(text):
    return capitalize(
        [
            m
            for m in re.findall(
                r"^[^0-9]\s+([^.;]+\s*)+[.;]+", normalize("NFKD", text), re.MULTILINE
            )
        ]
    )

def to_chunks(words, size):
    for idx in range(0, len(words), size):
        yield words[idx:idx + size]

def rebuild_text(words, size):
    return "\n".join([" ".join(w) for w in to_chunks(words, size)])

target_width = 396
target_height = 0
y_offset = 0
y_padding = 10
x_padding = 5

with Image(width=1000, height=1000, pseudo='xc:white') as img:
    for match in find_matches(text=fullText):
        ct += 1
        with Drawing() as ctx:
            ctx.font_size = 16
            ctx.text_alignment = 'center'
            words = match.split(" ")
            words.append("\n" + str(ct))
            word_count = len(words)
            while True:
                temp_text = rebuild_text(words, word_count)
                metrics = ctx.get_font_metrics(img, temp_text, multiline=True)
                if metrics.text_width > target_width:
                    word_count -= 1
                else:
                    text = temp_text
                    target_height = int(metrics.text_height + 0.5)
                    break
            ctx.push()
            ctx.fill_color = 'white'
            ctx.stroke_width = 4
            ctx.stroke_color = 'black'
            ctx.rectangle(0, y_offset + y_padding, width=2*x_padding+target_width,
                          height=2*y_padding+target_height)
            ctx.pop()
            ctx.text(x_padding + (target_width // 2), 4*y_padding+y_offset, text)
            ctx(img)
            y_offset = target_height + 4*y_padding
    img.trim()
    img.save(filename='patdrawdemoTest.png')

From this code, I get the following output:

I'm not really sure how to fix the strange spacing. The first and third boxes seem to be great, however there's that weird white space between the first and second box, the borders on the sides aren't even, and there's also two more boxes that are supposed to be there, as shown in the original post. Any help would be greatly appreciated!

A:
The only thing that I'm concerned with is making sure that all the text is the same font size (size 12 is great), with those bordered boxes resizing to the text. Thanks for any help!

Drop the Image.caption method (that does the opposite of what you want), and use Drawing.text method. The Drawing class also has a get_font_metrics method to calculate the finial rending size. This allows you to format text, check if it'll work, then draw (or re-format & repeat).
Take this rough example...
content = [
    """Donec pretium vulputate sapien nec sagittis aliquam malesuada. Neque aliquam vestibulum morbi blandit cursus risus at ultrices mi.\n111""",
    """Adipiscing elit ut aliquam purus sit amet luctus venenatis. Eget mauris pharetra et ultrices neque ornare aenean. Viverra orci sagittis eu volutpat odio facilisis mauris. Vitae proin sagittis nisl rhoncus mattis rhoncus. Sapien nec sagittis aliquam malesuada bibendum arcu vitae.\n222"""
]

def to_chunks(words, size):
    for idx in range(0, len(words), size):
        yield words[idx:idx + size]

def rebuild_text(words, size):
    return "\n".join([" ".join(w) for w in to_chunks(words, size)])
TARGET_WIDTH = 395
TARGET_HEIGHT = 0
BOX_Y_OFFSET = 0
BOX_Y_PADDING = 10
BOX_X_PADDING = 5

with Image(width=1000, height=1000, background='white') as img:
    for text in content:
        with Drawing() as ctx:
            ctx.font_size = 16
            ctx.text_alignment = 'center'
            words = text.split(" ")
            word_count = len(words)
            while True:
                tmp_text = rebuild_text(words, word_count)
                metrics = ctx.get_font_metrics(img, tmp_text, multiline=True)
                if metrics.text_width > TARGET_WIDTH:
                    word_count -= 1
                else:
                    text = tmp_text
                    TARGET_HEIGHT = int(metrics.text_height + 0.5)
                    break
            ctx.push()
            ctx.fill_color = 'white'
            ctx.stroke_width = 4
            ctx.stroke_color = 'black'
            ctx.rectangle(0, BOX_Y_OFFSET + BOX_Y_PADDING, width=2*BOX_X_PADDING+TARGET_WIDTH, height=2*BOX_Y_PADDING+TARGET_HEIGHT)
            ctx.pop()
            ctx.text(BOX_X_PADDING + (TARGET_WIDTH // 2), 4*BOX_Y_PADDING+BOX_Y_OFFSET, text)
            ctx(img)
            BOX_Y_OFFSET = TARGET_HEIGHT + 4*BOX_Y_PADDING

    img.trim()
    img.save(filename='output.png')

All this does is:

*

*Define a target width.

*While the to-be-rendered font is larger, decrease words per line.

*Draw box & text.

Please remember.

*

*ImageMagick is not a type-setter. You'll have to build a word-hyphenation / line-break algorithm.

*Special UTF-8 characters can become a challange

*The code posted above is an example, and doesn't handle errors or protect against recursive loops.


text:
Q: Passing Large Data to View What is the best way for loading large amount of data to view from controller? Or is there better approach than I'm currently doing? I currently have this code on my application. I just got 5k data on a table and it is already slow.
Controller
public function index() {
 $questions = Question::paginate();
 return view('admin.questions.index', compact(['questions']));
}

View
@foreach ($questions as $question)
 // datatable
@endforeach

A: First of all, you should be paginating the data. You aren't passing a limit to the paginator.
$questions = Question::paginate(20);

In your code, you aren't paginating the data. Secondly, you don't need to pass an array to compact(). Do this:
return view('admin.questions.index', compact('questions'));

If pagination isn't intended, then it isn't the size of the data that's being passed to the view. Instead it is the time that is taken up by SQL queries while the data is retrieved from the database.


text:
Q: Show/Hide icon toggle in password input field I have a simple HTML login form:

const passwordField = document.querySelector("#password");
const eyeIcon = document.querySelector("#eye");

eye.addEventListener("click", function() {
  this.classList.toggle("fa-eye-slash");
  const type = passwordField.getAttribute("type") === "password" ? "text" : "password";
  passwordField.setAttribute("type", type);
})

<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@200;400;500;600&display=swap" rel="stylesheet">

Welcome back.

    <form action="#" method="post">
      Email
      <input type="email" id="email" name="email" placeholder="Email" required>
      Password

        <input type="password" name="password" id="password" placeholder="Password" required>

      <button type="button" name="btn" id="btn-login">Login</button>
    </form>

Don't have an account? Create one here.

Everything works great except the icon toggle. There are no warnings and the password input field changes between password and text in the console but the icon does not change. Interestingly, if I add the fa-eye-slash class to the  in .password-container, and this.classList.toggle to fa-eye, it works perfectly. It's just that the icons are reversed. Why won't it work as is?

A: you attached the event listener to a non-existing variable. try this
eyeIcon.addEventListener("click", function() {
  this.classList.toggle("fa-eye-slash");
  const type = passwordField.getAttribute("type") === "password" ? "text" : "password";
  passwordField.setAttribute("type", type);
})

A: here is your solution
eye.addEventListener("click", function() {

  const type = passwordField.getAttribute("type") === "password" ? "text" : "password";
  passwordField.setAttribute("type", type);

   if (passwordField.getAttribute("type") === "password") {
        eyeIcon.classList.remove("fa fa-eye");
        eyeIcon.classList.add("fa fa-eye-slash");
   } else {
        eyeIcon.classList.remove("fa fa-eye-slash");
        eyeIcon.classList.add("fa fa-eye");
   }
})


text:
Q: What does "1\/1." mean in Ruby? I am learning Ruby and I have something to match with (/^1\/1. Guess a word from an anagram [RUBY]{4}$/)
Please, what does "1\/1." mean in this expression. Can anyone explain what's going on for me.
Thanks

A: Generally speaking, a backslash in a regular expression escapes the next character, so that it's treated as an ordinary character rather than whatever its special meaning would be. For instance a* matches zero or more of the letter a, but a\* matches, literally, an a followed by a star. Since most regular expressions in Ruby are wrapped in the delimiter /, we can't directly put forward slashes in our regex. If we had written
/^1/1. Guess a word from an anagram [RUBY]{4}$/

Then the regex would be /^1/ and the rest of the line would be a very confusing syntax error. This is for the same reasons that we can't put " characters directly inside of a "-delimited string.
So a backslash treats it as an actual slash in the expression rather than a delimiter.
/^1\/1. Guess a word from an anagram [RUBY]{4}$/

We're literally matches a 1 followed by a slash followed by a 1 at the start of the line.


text:
Q: Is possible to run support vector machine using following data to predict survival? Our data contain three types of independent variables.
Age: categorical variable
Sex: continuous variable
Lab1wk / Lab2wk / Lab4wk / Lab6wk: time series data of a specific laboratory value
------------Age-Sex-Lab1wk-Lab2wk-Lab4wk-Lab6wk---Survival
Case1--------31--1--------23-------21--------2--------31----------Yes
Case2---------2--2--------31-------31-------39--------92----------No
Case3---------9--1--------21--------0-------31--------34----------Yes
.....
Case3092---42--1--------93-------99-------32---------0----------Yes
To predict the survival I am trying to run support vector machine using python.
And I want to include all lab values (Lab1wk / Lab2wk / Lab4wk / Lab6wk) in the model,
because I think the unknown pattern of the lab values strongly affects the survival.
With approximately 3000 cases, is it reasonable to run support vector machine for the prediction of survival?
Or should I run another statistical method?
Thank you very much, in advance.

A: With the help of the information within this site, I solved this problem by ensemble model using deep neural network and recurrent neural network. Thank you~!


text:
Q: Rabbitmq Subscribe to multiple services but consume it in a round robin fashion I've got a working solution to my problem but wonder if there is a cleaner way of doing this.
My architecture is composed of several services, emitting messages through a Rabbitmq broker.
Some workers consume those messages and do background jobs.
The thing is that i wanted to be able to create different types of workers, all consuming the same services and be able to have several workers of the same type get the job through round robin.
To do this the messages are published by the service in a pub/sub fashion and consumed by a process that redistribute the messages in a work queue dedicated to a set of workers.
Is there a more elegant manner to do this?
Sorry if the explanation is not clear i'll edit it.
Thanks!
(I could have created one queue per worker in the services but with my solution I can subscribe as much as I want without touching any code)

A: Sounds like a perfect fit for topic exchange.

A: Please look:
https://www.rabbitmq.com/tutorials/tutorial-two-java.html
Section "Round-robin dispatching"
You have to set the parameter  channel.basicQos(X):
channel.basicQos(1);

final Consumer consumer = new DefaultConsumer(channel) {
  @Override
  public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    String message = new String(body, "UTF-8");

    System.out.println(" [x] Received '" + message + "'");
    try {
      doWork(message);
    } finally {
      System.out.println(" [x] Done");
      channel.basicAck(envelope.getDeliveryTag(), false);
    }
  }
};


text:
Q: How to remove the Ctrl-Z in the file with dos batch I found that every time I concatenate all the files into one file with
copy *.txt all.txt

, there is a Ctrl-Z character at the end of the file. I don't want this character. Is there any way to write a batch script to remove this character or avoid this to happen?
What I wanted to do is
cat *.txt > all.txt

in linux.

A: In the CP/M days, filesizes were not recorded in bytes, but BLOCKS of 128 bytes. It was therefore necessary to assign an END-OF-FILE byte (^Z=1AH) to indicate a partially-filled textfile block (and no-EOF meant "exactly fills the last 128-byte bock")
This convention was honoured by MSDOS and its derivatives - and is why COPY CON: filename is terminated by a ^Z.
The COPY command allows the ^Z to be interpreted differently - hence /a and /b modes, as demonstrated by the following code:
@ECHO OFF
SETLOCAL
:: set COPYCMD=Y to auto-allow overwriting of destination
SET copycmd=Y
:: copy using FRED1.txt (no ^Z-terminal)
>NUL COPY /a fred1.txt freda1.txt
>NUL COPY fred1.txt fred1a.txt /a
>NUL COPY /b fred1.txt fredb1.txt
>NUL COPY fred1.txt fred1b.txt /b
>NUL COPY /a fred1.txt freda1a.txt /a
>NUL COPY /a fred1.txt freda1b.txt /b
>NUL COPY /b fred1.txt fredb1a.txt /a
>NUL COPY /b fred1.txt fredb1b.txt /b

DIR fred*1*|FIND /i "fred"
ECHO.

:: copy using FRED2.txt (has ^Z-terminal) to fred*2*
>NUL COPY /a fred1.txt fred2.txt
>NUL COPY /a fred2.txt freda2.txt
>NUL COPY fred2.txt fred2a.txt /a
>NUL COPY /b fred2.txt fredb2.txt
>NUL COPY fred2.txt fred2b.txt /b
>NUL COPY /a fred2.txt freda2a.txt /a
>NUL COPY /a fred2.txt freda2b.txt /b
>NUL COPY /b fred2.txt fredb2a.txt /a
>NUL COPY /b fred2.txt fredb2b.txt /b

DIR fred*2*|FIND /i "fred"
ECHO.

:: append-copy using FRED1.txt+FRED2.txt to fred*3*
>NUL COPY /a fred1.txt+fred2.txt freda3.txt
>NUL COPY fred1.txt+fred2.txt fred3a.txt /a
>NUL COPY /b fred1.txt+fred2.txt fredb3.txt
>NUL COPY fred1.txt+fred2.txt fred3b.txt /b
>NUL COPY /a fred1.txt+fred2.txt freda3a.txt /a
>NUL COPY /a fred1.txt+fred2.txt freda3b.txt /b
>NUL COPY /b fred1.txt+fred2.txt fredb3a.txt /a
>NUL COPY /b fred1.txt+fred2.txt fredb3b.txt /b

DIR fred*3*|FIND /i "fred"
ECHO.

:: append-copy using FRED2.txt+FRED2.txt to fred*4*
>NUL COPY /a fred2.txt+fred2.txt freda4.txt
>NUL COPY fred2.txt+fred2.txt fred4a.txt /a
>NUL COPY /b fred2.txt+fred2.txt fredb4.txt
>NUL COPY fred2.txt+fred2.txt fred4b.txt /b
>NUL COPY /a fred2.txt+fred2.txt freda4a.txt /a
>NUL COPY /a fred2.txt+fred2.txt freda4b.txt /b
>NUL COPY /b fred2.txt+fred2.txt fredb4a.txt /a
>NUL COPY /b fred2.txt+fred2.txt fredb4b.txt /b

DIR fred*4*|FIND /i "fred"
ECHO.

GOTO :EOF

Run result:
26/07/2013  08:51                 7 fred1.txt
26/07/2013  08:51                 7 fred1a.txt
26/07/2013  08:51                 7 fred1b.txt
26/07/2013  08:51                 8 freda1.txt
26/07/2013  08:51                 8 freda1a.txt
26/07/2013  08:51                 7 freda1b.txt
26/07/2013  08:51                 7 fredb1.txt
26/07/2013  08:51                 7 fredb1a.txt
26/07/2013  08:51                 7 fredb1b.txt

26/07/2013  08:51                 8 fred2.txt
26/07/2013  08:51                 8 fred2a.txt
26/07/2013  08:51                 8 fred2b.txt
26/07/2013  08:51                 8 freda2.txt
26/07/2013  08:51                 8 freda2a.txt
26/07/2013  08:51                 7 freda2b.txt
26/07/2013  08:51                 8 fredb2.txt
26/07/2013  08:51                 8 fredb2a.txt
26/07/2013  08:51                 8 fredb2b.txt

26/07/2013  09:35                15 fred3a.txt
26/07/2013  09:35                14 fred3b.txt
26/07/2013  09:35                15 freda3.txt
26/07/2013  09:35                15 freda3a.txt
26/07/2013  09:35                14 freda3b.txt
26/07/2013  09:35                15 fredb3.txt
26/07/2013  09:35                16 fredb3a.txt
26/07/2013  09:35                15 fredb3b.txt

26/07/2013  09:35                15 fred4a.txt
26/07/2013  09:35                14 fred4b.txt
26/07/2013  09:35                15 freda4.txt
26/07/2013  09:35                15 freda4a.txt
26/07/2013  09:35                14 freda4b.txt
26/07/2013  09:35                16 fredb4.txt
26/07/2013  09:35                17 fredb4a.txt
26/07/2013  09:35                16 fredb4b.txt

Note how juxataposing /a and /b produces different results, all with various combinations of ^Z-inclusion or even appended.
Note also that a simple COPY can fail if the source is a BINARY file and the /b switch is omitted. I've never investigated it, but I found it happens occasionally on copying .MPGs. I suspect that if ^Z appears in the file before any byte >=80H then the file is assumed to be ASCII and hence terminated unceremoniously there and then - but as I say, I've not investigated it.

A: try this:
copy /b *.txt all.txt

For help, enter help copy.


text:
Q: How can there be so many zombies in The Walking Dead if they consume live people? In The Walking Dead, I've noticed that often when a person is attacked by the walking dead, the victim is totally consumed. For example,

 Rick's wife was eaten whole by one zombie.

So if they usually consume an entire person (or leave not much left of the original person) how can there be so many walkers? Shouldn't their numbers be smaller because they eat people whole?

A: Why aren't more people totally devoured?
It isn't explicitly stated on the show or in the comics, but the Max Brooks books World War Z and The Zombie Survival Guide suggest that zombies are very picky, and only eat fresh meat - either still-living, or killed within the last few minutes.  This might be true of TWD as well.  Furthermore, one zombie can't eat an entire person, even if it tried - you'd have to fit one person-sized amount of meat (minus some volume because large bones can't be eaten - they'd break the zombie's teeth) inside another person's stomach.  This is impossible, because a human is much larger than the human stomach, or even the entire human abdomen.
Thus, people can't be totally devoured by one zombie, or even two or three zombies.  A person can only be totally consumed by a large group of zombies, and even if there is such a group present, they usually don't finish eating the entire body.
We see this happen in Season 6, Episode 7, when a massive group of walkers attacks Nicholas, but eventually wanders off with much of his body, and his entire face, still intact.  Later in the same episode, we see another Alexandrian, who had been trapped by hundreds of zombies, reanimated and mostly intact.  This suggests that, as in Brooks' books, TWD zombies will stop eating when the body has been dead for long enough to be no longer "fresh", according to their standards.

Lori:
We saw one bloated zombie in the room where Lori's corpse had been, but that doesn't mean he ate her entire body.  Aside from the aforementioned problem of fitting an entire human being's muscle and organ tissue into another person's abdomen, no zombie, or herd of zombies, could eat a pelvis, skull, or femur.  Even the smaller  bones and shoulder blades  would be very difficult to consume.  As such, at least some of Lori's skeleton must have been left behind, and I refuse to believe that a single zombie ate the rest of her.

Natural Causes:
As we saw in Season 4, natural causes - injury, old age, and disease - are much more deadly now than they were before the world fell apart.  There are very few doctors left, access to medicine is extremely limited, there are no hospitals in operation (except rare exceptions like Grady Memorial, which is operating with drastically reduced supplies and resources, and has helped only a handful of people since the world essentially ended two years ago).
Getting sick is now a much more dangerous prospect than it had been when the miracles of modern medicine and technology were available.  The survivors are only slightly better off than people were thousands of years ago, when a simple broken leg or case of the flu was a virtual death sentence.  We're back to the days when 4/5 children died before their fifth birthday, and giving birth was highly likely to kill the mother, and often the baby as well.
Stress - emotional and physical - has a tremendous impact on the immune system, and the survivors are living under constant, intense stress, both emotionally and physically.  The emotional stress is obvious - constantly fighting to survive, watching loved ones die left and right, and unrelenting uncertainty and fear - but the physical stress is probably more detrimental.  Limited food resources, drastically reduced variety in the diet, limited access to drinking water, very little medicine - all of these things (which were slightly improved when the group reached Alexandria, but which are still a serious problem, even there) are taking their toll and making our protagonists less resistant to disease, and more susceptible to complications from injuries that we, in the pre-apocalyptic world, consider trivial.
Furthermore, the TWD Wikia points out:

The [zombie] pathogen itself does not kill its hosts, but it seems to weaken their immune systems considerably, to the point where even minor illnesses are far more fatal than normal to humans.

This is plausible, in light of what we've seen thus far on the show and in the comics, but had yet to be confirmed or explained.
In short, it is much more difficult to stay alive, even if we ignore the threat posed by zombies and hostile humans.  The things that might make us, in the real world, mildly uncomfortable, are likely to become life-threatening situations for the survivors on the show.

The Kill Count Prior to Season Five:
There are statistics for onscreen zombie and human deaths on the show up to the end of season four. This site lists the kill count in seasons 1 through 4;  I don't know if their numbers are exactly right, but assuming that they aren't wildly inaccurate, they are good enough for our purposes.  I have taken the liberty of breaking down the data and creating a spreadsheet.

The members of the group who are listed by name in the chart have killed 956 zombies and 39 people.  Other human characters have killed 229 zombies and 136 people. Zombies have killed 78 people.
The grand total:
1,185 zombies killed
253 people killed
In the comic books, and to a lesser extent on the show, Rick's group are depicted as being among the best fighters left in the world.  They have repeatedly fought off much larger forces of zombies and bad guys alike.  In comparison, people who aren't in Rick's group are usually zombie fodder.
The first four seasons of The Walking Dead represent perhaps 2 years of time.  In 2 years, the best zombie killers around have only managed to kill 956 zombies onscreen.  This does not bode well for humanity.

How Many People Versus How Many Zombies?
The blurb for the tenth issue of the comic book says:

After the ordeal Rick has endured last issue, he sets out to find safer shelter. More is learned about the zombies that now out-number us 5000 to 1, but when it comes to some things, it's better not to know. Rick begins to wonder if there is a light at the end of the tunnel his life has become. Even if there is, how can he ever expect to make it there?
Source

In Issue #10, Carl is brought to Herschel's farm for the first time, having just been shot by Otis.  This corresponds to the second episode of Season Two of the show.  The second episode of Season Two takes place about a week after Rick wakes up in the hospital, and a few weeks since the outbreak began.
This means that within weeks of the beginning of the outbreak, only 0.02% of the population was still alive.  What does this mean?
0.02% Humans, 99.98% Zombies:

*

*Worldwide:  1,400,000 people against 6,998,600,000 zombies.

*United States:  60,000 people against 299,940,000 zombies.

Conclusion:
We're doomed, and trying to survive is just playing for time.

A: The number of zombies currently has little to do with the fact the zombies consume the living whenever they get the chance.

*

*Not knowing the source of the original event, we are never privy to how many zombies there were initially or how the infection was spread. Since everyone is infected, unless their brains are destroyed, everyone who dies will eventually become a zombie.

*Since people don't have to be bitten for them to become zombies, nor do we know for certain how long a zombie lasts, we could be seeing zombies from the absolute beginning of the event. If they are decaying, it is at a rate far slower than the normal degradation of bodies that are "dead" so we can't estimate how many should be left after a given amount of time.

*Accidental deaths, suicides, from the horror of it all, starvation (likely to be one of the most likely cause of new zombie creation) are all likely sources of new zombie creation. People who may be bitten but not killed (but die later, anyway) are also good candidates to end up zombies without being eaten.

*I suspect eventually, the roaming herds of zombies will diminish as free-range humans get harder to find (either through the experience of fighting the walkers, or being exterminated by them) and their populations will slowly diminish. This means humanity will likely never truly be zombie free and will develop new ways of dealing with the dead should free-range humans get their act together against the zombie threat.

A: Well, if the whole body is already consumed the dead body can still become a walker because remember when Michonne saw a head but it was still alive and it was trying to consume her. The infection won't stop just because it lost a body part, and it will never stop unless the walker's brain is destroyed.

A: If you noticed in the show no matter how much a person got eaten he/she will turn, I saw a lot of heads without the body, so if you have legs to walk and you turn you will contribute :P.
At some places like in the hospital where rick was admitted soldiers shot people without knowing they will turn, and as the event progresses people start killing each other due to lack of food.
Not to mention off-course many people committed suicides too.
Source is {I watched the show with open eyes :P }

A: in the walking dead game they said whatevers left after they eat you comes back anyways. im not sure thats a good question

A: Everyon knows that people panic, so the first couple of days there will be riots and raids. And in those raids are people who die, and they become walkers and they kill more people.
It's 1 human out of every 5 walkers that die and there are at least 7.5 billion people. If every 5 walkers kills someone, that's around 1.5 billion undead in a pretty short period of time. Sooner or later they're going to get most or all of usS so pack up your shotgun good buddy and aim for da noggin'


text:
Q: Move array with days of week one day backwards js I have such code
const weekDays = [
    { label: 'Mon', name: 'Monday' },
    { label: 'Tue', name: 'Tuesday' },
    { label: 'Wed', name: 'Wednesday' },
    { label: 'Thu', name: 'Thursday' },
    { label: 'Fri', name: 'Friday' },
    { label: 'Sat', name: 'Saturday' },
    { label: 'Sun', name: 'Sunday' },
];
 let daysOfWeek = ['Tue','Thu', 'Sun']

const firstDayIndex = weekDays.findIndex(day => day.label === daysOfWeek[0]) // get current day index
daysOfWeek.unshift(weekDays[(firstDayIndex || weekDays.length) - 1].label) // add previous day by index
daysOfWeek.pop() // remove last day
console.log(daysOfWeek)

Now daysOfWeek shows ["Mon", "Tue", "Thu"] but I wanted daysOfWeek to show ["Mon", "Wed", "Sat"] I mean, for each item of daysOfWeek to be one day backwards

A: Just loop through daysOfWeek and find its occurance index in weekDays. Update the node from daysOfWeek with the index reference from weekDays
Previous day Working Fiddle

const weekDays = [{ label: 'Mon', name: 'Monday' }, { label: 'Tue', name: 'Tuesday' }, { label: 'Wed', name: 'Wednesday' }, { label: 'Thu', name: 'Thursday' }, { label: 'Fri', name: 'Friday' },{ label: 'Sat', name: 'Saturday' },{ label: 'Sun', name: 'Sunday' }];
const daysOfWeek = ['Tue', 'Thu', 'Sun'];
// const daysOfWeek = ['Mon', 'Tue', 'Sun'];
daysOfWeek.forEach((day, dayIndex) => {
    let index = weekDays.findIndex(item => item.label === day);
    index = index === 0 ? weekDays.length : index;
    index !== -1 ? daysOfWeek[dayIndex] = weekDays[index - 1].label : null;
});
console.log(daysOfWeek);

Next day working logic

const weekDays = [{ label: 'Mon', name: 'Monday' },{ label: 'Tue', name: 'Tuesday' },{ label: 'Wed', name: 'Wednesday' },{ label: 'Thu', name: 'Thursday' },{ label: 'Fri', name: 'Friday' },{ label: 'Sat', name: 'Saturday' },{ label: 'Sun', name: 'Sunday' }];
let daysOfWeek = ['Tue', 'Thu', 'Sun'];
// let daysOfWeek = ['Mon', 'Tue', 'Sat'];
daysOfWeek.forEach((day, dayIndex) => {
    let index = weekDays.findIndex(item => item.label === day);
    // index = index === 0 ? weekDays.length : index;
    if (index !== -1) {
        index = index === weekDays.length - 1 ? -1 : index;
        daysOfWeek[dayIndex] = weekDays[index + 1].label;
    }
});
console.log(daysOfWeek);

A: You could implement a circular doubly linked list, here indexed in an object by label.

const weekDays = [{ label: 'Mon', name: 'Monday' }, { label: 'Tue', name: 'Tuesday' }, { label: 'Wed', name: 'Wednesday' }, { label: 'Thu', name: 'Thursday' }, { label: 'Fri', name: 'Friday' },{ label: 'Sat', name: 'Saturday' },{ label: 'Sun', name: 'Sunday' }];

const days_list = weekDays
  .map((day) => ({ day, prev: null, next: null }))
  .reduce((list, node, idx, arr) => {
    node.next = arr[(idx + 1) % arr.length];
    node.prev = arr[(idx + arr.length - 1) % arr.length];

    list[node.day.label] = node;

    return list;
  }, {});

const daysOfWeek = ['Tue', 'Thu', 'Sun'];

const prevDays = daysOfWeek.map((label) => days_list[label].prev.day.label);
console.log(...prevDays); // Mon Wed Sat

const nextDays = daysOfWeek.map((label) => days_list[label].next.day.label);
console.log(...nextDays); // Wed Fri Mon

// update daysOfWeek
daysOfWeek.forEach((label, i) => (daysOfWeek[i] = days_list[label].prev.day.label));

console.log('updated daysOfWeek: ', ...daysOfWeek);

As noted in the comments, using an extra two loops to make the list is not particularly efficient, even if the result is convenient to use. An alternative would be to declare utility functions to get the next/prev day given a label.
function next_day(label) {
  let index = weekDays.findIndex((day) => day.label === label);
  if (index === -1) throw `'${label}' is not a valid day label`;
  index = index === weekDays.length - 1 ? 0 : index;

  return weekDays[index + 1];
}

function prev_day(label) {
  let index = weekDays.findIndex((day) => day.label === label);
  if (index === -1) throw `'${label}' is not a valid day label`;
  index = index === 0 ? weekDays.length : index;

  return weekDays[index - 1];
}

const weekDays = [{ label: 'Mon', name: 'Monday' }, { label: 'Tue', name: 'Tuesday' }, { label: 'Wed', name: 'Wednesday' }, { label: 'Thu', name: 'Thursday' }, { label: 'Fri', name: 'Friday' },{ label: 'Sat', name: 'Saturday' },{ label: 'Sun', name: 'Sunday' }];

function next_day(label) {
  let index = weekDays.findIndex((day) => day.label === label);
  if (index === -1) throw `'${label}' is not a valid day label`;
  index = index === weekDays.length - 1 ? 0 : index;

  return weekDays[index + 1];
}

function prev_day(label) {
  let index = weekDays.findIndex((day) => day.label === label);
  if (index === -1) throw `'${label}' is not a valid day label`;
  index = index === 0 ? weekDays.length : index;

  return weekDays[index - 1];
}

const daysOfWeek = ['Tue', 'Thu', 'Sun'];

const prevDays = daysOfWeek.map((day) => prev_day(day).label);
console.log('prevDays: ', ...prevDays); // Mon Wed Sat

const nextDays = daysOfWeek.map((day) => next_day(day).label);
console.log('nextDays: ', ...nextDays); // Wed Fri Mon

// or change daysOfWeek in place
daysOfWeek.forEach((day, i) => (daysOfWeek[i] = prev_day(day).label));
console.log('updated daysOfWeek: ', ...daysOfWeek);

These two functions share a lot of logic and can easily be combined into a single offset_day utility function which accepts an offset to return days +n or -n from the passed day label, if offset is omitted, 0, or evenly divisible by weekDays.length, it returns the day object of the passed label.
function offset_day(label, offset = 0) {
  let index = weekDays.findIndex((day) => day.label === label);

  if (index === -1) throw `'${label}' is not a valid day label`;

  const length = weekDays.length;
  const _offset = offset % length;
  if (_offset) {
    index = index + _offset;
    index = index < 0 ? index + length : index >= length ? index - length : index;
  }

  return weekDays[index];
}

const weekDays = [{ label: 'Mon', name: 'Monday' }, { label: 'Tue', name: 'Tuesday' }, { label: 'Wed', name: 'Wednesday' }, { label: 'Thu', name: 'Thursday' }, { label: 'Fri', name: 'Friday' },{ label: 'Sat', name: 'Saturday' },{ label: 'Sun', name: 'Sunday' }];

function offset_day(label, offset = 0) {
  let index = weekDays.findIndex((day) => day.label === label);

  if (index === -1) throw `'${label}' is not a valid day label`;

  const length = weekDays.length;
  const _offset = offset % length;
  if (_offset) {
    index = index + _offset;
    index = index < 0 ? index + length : index >= length ? index - length : index;
  }

  return weekDays[index];
}

const daysOfWeek = ['Tue', 'Thu', 'Sun'];

const prevDays = daysOfWeek.map((day) => offset_day(day, -1).label);
console.log('prevDays: ', ...prevDays); // Mon Wed Sat

const nextDays = daysOfWeek.map((day) => offset_day(day, 1).label);
console.log('nextDays: ', ...nextDays); // Wed Fri Mon

// offset by 'n' days either way
const minusThree = daysOfWeek.map((day) => offset_day(day, -3).label);
console.log('minusThree: ', ...minusThree); // Sat Mon Thur

const plusThree = daysOfWeek.map((day) => offset_day(day, 3).label);
console.log('plusThree: ', ...plusThree); // Fri Sun Wed


text:
Q: Strange header ("b8") in node-static web server page I am trying to create a very basic static web server that records the IP addresses of each client machine served.
By and large, it is working... but the web site as served has a strange header... b8:

This header doesn't show up in my html at all, and I'm rather confused.
index.html code:
<!DOCTYPE html>

        <title>Science Treasure Hunt</title>

Eventual Home of Science Treasure Hunt Webpage

My guess is that it is somewhere on the node.js side of things, but I don't know what could be causing it from that end, either...
index.js code:
let http = require('http');
let requestIp = require('request-ip');
let winston = require('winston');
let static = require('node-static');

http.createServer(onRequest).listen(80);

let logger = winston.createLogger({
    level: 'info',
    format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.printf(info => {
            return `${info.timestamp} ${info.level}: ${info.message}`;
        })
    ),
    transports: [
    new winston.transports.Console(),
    new winston.transports.File({filename: 'firstlog.log'})
    ]
});

var file = new(static.Server)('./public');

function onRequest(request, response) {
    file.serve(request, response);
    var ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;
    logger.log('info', ip);
    response.writeHead(200);
}

What might be happening here?


text:
Q: How to Get URL-rewritten Parameter Values in MVC 3 For this:
http://example.com/ClubOpeningTool?c=66
I know I can use the controller method parameter or
  Request.QueryString["c"];

I created a routing rule in Global.asax which transforms the above URL to:
http://example.com/ClubOpeningTool/Index/Club/66
I noticed that Request.QueryString["c"]; does not work in that case, because the Request.QueryString[] array is empty. This seems strange that MVC has no idea of the routing rule that I created when it hydrates the Request.QueryString[] array. Shouldn't it still consider those keys and values query string values and put them in the array?
How can I access the rewritten query string params? Is there another global array that they get stored in?
Thanks

A: There is a stark difference between routing and handling parameters. If you setup a route for something, you will need to make sure that the method in your controller is setup to take in the arguments that you are looking for.
If your route looks like the below example.
routes.MapRoute(
            name: "HandleClub",
            url: "ClubOpeningTool/Club/{c}",
            defaults: new { controller = "ClubOpeningTool", action = "Club", c = UrlParameter.Optional }
        );

Notice that I specified that this is going to the ClubOpeningTool and I am passing in c as an optional parameter for the club that I want to open. In order to read "c" though I will need to make sure that my "Club" action that I am calling has c as one of the parameters. If you want it to be optional your club opening controller could look something like this.
 public class ClubOpeningToolController : Controller
{
    //
    // GET: /ClubOpeningTool/

    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public ActionResult Club(int c = 0)
    {
        return View();
    }

}

You will probably need to setup a different view for this or return the proper view. But this should at least get ya going.
Keep in mind that Request.QueryString[]; will only contain things in the actual uri's query params. (anything after the ?)


text:
Q: WPF application plugin using resources from host application I've got a similar situation to this question. However, that users glazes over how they were able to have plugins take advantage of static resources from the host application at run-time. That is my stumbling block.
Lets call the host "K". At the moment I've made a resource dictionary called KResources.xaml where all of the application's resources are held (app.xaml just merges this dictionary and calls it a day).
In my plugin I'm creating a view, V, that needs to use the KResources dictionary. This is what I'm currently trying:
<UserControl.Resources>
 <ResourceDictionary>
  <ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="/K;component/Resources/KResources.xaml" />
  </ResourceDictionary.MergedDictionaries>
 </ResourceDictionary>
</UserControl.Resources>

Ive also tried the following syntax:
<ResourceDictionary
    Source="pack://application:,,,/K;component/Resources/KResources.xaml" />

Compilation goes well and my V.xaml file recognizes the resources, but I get an exception at runtime when this view is created:
System.Windows.Markup.XamlParseException occurred
HResult=-2146233087
LineNumber=19
LinePosition=8
Message='The invocation of the constructor on type 'K.UI.Infrastructure.CaliburnBootstrapper' that matches the specified binding constraints threw an exception.' Line number '19' and line position '8'.
Source=PresentationFramework
StackTrace:
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
InnerException:
   HResult=-2147024809
   Message=An item with the same key has already been added.
   Source=mscorlib
   StackTrace:
        at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
        at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
        at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
        at Caliburn.Micro.AssemblySourceCache.<Install>b__4(Type t)
        at Caliburn.Micro.EnumerableExtensions.Apply[T](IEnumerable`1 enumerable, Action`1 action)
        at Caliburn.Micro.AssemblySourceCache.<Install>b__0(Object s, NotifyCollectionChangedEventArgs e)
        at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        at Caliburn.Micro.BindableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        at Caliburn.Micro.BindableCollection`1.<>c__DisplayClasse.<AddRange>b__d()
        at Caliburn.Micro.XamlPlatformProvider.OnUIThread(Action action)
        at Caliburn.Micro.BindableCollection`1.AddRange(IEnumerable`1 items)
        at Caliburn.Micro.BootstrapperBase.StartRuntime()
        at Caliburn.Micro.BootstrapperBase.Initialize()
        at K.UI.Infrastructure.CaliburnBootstrapper..ctor() in C:\Dev\K\source\K.UI\Infrastructure\CaliburnBootstrapper.cs:line 44

The line Message=An item with the same key has already been added. stands out.
Any insight would be greatly appreciated. Thanks in advance!

A: So it turns out that omitting the Merged dictionary code altogether resulted in the static resources I required being located properly at run-time anyway. The downside is that during design time the IDE highlights them as if they don't exist.
This leaves me at the same point as this question : https://stackoverflow.com/questions/29749256/static-resources-in-wpf-in-pluggable-application


text:
Q: My docker was stuck by down whalesay, what should I do? I am new with docker, and I learn the start with docker, then something went wrong with docker pull whalesay: it's to big, and my download was stuck.
My operating system is OS X El Capitan.
Here is my docker version:
JocelyndeMacBook-Pro:~ jocelyn$ docker version
Client:
 Version:      1.9.1
 API version:  1.21
 Go version:   go1.4.3
 Git commit:   a34a1d5
 Built:        Fri Nov 20 17:56:04 UTC 2015
 OS/Arch:      darwin/amd64

Server:
 Version:      1.9.1
 API version:  1.21
 Go version:   go1.4.3
 Git commit:   a34a1d5
 Built:        Fri Nov 20 17:56:04 UTC 2015
 OS/Arch:      linux/amd64

A: From your Mac, simply shutdown the current VM (I suspect it is named default: do a docker-machine ls to make sure of its name)
docker-machine stop default

Then restart:
docker-machine start default
docker-machine ssh default

And try to pull another image.

Note that issue 12823 "Docker can hang indefinitely waiting for a nonexistant process to pull an image" is being addressed by PR 19743 "Set idle timeouts for HTTP reads and writes in communications with a registry": commit e23ea05, possibly for docker 1.10 early February.
If the remote size becomes unresponsive for any reason... at least it will now timeout.


text:
Q: Run MySQL Query if condition is true else run another query I need to split address column into streetName and streetNumber. The problem is sometimes the complete address in located in the streetName column , and sometimes too inside the streetNumber column. I am using this code to do the splitting
    replace(streetName, substring_index(streetName, ' ', -1), '') as
    street,substring_index(streetName, ' ', -1) as number
and
    replace(streetNumber, substring_index(streetNumber, ' ', -1), '') as
    street,substring_index(streetNumber, ' ', -1) as number.
What I want to do is run this section of my select query statement if streetName is null or empty execute the code with the streetNumber and vice versa.
I have to sections ifStreet() and IfStreetNumber() in a stored Procedure. But I get an error when I run it , and If I put the code directly inside the case statements it does not work as well.I get an error message, You have an error in your SQL Syntax. Is it possible to run a query base on condition or what is wrong with my approach? Thank you,
  SELECT
    firstName,
    lastName,
    D.email AS email,
    streetName,
    streetNumber,
    zipCode,
    city,
    IF(length(zipCode) =5,'Germany','') As country,
    registeredOn,
    N.email AS matchedEmail,
     CASE
        WHEN gender = 'Frau' OR gender = 'f' THEN 'f'
        WHEN gender = 'Herr' OR gender = 'm' THEN 'm'
        ELSE ''
    END AS Title,
    CASE
        WHEN gender = 'Frau' OR gender = 'f' THEN 'Frau'
        WHEN gender = 'Herr' OR gender = 'm' THEN 'Herr'
        ELSE ''
    END AS Salutation,
    CASE
        WHEN streetName !='' THEN
          call ifStreet()
    ELSE
           call ifStreetNumber()
    END

FROM
    matchFiles.TableA AS D
        INNER JOIN
    matchFiles.TableB AS N ON D.email = N.email
WHERE
    registeredOn <= '2018-08-31';

A: Stored Procedures are not allowed within SELECT Statements. So your approach will not work.
Try to shift your logic from your stored procedure into adequate subquery.

A: I restructured the query and also dropped using a stored procedure . I using an IFNULL function to do the alternation to use either streetName or streetNumber depending on which column has a the full address string.
replace(IFNULL(streetName,streetNumber), substring_index(IFNULL(streetName,streetNumber), ' ', -1), '') as street,substring_index(IFNULL(streetName,streetNumber), ' ', -1) as number


text:
Q: user input to change a variable in a script I'm using a widget on a web page but learning to code
this is the code i insert into my page:

one of the variables "data-room" i wish to change the value by way of user input. what script/code do i need in order to ask the user for the input and then replace the default value "meetingroom1"
Thanks

A: Let us say you have an input
<input id="myInput" type="text"/>

Add JS like following
$("#myInput").blur(function(){

    $(".bistri-conference").data("room", $(this).val());
});

A: One approach, using plain JavaScript in this case, is as follows; first showing the HTML:

<form action="#" method="post">

    Change the meeting room venue:

        <input data-attribute="room" type="text" />

    Change the venue capacity:
        <input data-attribute="capacity" type="text" />

    <button type="button" id="update">Update</button>
</form>

And the JavaScript:
function updateData() {
    var inputArray = Array.prototype.slice.call(this.form.querySelectorAll('input'), 0),
        toUpdate = document.querySelector('.bistri-conference');

    inputArray.forEach(function (input) {
        if (input.value !== input.defaultValue) {
            toUpdate.dataset[input.dataset.attribute] = input.value;
        }
    });
}

document.getElementById('update').addEventListener('click', updateData);

// a named function:
function updateData() {

  // Using Function.prototype.call() to use
  // Array.prototype.slice() to convert the NodeList
  // returned by 'querySelectorAll()' to be converted
  // into an Array:
  var inputArray = Array.prototype.slice.call(this.form.querySelectorAll('input'), 0),

    // retrieving the element to be updated by this function:
    toUpdate = document.querySelector('.bistri-conference');

  // iterating over the array of <input> elements, using
  // Array.prototype.forEach():
  inputArray.forEach(function(input) {
    // the 'input' is the current array-element
    // from the array over which we're iterating.

    // if the value of the <input> is not the
    // default-value of the <input>:
    if (input.value !== input.defaultValue) {

      // we update the data-* attribute of the
      // element equivalent to the value held in
      // the <input> element's 'data-attribute',
      // setting it to the value entered in the <input>:
      toUpdate.dataset[input.dataset.attribute] = input.value;
    }
  });
}

// binding the 'click' event-handler function (note the lack of
// of parentheses after the function's name) of the button:
document.getElementById('update').addEventListener('click', updateData);
label {
  display: block;
}
div[data-room]::before {
  content: 'current value: ' attr(data-room);
  display: block;
}
div[data-room]::after {
  content: 'current value: ' attr(data-capacity);
  display: block;
}
<form action="#" method="post">
  Change the meeting room venue:
    <input data-attribute="room" type="text" />

  Change the venue capacity:
    <input data-attribute="capacity" type="text" />

  <button type="button" id="update">Update</button>
</form>

JS Fiddle demo.
References:

*

*Array.prototpe.forEach().

*Array.prototype.slice().

*document.getElementById().

*document.querySelector().

*document.querySelectorAll().

*Function.prototype.call().

*HTMLElement.dataset.

*HTMLInputElement.

A: if you are looking something like this ... then try this ;)

         <input type="text" id="something" onblur="javascript:Onblur(event)" value="Text field" />


text:
Q: Как смонтировать SD карту в ext4 на Android? Имеется SD карта (32гб). Нужно смонтировать её в телефон, подключаю через OTG. Да только вот одна проблема: Android даже родной ext4 в упор не видит, предлагает форматировать SD карту в FAT32 (а это меня, в свою очередь, крайне не устраивает). Пробую форматировать в ext4 (с ПК). Но SD не видно даже в /dev/block (!)
root@termux:~# ls /dev/block | grep sda
sda
root@termux:~# mkfs.ext4 /dev/block/sda
Found msdos partition table on /dev/block/sda.
Proceed anyway?(y/N)y

Но, даже после этого карта в упор не хотела монтироваться. Решил поменять fstab, а именно: поменять формат монтирования с vfat на ext4. Однако, после редактирования ловлю бутлуп. А что самое худшее - fstab был в разделе /vendor, да и вообще я не делал бэкапа /vendor! Пришлось вообще выносить строку, указывающую на монтирование внешнего девайса. Так что вопрос: как заставить Android монтировать ext4 (впрочем, подойдёт любой ext-формат, но ни в коем случае не FAT, за исключением exFAT. Подойдёт и NTFS/f2fs)

A: Если есть другой смартфон (желательно такой же версии Android) попробуй в него вставить SD карту и уже с помощью него отформатируй, и потом используй в том котором хотел. Мне это помогло когда один телефон не видел SD карту
P.S. Убедись что телефон поддерживает SD карты такого объема памяти


text:
Q: Trace arc from two points and center in Python I am trying to clean this figure that I've produced with python and matplotlib - I would like for each pair of red points on the same cicle be connected by an arc (or partial circle). However, I have only managed to plot the entirety of the circles.
The end goal is to get a clean offset of my convex shape (black outline), in a continuous dashed red line.

I know the coordinates of the center of each circle, and the coordinates of each red dot. Does anyone know how I could go about this? Also, each circle has the same diameter.

A: Try https://matplotlib.org/stable/api/_as_gen/matplotlib.patches.Arc.html with the same width and height.


text:
Q: How to add active class to onclick element? I have a HTML that looks and I want to click any  element, it will add class active.
First, I have element:

. After click button Fetch, it will reload and add list  thought by Ajax.
I tried with sample code:

$(function() {
  $('#listURL').find('a').click(function() {
    $('#listURL').find('a').removeClass('active');
    $(this).addClass('active');
  });
});
.active {
  color: red
}

  Link 1
  Link 2
  Link 3
  Link 4

A: Use a delegated event for dynamically added elements:
$(function() {
  $('#listURL').on("click", "a", function() {
    $(this).addClass('active').siblings().removeClass('active');
  });
});

A: I think you are trying adding active to current element and remove active other element which are active
$(function(){
    $('#listURL a').click(function(event) {
        $(this).addClass('active').siblings().removeClass('active');
      });
  })


text:
Q: How to run mysql scripts in docker image? In my Dockerfile
FROM mysql:5.7

ADD ./mysql_scripts /mysql_scripts
WORKDIR /mysql_scripts
RUN mysql -u root -p < create_user.sql &&\
    mysql -u root -p < create_database.sql &&\
    mysql -u root -p < create_tables.sql

EXPOSE 3306

but when I build that image I have problem like:Enter password: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

A: You cannot run those mysql commands, because the container is not running yet, so neither is MySQL.
What you can do is copy your .sql files to /docker-entrypoint-initdb.d. MySQL will run all .sql, .sql.gz and .sh located in this directory after initialization, which would result in the following Dockerfile:
FROM mysql:5.7

COPY ./mysql_scripts /docker-entrypoint-initdb.d

EXPOSE 3306

More information can be found on the dockerhub page of mysql

A: You can not import database at build time, as every RUN command run in separate shell plus MySQL process also not ready to accept the connection.
You can take benefits from docker entrypoint that does these out of the box.
COPY create_user.sql  /docker-entrypoint-initdb.d/
COPY create_database.sql /docker-entrypoint-initdb.d/
COPY create_tables.sql /docker-entrypoint-initdb.d/

So when the container started it will run the above script in alphabetical order

When a container is started for the first time, a new database with the specified name will be created and initialized with the provided configuration variables. Furthermore, it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. You can easily populate your mysql services by mounting a SQL dump into that directory and provide custom images with contributed data. SQL files will be imported by default to the database specified by the MYSQL_DATABASE variable.

mysql-docker-init-db
Also you use MYSQL_USER to create user.


text:
Q: Request method 'POST' not supported - Spring JPA I want the passenger details to my savePassenger function using request mapping but it is showing me error.
Controller savePass
JPA file
JPA file
It is Showing this Message
[org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]

A: Controller method of savePass is get(RequestMethod.GET) but in your jpa file form action savePass method is post, they should match each other. Please edit the method of controller method to RequestMethod.POST. Please have a try.
@RequestMapping(value = "/savePass", method = RequestMethod.POST)

A: Use RequestMethod.POST
@RequestMapping(value = "/savePass", method = RequestMethod.POST)
instead of
@RequestMapping(value = "/savePass", method = RequestMethod.Get) then you will be able to call post .


text:
Q: Swing JTree with Checkbox and JFileChooser By using JFileChooser I am able to select file and folders getting JList with File Objects and I am showing it with checkbox. Now my requirement is like I want to show the selected file and folder in tree structure with checkbox and the checkbox should be only for root elements not for all child elements.
Example : For Example, I selected folders ABC and PQR which containt sub folders and few files
now on UI It should be display
Checkbox1 ABC--
          --SubFolders
          .           --SubFolder
          .                      --Files
          --Files
Checkbox2 PQR--
          --SubFolders
          .           --SubFolder
          .                      --Files
          --Files

A: Sounds a bit complicated... as far as the tree goes, there's an online post of code from the OReilly Java Cookbook that might help you:
http://java.codefetch.com/cache?url=http://examples.oreilly.com/javacook2/javacooksrc2.jar&path=gui/FileTree.java&lang=java&qy=jtree+file


text:
Q: Convert time interval given in seconds into more human readable form I need a code snippet for converting amount of time given by number of seconds into some human readable form. The function should receive a number and output a string like this:
34 seconds
12 minutes
4 hours
5 days
4 months
1 year

No formatting required, hard-coded format will go.

A:  function secondsToString(seconds)
{
var numyears = Math.floor(seconds / 31536000);
var numdays = Math.floor((seconds % 31536000) / 86400);
var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;
return numyears + " years " +  numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";

}

A: To Convert time in millisecond to human readable format.
 function timeConversion(millisec) {

        var seconds = (millisec / 1000).toFixed(1);

        var minutes = (millisec / (1000 * 60)).toFixed(1);

        var hours = (millisec / (1000 * 60 * 60)).toFixed(1);

        var days = (millisec / (1000 * 60 * 60 * 24)).toFixed(1);

        if (seconds < 60) {
            return seconds + " Sec";
        } else if (minutes < 60) {
            return minutes + " Min";
        } else if (hours < 24) {
            return hours + " Hrs";
        } else {
            return days + " Days"
        }
    }

A: With help of Royi we've got code that outputs time interval in a human readable form:
function millisecondsToStr (milliseconds) {
    // TIP: to find current time in milliseconds, use:
    // var  current_time_milliseconds = new Date().getTime();

    function numberEnding (number) {
        return (number > 1) ? 's' : '';
    }

    var temp = Math.floor(milliseconds / 1000);
    var years = Math.floor(temp / 31536000);
    if (years) {
        return years + ' year' + numberEnding(years);
    }
    //TODO: Months! Maybe weeks?
    var days = Math.floor((temp %= 31536000) / 86400);
    if (days) {
        return days + ' day' + numberEnding(days);
    }
    var hours = Math.floor((temp %= 86400) / 3600);
    if (hours) {
        return hours + ' hour' + numberEnding(hours);
    }
    var minutes = Math.floor((temp %= 3600) / 60);
    if (minutes) {
        return minutes + ' minute' + numberEnding(minutes);
    }
    var seconds = temp % 60;
    if (seconds) {
        return seconds + ' second' + numberEnding(seconds);
    }
    return 'less than a second'; //'just now' //or other string you like;
}

A: If you are interested in an existing javascript library that does the job very well, you may want to check moment.js.
More specifically, the relevant moment.js piece for your question is durations.
Here are some examples of how you can take advantage of it to achieve your task:
var duration = moment.duration(31536000);

// Using the built-in humanize function:
console.log(duration.humanize());   // Output: "9 hours"
console.log(duration.humanize(true));   // Output: "in 9 hours"

moment.js has built-in support for 50+ human languages, so if you use the humanize() method you get multi-language support for free.
If you want to display the exact time information, you can take advantage of the moment-precise-range plug-in for moment.js that was created exactly for this purpose:
console.log(moment.preciseDiff(0, 39240754000);
// Output: 1 year 2 months 30 days 5 hours 12 minutes 34 seconds

One thing to note is that currently moment.js does not support weeks / days (in week) for duration object.
Hope this helps!

A: Thanks to @Dan / @ Royi for the logic. However the implementation doesn't build time string like XX days, XX mins. I adjusted their code a bit:
function millisecondsToStr( milliseconds ) {
    let temp = milliseconds / 1000;
    const years = Math.floor( temp / 31536000 ),
          days = Math.floor( ( temp %= 31536000 ) / 86400 ),
          hours = Math.floor( ( temp %= 86400 ) / 3600 ),
          minutes = Math.floor( ( temp %= 3600 ) / 60 ),
          seconds = temp % 60;

    if ( days || hours || seconds || minutes ) {
      return ( years ? years + "y " : "" ) +
      ( days ? days + "d " : "" ) +
      ( hours ? hours + "h " : ""  ) +
      ( minutes ? minutes + "m " : "" ) +
      Number.parseFloat( seconds ).toFixed( 2 ) + "s";
    }

    return "< 1s";
}

When one runs it
console.log("=", millisecondsToStr( 1540545689739 - 1540545684368 ));
console.log("=", millisecondsToStr( 351338536000 ));

The results look like:
= 5.37s
= 11y 51d 10h 2m 16.00s

A: Adding to the myriad of methods, here's a cheap and short way to retrieve a human readable time with only a single time unit.
const timeScalars = [1000, 60, 60, 24, 7, 52];
const timeUnits = ['ms', 'secs', 'mins', 'hrs', 'days', 'weeks', 'years'];

const getHumanReadableTime = (ms, dp = 0) => {
  let timeScalarIndex = 0, scaledTime = ms;

  while (scaledTime > timeScalars[timeScalarIndex]) {
    scaledTime /= timeScalars[timeScalarIndex++];
  }

  return `${scaledTime.toFixed(dp)} ${timeUnits[timeScalarIndex]}`;
};

Example outputs:
getHumanReadableTime(512000);
getHumanReadableTime(5120000);
getHumanReadableTime(51200000);
getHumanReadableTime(51200000, 2);
getHumanReadableTime(51200000, 6);

/*

Output:
    '9 min'
    '1 hrs'
    '14 hrs'
    '14.22 hrs'
    '14.222222 hrs'

*/

A: Took a swing based on @Royi's response:
/**
 * Translates seconds into human readable format of seconds, minutes, hours, days, and years
 *
 * @param  {number} seconds The number of seconds to be processed
 * @return {string}         The phrase describing the amount of time
 */
function forHumans ( seconds ) {
    var levels = [
        [Math.floor(seconds / 31536000), 'years'],
        [Math.floor((seconds % 31536000) / 86400), 'days'],
        [Math.floor(((seconds % 31536000) % 86400) / 3600), 'hours'],
        [Math.floor((((seconds % 31536000) % 86400) % 3600) / 60), 'minutes'],
        [(((seconds % 31536000) % 86400) % 3600) % 60, 'seconds'],
    ];
    var returntext = '';

    for (var i = 0, max = levels.length; i < max; i++) {
        if ( levels[i][0] === 0 ) continue;
        returntext += ' ' + levels[i][0] + ' ' + (levels[i][0] === 1 ? levels[i][1].substr(0, levels[i][1].length-1): levels[i][1]);
    };
    return returntext.trim();
}

Nice thing about mine is that there is no repetitive ifs, and won't give you 0 years 0 days 30 minutes 1 second for example.
For example:
forHumans(60) outputs 1 minute
forHumans(3600) outputs 1 hour
and forHumans(13559879) outputs 156 days 22 hours 37 minutes 59 seconds

A: function millisecondsToString(milliseconds) {
    var oneHour = 3600000;
    var oneMinute = 60000;
    var oneSecond = 1000;
    var seconds = 0;
    var minutes = 0;
    var hours = 0;
    var result;

    if (milliseconds >= oneHour) {
        hours = Math.floor(milliseconds / oneHour);
    }

    milliseconds = hours > 0 ? (milliseconds - hours * oneHour) : milliseconds;

    if (milliseconds >= oneMinute) {
        minutes = Math.floor(milliseconds / oneMinute);
    }

    milliseconds = minutes > 0 ? (milliseconds - minutes * oneMinute) : milliseconds;

    if (milliseconds >= oneSecond) {
        seconds = Math.floor(milliseconds / oneSecond);
    }

    milliseconds = seconds > 0 ? (milliseconds - seconds * oneSecond) : milliseconds;

    if (hours > 0) {
        result = (hours > 9 ? hours : "0" + hours) + ":";
    } else {
        result = "00:";
    }

    if (minutes > 0) {
        result += (minutes > 9 ? minutes : "0" + minutes) + ":";
    } else {
        result += "00:";
    }

    if (seconds > 0) {
        result += (seconds > 9 ? seconds : "0" + seconds) + ":";
    } else {
        result += "00:";
    }

    if (milliseconds > 0) {
        result += (milliseconds > 9 ? milliseconds : "0" + milliseconds);
    } else {
        result += "00";
    }

    return result;
}

A: Here is my take.
Feel free to play around with it in the jsbin.
// This returns a string representation for a time interval given in milliseconds
// that appeals to human intuition and so does not care for leap-years,
// month length irregularities and other pesky nuisances.
const human_millis = function (ms, digits=1) {
    const levels=[
      ["ms", 1000],
      ["sec", 60],
      ["min", 60],
      ["hrs", 24],
      ["days", 7],
      ["weeks", (30/7)], // Months are intuitively around 30 days
      ["months", 12.1666666666666666], // Compensate for bakari-da in last step
      ["years", 10],
      ["decades", 10],
      ["centuries", 10],
      ["millenia", 10],
    ];
    var value=ms;
    var name="";
    var step=1;
    for(var i=0, max=levels.length;i<max;++i){
        value/=step;
        name=levels[i][0];
        step=levels[i][1];
        if(value < step){
            break;
        }
    }
    return value.toFixed(digits)+" "+name;
}

console.clear();
console.log("---------");
console.log(human_millis(1));
console.log(human_millis(10));
console.log(human_millis(100));
console.log(human_millis(1000));
console.log(human_millis(1000*60));
console.log(human_millis(1000*60*60));
console.log(human_millis(1000*60*60*24));
console.log(human_millis(1000*60*60*24*7));
console.log(human_millis(1000*60*60*24*30));
console.log(human_millis(1000*60*60*24*365));
console.log(human_millis(1000*60*60*24*365*10));
console.log(human_millis(1000*60*60*24*365*10*10));
console.log(human_millis(1000*60*60*24*365*10*10*10));
console.log(human_millis(1000*60*60*24*365*10*10*10*10));

If you use Typescript type and cast to make it work
let name : string | number = "";
    let step : string | number =1;
    for(var i=0, max=levels.length;i<max;++i){
        value/= step as number;
        name=levels[i][0];
        step=levels[i][1];
        if(value < step){
            break;
        }

    }

Output:
"---------"
"1.0 ms"
"10.0 ms"
"100.0 ms"
"1.0 sec"
"1.0 min"
"1.0 hrs"
"1.0 days"
"1.0 weeks"
"1.0 months"
"1.0 years"
"1.0 decades"
"1.0 centuries"
"1.0 millenia"
"10.0 millenia"

A: This function outputs seconds in this format : 11h 22m, 1y 244d, 42m 4s etc
Set the max variable to show as many identifiers as you want.
function secondsToString (seconds) {

var years = Math.floor(seconds / 31536000);
var max =2;
var current = 0;
var str = "";
if (years && current<max) {
    str+= years + 'y ';
    current++;
}
var days = Math.floor((seconds %= 31536000) / 86400);
if (days && current<max) {
    str+= days + 'd ';
    current++;
}
var hours = Math.floor((seconds %= 86400) / 3600);
if (hours && current<max) {
    str+= hours + 'h ';
    current++;
}
var minutes = Math.floor((seconds %= 3600) / 60);
if (minutes && current<max) {
    str+= minutes + 'm ';
    current++;
}
var seconds = seconds % 60;
if (seconds && current<max) {
    str+= seconds + 's ';
    current++;
}

return str;
}

A: With the help of Dan answer, I came up with this if you want to calculate the difference between the post created time (from DB it should be retrieved as UTC) and the users system time and then show them the elapsed time, you could use below function
function dateToStr(input_date) {
  input_date= input_date+" UTC";
  // convert times in milliseconds
  var input_time_in_ms = new Date(input_date).getTime();
  var current_time_in_ms = new Date().getTime();
  var elapsed_time = current_time_in_ms - input_time_in_ms;

  function numberEnding (number) {
      return (number > 1) ? 's' : '';
  }

  var temp = Math.floor(elapsed_time / 1000);
  var years = Math.floor(temp / 31536000);
  if (years) {
      return years + ' year' + numberEnding(years);
  }
  //TODO: Months! Maybe weeks?
  var days = Math.floor((temp %= 31536000) / 86400);
  if (days) {
      return days + ' day' + numberEnding(days);
  }
  var hours = Math.floor((temp %= 86400) / 3600);
  if (hours) {
      return hours + ' hour' + numberEnding(hours);
  }
  var minutes = Math.floor((temp %= 3600) / 60);
  if (minutes) {
      return minutes + ' minute' + numberEnding(minutes);
  }
  var seconds = temp % 60;
  if (seconds) {
      return seconds + ' second' + numberEnding(seconds);
  }
  return 'less than a second'; //'just now' //or other string you like;
}

eg: usage
var str = dateToStr('2014-10-05 15:22:16');

A: There is the Intl.RelativeTimeFormat API, which is supported in recent versions of Chrome and Firefox.
An few examples:
let rtf = new Intl.RelativeTimeFormat("en");
rtf.format(-1, "day"); // 'yesterday'
rtf.format(-2, 'day'); // '2 days ago'
rtf.format(13.37, 'second'); // 'in 13.37 seconds'

And there's a lot more in this blog post and in the proposal itself.

A: Try following:
seconds = ~~(milliseconds / 1000);
minutes = ~~(seconds / 60);
hours = ~~(minutes / 60);
days = ~~(hours / 24);
weeks = ~~(days / 7);
year = ~~(days / 365);

Note:

*

*A usual year has 365 days. A leap year has 366 days, so you need additional check if this is an issue for you.

*The similar problem with daylight saving. Some days have 23 and some 25 hours when time's changed.

Conclusion: this is a rude but small and simple snippet :)

A: millisToTime = function(ms){

    x = ms / 1000;
    seconds = Math.round(x % 60);
    x /= 60;
    minutes = Math.round(x % 60);
    x /= 60;
    hours = Math.round(x % 24);
    x /= 24;
    days = Math.round(x);

    return {"Days" : days, "Hours" : hours, "Minutes" : minutes, "Seconds" : seconds};
}

This will take milliseconds as an int, and give you an JSON object containing all the info you could need

A: Way more simple and readable.
milliseconds = 12345678;
mydate=new Date(milliseconds);
humandate=mydate.getUTCHours()+" hours, "+mydate.getUTCMinutes()+" minutes and "+mydate.getUTCSeconds()+" second(s)";

Which gives:

"3 hours, 25 minutes and 45 second(s)"

A: To show only what you need and not day 0, hours 0...
formatTime = function(time) {
        var ret = time % 1000 + ' ms';
        time = Math.floor(time / 1000);
        if (time !== 0) {
            ret = time % 60 + "s "+ret;
            time = Math.floor(time / 60);
            if (time !== 0) {
                ret = time % 60 + "min "+ret;
                time = Math.floor(time / 60);
                if (time !== 0) {
                    ret = time % 60 + "h "+ret;
                     ...
                }
            }
        }
        return ret;
    };

A: Following a similar approach to @Dan, I have modified @Royi Namir's code to output a string with commas and and's:
secondsToString = function(seconds) {
    var numdays, numhours, nummilli, numminutes, numseconds, numyears, res;
    numyears = Math.floor(seconds / 31536000);
    numdays = Math.floor(seconds % 31536000 / 86400);
    numhours = Math.floor(seconds % 31536000 % 86400 / 3600);
    numminutes = Math.floor(seconds % 31536000 % 86400 % 3600 / 60);
    numseconds = seconds % 31536000 % 86400 % 3600 % 60;
    nummilli = seconds % 1.0;
    res = [];
    if (numyears > 0) {
        res.push(numyears + " years");
    }
    if (numdays > 0) {
        res.push(numdays + " days");
    }
    if (numhours > 0) {
        res.push(numhours + " hours");
    }
    if (numminutes > 0) {
        res.push(numminutes + " minutes");
    }
    if (numseconds > 0) {
        res.push(numseconds + " seconds");
    }
    if (nummilli > 0) {
        res.push(nummilli + " milliseconds");
    }
    return [res.slice(0, -1).join(", "), res.slice(-1)[0]].join(res.length > 1 ? " and " : "");
};

It has no period so one can add sentences after it, like here:
perform: function(msg, custom, conn) {
    var remTimeLoop;
    remTimeLoop = function(time) {
        if (time !== +custom[0]) {
            msg.reply((secondsToString(time)) + " remaining!");
        }
        if (time > 15) {
            return setTimeout((function() {
                return remTimeLoop(time / 2);
            }), time / 2);
        }
    };
    // ...
    remTimeLoop(+custom[0]);
}

Where custom[0] is the total time to wait for; it will keep dividing the time by 2, warning the time remaining until the timer ends, and stop warning once the time is under 15 seconds.

A: Below will work for both past and future datetime, also have option to pass locale.
function relativeTime(isoString, locale = "en") {
  const timestamp = Date.parse(isoString);
  const msPerMinute = 60 * 1000;
  const msPerHour = msPerMinute * 60;
  const msPerDay = msPerHour * 24;
  const msPerMonth = msPerDay * 30;
  const msPerYear = msPerDay * 365;

  const current = Date.now();
  let elapsed = current - timestamp;

  const sign = elapsed > 0 ? -1 : 1;

  elapsed = Math.abs(elapsed);

  const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });

  if (elapsed < msPerMinute) {
    return rtf.format(sign * Math.floor(elapsed / 1000), "seconds");
  } else if (elapsed < msPerHour) {
    return rtf.format(sign * Math.floor(elapsed / msPerMinute), "minutes");
  } else if (elapsed < msPerDay) {
    return rtf.format(sign * Math.floor(elapsed / msPerHour), "hours");
  } else if (elapsed < msPerMonth) {
    return rtf.format(sign * Math.floor(elapsed / msPerDay), "days");
  } else if (elapsed < msPerYear) {
    return rtf.format(sign * Math.floor(elapsed / msPerMonth), "months");
  } else {
    return new Date(timestamp).toLocaleString(locale);
  }
}

Output:
relativeTime(new Date().toISOString()) //'2021-11-13T18:48:58.243Z'
-> now

relativeTime('2021-11-13T18:48:50.243Z')
-> 8 seconds ago

relativeTime('2021-11-14T18:48:50.243Z')
-> in 23 hours

relativeTime('2021-11-15T18:48:50.243Z')
-> tomorrow

relativeTime('2021-10-15T18:48:50.243Z')
-> 29 days ago

relativeTime('2021-12-15T18:48:50.243Z')
-> next month

A: This is a solution. Later you can split by ":" and take the values of the array
 /**
 * Converts milliseconds to human readeable language separated by ":"
 * Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
 */
function dhm(t){
    var cd = 24 * 60 * 60 * 1000,
        ch = 60 * 60 * 1000,
        d = Math.floor(t / cd),
        h = '0' + Math.floor( (t - d * cd) / ch),
        m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
    return [d, h.substr(-2), m.substr(-2)].join(':');
}

//Example
var delay = 190980000;
var fullTime = dhm(delay);
console.log(fullTime);

A: I'm a big fan of objects, so I created this from https://metacpan.org/pod/Time::Seconds
Usage:
var human_readable = new TimeSeconds(986543).pretty(); // 11 days, 10 hours, 2 minutes, 23 seconds

;(function(w) {
  var interval = {
    second: 1,
    minute: 60,
    hour: 3600,
    day: 86400,
    week: 604800,
    month: 2629744, // year / 12
    year: 31556930 // 365.24225 days
  };

  var TimeSeconds = function(seconds) { this.val = seconds; };

  TimeSeconds.prototype.seconds = function() { return parseInt(this.val); };
  TimeSeconds.prototype.minutes = function() { return parseInt(this.val / interval.minute); };
  TimeSeconds.prototype.hours = function() { return parseInt(this.val / interval.hour); };
  TimeSeconds.prototype.days = function() { return parseInt(this.val / interval.day); };
  TimeSeconds.prototype.weeks = function() { return parseInt(this.val / interval.week); };
  TimeSeconds.prototype.months = function() { return parseInt(this.val / interval.month); };
  TimeSeconds.prototype.years = function() { return parseInt(this.val / interval.year); };

  TimeSeconds.prototype.pretty = function(chunks) {
    var val = this.val;
    var str = [];

    if(!chunks) chunks = ['day', 'hour', 'minute', 'second'];

    while(chunks.length) {
      var i = chunks.shift();
      var x = parseInt(val / interval[i]);
      if(!x && chunks.length) continue;
      val -= interval[i] * x;
      str.push(x + ' ' + (x == 1 ? i : i + 's'));
    }

    return str.join(', ').replace(/^-/, 'minus ');
  };

  w.TimeSeconds = TimeSeconds;
})(window);

A: I cleaned up one of the other answers a bit provides nice '10 seconds ago' style strings:
function msago (ms) {
    function suffix (number) { return ((number > 1) ? 's' : '') + ' ago'; }
    var temp = ms / 1000;
    var years = Math.floor(temp / 31536000);
    if (years) return years + ' year' + suffix(years);
    var days = Math.floor((temp %= 31536000) / 86400);
    if (days) return days + ' day' + suffix(days);
    var hours = Math.floor((temp %= 86400) / 3600);
    if (hours) return hours + ' hour' + suffix(hours);
    var minutes = Math.floor((temp %= 3600) / 60);
    if (minutes) return minutes + ' minute' + suffix(minutes);
    var seconds = Math.floor(temp % 60);
    if (seconds) return seconds + ' second' + suffix(seconds);
    return 'less then a second ago';
};

A: function java_seconds_to_readable(seconds)
{
    var numhours = Math.floor(seconds / 3600);
    var numminutes = Math.floor((seconds / 60) % 60);
    var numseconds = seconds % 60;
    return numhours + ":" + numminutes + ":" + numseconds;
}

More simple way. You can years and days respectively.

A: if you use node :
const humanize = require('human-date');

let yesterday = new Date(new Date().setDate(new Date().getDate()-1));

console.log(humanize.relativeTime(yesterday)); //=> 1 day ago

A: function secondsToTimeString(input) {
  let years = 0, days = 0, hours = 0, minutes = 0, seconds = 0;
  let ref = [31536000,86400,3600,60,1];
  for (let i = 0;i < ref.length;i++) {
    let val = ref[i];
    while (val <= input) {
      input -= val;
      if (i === 0) years++;
      if (i === 1) days++;
      if (i === 2) hours++;
      if (i === 3) minutes++;
      if (i === 4) seconds++;
    }
  return {years, days, hours, minutes, seconds};
  }


text:
Q: Python should return more than 1 argument Hello I'm beginner in python and I'm trying to execute this program to create an inverted index for a collection file:
import sys
import re
from porterStemmer import PorterStemmer
from collections import defaultdict
from array import array
import gc

porter=PorterStemmer()

class CreateIndex:

def __init__(self):
    self.index=defaultdict(list)    #the inverted index

def getStopwords(self):
    '''get stopwords from the stopwords file'''
    f=open(self.stopwordsFile, 'r')
    stopwords=[line.rstrip() for line in f]
    self.sw=dict.fromkeys(stopwords)
    f.close()

def getTerms(self, line):
    '''given a stream of text, get the terms from the text'''
    line=line.lower()
    line=re.sub(r'[^a-z0-9 ]',' ',line) #put spaces instead of non-alphanumeric characters
    line=line.split()
    line=[x for x in line if x not in self.sw]  #eliminate the stopwords
    line=[ porter.stem(word, 0, len(word)-1) for word in line]
    return line

def parseCollection(self):
    ''' returns the id, title and text of the next page in the collection '''
    doc=[]
    for line in self.collFile:
        if line=='</page>\n':
            break
        doc.append(line)

    curPage=''.join(doc)
    pageid=re.search('<id>(.*?)</id>', curPage, re.DOTALL)
    pagetitle=re.search('<title>(.*?)</title>', curPage, re.DOTALL)
    pagetext=re.search('<text>(.*?)</text>', curPage, re.DOTALL)

    if pageid==None or pagetitle==None or pagetext==None:
        return {}

    d={}
    d['id']=pageid.group(1)
    d['title']=pagetitle.group(1)
    d['text']=pagetext.group(1)

    return d

def writeIndexToFile(self):
    '''write the inverted index to the file'''
    f=open(self.indexFile, 'w')
    for term in self.index.iterkeys():
        postinglist=[]
        for p in self.index[term]:
            docID=p[0]
            positions=p[1]
            postinglist.append(':'.join([str(docID) ,','.join(map(str,positions))]))
        print >> f, ''.join((term,'|',';'.join(postinglist)))

    f.close()

def getParams(self):
    '''get the parameters stopwords file, collection file, and the output index file'''
    param=sys.argv
    self.stopwordsFile=param[0]
    self.collectionFile=param[1]
    self.indexFile=param[2]

def createIndex(self):
    '''main of the program, creates the index'''
    self.getParams()
    self.collFile=open(self.collectionFile,'r')
    self.getStopwords()

    #bug in python garbage collector!
    #appending to list becomes O(N) instead of O(1) as the size grows if gc is enabled.
    gc.disable()

    pagedict={}
    pagedict=self.parseCollection()
    #main loop creating the index
    while pagedict != {}:
        lines='\n'.join((pagedict['title'],pagedict['text']))
        pageid=int(pagedict['id'])
        terms=self.getTerms(lines)

        #build the index for the current page
        termdictPage={}
        for position, term in enumerate(terms):
            try:
                termdictPage[term][1].append(position)
            except:
                termdictPage[term]=[pageid, array('I',[position])]

        #merge the current page index with the main index
        for termpage, postingpage in termdictPage.iteritems():
            self.index[termpage].append(postingpage)

        pagedict=self.parseCollection()

    gc.enable()

    self.writeIndexToFile()

if __name__=="__main__":
c=CreateIndex()
c.createIndex()

and it says that there is only 1 argument in the sys.argv...
how should the other arguments appear???

A: In the getParams function, you can see that your code request 3 parameters.
When you call your program:
python your_program.py
# sys.argv[0] = 'your_program.py'

It has 1 argument. So you need two more:
python your_program.py arg_1 arg_2
# sys.argv[0] = 'your_program.py'
# sys.argv[1] = 'arg_1'
# sys.argv[2] = 'arg_2


text:
Q: Using Windows Media Player in C# for sound So I've gone through about 10000 forums and postings that go about explaining how to use WindowsMediaPlayer for sound in my C# application.
What I have so far is
        WMPLib.WindowsMediaPlayer axMusicPlayer = new WMPLib.WindowsMediaPlayer();

        string path = Path.GetFullPath("music.mp3");

        axMusicPlayer.URL = path;

        axMusicPlayer.settings.setMode("loop", true);

        axMusicPlayer.controls.play();

Now, according to a million people this should work, but when I run the application there is no sound, maybe I'm missing something, but I've just about reached my breaking point with this one. I know you can use SoundPlayer, but I'm reserving that for sound effects, which is why I want to use WindowsMediaPlayer for music.

A: Try playing a .wav file. That worked for me.

A: I think you should try using the .. command to go to the parent directory in your file path.
Since the default path for GetFullPath takes you into the MyProject\bin\Debug folders you need to get back to MyProject
For example:
    string path = Path.GetFullPath(@"..\..\music.mp3");

This will take you out of the Debug and bin folders and to the main folder of your project.
I tried to use your solution and this worked for me!


text:
Q: ¿Cómo puedo convertir un String a Image? Ocupo tomar de la base de datos una Imagen pero no puedo porque dice que no puedo convetir de String a Image:
  public static Mascota mostrarImagen(Mascota mostrar) {

    String sql;

    java.sql.ResultSet rs;

    try {

        sql = "Select imagenMascota from TMascotas where idMascota = 2";

        rs = Conexion.getConector().ejecutarSQL(sql, true);

        mostrar.setImagenMascota(rs.getString("imagenMascota"));

    } catch (Exception e) {

        System.out.println("No se encuentra " + e);

    }

    return mostrar;
}

Y lo estoy guardando así:
    Mascota imagenMasc = new Mascota();
    Image foto = null;
    File archivo;
    try {
        JFileChooser flcAbrirArchivo = new JFileChooser();
        flcAbrirArchivo.setFileFilter(new FileNameExtensionFilter("archivo de imagen", "jpg", "jpeg"));
        int respuesta = flcAbrirArchivo.showOpenDialog(this);
        if (respuesta == JFileChooser.APPROVE_OPTION) {

            archivo = flcAbrirArchivo.getSelectedFile();
            jTextField1.setText(archivo.getAbsolutePath());
            foto = getToolkit().getImage(jTextField1.getText());
            foto = foto.getScaledInstance(110, 110, 1);
            jLabel4.setIcon(new ImageIcon(foto));

        }
        imagenMasc.setImagenMascota(foto);

        Gestor.guardarImagen(imagenMasc);
    } catch (Exception ex) {
        Logger.getLogger(RegistrarMascota.class.getName()).log(Level.SEVERE, null, ex);
    }

A: Tu error es que setImagenMascota, utiliza el prototipo setImagenMascota(java.awt.Image) (en algúna parte del mismo), no obstante tu le estás enviando un java.lang.String. Para crear una Imagen necesitas primero leer los datos de la base de datos como java.io.InputStream, posteriormente crear la Imagen analizando el flujo de bytes
...
mostrar.setImagenMascota(
  javax.imageio.ImageIO.read(
    rs.getBinaryStream("imagenMascota")
  )
);
...


text:
Q: npm run watch runs only once, React with Laravel 6 Good day,
I have an issue, and it is a week I can't figure out the reason.
I have no idea about Laravel, I only work on the front-end side of the project.
So, when I run the yarn watch or npm run watch command, to see live changes in the browser, it works only once.
Finally, when I do some changes and save the file to see the results on the browser, it seems that the watcher runs again but throws an error.
This is the Error thrown.
[webpack-cli] Error: The loaded module contains errors
at C:\OpenServer\domains\cuckoo\node_modules\webpack\lib\dependencies\LoaderPlugin.js:109:11
at C:\OpenServer\domains\cuckoo\node_modules\webpack\lib\Compilation.js:1934:5
at C:\OpenServer\domains\cuckoo\node_modules\webpack\lib\util\AsyncQueue.js:352:5
at Hook.eval [as callAsync] (eval at create (C:\OpenServer\domains\cuckoo\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1)
at AsyncQueue._handleResult (C:\OpenServer\domains\cuckoo\node_modules\webpack\lib\util\AsyncQueue.js:322:21)
at C:\OpenServer\domains\cuckoo\node_modules\webpack\lib\util\AsyncQueue.js:305:11
at C:\OpenServer\domains\cuckoo\node_modules\webpack\lib\Compilation.js:1396:15
at C:\OpenServer\domains\cuckoo\node_modules\webpack\lib\HookWebpackError.js:68:3
at _done (eval at create (C:\OpenServer\domains\cuckoo\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:9:1)
at Hook.eval [as callAsync] (eval at create (C:\OpenServer\domains\cuckoo\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:39:22)
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I have tried to

*

*delete node_modules, and reinstall,

*change node versions (from 8 to 18), but the project works only on version 17.18.1.

*change typescript version,

*change React version

Here are my scripts in package.json
  "scripts": {
"dev": "mix",
"lint": "eslint 'resources/js/**/*.{js,jsx,ts,tsx}'",
"lint:fix": "prettier-eslint --write 'resources/js/**/*.{js,jsx,ts,tsx}'",
"svgr": "npx @svgr/cli public/images/svg --icon --out-dir resources/js/components/UI/iconComponents --typescript --template svg-template.js --index-template icon-index-template.js",
"watch": "mix watch",
"hot": "mix watch --hot",
"prod": "mix --production"

},

I have no idea about Laravel.