text:
Q: On proving $\{0,1\}^\mathbb{N}\sim\{0,1,2\}^\mathbb{N}$ I'm trying to prove $\{0,1\}^\mathbb{N}\sim\{0,1,2\}^\mathbb{N}$ (the sets are equinumerous).
I have already proved that $\{0,1\}^\mathbb{N}\sim\mathbb{N}^\mathbb{N}$, with the following method:

*

*For every countable $X\subset\{0,1\}^\mathbb{N}$, $\{0,1\}^\mathbb{N}\sim\{0,1\}^\mathbb{N}\setminus X$.

*There exists an injective mapping $f:\mathbb{N}^\mathbb{N}\rightarrow \{0,1\}^\mathbb{N}$ for which $\{0,1\}^\mathbb{N}\setminus f\left(\mathbb{N}^\mathbb{N}\right)$ is countable

*From 1. and 2. it follows directly that $\{0,1\}^\mathbb{N}\sim\mathbb{N}^\mathbb{N}$

Points 1. and 3. should be clear, let me elaborate on 2. a little bit more by constructing this $f$.
Let $(n_0,n_1,\ldots)\in\mathbb{N}^\mathbb{N}$. We construct $(a_0,a_1,\ldots)\in\{0,1\}^\mathbb{N}$ by:

*

*The sequence starts with $n_0$ zeroes, so $a_0 = \ldots = a_{n_0-1} = 0$

*Then a one, so $a_{n_0}=1$

*We continue with $n_1$ zeroes, so $a_{n_0+1}=\ldots=a_{n_0+n_1-1}=0$

*$a_{n_0+n_1}=1$

*$\vdots$

Now the only sequences not reached are the ones that will be zero from some point on. This would namely require an ''$a_n=\infty$'' for some $n$. Thereby we constructed the injective $f$.
Now, what I want is a similar proof for $\{0,1,2\}^\mathbb{N}\sim\mathbb{N}^\mathbb{N}$, but I haven't been able to construct a function like in 2. Is this the way to go, or is there a direct way to prove equinumerosity?

A: $\{0,1\}^\Bbb N$ is the set of sequences of $0$s and $1$s. For example, $001101010\dots$. $\{0,1,2\}^\Bbb N$ is the set of sequences of $0$s, $1$s, and $2$s. For example, $110210100\dots$.
Define $f:\{0,1,2\}^\Bbb N\to\{0,1\}^\Bbb N$ by the following. For any sequence $S\in\{0,1,2\}^\Bbb N$, let $f(S)$ be $S$ with all $1$s replaced by $10$s, and all $2$s replaced by $11$s. For example:
$$f(110210100\dots)=10\,10\,0\,11\,10\,0\,10\,0\,0\dots$$
(spaces added to make it easier to read). Can you prove that $f$ is a bijection?

A: Hint:
It is much easier to show that $$\{0,1,2,3\}^{\mathbb N}\sim \{0,1\}^{\mathbb N}$$ and then show that there there are $1-1$ functions:
$$ \{0,1\}^{\mathbb N}\to \{0,1,2\}^{\mathbb N}\to \{0,1,2,3\}^{\mathbb N}$$

A: Since you already know $\{0,1\}^{\mathbb{N}} \cong \mathbb{N}^{\mathbb{N}}$, there is an injective map $\{0,1,2\}^{\mathbb{N}} \to \mathbb{N}^{\mathbb{N}} \cong \{0,1\}^{\mathbb{N}}$. There is also an injective map in the other direction, just the inclusion. Hence, you may apply the Schröder-Bernstein theorem.

A: Why not just use the Schröder-Bernstein theorem?
Let us build an injective map from $\{0,1,2\}^\mathbb{N}$ to $\{0,1\}^\mathbb{N}$. Given $A\in\{0,1,2\}^\mathbb{N}$, represented by $\{a_n\}_{n\in\mathbb{N}}$, with $a_n\in\{0,1,2\}$, we may consider the binary representation of:
$$ r_A = \sum_{n\geq 0}\frac{a_n}{10^{n+1}}.$$
In the opposite direction, given $B\in\{0,1\}^{\mathbb{N}}$, represented by $\{b_n\}_{n\in\mathbb{N}}$, with $b_n\in\{0,1\}$, we may consider the ternary representation of
$$ r_B = \sum_{n\geq 0}\frac{b_n}{10^{n+1}}.$$
The existence of these injective maps ensures $\left|\{0,1\}^{\mathbb{N}}\right|=\left|\{0,1,2\}^{\mathbb{N}}\right|$, i.e. $2^{\aleph_0}=3^{\aleph_0}$.
We chose $10$ in order to avoid ambiguities deriving from:
$$ 0.1111\ldots_2 = 1_2,\qquad  0.2222\ldots_3 = 1_3.$$

A: Consider the inclusion map $i:\{0,1\}^{\mathbb N}\to \{0,1,2\}^{\mathbb N}$, i.e. for a sequence $x:=\{x_n\}\in\{0,1\}^{\mathbb N}$, $i(x)_n = x_n$ for all $n$. Clearly $i$ is injective, so $\#\{0,1\}^{\mathbb N}\leqslant \#\{0,1,2\}^{\mathbb N}$.
Now consider the map $f:\{0,1,2\}^{\mathbb N}\to\{0,1\}^{\mathbb N}$ where
$$f(x) = \{\delta_{x_1,2},\delta_{x_1,1}, \delta_{x_3,2},\delta_{x_4,1}, \ldots, \delta_{x_{2n-1},2}, \delta_{x_{2n},1}, \ldots, \}.$$
Then if $f(x) = f(y)$, $f(x)_n=f(y)_n$, that is, $\delta_{x_{2n-1},2}=\delta_{y_{2n-1},2}$ and $\delta_{x_{2n},1}=\delta_{y_{2n},1}$ for all $n$. Since for any $n$, $f(x)_n,f(y)_n\in\{0,1\}$, it follows that $x_n=y_n$ for all $n$, and so $x=y$ and $f$ is injective. Hence $\#\{0,1,2\}^{\mathbb N}\leqslant \#\{0,1\}^{\mathbb N}$.


text:
Q: How to make a special auto-subtractor? I want to make with JS, a subtraction which auto-subtract the biggest number from the smallest one... How to do so ? Thanks

A: Using HTML5, if you listen for the oninput event of two <input type="number" /> fields, you can call Math.abs() on the difference between the two numbers, and it will update constantly.
Here's a small demo:

var input1 = document.getElementById("firstNum"),
    input2 = document.getElementById("secondNum"),
    output = document.getElementById("output");

input1.oninput = input2.oninput = function() {
  var num1 = parseInt(input1.value),
      num2 = parseInt(input2.value);
  output.innerHTML = Math.abs(num1 - num2);
};
Input 1: <input type="number" value="0" id="firstNum" />

Input 2: <input type="number" value="0" id="secondNum" />

Output: 0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hibernate Criteria for elements inside a Set I have one entity that contains a set of another entity.
Entity1 contains Set entityTwos
I want to create a search criteria for an "id" field inside entityTwos.
I searched, but didn't get any answers. Anybody have an idea?
Thanks,
Sri

A: It was easy. Something like:
criteria.createAlias("entityTwos", "entityTwo");
criteria.add(Restrictions.eq("entityTwo.id", ...));


text:
Q: Best way to transfer files over a LAN between two Linux computers I want to transfer files (a music folder) between two Linux computers. After searching for the best way to do this, I've seen that there are lots of ways of doing this. I know this has been asked a lot, everywhere and all the time. The main problem with this is that there is no clear, recent consensus on one best way to do this task in 2011 for Linux beginners (even depending on some parameters).
So in the spirit of the Stack Exchange websites, I want this not to be related to my particular situation, but more of a guide to others as well on how to transfer files between two Linux computers over a local network. I think a wiki would be useful for many.
Here's what I found so far:

*

*ssh

*sshfs

*scp

*sftp

*nfs

*samba

*giver

What is the easiest? Most flexible? Simplest? Best solution? What are the pros and cons of each? Are there other (better) options? What are the parameters in choosing the best method (solution might depend on number of files, filesize, easiness vs. flexibility, ...)?

A: In a Linux environment, for both security and ease of use, ssh is the best way to go. SSH, SSHFS, SCP, and SFTP as you list are all just different services built on top of the SSH protocol. SCP is very easy to use, it works just like CP but you can provide user and machine names in the path. So, we might do a CP like cp ~/music/ ~/newmusic/, but we could just as easily do scp ~/music/ user@host:~/newmusic to send it to the computer named host. That's it - we don't need to set anything up. You'll be prompted for the account password on the other machine if you don't have certificate or some other authentication set up (scp shares those settings with ssh, of course).
SFTP is a tool that makes it easy to do a lot of operations on a remote file system - it works just like FTP, but it runs through SSH so it's secure and requires only an SSH server. man sftp will tell you all about how to use it. I don't use SFTP just to move a folder between two machines, it's more useful when you have a lot of operations to do, like if you're rearranging files on another computer.
SSHFS just extends SFTP in to a file system: it allows you to mount a virtual host in to your file system, so the network stuff happens totally transparently. SSHFS is for semi-permanent setups, not just a one-time file transfer. It takes some more effort to get set up, which you can read about on the project website.
If you need to work in a mixed-OS environment, Samba becomes your next best bet. Windows and OS X support Samba completely automatically, and Linux does as well although it's sometimes rough to use.

A: My personal favorite for cases where security doesn't matter is netcat + tar:
To send a directory, cd to inside the directory whose contents you want to send on the computer doing the sending and do:
tar -cz . | nc -q 10 -l -p 45454
On the computer receiving the contents, cd to where you want the contents to appear and do:
nc -w 10 $REMOTE_HOST 45454 | tar -xz
Replace $REMOTE_HOST with ip / hostname of computer doing the sending. You can also use a different port instead of 45454.
What's actually happening here is that the 'receiving' computer is connecting to the sending computer on port 45454 and receiving the tar'd and gzip'd contents of the directory, and is passing that directly to tar (and gzip) to extract it into the current directory.
Quick example (using localhost as a remote host)
Computer 1
caspar@jumpy:~/nctest/a/mydir$ ls
file_a.txt  file_b.log
caspar@jumpy:~/nctest/a/mydir$ tar -cz . | nc -q 10 -l -p 45454

Computer 2
caspar@jumpy:~/nctest/b$ ls
caspar@jumpy:~/nctest/b$ nc -w 10 localhost 45454 | tar -xz
caspar@jumpy:~/nctest/b$ ls
file_a.txt  file_b.log

A: If it absolutely has to be done over the LAN, I'd use rsync, as it will pick up where it left off if it gets interrupted.  It also has a few other tricks for minimizing the amount of data that gets transferred, although I doubt that many/any of them would be relevant to the case of copying a music library to a virgin location.  If security is a concern, just set RSYNC_RSH=ssh first and the data will be tunneled over ssh.
If I were actually doing it, though, I probably wouldn't use the LAN at all.  I'd copy the files onto, then off of, a USB hard drive.  In my experience, this can easily be multiple orders of magnitude faster than going over the LAN, despite having to copy the files twice - USB 2.0 is rated for 480Mbps, which is faster than anything short of gigabit ethernet, plus it's less sensitive to conditions which will degrade the performance of a LAN.  It's also completely OS-independent, provided you use a file system that all involved machines can handle - I'd recommend VFAT/FAT32, since that's pretty much universal.

A: A lot of great answers were mentioned, I thought I would add another alternative, rclone and is a personal favourite because of it's support for many cloud storage providers and support for Windows.
On the host machine:
rclone serve sftp . --addr 0.0.0.0:2222

This will spin up an SFTP server, listening on port 2222 on all addresses. By default it will use the current user's authorized keys file (~/.ssh/authorized_keys)
On the client system:
You can use any SFTP-supported GUI or CLI program. Unfortunately, it doesn't seem to support SCP. But you can connect to the SFTP server in the terminal similar to
sftp -P 2222 dave@10.75.0.200

The rclone serve command also supports additional protocols, including Webdav, DLNA, FTP, HTTP(s), if you're limited to a certain protocol.
If you need to synchronize two folders, you could use the built-in sync command. However you'll need to configure rclone, using rclone config and add the remote FTP/SFTP server.
An example:
rclone sync /home/dave/projects localSftpServer:projects

A: I would suggest rsync as it will copy files incrementally.  You can set it up to copy either only modified or new files only once you have done the initial update.  You can use ssh as a transport layer if you wish.

A: I use Unison, which is an awesome file synchronizer over many different protocols. You can configure it to use scp, rcp, ftp or even locally on the filesystem between two folders. I use it to synchronize my music library, as it can transfer multiple files at once over the network and is really tuneable in its configuration. I keep my music collection backed up and in sync over 2-3 computers. It will only copy changed files, and does so by keeping an index on both ends of the transfer so as to be able to tell when a client has changed the file or when the server file has changed.
Your mileage may vary, but it's certainly a lot better than scping your entire music collection every time you add a new song :)

A: For one time moves, scp is recommended.
But if you find that this dir may work and you need to move it many times to keep the other position updated then you can use rsync (with ssh).
Since rsync has a lot of arguments I usually put it in a small shell so I get it right (every time). The idea is to only send things that has changed since the last time it ran.
#!/bin/bash

user="nisse"
host="192.168.0.33"

echo "Sync: /home/media/music/"
rsync --archive --delete -v --progress -e "ssh -l $user " /home/media/music/ $host:/home/media/music/

This will move a dir called "/home/media/music/" from the local computer to the the pc called 192.168.0.33, using user "nisse". And delete anything on the target that doesn't exist on the local pc.

A: Caspar's netcat approach is awesome for its simplicity, but there may be situations where you want don't want to send unencrypted files over the network.
To really get this right, you should probably use a mature solution like scp, SFTP, samba, or magic-wormhole (a really cool one, but as of the time of writing unfortunately not great for sending huge folders).
But considering you are in this situation:

*

*you don't want to setup a user account for the other party, or don't know how to configure it so the other person can't execute shell commands on your PC (so SCP/SFTP is out of the picture)

*the configuration overhead of FTPS/samba is too much as well for a one-off transfer

*your folders are too large for magic-wormhole

*and you don't expect serious attackers

The following solution may be interesting:
Using gpg -c for encryption
Pull mode:
serve (host):     tar -cz . | gpg -c --cipher-algo AES256 | ncat -lp 8000
fetch (client):   ncat HOST 8000 --recv-only | gpg -d | tar -xz

(here, using nmap's ncat implementation. For others, see below..)
Push mode:
In case the receiver is easier to connect to than the sender, you can easily invert their roles by changing the netcat commands in the pipeline:
send (client):    tar -cz . | gpg -c --cipher-algo AES256 | ncat HOST 8000
recv (host):      ncat -lp 8000 --recv-only | gpg -d | tar -xz

The host command always has to be executed first.
Password via command line:
If you want, the password can be provided on both ends using

*

*gpg [...] --batch --passphrase-fd 3 3<<<'PASSWORD', or

*gpg [...] --batch --passphrase-file <(cat <<<'PASSWORD'), or simply

*gpg [...] --batch --passphrase PASSWORD. However, this form should mostly be avoided, especially on multi-user systems.

Caution:
As far as I understand, GPG does authenticate the ciphertext against the password, but this happens very late, so that the tar extraction process may already be impossible to roll back and could have overwritten files in your local directory if some part of the ciphertext was replaced or incorrectly transmitted. For this reason, always cd to a new empty directory before doing this.
Note that I'm no expert on GPG/crypto and can't promise this is not immensively unsafe in other ways as well.
Things you could also try
OpenBSD netcat
I think it works, but no guarantees:
Pull mode:
serve (host):     ENCRYPT | nc -lNp 8000
fetch (client):   nc -d HOST 8000 | DECRYPT

Push mode:
send (client):    ENCRYPT | nc -N HOST 8000
receive (host):   nc -ldp 8000 | DECRYPT

GNU netcat
In theory, this could work:
Pull mode:
serve (host):     ENCRYPT | nc -clp 8000
fetch (client):   nc HOST 8000 | DECRYPT

Push mode:
send (client):    ENCRYPT | nc -c HOST 8000
receive (host):   nc -lp 8000 | DECRYPT

However, in my trials it often failed due to closing the connection before all bytes were sent/received.
This can be mitigated by either not specifying the -c option (in which case you have to close the connection manually using Ctrl+C, when you think it's done), or by building in some delay on the sender side:
(ENCRYPT; sleep 10s) | nc -clp 8000

Different netcat implementations on client/server
Should work.
Encrypt the stream using openssl enc
Serve files:
tar -cz . | openssl enc -e -aes-256-ctr -pbkdf2 | ncat -lp 8000

Fetch files:
ncat HOST 8000 --recv-only | openssl enc -d -aes-256-ctr -pbkdf2 | tar -xz

openssl will ask you for the password. Alternatively, you can provide the password using the -k PASSWORD command-line option on both ends, or on multi-user systems, using -pass file:<(cat<<<PASSWORD).
Beware that this does not provide authenticated encryption - which means that there is no guarantee that the stream is unaltered. So, someone could really mess up your filesystem if they change a few bytes. Although, you get basic redundancy checks in the gzip archive enabled by the -z option, this will not reliably protect you. This is probably fine to protect a love letter against your friends, but don't use it if there may be someone even more nefarious in the network!
Unfortunately, openssl's enc doesn't support any authenticated encryption modes.
Using zip for encryption
Server:
tar -cz . | zip -e -Ppassword | ncat -lp 8000

Client:
ncat HOST 8000 --recv-only | funzip -password | tar -xz

Seems to work, but prints the following error:
funzip error: invalid compressed data--length error

(not due to network errors, I get the same error when calling funzip in a local pipe, like echo text | zip | funzip.)

A: I would recommend you trying alternatives instead going straight with SSH for moving files inside your own LAN as the overhead is IMMENSE.
I would go with Caspar's solution if this one for whatever reason won't work for you:
At the source:
$ python3 -m http.server {PICK_YOUR_PORT}

On destination:
$ wget -r {ip / hostname}:{port}/{File / Directory}

This won't only be lighter than using SSH but far faster with speeds ranging 45~65MiB on standard CAT6 UTP.
If you really want to squeeze the most out of the connection try replacing wget with lftp and using pget -n20 and mirror -r commands.

A: The fastest is probably netcat (as caspar described).
I like the combination of tar & ssh, which is secure and still fast:
On the source
tar -cf - . | ( ssh user@target && cd /target/path && tar -xf - )

Doing that as root, it preserves file permissions. Or use -p on both sides. Also -S might be considered if you have sparse files.
It's possible to reduce the encryption overhead of ssh if you use arcfour as cipher which works with openSSH:
tar -cpSf - . | ( ssh -c arcfour user@targethost && cd /target/path && tar -xpSf - )

To update the remote path, rsync is perfect:
rsync -av --sparse --delete -e "ssh -c arcfour" . root@targethost:/target/path

A: I followed ssh process for passwordless login first http://www.tecmint.com/ssh-passwordless-login-using-ssh-keygen-in-5-easy-steps/
For scripts and text files the following works for me just fine
To transfer data from local host to remote host.
cat localfile | ssh <user>@<ip> "cat > <path>/<remotefile>"
To transfer data from remote host to local host.
ssh <user>@<ip> "cat > <path>/<remotefile>" | cat > localfile
This works for me to transfer files on embedded systems that don't have ssh client or scp built in.
No scp - only ssh.


text:
Q: Quiero imprimir los datos en un excel dinamico Hola amigos tengo el siguiente codigo.
  const students = [
        {
            name: 'John', edad: '25',
        },
        {
            name: 'Jane', edad: '23',
        },
        {
            hobbies: 'Cinema'
        }
    ]
const ws = XLSX.utils.json_to_sheet(students);

const wb = XLSX.utils.book_new();

XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
console.log(wb)
//ginerate boofer
const buffer = XLSX.write(wb, { bookType: 'xlsx', type: 'buffer' });
// binary data
XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

XLSX.writeFile(wb, 'file.xlsx');

cuando le digo a la libreria XLSX que me exporta esa data me sale asi:

y lo que yo quiero que me salga es:


text:
Q: Change Page for jQuery Mobile between two html files I'm trying to make a simple site with two pages, "Search" and "Results".
At first, I had a multi-page template working fairly well.  I would change the page, and on page change I would use ajax to get the results.  The problem was that I wanted to be able to load the results page without first going back to the search page.
I want to pass parameters to the results page via the querystring so that I can have something like this:
search.html + "some search terms"  ->  results.html?q=some+search+terms
The problem is that I can't seem to get anything to work right when I split up the html into two files.
I try calling
$.mobile.changePage("results.html?q=" + escape(search))

on the search page, but the $(document).ready function is not firing.  I kind of get why it doesn't, since changePage is loading the second page into the DOM?
I also tried manually redirecting, in which case the $(document).ready function does fire on results.html, but using the back button or going back to the search page doesn't fire THAT $(document).ready.
I tried wiring up the pagechange function to search.html, assuming that this would fire when I load the second page, but nothing happened.
Does anyone have suggestions as to how I would pull this off?  Or the best way to get the results page to act more independent of the search page?

A: I've been bitten by this too, it really isn't a good idea to pass parameters through the query string and it makes jQueryMobile behave in an odd way.
Instead I've been using sessionStorage which works perfectly. You could also use a cookie.

A: I'm not 100% sure where you're actually having issues, but here is some important jQuery Mobile specific info that can help you.
First, read the big yellow section at the top of this page: http://jquerymobile.com/demos/1.1.0/docs/api/events.html
document.ready does not fire when a page is brought into the DOM from an external document. Instead you need to use event delegation and the page-events specified in the link above. Most likely you want to use pageinit as a replacement for document.ready.
Then read the top section of this page: http://jquerymobile.com/demos/1.1.0/docs/api/methods.html (the part about $.mobile.changePage()).
The important part about the second link is that you can pass data via the $.mobile.changePage() function like so:
$.mobile.changePage('results.html', { data : { q : search } });

You can even set the type option to post so there will not be a query-string sent (this should ensure you don't get multiple of the same page in the DOM at a time).
$.mobile.changePage('results.html', { data : { q : search }, type : 'post' });

Another fix would be to manually add the data-url attribute to the <div data-role="page" id="results"> page. When you grab a page like this:
 $.mobile.changePage("results.html?q=search+term+here");

It's data-url gets set to: results.html?q=search+term+here. If you manually set the data-url to results.html then you can navigate to the page like this:
 $.mobile.changePage("results.html", { data : { q : 'search+term+here' } });

Which will look first for the data-role="page" element that has the data-url attribute set to results.html before re-loading the pseudo-page via AJAX.

A: Thanks for the input guys. I used a plugin that allows me to use faux-query parameters in the hash for a multi-page layout.
https://github.com/jblas/jquery-mobile-plugins/tree/master/page-params
I just added this in and ran the search on page change, getting those page parameters for the search.


text:
Q: did not working well..what should i do i've try to session above the <!doctype>..but when i check the syntax by using PHPtester ..the output was:
"FATAL ERROR syntax error, unexpected 'is' (T_STRING) on line number 1"
the syntax:
 <?php session_start(); ?>
<!doctype html>

<meta charset="utf-8">

<form id="userForm" method="post" action="form-process.php">

    <fieldset>
    <legend>User Information</legend>

    <?php
    if(isset($_SESSION['error']) && isset($_SESSION['formAttempt'])){
        unset($_SESSION['formAttempt']);
        print "Errors encountered
\n";
        foreach($_SESSION['error'] as $error){
            print $error."
\n";
        } //end foreach
    }//end if
    ?>

A: Are you talking about http://phptester.net/? It's ridiculous, it changes checked code.
Try http://sandbox.onlinephpfunctions.com/ - your code is fine there.


text:
Q: Unity Animation Plays In Preview But Not When Playing Game I made a simple animation for a sword gameobject to constantly slowly move up and down while the player character is standing still.
My sword has an Animator component attached:

The Animator Controller is also very simple, with this animation being attached to my default state:

The animation plays just fine in the preview mode of the Animation window. But when I run my game, the animation does not play at all, the sword just stands still instead of moving.
What is the cause of this problem?

A: I finally solved the problem. It turns out that all I needed to do was turn off "Apply Root Motion" on my Animator for it to work properly.

A: In case you are testing out on an Android Device I would suggest you to go to Build Settings > Player Settings > Other Settings > Uncheck "Static Batching". Build and deploy apk on your phone. Animations should work smoothly now.


text:
Q: What's the difference between a "stopped" and an "exited" container? Is there a functional difference here?  I can docker start either one to make it go again.  What's the difference?

A: It is quite different.
A stopped container can be restarted, unlike an exited container.
Suppose you have a stopped container, which has an id of 21F123 (that is enough to identify it).
docker start 21F123
may succeed.
If you container exits, you can try again ti launch it, but it will have a new, different pid in
docker ps


text:
Q: if is_grandchild for single and category I've been searching around and can't seem to find (or piece together) code that checks to see if the current category OR post is a grandchild of a certain category. Basically, is there any way to properly code for:
<?php if ( is_grandchild(147) || in_grandchild(147) ) { do something } ?>

A: function get_topmost_parent($post_id){
  $parent_id = get_post($post_id)->post_parent;
  if($parent_id == 0){
    return $post_id;
  }else{
    return get_topmost_parent($parent_id);
  }
}

try this will return top mostparent !


text:
Q: Как сложить словари в цикле Есть код, который перебирает один список для другого, преобразуя все это в словари.
all_colors = ["black", "silver", "gray", "white", "maroon", "red", "purple"]
all_models = ["Audi RS2", "Vauxhall Ampera", "Dacia Duster", "Lamborghini Gallardo"]

h = {}
for i in all_models:
    for k in all_colors:
        d = {i: k}
        h.update(d)
print(h)

Дело в том, что на выходе я получаю
>>> {'Audi RS2': 'purple', 'Vauxhall Ampera': 'purple', 'Dacia Duster': 'purple', 'Lamborghini Gallardo': 'purple'}

Хотя, по идее, должно быть так
>>> {'Audi RS2': 'black', 'Audi RS2': 'silver', ... 'Vauxhall Ampera': 'black', 'Vauxhall Ampera': 'silver' и т.д.}

Когда прописываю print(d) внутри цикла, то все хорошо, словари формируются как надо, осталось только соединить, но update соединяет почему-то только последний цвет в списке для каждой машины другого списка. Прошу помощи с этим у вас, как исправить?

A: Используйте zip для одновременного перебора двух (и более коллекций):
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
...     print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')


text:
Q: Mock Beans from Spring Context I want create tests working with the Spring Context, with mocked Repository beans. I'm using Spring Boot 1.3.2.BUILD-SNAPSHOT + JUnit + Mockito.
Here is my Test config class:
@ComponentScan(basePackages = "myapp", excludeFilters =
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
        value = {
                OfferRepository.class
        }
)
)
@Configuration
public class TestEdge2EdgeConfiguration {

    @Bean
    public OfferRepository offerRepository() {
       return mock(OfferRepository.class);
    }

}

Purpose of this configuration is to exclude OfferRepository from Spring Context and mock it, thank to this I'll be able to write tests who are using Spring Context with mocked database Repository.
Here is my test class:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestEdge2EdgeConfiguration.class})
@WebAppConfiguration
public class OfferActionsControllerTest {

    @Autowired
    private OfferRepository offerRepository;

    @Autowired
    private OfferActionsController offerActionsController;

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void saveOffer() {
        //given
        BDDMockito.given(offerRepository.save(any(Offer.class))).willReturn(new Offer());
        //when
        ResponseEntity<Offer> save = offerActionsController.save(new Offer());

        //then
        org.springframework.util.Assert.notNull(save);
    }
}

Test and test configuration directory is:
src/test/java/myapp

My application configuration and packages containing OfferRepository directory is:
src/main/java/myapp/

The problem is that Spring Boot is not loading my configuration from TestEdge2EdgeConfiguration.class and mock for OfferRepository  is never created.
Can any body help me with this, please?

A: This is how you should be doing it (Assuming you are writing a test for offerActionsController and injecting offerRepository):
@Mock
private OfferRepository offerRepository;

@InjectMocks
private OfferActionsController offerActionsController;

@Before
public void setUp(){
    MockitoAnnotations.initMocks(this);
}

You can write your test method as follows:
@Test
public void saveOffer() {
    /* Given */
    Mockito.when(offerRepository.save(Mockito.any(Offer.class))).thenReturn(new Offer());

    //when
    ResponseEntity<Offer> save = offerActionsController.save(new Offer());

    //then
    org.springframework.util.Assert.notNull(save);
}

A: Use Spingockito to replace the bean with a mock using @ReplaceWithMock. Don't forget to use @Autowired with @ReplaceWithMock if you need access to the mocked bean in the test.


text:
Q: How to Access PHP File in Separate Folders I'm trying to link a website system in php, and I encountered a problem when organizing sub folders. For example, I have a php file in the directory path C:/Demo/Subfolder/index.php, and it has a php include function that links to another php file in C:/Demo/header.php (by using the backing out of folders tool). Then my header.php is linking to an image. The image is in C:/Demo/image.png (same folder as header).
The code for index.php:
<?php
include("../header.php");
?>

The code for header.php:

When I open up header.php, it shows the image.
When I open up index.php, it can't find the image. This is because it is trying to find the image using the directory C:/Demo/Subfolder/image.png based off of the location of index.php rather than the location of header.php.
How do I access the image in both header.php and index.php without copying it over or moving it around?

A: Try like this

If you use without / the code will take the same folder where you call...

A: it is better you use direct Address
include_once(addslashes(realpath($_SERVER['DOCUMENT_ROOT'])).((DIRECTORY_SEPARATOR == '/') ? '/' : '\\\\')."Folder example/header.php");

////defining CONST for recognition your Operation System  is windows or linux or mac USE / OR \....
define('DS', ((DIRECTORY_SEPARATOR == '/') ? '/' : '\\\\'));
define('_Site_PATH_', addslashes(realpath(dirname(__FILE__))) . DS );


text:
Q: Is ubuntu 18.10 using Wayland as default? Do you know please if ubuntu 18.10 uses wayland as default?

A: It uses X.Org. 18.10 release notes don't mention it, but 18.04 mentions that they switched from Wayland to X.Org:

X is the default display server. Wayland is provided as a Technical Preview and is expected to be the default display server in 20.04 LTS

A: From: Is this cuttlefish really all that cosmic? Ubuntu 18.10 arrives with extra spit, polish, 4.18 kernel
This:

Wayland fans will be saddened but unsurprised to learn that Ubuntu
  has, sensibly, stuck with X this time around, although you can switch
  if you really want to. However, for most users, what comes out of the
  box works more than adequately.


text:
Q: How to convert PC or Laptop into ISP provider to Router? I need some information about the router. I want to test the Broadband Device for the frequency range, Bandwidth and control the Bandwidth also so I need to take the control of Broadband Device is an option for the above questions please let me know. thanks for the contributions.

A: I think your question is not certainly clear that you can use your hotspot tethering service but still, the ISP will be the one who is providing you the broadband facility, so please edit your question and provide more information.


text:
Q: How can I gets histogram using arrays in java? Take input from user in an array in form of numeric and show histogram Where i'm     wrong The code is given in java the user can enter 5 input in number and  histogram should show in any form with no constraints
package p21;
import java.util.Scanner;

public class P21 {
 public static void main(String[] args) {
   {
    int count[] = new int[10]; // count array will keep elements of element
    // in particular range;
    int elements[]; // for example   27 15 34 22 11 11 19
    { // in above input there is count[0]=0;
     for (int i = 0; i < elements.length; i++) // count[1]=4 and count[2]=2 and count[3]=1;
     {
      if (elements[i] >= 0 && elements[i] < 50) {
       if (elements[i] < 10) {
        count[0]++;}
        else if (elements[i] >= 10 && elements[i] < 20) {
        count[1]++;}
        else if (elements[i] >= 20 && elements[i] < 30) {
        count[2]++;}
        else if (elements[i] >= 30 && elements[i] < 40) {
        count[3]++;}
        else {
        count[4]++;
       }}
       else if (elements[i] >= 50 && elements[i] <= 100) {
       if (elements[i] < 60) {
        count[5]++;}
        else if (elements[i] >= 60 && elements[i] < 70) {
        count[6]++;}
        else if (elements[i] >= 70 && elements[i] < 80) {
        count[7]++;}
        else if (elements[i] >= 80 && elements[i] < 90) {
        count[8]++;}
        else {
        count[9]++;

      }}}}

     {
     System.out.println("Histogram of the elements:");
     for (int i = 0; i < count.length; i++) // this loop will print line
     {
      for (int j = 0; j < count[i]; j++) // this will print elements element(*)
      { // at each line.
       System.out.print("* ");
      }
      if (count[i] != 0) // if line does'nt contain zero
       System.out.println(""); // then if will change the row;
     }
    }
   }
   /*
   in above code if count[i]=zero means if there is elements
   element in particular range say [0-9] then it will
   elementst jump on next line;
   */
   {
    {
     Histogram hg = new Histogram();
     System.out.println("Enter the elements of Elements want in a  Histogram:");
     Scanner sc = new Scanner(System.in);

     int noOfElements = sc.nextInt();
     int histogramElements[] = new int[noOfElements];

     System.out.println("Enter the Elements for Histogram:");
     for (int i = 0; i < noOfElements; i++) {
      histogramElements[i] = sc.nextInt();
     }

     hg.showHistogram(histogramElements);
    }

A: For your binning approach.....  since you only care about groups of 10. Divide the input number by 10.   Bound the divided result then use the result to index your counter array.


text:
Q: Find $\int F.dr$ where $F= \frac{y i - x j}{x^{2}+y^{2}}$ and $C$ is the circular path $x^{2} + y^{2} = 1$ in cartesion coordinate system. Find $\int F.dr$ where $F= \frac{y i - x j}{x^{2}+y^{2}}$ and $C$ is the circular path $x^{2} + y^{2} = 1$ described in counter clockwise sense.
The formula for flux is $\int {F_1 dy - F_2 dx}$ where $$F_1 = \frac{y}{(x^{2}+y^{2})},$$ $$F_2 = \frac{-x}{x^{2} + y^{2}}$$
$$\int F.dr = \int (\frac{y}{x^{2}+y^{2}}dy - \frac{-x}{x^{2}+y^{2}}dx$$
$$=\int_{-1}^{1} ydy + xdx$$
$($since $(x^{2}+y^{2} = 1$ and in given circle both x and y vary from -1 to 1 $)$
so the flux I get is
$2$ which is not right answer.
the right answer is $-2\pi$ which can be found by using polar coordinates and applying same formula of flux , i used in above method.
What is wrong with the method I applied to evaluate flux? How to find flux using cartesion coordinates?

A: It's hard to understand what you really meant, but first parametrize the unit canonical circle (positive direction):
$$r(t)=(\cos t,\,\sin t)\;,\;\;t\in[0,2\pi]\implies r'(t)=(-\sin t,\,\cos t)$$
so
$$\int_c\vec F\cdot d\vec r=\int_0^{2\pi}(\sin t,\,-\cos t)\cdot(-\sin t,\,\cos t)dt=\int_0^{2\pi}-dt=-2\pi$$
In cartesian coordinates:
With $\;y=\pm\sqrt{1-x^2}\;$ (upper and lower semicircle, resp.), we can do the parametrizations:
$$\begin{cases}r_1(x)=(x,\,\sqrt{1-x^2})\implies r_1'(x)=\left(1,\,-\frac x{\sqrt{1-x^2}}\right)\\{}\\
r_2(x)=(x,\,-\sqrt{1-x^2})\implies r_2'(x)=\left(1,\,\frac x{\sqrt{1-x^2}}\right)\end{cases}\;\;,\;\;\;-1\le x\le 1$$
and from here (be very careful with the direction!!):
$$\text{Over the upper semicircle $C_1$}: -\int_{C_1}\frac{\sqrt{1-x^2}}{x^2+y^2}dx-\frac x{x^2+y^2}dy =$$
$$=-\int_{-1}^1\left(\sqrt{1-x^2}+\frac{x^2}{\sqrt{1-x^2}}\right)\,dx=-\int_{-1}^1\frac{dx}{\sqrt{1-x^2}}=-\int_{-\pi/2}^{\pi/2}dt=-\pi$$
I'll let you try to complete the calculation on the lower semicircle.

A: The mistake comes from the fact that what you are trying to compute is not a flux (I believe that is called circulation in english). The formula for the (1-dim) flux is
$$
\Phi= \int_C \mathbf{F} \cdot \mathbf{n} d s
$$
where $\mathbf{n}$ is the unit vector normal to the curve $C$ pointing out, while $ds$ is the arclength on the curve $C$.
The above integral is clearly zero as $\mathbf{F}$ is tangent to the circle $C$.  By the way this also shows up in your calculation as $\int_{-1}^1 x dx =0$.
However what you are given is, presumably,
$$
\int_C \mathbf{F} \cdot \mathbf{dr}
$$
where $\mathbf{dr}$ is the infinitesimal arclength times the unit tangent to the curve.
In this case
$$
\mathbf{F} \cdot \mathbf{dr} = -\frac{1}{r} ds
$$
integrating this over $C$ you obtain $-2\pi$. This is essentially the derivation in polar coordinates


text:
Q: When I resize my window and make it smaller I get this white gap at the bottom of my project

body{
    margin-top: 140px;
}
.outline{
    font-size: 75px;
    text-align: center;
    text-shadow:
    0 0 7px #fff,
      0 0 10px #fff,
      0 0 21px #fff,
      0 0 42px #999,
      0 0 82px #999,
      0 0 92px #999,
      0 0 102px #999,
      0 0 151px #999;;
    -webkit-text-stroke:1px white;
  -webkit-text-fill-color:transparent;
}
.container{
    max-width: 400px;
    margin:10vh auto 0 auto;
    box-shadow: 0px 0px 43px 17px grey;
}
#display{
    text-align: right;
    height: 120px;
    line-height: 120px;
    padding-top: 18px;
    font-size: 50px;
    font-weight: 200;
    border-left: 1.5px solid #999;
    color: white;
    text-shadow: 0 0 10px white;
}

.buttons{
    display: grid;
    border-bottom: 1px solid #999;
    border-left: 1px solid #999;
    border-bottom: 3px solid #edebe8;
    grid-template-columns: repeat(4,1fr);
    font-weight:200px;
    color:white;
}

.buttons > div {
    border-top: 2.5px solid #edebe8;
}

.button{
    border:0.5px solid #999;
    line-height: 100px;
    text-align: center;
    font-size: 25px;
    cursor:pointer;
}

#equal{
    background-color: whitesmoke;
    font-size: 35px;
    opacity: 0.3;
    color:black;
}

.button:hover{
    background-color: #323330;
    color:white;
    transition: 0.5s ease-in-out;
}
.foot{
    position: relative;
    text-align: center;
    top:200px;
    color:white;
    text-shadow: 0 0 10px white;
}
@keyframes move-twink-back {
    from {background-position:0 0;}
    to {background-position:-10000px 5000px;}
}
@-webkit-keyframes move-twink-back {
    from {background-position:0 0;}
    to {background-position:-10000px 5000px;}
}
@-moz-keyframes move-twink-back {
    from {background-position:0 0;}
    to {background-position:-10000px 5000px;}
}
@-ms-keyframes move-twink-back {
    from {background-position:0 0;}
    to {background-position:-10000px 5000px;}
}

@keyframes move-clouds-back {
    from {background-position:0 0;}
    to {background-position:10000px 0;}
}
@-webkit-keyframes move-clouds-back {
    from {background-position:0 0;}
    to {background-position:10000px 0;}
}
@-moz-keyframes move-clouds-back {
    from {background-position:0 0;}
    to {background-position:10000px 0;}
}
@-ms-keyframes move-clouds-back {
    from {background-position: 0;}
    to {background-position:10000px 0;}
}

.stars, .twinkling {
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  width:100%;
  height:100%;
  display:block;
}

.stars {
  background:#000 url(http://www.script-tutorials.com/demos/360/images/stars.png) repeat top center;
  z-index:-2;
  min-height: 100%;
}

.twinkling{
  background:transparent url(http://www.script-tutorials.com/demos/360/images/twinkling.png) repeat top center;
  z-index:-1;
  -moz-animation:move-twink-back 200s linear infinite;
  -ms-animation:move-twink-back 200s linear infinite;
  -o-animation:move-twink-back 200s linear infinite;
  -webkit-animation:move-twink-back 200s linear infinite;
  animation:move-twink-back 200s linear infinite;
  min-height: 100%;
}
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Calculator</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles/style.css">
        <link rel="stylesheet" href="styles/background.css">

The Galaxy Calculator

%

/

C

←

7

8

9

*

4

5

6

-

1

2

3

+

&plusmn

0

.

=

©MSA 2021, The Galaxy Calculator; Design by Samee

I tried fixing the margins however it still leaves a bit of whitespace at the bottom. I tried removing certain elements, adjusting my width and height for different tags to see if it made a difference and still the same. I'm guessing it has something to do with my stars and twinkle div. Also when i check my project in developer tools my html and body tag dont extend to the bottom of the page. Really confused, any help would be appreciated.

A: You had to remove position:relative from your .foot css rule so that your footer doesn't mess up the layout.
Plus for the background to fit the entire page also when you resize the window, I moved the css property in the body selector:
background: #000 url(http://www.script-tutorials.com/demos/360/images/stars.png) repeat top center;
But more importantly, the height 100% to work needs a parent with a determined height except for the root element. So the quickest solution was to set height:100% to the html element through a css rule.
You can see with your own eyes running the snippet and going full page:

html{
  height: 100%;
}

body{
  margin-top: 140px;
  background: #000 url(http://www.script-tutorials.com/demos/360/images/stars.png) repeat top center;
}
.outline{
    font-size: 75px;
    text-align: center;
    text-shadow:
    0 0 7px #fff,
      0 0 10px #fff,
      0 0 21px #fff,
      0 0 42px #999,
      0 0 82px #999,
      0 0 92px #999,
      0 0 102px #999,
      0 0 151px #999;;
    -webkit-text-stroke:1px white;
  -webkit-text-fill-color:transparent;
}
.container{
    max-width: 400px;
    margin:10vh auto 0 auto;
    box-shadow: 0px 0px 43px 17px grey;
}
#display{
    text-align: right;
    height: 120px;
    line-height: 120px;
    padding-top: 18px;
    font-size: 50px;
    font-weight: 200;
    border-left: 1.5px solid #999;
    color: white;
    text-shadow: 0 0 10px white;
}

.buttons{
    display: grid;
    border-bottom: 1px solid #999;
    border-left: 1px solid #999;
    border-bottom: 3px solid #edebe8;
    grid-template-columns: repeat(4,1fr);
    font-weight:200px;
    color:white;
}

.buttons > div {
    border-top: 2.5px solid #edebe8;
}

.button{
    border:0.5px solid #999;
    line-height: 100px;
    text-align: center;
    font-size: 25px;
    cursor:pointer;
}

#equal{
    background-color: whitesmoke;
    font-size: 35px;
    opacity: 0.3;
    color:black;
}

.button:hover{
    background-color: #323330;
    color:white;
    transition: 0.5s ease-in-out;
}
.foot{
    /*position: relative;*/
    text-align: center;
    top:200px;
    color:white;
    text-shadow: 0 0 10px white;
}

/*-------------------------------------------*/

@keyframes move-twink-back {
    from {background-position:0 0;}
    to {background-position:-10000px 5000px;}
}
@-webkit-keyframes move-twink-back {
    from {background-position:0 0;}
    to {background-position:-10000px 5000px;}
}
@-moz-keyframes move-twink-back {
    from {background-position:0 0;}
    to {background-position:-10000px 5000px;}
}
@-ms-keyframes move-twink-back {
    from {background-position:0 0;}
    to {background-position:-10000px 5000px;}
}

@keyframes move-clouds-back {
    from {background-position:0 0;}
    to {background-position:10000px 0;}
}
@-webkit-keyframes move-clouds-back {
    from {background-position:0 0;}
    to {background-position:10000px 0;}
}
@-moz-keyframes move-clouds-back {
    from {background-position:0 0;}
    to {background-position:10000px 0;}
}
@-ms-keyframes move-clouds-back {
    from {background-position: 0;}
    to {background-position:10000px 0;}
}

.stars, .twinkling {
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  width:100%;
  height:100%;
  display:block;
}

.stars {
  /*backgbackgroundround:#000 url(http://www.script-tutorials.com/demos/360/images/stars.png) repeat top center;*/
  z-index:-2;
  min-height: 100%;
}

.twinkling{
  background:transparent url(http://www.script-tutorials.com/demos/360/images/twinkling.png) repeat top center;
  z-index:-1;
  -moz-animation:move-twink-back 200s linear infinite;
  -ms-animation:move-twink-back 200s linear infinite;
  -o-animation:move-twink-back 200s linear infinite;
  -webkit-animation:move-twink-back 200s linear infinite;
  animation:move-twink-back 200s linear infinite;
  min-height: 100%;
}
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Calculator</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">

The Galaxy Calculator

%

/

C

←

7

8

9

*

4

5

6

-

1

2

3

+

&plusmn

0

.

=

©MSA 2021, The Galaxy Calculator; Design by Samee


text:
Q: The associated prime ideals of $Ext^i_R(M,N)$ If R is a commutative noetherian ring, M and N are modules with M finite. It is well known in commutative algebra that $AssHom_R(M,N)=Supp(M)\cap Ass(N)$. But I want to know whether there is a formular for $AssExt_R^i(M,N) ?$ Thanks!

A: The short answer is no, as hinted at in the comments by Karl and Graham. I would argue that even the question of understanding the minimal primes of $\text{Ext}^i(M,N)$ (which is the minimal set of the associated primes, hence an easier question) is intractable. Let's assume that $R$ is Noetherian and $M,N$ are finitely generated.
Since $\text{Ext}$ localizes, one essentially needs to understand when $\text{Ext}^i(M,N)$ vanishes over a local ring $R$. There is no good answer in general. Even in the very nice case when $N$ is the canonical module (assuming it exists), these $\text{Ext}$ are Matlis dual to the local cohomology modules of $M$, and while there are good bounds on the indices when they vanish (below the depth and beyond the dimension), there are no general result which can tell you exactly when.
Here is one more way to see the complexity of the problem even when $i=1$. Take a free cover of $M$ to get an exact sequence $0 \to M_1 \to F \to M \to 0$. Applying $\text{Hom}(-,N)$ to get:
$$0 \to \text{Hom}(M,N) \to \text{Hom}(F,N) \to \text{Hom}(M_1,N) \to  \text{Ext}^1(M,N) \to 0$$
Assuming some mild condition on $M,N$ (reflexive for example), this shows that the set of associated prime of $\text{Ext}^1(M,N)$ is a subset of the set of primes $p$ such that $\text{depth}(\text{Hom}(M,N)_p) = 2$. Again, this set is not very well understood in general.


text:
Q: making changes to svg element on the fly I'm new to react, here i have svg element which is not in my code as you can see code i have provided, but it is in console, i want to change those 'height: 569px;width: 800px;' to height: 100%;width: 100%; my problem is, that does not have className and neither and id, so how can i change those values ? the other one which is above it i have changed that using that id.
that svg element have just 'name'

const _zoomConfig = () => {
    const z = d3Select(`#graph-id-graph-wrapper`)
      .call(d3Zoom() as any)
      .on('wheel.zoom', null)
      .on('dblclick.zoom', null)
      .on('mousedown.zoom', null)
      .on('touchstart.zoom', null)
      .on('touchmove.zoom', null)
      .on('touchend.zoom', null);
  };

  useEffect(() => {
    _zoomConfig();
  });
#graph-id-graph-wrapper {
  /* margin-left: -100%; */
  width: 100%;
  height: 100%;
}

console:

i dont know if this is reacts way, i have tried this:

useEffect(() => {
    const k = Array.from(document.getElementsByTagName('svg')).map(
      (elem) => elem,
    );

    k.map((elem) => {
      if (elem.getAttribute('name') === 'svg-container-graph-id') {
        elem.setAttribute('height', '100%');
        elem.setAttribute('width', '100%');
      }
    });
  });

it doesnt affect it:

English is not my mother language so there could be mistakes.

A: You could change the inline style properties instead:
elem.style.width = '100%';
elem.style.height = '100%';

But I guess the graphs dimensions i.e. aspect ratio is also needed for a proper display. So adding a viewBox attribute might be a good idea:
elem.setAttribute('viewBox', '0 0 569 800');

Ideally you'll set these properties on creation/initialization.
See also: A simple way to make D3.js charts responsive


text:
Q: Алгоритм сортировка Решал такую задачу:
Тимофей решил организовать соревнование по спортивному программированию, чтобы найти талантливых стажёров. Задачи подобраны, участники зарегистрированы, тесты написаны. Осталось придумать, как в конце соревнования будет определяться победитель.
Каждый участник имеет уникальный логин. Когда соревнование закончится, к нему будут привязаны два показателя: количество решённых задач Pi и размер штрафа Fi. Штраф начисляется за неудачные попытки и время, затраченное на задачу.
Тимофей решил сортировать таблицу результатов следующим образом: при сравнении двух участников выше будет идти тот, у которого решено больше задач. При равенстве числа решённых задач первым идёт участник с меньшим штрафом. Если же и штрафы совпадают, то первым будет тот, у которого логин идёт раньше в алфавитном (лексикографическом) порядке.
Тимофей заказал толстовки для победителей и накануне поехал за ними в магазин. В своё отсутствие он поручил вам реализовать алгоритм быстрой сортировки (англ. quick sort) для таблицы результатов. Так как Тимофей любит спортивное программирование и не любит зря расходовать оперативную память, то ваша реализация сортировки не может потреблять O(n) дополнительной памяти для промежуточных данных (такая модификация быстрой сортировки называется "in-place").
Как работает in-place quick sort
Как и в случае обычной быстрой сортировки, которая использует дополнительную память, необходимо выбрать опорный элемент (англ. pivot), а затем переупорядочить массив. Сделаем так, чтобы сначала шли элементы, не превосходящие опорного, а затем —– большие опорного.
Затем сортировка вызывается рекурсивно для двух полученных частей. Именно на этапе разделения элементов на группы в обычном алгоритме используется дополнительная память. Теперь разберёмся, как реализовать этот шаг in-place.
Пусть мы как-то выбрали опорный элемент. Заведём два указателя left и right, которые изначально будут указывать на левый и правый концы отрезка соответственно. Затем будем двигать левый указатель вправо до тех пор, пока он указывает на элемент, меньший опорного. Аналогично двигаем правый указатель влево, пока он стоит на элементе, превосходящем опорный. В итоге окажется, что что левее от left все элементы точно принадлежат первой группе, а правее от right — второй. Элементы, на которых стоят указатели, нарушают порядок. Поменяем их местами (в большинстве языков программирования используется функция swap()) и продвинем указатели на следующие элементы. Будем повторять это действие до тех пор, пока left и right не столкнутся.
На рисунке представлен пример разделения при pivot=5. Указатель left — голубой, right — оранжевый.
Формат ввода
В первой строке задано число участников n, 1 ≤ n ≤ 100 000.
В каждой из следующих n строк задана информация про одного из участников.
i-й участник описывается тремя параметрами:
уникальным логином (строкой из маленьких латинских букв длиной не более 20)
числом решённых задач Pi
штрафом Fi
Fi и Pi — целые числа, лежащие в диапазоне от 0 до 109.
Формат вывода
Для отсортированного списка участников выведите по порядку их логины по одному в строке.
Пример 1
Ввод           Вывод
5              gena
alla 4 100     timofey
gena 6 1000    alla
gosha 2 90     gosha
rita 2 90      rita
timofey 4 80

Учитель просит подкорректировать код:
Нужно написать свой класс для отображения участника. (Подсказка: достаточно реализовать метод init для сохранения значений в атрибуты класса.)
Использовать метод lt, который позволяет реализовать проверку на «меньше чем».
Но я не пойму как это реализовать.Очень прошу помочь
Вот мой код:
def quicksort(nums):
    if len(nums) <= 1:
        return nums

    q = nums[len(nums) // 2]
    s_nums = []
    m_nums = []
    e_nums = []

    for n in nums:
        if n[1] > q[1]:
            s_nums.append(n)
        elif n[1] < q[1]:
            m_nums.append(n)
        else:
            if n[0] == q[0]:
                e_nums.append(n)
            elif n[2] != q[2]:
                s_nums.append(n) if n[2] < q[2] else m_nums.append(n)
            else:
                s_nums.append(n) if n[0] < q[0] else m_nums.append(n)

    return quicksort(s_nums) + e_nums + quicksort(m_nums)

def main():
    n = int(input())
    p = []
    for i in range(n):
        q = list(input().split())
        q[1] = int(q[1])
        q[2] = int(q[2])
        p.append(q)
    sort = quicksort(p)
    for s in sort:
        print(s[0])

A: Вам нужно просто вставить правильное условие в сортировке. Я взял быструю сортировку здесь. Когда мы сравниваем элементы, то мы должны сравнить сначала Pi, потом Fi и в конце имя. Я решил для чистоты кода использовать датаклассы.
from dataclasses import dataclass
import random

@dataclass
class Person:
    name: str
    solved: int
    errors: int

    def __gt__(self, other):
        """
        "Больше", т.е. ниже в списке.
        У этого участника меньше Pi, больше Fi и имя в алфавите ниже.
        """
        if self.solved == other.solved:
            if self.errors == other.errors:
                return self.name > other.name
            return self.errors > other.errors
        return self.solved < other.solved

    def __lt__(self, other):
        """
        "Меньше", т.е. выше в списке.
        У этого участника больше Pi, меньше Fi и имя в алфавите выше.
        """
        if self.solved == other.solved:
            if self.errors == other.errors:
                return self.name < other.name
            return self.errors < other.errors
        return self.solved > other.solved

def quicksort(nums, left, right):
   if left >= right:
       return

   i, j = left, right
   pivot = nums[random.randint(left, right)]

   while i <= j:
       while nums[i] < pivot:
           i += 1
       while nums[j] > pivot:
           j -= 1

       if i <= j:
           nums[i], nums[j] = nums[j], nums[i]
           i, j = i + 1, j - 1

   quicksort(nums, left, j)
   quicksort(nums, i, right)

def main():
    n = int(input())
    persons = []
    for _ in range(n):
        name, solved, errors = input().split()
        persons.append(
            Person(name, int(solved), int(errors))
        )

    quicksort(persons, 0, n - 1)
    for person in persons:
        print(person.name)

main()


text:
Q: Mesos Configuration with existing Apache Spark standalone cluster I am  a beginner in Apache-spark!
I have setup Spark standalone cluster using 4 PCs.
I want to use Mesos with existing Spark standalone cluster. But I read that I need to install Mesos first then configure the spark.
I have also seen the Documentation of Spark on setting with Mesos, but it is not helpful for me.
So how to configure Mesos with existing spark standalone cluster?

A: Mesos is an alternative cluster manager to standalone Spark manger. You don't use it with, you use it instead of.

*

*to create Mesos cluster follow https://mesos.apache.org/gettingstarted/

*make sure to distribute Mesos native library is available on the machine you use to submit jobs

*for cluster mode start Mesos dispatcher (sbin/start-mesos-dispatcher.sh).

*submit application using Mesos master URI (client mode) or dispatcher URI (cluster mode).


text:
Q: WCF Duplex callback method never executes when invoked from a different thread Ok I am at my wit's end with this thing. I have a WCF duplex service. Here is how the architecture works:

*

*The client opens a connection to the endpoint and supplies a callback implementation

*The service takes that request and does some stuff on other threads(could be 1 second could be 2 minutes, which is the reason I am not using async operations)

*When the processing is done, it calls the callback of the client

The problem is when the service calls that callback, seemingly nothing happens. No error, no anything. Upon further investigation I found an exception in the server trace:
The I/O operation has been aborted because of either a thread exit or an application request

This happens right after attempting to execute the callback.
The client never receives a response, or closes. All that happens is, since the initial request is made on a thread different from the main one, it just waits there forever for that thread to complete.
The most weird thing is, that if I try to call the callback in the operation that the client invokes, without going into another thread, everything works fine - the callback is successfully called, which leads me to believe that I have configured the service correctly, but have a threading/deadlocking problem.
Here is how I am calling the service:
SubmissionServiceClient client = CreateClientInstance();
        client.Open();
        Guid executionId = await client.SubmitAsync(submission);
        submissionCompletionSource.Task.Wait(); //waits for the callback to be called (I omitted the extra wiring code for better readability)
        client.Close();

private SubmissionServiceClient CreateClientInstance()
{
    NetHttpBinding binding = new NetHttpBinding();
    binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;
    EndpointAddress endpointAddress = new EndpointAddress("ws://localhost:9080/SubmissionRouter");
    InstanceContext instanceContext = new InstanceContext(this);
    SubmissionServiceClient submissionServiceClient = new SubmissionServiceClient(instanceContext,binding,endpointAddress);
    return submissionServiceClient;
}

This is the callback operation:
public void SubmissionProcessed(SubmissionResultDto result)
        {
            submissionCompletionSource.TrySetResult(result);
        }

This is the service operation that the client calls:
public Guid Submit(SubmissionDto submission, ISubmissionCallback callback)
        {
            ExecutionDto execution = new ExecutionDto()
            {
                Id = Guid.NewGuid(),
                Submission = submission
            };
            RequestExecution(execution); //Queues the execution of the operation
            submissions.Add(execution.Id, callback);

            return execution.Id;
        }

And this is where the service calls the callback of the client(this method is executed on a different thread from the one that the initial request was made on):
                ISubmissionCallback callback = submissions[submissionResult.ExecutionId];
                    callback.SubmissionProcessed(submissionResult);

Service behaviour:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Reentrant)]

As you can see upon submission, the service stores the callback in a dictionary, paired with an id, which it later uses to retrieve the callback and invoke it. I believe the reason it is failing is because I am trying to do that on a different thread.
EDIT:
I added a Ping operation to the service, that calls another thread, which hangs for 3 seconds and then calls a Pong function on the client.
public void Ping()
        {
            var callback = OperationContext.Current.GetCallbackChannel<ISubmissionCallback>();
            Task.Run(() =>
            {
                System.Threading.Thread.Sleep(3000);
                callback.Pong();
            });
        }

client:
    class Program
    {
        static void Main(string[] args)
        {
            NetHttpBinding binding = new NetHttpBinding();
            binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;
            EndpointAddress endpointAddress = new EndpointAddress("ws://localhost:9080/SubmissionRouter");
            InstanceContext instanceContext = new InstanceContext(new Callback());
            SubmissionServiceClient submissionServiceClient = new SubmissionServiceClient(instanceContext, binding, endpointAddress);
        submissionServiceClient.Ping();

        Console.Read();
    }

    public void SubmissionProcessed(SubmissionResultDto result)
    {
        throw new NotImplementedException();
    }
    class Callback : ISubmissionServiceCallback
    {
        public void Pong()
        {
            Console.WriteLine("Pong!");
        }

        public void SubmissionProcessed(SubmissionResultDto result)
        {

        }
    }
}

This actually worked successfully. I managed to receive my answer on the client side. I am now officially completely lost.

A: If you are blocking the UI thread with submissionCompletionSource.Task.Wait(); that is causing your deadlock. WCF Callbacks happen on the UI thread by default, you can change the behavior by using CallbackBehaviorAttribute
[CallbackBehaviorAttribute(UseSynchronizationContext=false)]
class Callback : ISubmissionServiceCallback
{
    public void Pong()
    {
        Console.WriteLine("Pong!");
    }

    public void SubmissionProcessed(SubmissionResultDto result)
    {

    }
}

or by not blocking the UI thread.
SubmissionServiceClient client = CreateClientInstance();
client.Open();
Guid executionId = await client.SubmitAsync(submission);
await submissionCompletionSource.Task; //awaits for the callback to be called without blocking the UI.
client.Close();


text:
Q: Does Removing items from SelectedItems source remove them from the ItemsSource? If I had 2 ObservableCollections<someObject> one represents the ItemsSource and one represents the SelectedItems source.
Does calling the Clear() function on the SelectedItems source remove those items from the ItemsSource?

A: No it would just affect your SelectedItems collection (by emptying it of course). Clear just removes items from a collection not another one :

*

*ItemsSource references an ObservableCollection containing object references.

*SelectedItems references another ObservableCollection containing some objects references also contained into your ItemsSources collection;

Calling Clear method on your SelectedItems collection will only removes object references contained in SelectedItems, not objects (themself) or object references from another collection (here ItemsSource).


text:
Q: How to use Kal calendar Api to draw calendar? How to use Kal calendar Api to draw calendar like this ?
If any one know how to do this please give a quick reply with code
or any info on this topic
source code of this API is here http://github.com/klazuka/Kal

A: Check http://github.com/devinross/tapkulibrary. There is a daily view developed inside. However, only monthly view showed in the example. You have to do it yourself.


text:
Q: Person has 1.15 in dimes and quarters. There are 7 coins all together how many of each does she have? Let $d$ stands for dimes
Let $q$ stands for quarters
The closest I can get is $10d + 25q = 115$

A: This is a nice start. You have the additional information that there are 7 coins altogether. Thus the second equation is $d+q=7$. Soving this equation for $d$ gives $d=7-q$. Now you  put the term for $d$ into your equation.
$$ 10\cdot (7-q) + 25q = 115$$
Solve this equation for $q$.


text:
Q: Creating a generic class method update on Cassandra db Examining the documentation at datastax on the cassandra c# driver (cassandra C# driver documentation), the following code is presented:
// Update
users.Where(u => u.UserId == "john")
     .Select(u => new User { LastAccess = TimeUuid.NewId()})
     .Update()
     .Execute();

I decided to create a repository like this:
    public bool Update(Func<T,bool> whereExpression,Func<T,T> selectExpression)
    {
        try
        {
            this.AllRecords
                .Where(whereExpression)
                .Select(selectExpression)
                .Update()
                .Execute();

        }
        catch (Exception)
        {

            throw;
        }
    }

I received the following error:

Error 1   'System.Collections.Generic.IEnumerable' does not contain a definition for 'Update' and no extension method 'Update' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?)

I have imported all the necssary namespaces

using System.Linq;
  using Cassandra.Data.Linq;

A: The problem lies with the construction of your method parameters. If you inspect the Cassandra.Data.Linq namespace, the Where extension method is presented as:
public static CqlQuery<TSource> Where<TSource>(this CqlQuery<TSource> source, Expression<Func<TSource, bool>> predicate);

Hence, you should update your code as:
 public bool Update(Expression<Func<T,bool>> whereExpression, Expression<Func<T,T>> selectExpression)
{
    try
    {
        this.AllRecords
            .Where(whereExpression)
            .Select(selectExpression)
            .Update()
            .Execute();

    }
    catch (Exception)
    {

        throw;
    }
}

Also, don't forget to import the following namespace for this to work:
using System.Linq;
using System.Linq.Expressions;
using Cassandra.Data.Linq;

That's all that you need to do to get this working...


text:
Q: distinct key word only for one column I'm using postgresql as my database, I'm stuck with getting desired results with a query,
what I have in my table is something like following,
nid    date_start    date_end

1      20            25
1      20            25
2      23            26
2      23            26

what I want is following
nid    date_start    date_end

1      20            25
2      23            26

for that I used SELECT DISTINCT nid,date_start,date_end from table_1 but this result duplicate entries, how can I get distinct nid s with corresponding date_start and date_end?
can anyone help me with this?
Thanks a lot!

A: Based on your sample data and sample output, your query should work fine.  I'll assume your sample input/output is not accurate.
If you want to get distinct values of a certain column, along with values from other corresponding columns, then you need to determine WHICH value from the corresponding columns to display (your question and query would otherwise not make sense).  For this you need to use aggregates and group by.  For example:
SELECT
   nid,
   MAX(date_start),
   MAX(date_end)
FROM
   table_1
GROUP BY
   nid

A: That query should work unless you are selecting more columns.
Or maybe you are getting the same nid with a different start and/or end date

A: Try distinct on:
select distinct on (col1) col1, col2 from table;

A: DISTINCT can't result in duplicate entries - that's what it does... removed duplicates.
Is your posted data is incorrect? Exactly what are your data and output?


text:
Q: Infer parameter type depending on other parameters in method Suppose I have this function declaration:
function foo<T extends {}>(bar: Array<{ key: keyof T, value: any, otherParam: string}>): T[]

And I have this interface:
interface C {
    d: string
    e: number
}

When I call foo like this:
foo<C>([{key: 'd', value: 'myValue', otherParam: 'other'}, {key: 'e', value: 100, otherParam: 'other'}])

I want to infer the type of the second parameter value and get rid of that awful any.
How can I do that?
Thanks!

A: Use mapped types to convert T to your desired shape.
type Bar<T> = {
    [P in keyof T]: { key: P, value: T[P], otherParam: string }
}[keyof T];

Full solution:
type Bar<T> = {
    [P in keyof T]: { key: P, value: T[P], otherParam: string }
}[keyof T];

declare function foo<T extends object>(bar: Bar<T>[]): T[]

interface C {
    d: string
    e: number
}

foo<C>([{key: 'd', value: 'string', otherParam: 'other'}, {key: 'e', value: 100, otherParam: 'other'}])

TypeScript Playground


text:
Q: How to make class iterable with foreach? I have this class:
import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;

public class Polynomial<T> implements Iterable<T>  {
    Map<Integer, Object> polynomial;

    public Polynomial(){
        polynomial = new HashMap<Integer, Object>();
    }
    public  Polynomial(int numberOfMembers){
        polynomial = new HashMap<Integer, Object>(numberOfMembers);
    }
    public void addElm(int power, int coefficient){
        if (power < 0) {
            power = Math.abs(power);
            throw new RuntimeException("ERROR: The power must be an absolute number, converting to absolute");
        }
        for (Map.Entry m : polynomial.entrySet()) {
            if ((Integer) m.getKey() == power){
                polynomial.put(power,m.getValue());
            }
        }
    }
    @Override
    public Iterator<T> iterator() {
        // TODO Auto-generated method stub
        return (Iterator<T>) new Object;
    }

}

And here is part of main function:
 Polynomial<Integer> p1=new Polynomial<Integer>();
 for (Integer r : p1)
 System.out.println(r.toString());

As you can see above I need to make foreach on Polynomial class, that's why Polynomial implement Iterable interface. But my problem that I don't know how to implement iterator() method. How can I do that?

A: Your code is very confusing. What is T? Why is T not used in the class? What is the coefficient parameter used for? What are you trying to do?
My best guess is that T is the type of coefficient of the polynomial, and you are trying to return an iterator that iterates through the coefficients.
I rewrote your code like this:
public class Polynomial<T> implements Iterable<T>  {
    Map<Integer, T> polynomial;

    public Polynomial(){
        polynomial = new HashMap<Integer, T>();
    }
    public  Polynomial(int numberOfMembers){
        polynomial = new HashMap<Integer, T>(numberOfMembers);
    }
    public void addElm(int power, T coefficient){
        if (power < 0) {
            throw new RuntimeException("ERROR: The power must be an absolute number");
        }
        polynomial.put(power,coefficient);
    }
    @Override
    public Iterator<T> iterator() {
        return polynomial.values().iterator();
    }

}


text:
Q: Is it possible to log mysql queries from other hosts in general log? I'm having a task to figure out what are the hosts that are still running scripts that accessing our database directly so we can prevent that from happening(we only want our web app to access the database but nothing else). I just learnt that enabling general_log would give me a nice table of access log. My problem is that the table grows too fast and easily lost control.
For my specific use case, my question would be: is there a mysql feature to make general_log only record database access from other hosts so general_log could record less data? I know it's pretty unlikely to happen, so my last option is to periodically delete the records that are local access. But this might cause performance issue. Do you think it makes sense to do that? Is there a better way to do it? Thanks.

A: You may use the mcaffee audit plugin https://github.com/mcafee/mysql-audit/wiki/Installation there you can filter hosts in logging.
You could also refuse all hosts specifying a mysql User with an appropriate Host. ('user'@'allowedHostIpRange').


text:
Q: Can a graphql mutation be wired inside a DataFetcher class along with query? Error:FieldUndefined: Field 'createUser' in type 'Query' is undefined @ 'createUser'"
@Service
public class GraphQlService {

    @Value("classpath:schema.graphql")
    Resource resource;

    private GraphQL graphQL;

    @Autowired
    UserDataFetcher userFetcher;
    @Autowired
    PostDataFetcher postFetcher;

    @PostConstruct
    public void loadSchema() throws IOException {

        File schemaFile = resource.getFile();
        TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(schemaFile);
        RuntimeWiring wiring = buildRuntimeWiring();
        GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(typeRegistry, wiring);
        graphQL = GraphQL.newGraphQL(schema).build();

    }

    private RuntimeWiring buildRuntimeWiring() {
        return RuntimeWiring.newRuntimeWiring()
                .type("Query", typeWiring -> typeWiring
                        .dataFetcher("user", userFetcher)
                        .dataFetcher("post", postFetcher))
                .type("Mutation", typeWiring -> typeWiring
                        .dataFetcher("createUser", userFetcher))
                .build();
    }

    public GraphQL getGraphQL() {
        return graphQL;
    }

}

1. Cant I use common datafetcher/reslover for both Query and Mutation
    as I have done below in a single class.It is not able to find
    createUser?
@Component
public class UserDataFetcher implements DataFetcher<List<User>> {
@Autowired
UserRepository userRepository;

public User createUser(DataFetchingEnvironment environment) {
    String username = environment.getArgument("username");
    String location= environment.getArgument("location");
    User[] follower = environment.getArgument("followers");
    User[] following = environment.getArgument("following");
    Post[] pos = environment.getArgument("posts");

    User user = new User();
    user.setUsername(username);
    user.setFollowers(follower);
    user.setFollowing(following);
    user.setLocation(location);
    user.setPosts(pos);
    return userRepository.save(user);
}

@Override
public List<User> get(DataFetchingEnvironment environment) {
    return userRepository.findAll();
}
}

//SDL below for schema
schema {
    query: Query
    mutation: Mutation
}

type User{
    id:ID!
    username:String!
    followers:[User]
    following:[User]
    location:String!
    posts:[Posts]
}

type Post{
    id: ID
    title: String!
    author: User!

}

type Query{
    user: [User]
    post: [Post]
}

type Mutation{
    createUser(username: String!, location: String!,followers: [User],following:[User],posts:[Post]):User

}

2. Is the schema correct because it would say User and Post are not mentioned as InputType. I tried InputType for User and Post but
    couldnt get it working.How should correct schema for storing
    followers and following look like ?

A: 1) No, each DataFetcher implementation can do a single operation only - that's the get method the interface specifies. How would the framework know to call the createUser method?
2) No, the schema is not valid. You can not use User as an argument (input) type. You need to define a separate input type, e.g.
input UserInput {
   username:String!
   followers:[ID!]
   following:[ID!]
   location:String!
}

Just think, if you could make User the input, how would you provide the mandatory ID? What if User implements an interface, since interfaces are not defined for inputs? Imagine if User had a recursive field type. In output, that would be fine (as you control the nesting level directly), but would be impossible to satisfy for an input type.
The rules for inputs and output are quite different, so the types need to be defined separately.
Also, in this example, only the IDs are optionally expected for the followers or the followed, instead of the full objects, as it often makes more sense.


text:
Q: start sms intent without recipients I want to open the sms intent without predefined recipients, this is my code.
Uri myuri = Uri.parse("to:");
Intent smsintent = new Intent(Intent.ACTION_SENDTO, myrui);
smsintent.putExtra("sms_body", "new sms here boddy");
startActivity(smsintent);

i get exception that
myuri can't be parsed

why that?

A: I think you want this.
Use Uri myuri = Uri.parse("smsto:"); instead of Uri.parse("to:");

or
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"));
sendIntent.putExtra("sms_body", "new sms here boddy");
startActivity(sendIntent);


text:
Q: how to get the expect value by using perl In the array @fruit, there are many values. I want to search whether the line contains the values in the array.
I want to find out 'fresh apple' rather than 'apple. but my code will return both 'fresh apple' and 'apple':
my $line = "this is one fresh apple!";
my @fruit= ("apple","fresh apple","banana","fresh banana","rice");

foreach my $fruit(@fruit){

    if ($line =~ /$fruit/){
        print "$fruit \n";
    }

}

A: The easiest approach is probably to a) sort your array so the longest strings appear first and b) stop searching once you've found a match:
my $line = "this is one fresh apple!";
my @fruit= ("apple","fresh apple","banana","fresh banana","rice");

@fruit = sort { length $b <=> length $a } @fruit;

foreach my $fruit(@fruit){

    if ($line =~ /$fruit/){
        print "$fruit \n";
        last;
    }

}

You can improve this by creating a single regex and avoiding the loop:
use feature 'say';

my $line = "this is one fresh apple!";
my @fruit= ("apple","fresh apple","banana","fresh banana","rice");

@fruit = sort { length $b <=> length $a } @fruit;

my $re = '\b(' . join('|', @fruit) . ')\b';

if ($line =~ /$re/) {
  say $1;
}

A: Just you need to put a check on one line.
my $line = "this is one fresh apple!";
my @fruit= ("apple","fresh apple","banana","fresh banana","rice");

foreach my $fruit(@fruit)
{

Validate the array here check the value apple or space
    next if($fruit=~m/^apple$/ || $fruit!~m/[ ]/);

Skip the value of apple
    if ($line =~ / $fruit/){
    print "$fruit \n";
    }

}

A: If you want the "longuest" match, one option is to track it while you walk the array:
use strict;
use warnings;

my $line =  "this is one fresh apple!";
my @fruit = ("apple","fresh apple","banana","fresh banana","rice");

my $res;
my $res_length = -1;

for my $fruit(@fruit) {
    next if $line !~ /$fruit/;
    next if length($fruit) <= $res_length;
    $res = $fruit;
    $res_length = length($fruit);
}

print $res, "\n" if $res_length > 0;


text:
Q: Asp.Net Web API JWT Authentication I have implemented user authentication using JWT in my Asp.Net Web API application. It's working fine whenever a user logs in, an access token is generated and returned to the client and the client sends back with every request to access the secured resource. But if I copy the same access token and prepare a request from any other client (like Postman) using the same access token it gives the access to the protected resource. I think it's a normal behavior. But is there any better solution to get rid of this i.e. don't allow any other client even if using the same access token. So that to make it client specific as well.

A: If you don't want any other intruder to copy your access token and access the protected resource, then you must use SSL.
To protect extremely sensitive data, you should keep the token lifetime to a very short window of time. If you are protecting something less sensitive, you could make the lifetime longer. The longer the token if valid, the larger the window of time a attacker will have to impersonate the authenticated user if the user's machine is compromised.
You can check this great answer to learn a few things

A: You should be passing in a username and password to obtain the token in the first place. That password is the private key that provides security to make sure no one else can obtain a token for that user. As long as your traffic is over https(ssl) then that token is protected in transit and no one else should be able to intercept it.


text:
Q: Get record matching on both table in mysql I have following table structure
Table 1                  Table 2
----------             -------------------
Id  value              Id   ids    value
1   item1              1    1,3    Item1
2   item2              2    2,1    Item2
3   item3              3    1,3,5  Item3
4   item4              4    1      Item4
5   item5              5    2,1    Item5

Now I want to get all record from table 2 value which match from table 1 e.g. Id from table 1 matches ids from table 2
I want result like this
table1.value           table2.value
item1                  Item1
item1                  Item2
item1                  Item3
item1                  Item4
item1                  Item5
item2                  Item2
item2                  Item5
item3                  Item1
item3                  Item3
item5                  Item3

I have use following query
SELECT table1.value, table2.value FROM table1, table2 WHERE table1.id IN (table2.ids)

But not getting out put as I mentioned above. Any Help?

A: This is evidence of a bad data structure.  Your data should be stored using an association table rather than a list.  But you can do this as:
select t1.value, t2.value
from table2 t2 join
     table1 t1
     on find_in_set(t1.id, t2.ids) > 0;

An alternative way of phrasing this is using like.  This idea works in any database, although the string concatenation differs:
select t1.value, t2.value
from table2 t2 join
     table1 t1
     on concat(',', t2.ids, ',') like concat('%,', t1.id, ',%')


text:
Q: Is it possible to make a route's model a computed / tracked property? I'm trying to have a route's model hook return some array that is constantly updated via a polling mechanism using Ember later. The route file looks like this:
export default class IndexRoute extends Route {
  recent: [],

  init() {
    ...
    this.getRecent();
  }

  getRecent() {
    // poll data / fetch latest
    this.recent.push(newStuff);

    later(this, this.getRecent, 2000);
  }

  model() {
    return this.recent;
  }
}

Then in my controller, I wanted to create a @computed / @tracked property based on the route's model:
export default class IndexController extends Controller {
  // @tracked model; // this also didn't work
  @computed('model.@each') // this doesn't work
  get computedModel() {
    console.log('computedModel'); // prints only once, when the model hook is first run
    return this.model;
  }
}

I thought what this SO post suggested would have worked but it didn't :(
I saw this post but this was for Ember 1.13 so not exactly a modern solution.
Similarly this post had outdated content too.
Is what I'm trying to do possible? Alternatively I was thinking of moving the data into the Controller and making a computed property of a Controller variable instead. Taking all suggestions!

A: The fundamental problem with your current approach is that you are not using Ember Array specific functions. There is often some magic that happens when you create arrays in Ember that automatically creates them as Ember arrays (at least this was the case when using the old style syntax with .create and when prototype extensions were allowed). You can always explicitly create an Ember array with:
import { A } from '@ember/array';

export default class ApplicationRoute extends Route{
  recent = A([]);
}

Anyway, when you just use this.recent.push(newStuff);, this native array prototype is not instrumented in a way that Ember's tracking/observer system can know that the a new value has been added to this.recent and subsequently trigger a rerender. This applies to both tracked properties as well as the traditional observer system pre-Octane.
Instead, when interacting with arrays that are being displayed in templates (ie arrays that need to be observed), you must use special Ember.Array specific functions pushObject like this.recent.pushObject(newStuff).
getRecent() {
  // poll data / fetch latest
  this.recent.pushObject(this.current);
  this.current = this.current + 1;

  later(this, this.getRecent, 2000);
}

If you wanted to go full on tracked property style, you can avoid using the Ember array, but you must force a recompute by reassigning the array to the tracked property. Here's an example in a component
import Component from '@glimmer/component';
import { tracked} from '@glimmer/tracking';
import { later } from '@ember/runloop';
export default class extends Component {
  @tracked
  trackedArray = [];

  current = 0;
    constructor(){
    super(...arguments);
    this.doPoll();
  }

    doPoll() {
    // essentially pushing but via a reassign with the new element
    // you could also `pushObject` here if that feels better
    this.trackedArray = [...this.trackedArray, this.current];
    this.current = this.current + 1;

    later(this, this.doPoll, 2000);
  }
}

Here is a Ember Twiddle that shows both approaches in action.
PS. The model property of a route is only quasi-dynamic. During the transition, the return value of the model hook is automatically assigned to the route's currentModel property. This value is then passed into setupController as the second parameter and automatically assigned to the controller's model property if no setupController is defined or if the setupController invokes super of the base implementation. When modelFor is called for a particular route, the currentModel property is returned and model is not reinvoked. This is all to say that having the poll in the model function itself would not automatically update the controller's model property. Everything works fine in your example since the model reference never changes (you're just mutating the array).


text:
Q: Looking for a side menu for the new Xamarin IOS project In Xamarin there is the choice to choose between the IOS classic and the new IOS version to develop native IOS apps.
I have chosen for the new IOS project. but this version uses Xamarin.IOS in place of MONOTOCH foundation.
and i'm looking for a library for adding a slide in menu to my app.
do anyone now any nuGet pacakges or GitHub packages that i can use?.

A: Try these libraries. I think that's what you need  https://github.com/thedillonb/MonoTouch.SlideoutNavigation
https://github.com/jdehlin/Xamarin-Sidebar

A: Not sure how far down the road you are with the project but sounds like your just getting started. If so a Cross-Platform App (Xamarin.Forms) has a MasterDetail View that I believe renders as a sliding left menu on IOS.

A: Give a chance also to JASidePanels, it's published by Xamarin Inc so it should be possible to have their support on Xamarin forum and I suppose they will keep updating it whenever will be necessary.
Most recent versions support also ios64.
Here the link to the component but I think it's possible to use it just referencing the library and following the samples.
Since it also exist the native version of JASidePanels should be also easier to find around examples on how to customize or solutions in case of problems.
https://components.xamarin.com/gettingstarted/jasidepanels/true