text:
Q: label widget not updating with 'after' method in Tkinter for-loop I'm trying to update the text of and display a label inside of a for-loop in tkinter.  This should happen after a second, according to the .after method.
def rightString(self, gro, string):
    for z in string:
        self.message2.configure(text="Good job, %s is a member of %s!" % (z, gro.getName()))

        root.after(1000)
        self.message2.grid()
        print(z, " should be displayed!")

I hope this is enough info; I feel like there is something very basic I'm missing.  The print function calls and displays each of the members of 'string' in IDLE.  I don't understand why self.message2 does not display.  It displays in other parts of the script which do not include 'after' methods.
I will post more of the code if it is necessary.
Thanks.

A: If you want to change the text of the label each second, then you have to schedule the function again with after:
def rightString(self, gro, string):
    if string:
        z = string[0]
        self.message2.configure(text="Good job, %s is a member of %s!" % (z, gro.getName()))
        root.after(1000, lambda: self.rightString(gro, string[1:])
        print(z, " should be displayed!")

As I've said in my comment, calling grid() each time you change the text is not necessary.

Edit: To execute a different function when the processing of all strings has finished, you can add a call to it in an else block:
def rightString(self, gro, string):
    if string:
        # ...
    else:
        doSomethingElse()

A: It doesn't display because you are preventing the event loop from processing events, specifically the event that causes it to redraw the window on the screen. You need to restructure your code to avoid calling after with just a single argument.


text:
Q: Tricky Nested Summation I am trying to analyze a programming algorithm that has three nested loops. The algorithm looks like this: $$\sum_{i=0}^{n} \sum_{j=i}^{n}\sum_{k=i}^{j} 1$$.
I am trying to simplify it. These are the steps I have taken so far:
Step 1 $\sum_{i=0}^{n} \sum_{j=i}^{n} (j - i + 1)$
Step 2 $\sum_{i=0}^{n} \sum_{j=i}^{n - i + 1} (j)$
Step 3 $\sum_{i=0}^{n} \frac{(n - i + 1)(n - i + 2)}{2}$
What would I do next?
Thanks

A: Your second step should have
$$\sum_{i=0}^n\sum_{j=\color{red}1}^{n-i+1}j\;,$$
though judging by your third step, that was just a typo. You can now simplify your third stage. As $i$ runs from $0$ through $n$, $n-i+1$ runs from $n+1$ down through $1$, so we can let $\ell=n-i+1$:
$$\begin{align*}
\sum_{i=0}^n\frac{(n-i+1)(n-i+2)}2&=\frac12\sum_{\ell=1}^{n+1}\ell(\ell+1)\\
&=\frac12\left(\sum_{\ell=1}^{n+1}\ell^2+\sum_{\ell=1}^{n+1}\ell\right)\;.
\end{align*}$$
If you don't know the formula
$$\sum_{k=1}^nk^2=\frac{n(n+1)(2n+1)}6\;,$$
this is a good time to learn it; it's the only remaining tool that you need.
Alternatively, you can notice that you're really just counting the triples $\langle i,j,k\rangle$ such that
$$0\le i\le k\le j\le n\;.\tag{1}$$
If we let $k'=k+1$ and $j'=j+2$, we find that $\langle i,j,k\rangle$ satisfies $(1)$ if and only if
$$0\le i<k'<j'\le n+2\;.$$
There are $n+3$ integers in the range $[0,n+2]$, so there are $\binom{n+3}3$ ways to choose $3$ distinct integers $i,j'$, and $k'$ from this range. Once they've been chosen, there's only one way to order them so that $i<k'<j'$, and replacing $k'$ and $j'$ by $k=k'-1$ and $j=j'-2$, respectively, gives us a triple $\langle i,j,k\rangle$ satisfying $(1)$. Thus, your original summation is equal to
$$\binom{n+3}3=\frac16(n+3)(n+2)(n+1)\;.$$

A: $$\begin{align}
\sum_{i=0}^n\sum_{j=i}^n\sum_{k=i}^j 1
&=\sum_{j=0}^n\sum_{k=0}^j\sum_{i=0}^k \binom {i+0}0
&&(0\le i\le k\le j\le n)\\
&=\sum_{j=0}^n\sum_{k=0}^j\binom {k+1}1\\
&=\sum_{j=0}^n\binom {j+2}2\\
&=\binom {n+3}3\qquad\blacksquare
\end{align}$$

A: *

*Multiply $n-i+1\quad$ and $n-i+2\quad$.

*The result will be a quadratic polynomial in $i\quad$ in the form $a+bi+ci^2\quad$.

*Your desired result will be $(a·(n+1)+b·(n^2+n)/2+c·(2·n^3+3·n^2+n)/6)/2\quad$.

A: For a first approximation,
approximate the sums
by integrals:
$\begin{array}\\
\sum_{i=0}^{n} \sum_{j=i}^{n}\sum_{k=i}^{j} 1
&\approx \int_{0}^{n} dx \int_{x}^{n} dy\int_{x}^{y} dz\\
&=\int_{0}^{n} dx \int_{x}^{n}(y-x) dy\\
&=\int_{0}^{n} dx (\frac{y^2}{2}-xy)|_{x}^{n}\\
&=\int_{0}^{n} dx (\frac{n^2-x^2}{2}-x(n-x))\\
&=\int_{0}^{n} dx (\frac{n^2+x^2}{2}-xn)\\
&= (\frac{xn^2}{2}+\frac{x^3}{6}-\frac{x^2n}{2})|_{0}^{n}\\
&= (\frac{n^3}{2}+\frac{n^3}{6}-\frac{n^3}{2})\\
&= \frac{n^3}{6}\\
\end{array}
$
For many usages,
this is good enough.

A: In this answer, it is shown that
$$
\sum_{j=k}^n\binom{j}{k}=\binom{n+1}{k+1}\tag{1}
$$
We can apply $(1)$ twice to get
$$
\begin{align}
\sum_{i=0}^n\sum_{j=i}^n\sum_{k=i}^j1
&=\sum_{i=0}^n\sum_{j=i}^n\binom{j-i+1}{1}\tag{2}\\
&=\sum_{i=0}^n\sum_{j=1}^{n-i+1}\binom{j}{1}\tag{3}\\
&=\sum_{i=0}^n\binom{n-i+2}{2}\tag{4}\\
&=\sum_{i=2}^{n+2}\binom{i}{2}\tag{5}\\[3pt]
&=\binom{n+3}{3}\tag{6}
\end{align}
$$
Explanation:
$(2)$: write the sum as a binomial coefficient
$(3)$: $j\mapsto j+i-1$
$(4)$: apply $(1)$
$(5)$: $i\mapsto n+2-i$
$(6)$: apply $(1)$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to prevent rewrite after deny I have a website inside "/directory/", and a special variation of the website inside "/directory/subdirectory/" which should only be accessible by a few specific IP addresses. The subdirectory, however is a virtual URL, the website code is still in the parent  directory called "directory" in this example. So I need rewrites.
This is the relevant part of my current nginx config file:
location /directory {
    # here are various rewrites for my website

    location /directory/subdirectory/ {
        allow 10.0.0.0/8; # example range of IP addresses allowed
        deny all; # disable access for others
        rewrite ^/directory/subdirectory/(.*)$ /directory/$1 last; # the website location is still in the parent folder but the PHP code knows this specific version is to be used when the user surfs into subdirectory, which is why there is this rewrite
    }

    try_files $uri $uri/ /directory/index.php?q=$uri&$args;
}

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi.conf;
    fastcgi_read_timeout 43200;
}

The problem I'm facing: I don't know how to stop the execution as soon as the "deny all" hits. If you're surfing into the subdirectory, the rewrite always executes, no matter if your IP is allowed or not by the directives above it. So someone surfing to the subdirectory with an IP address which is not allowed can see the website inside subdirectory, which is of course not what I want. If I comment out the rewrite, then the allow/deny directives work as they are supposed to.
So: how can I specify this rewrite is ONLY to be executed if the visitor is not denied?
Tried adding "error_page 403 /403.html;" to that location after the "deny all;" directive but it only changes the 403 page (and can only be seen again when commenting the rewrite rule in the subdirectory). Been searching the net for days already with various search terms to make this happen, and been fiddling with variations of the config, but to no avail.
Also: the "deny all" doesn't work anymore as soon as I surf to an URL inside subdirectory, ending with ".php". I assume it is because of the "location ~ .php$" directive, getting priority for some reason over the nested location directives above. I could get around this by doing:
location ^~ /directory/subdirectory/ {
    allow 10.0.0.0/8; # example range of IP addresses allowed
    deny all; # disable access for others
    rewrite ^/directory/subdirectory/(.*)$ /directory/$1 last;
}

location /directory {
    # here are various rewrites for my website

    try_files $uri $uri/ /directory/index.php?q=$uri&$args;
}

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi.conf;
    fastcgi_read_timeout 43200;
}

Now the "location ^~ /directory/subdirectory/" directive gets priority over the "location ~ .php$" directive which makes the "deny all" work but I don't know if that's the way to go since it doesn't seem like the most "clear to read" solution because I move something from within the "directory/" location out of that location block. And also, that still doesn't solve my main problem (only making the "rewrite ^/directory/subdirectory/(.*)$ /directory/$1 last;" execute for allowed IP addresses and not those getting denied by the "deny all".
Thank you.

A: The issue you are facing is related to the precedence/order in which nginx handles it's directives. A detailed explanation can be found here (hats off to the author!):

In their execution order the phases are post-read, server-rewrite,
  find-config, rewrite, post-rewrite, preaccess, access, post-access,
  try-files, content, and finally log

Since "rewrite" comes before "access", the "rewrite" directive is handled first.
Since "if" is handled in "rewrite"-phase as well, one could write:
location ~ \.php$ {
 if ($remote_addr != "172.17.0.1") {
  return 403;
 }
 rewrite ^ /your-redirect last;
}


text:
Q: "mv: cannot stat" error when using find to move files via xargs I'm working on a bash script that needs to (recursively) move all files and folders within a source folder into a destination folder.
In trying to make this as robust as possible, and address potential argument list too long - errors, I opted to use the find command (to safely determine the files to move) piped into xargs (to efficiently group the moves together).  I'm also using -print0 and -0 to address potential problems with spaces.
I've written the following test script:
#!/bin/bash

# create test source file structure, and destination folder
mkdir -p sourceDir/{subdir1,subdir\ with\ space\ 2}
mkdir -p destDir
touch sourceDir/subdir1/{a1.txt,noExtension1,file1\ with\ space.txt}
touch sourceDir/subdir\ with\ space\ 2/{a2.txt,noExtension2,file2\ with\ space.txt}

#move files/folders from source to destination
find sourceDir -mindepth 1 -print0 | xargs -0 mv --target-directory=destDir

Which seems to work (i.e. the files are moved) but for some reason I get numerous errors as follows:
mv: cannot stat `sourceDir/subdir with space 2/file2 with space.txt': No such file or directory
mv: cannot stat `sourceDir/subdir with space 2/noExtension2': No such file or directory
mv: cannot stat `sourceDir/subdir with space 2/a2.txt': No such file or directory
mv: cannot stat `sourceDir/subdir1/file1 with space.txt': No such file or directory
mv: cannot stat `sourceDir/subdir1/noExtension1': No such file or directory
mv: cannot stat `sourceDir/subdir1/a1.txt': No such file or directory

Should there not be a way to do this (for the source files indicated in my script) without generating errors?
Why are these errors being generated (since the files and folders are in fact being moved)?

A: I've sussed it.
Short answer: I was missing the -maxdepth 1 tag.  The following command works
find sourceDir -mindepth 1 -maxdepth 1 -print0 | xargs -0 mv --target-directory=destDir
# as does
find sourceDir -mindepth 1 -maxdepth 1 -exec mv --target-directory=destDir '{}' +

Longer answer:
My original find command was listing the paths to each and every file, and then trying to move each and every one of them.  Once a top level folder had been moved, there was then no need to move any files/folders underneath - but the script was still trying to!
The script below demonstrates this (without actually performing the moves):
#!/bin/bash

mkdir -p sourceDir/{subdir1/subsubdir1,subdir\ with\ space\ 2}
touch sourceDir/subdir1/{subsubdir1/deeperFile.log,a1.txt,noExtension1,file1\ with\ space.txt}
touch sourceDir/subdir\ with\ space\ 2/{a2.txt,noExtension2,file2\ with\ space.txt}
touch sourceDir/rootFile.txt

echo -e "\n--- Output of 'ls -1: sourceDir':"
echo "$(ls -1 sourceDir)"

echo -e "\n--- original incorrect attempt was trying to move each of the following:"
find sourceDir -mindepth 1

echo -e "\n--- working attempt only needs to move each of the top level files/folders, everything underneath any folders will get moved automatically"
find sourceDir -mindepth 1 -maxdepth 1

giving output:
--- Output of 'ls -1: sourceDir':
rootFile.txt
subdir1
subdir with space 2

--- original incorrect attempt was trying to move each of the following:
sourceDir/rootFile.txt
sourceDir/subdir with space 2
sourceDir/subdir with space 2/file2 with space.txt
sourceDir/subdir with space 2/noExtension2
sourceDir/subdir with space 2/a2.txt
sourceDir/subdir1
sourceDir/subdir1/file1 with space.txt
sourceDir/subdir1/noExtension1
sourceDir/subdir1/a1.txt
sourceDir/subdir1/subsubdir1
sourceDir/subdir1/subsubdir1/deeperFile.log

--- working attempt only needs to move each of the top level files/folders, everything     underneath any folders will get moved automatically
sourceDir/rootFile.txt
sourceDir/subdir with space 2
sourceDir/subdir1

A: Why don't do that directly with the find command ?
$ find [...] -exec mv '{}' [...] ';'

Where {} means each file found and ; the end of the arguments passed to mv

A: By default the output of find command starts with parent directory, then directory contain.
Simple find command on your directroy structure gives following output:
sourceDir/subdir1
sourceDir/subdir1/a1.txt
sourceDir/subdir1/noExtension1
sourceDir/subdir1/file1 with space.txt
sourceDir/subdir with space 2
sourceDir/subdir with space 2/noExtension2
sourceDir/subdir with space 2/file2 with space.txt

If you use this output in xargs or -exec , It will first process the parent directory and after that its contents. In this case your command executes fine and move all whole  sourceDir/subdir1 directory to destDir/subdire1. After that there is no files/directory like sourceDir/subdir1/a1.txt or sourceDir/subdir1/noExtension1 in sourceDir because it is already moved to destDir.
To avoid this use -depth option.
-depth Process each directory's contents before the directory itself.

In your case you can add -type d  option to move top level source dir to destDir.
find sourceDir   -mindepth 1 -type d  -print0 | xargs -0 mv --target-directory=destDir

Or
find sourceDir -mindepth 1 -type d  -exec mv -t destDir "{}"  \+

It will solve your problem.


text:
Q: MD5 with ASCII Char I have a string
    wDevCopyright = [NSString stringWithFormat:@"Copyright: %c 1995 by WIRELESS.dev, Corp Communications Inc., All rights reserved.",0xa9];

and to munge it I call
-(NSString *)getMD5:(NSString *)source
{

 const char *src = [source UTF8String];
 unsigned char result[CC_MD5_DIGEST_LENGTH];
 CC_MD5(src, strlen(src), result);

     return [NSString stringWithFormat:
   @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
   result[0], result[1], result[2], result[3],
   result[4], result[5], result[6], result[7],
   result[8], result[9], result[10], result[11],
   result[12], result[13], result[14], result[15]
   ]; //ret;
}

because of 0xa9 *src = [source UTF8String] does not create a char that represents the string, thus returning a munge that is not comparable with other platforms.
I tried to encode the char with NSASCIIStringEncoding but it broke the code.
How do I call CC_MD5 with a string that has ASCII characters and get the same hash as in Java?

Update to code request:
Java
private static char[] kTestASCII = {
        169
        };

System.out.println("\n\n>>>>> msg## " + (char)0xa9 + " " + (char)169 + "\n  md5 " + md5(new String(kTestASCII), false) //unicode = false

Result >>>>> msg## \251 \251
  md5 a252c2c85a9e7756d5ba5da9949d57ed
ObjC
     char kTestASCII [] = {
            169
        };

NSString *testString = [NSString stringWithCString:kTestASCII encoding:NSUTF8StringEncoding];

NSLog(@">>>> objC msg## int %d char %c md5: %@", 0xa9, 169, [self getMD5:testString]);

Result >>>> objC msg## int 169 char © md5: 9b759040321a408a5c7768b4511287a6
** As stated earlier - without the 0xa9 the hashes in Java and ObjC are the same.  I am trying to get the hash for 0xa9 the same in Java and ObjC

Java MD5 code
private static char[] kTestASCII = {
    169
    };

md5(new String(kTestASCII), false);

    /**
     * Compute the MD5 hash for the given String.
     * @param s the string to add to the digest
     * @param unicode true if the string is unciode, false for ascii strings
     */
    public synchronized final String md5(String value, boolean unicode)
    {
        MD5();
        MD5.update(value, unicode);
        return WUtilities.toHex(MD5.finish());

    }
    public synchronized void update(String s, boolean unicode)
{

    if (unicode)
    {
        char[] c = new char[s.length()];
        s.getChars(0, c.length, c, 0);
        update(c);
    }
    else
    {
        byte[] b = new byte[s.length()];
        s.getBytes(0, b.length, b, 0);
        update(b);
    }
}

public synchronized void update(byte[] b)
{
    update(b, 0, b.length);
}

//--------------------------------------------------------------------------------

/**
 * Add a byte sub-array to the digest.
 */
public synchronized void update(byte[] b, int offset, int length)
{
    for (int n = offset; n < offset + length; n++)
        update(b[n]);
}

/**
 * Add a byte to the digest.
 */
public synchronized void update(byte b)
{
    int index = (int)((count >>> 3) & 0x03f);
    count += 8;
    buffer[index] = b;
    if (index >= 63)
        transform();
}

I believe that my issue is with using NSData withEncoding as opposed to a C char[] or the Java byte[].  So what is the best way to roll my own bytes into a byte[] in objC?

A: The character you are having problems with, ©, is the Unicode COPYRIGHT SIGN (00A9). The correct UTF-8 encoding of this character is the byte sequence 0xc9 0xa9.
You are attempting, however to convert from the single-byte sequence 0xa9 which is not a valid UTF-8 encoding of any character. See table 3-7 of http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G7404 . Since this is not a valid UTF-8 byte sequence, stringWithCString is converting your input to the Unicode REPLACEMENT_CHARACTER (FFFD). When this character is then encoded back into UTF-8, it yields the byte sequence 0xef 0xbf 0xbd. The MD5 of this sequence is 9b759040321a408a5c7768b4511287a6 as reported by your Objective-C example.
Your Java example yields an MD5 of a252c2c85a9e7756d5ba5da9949d57ed, which simple experimentation shows is the MD5 of the byte sequence 0xa9, which I have already noted is not a valid UTF-8 representation of the desired character.
I think we need to see the implementation of the Java md5() method you are using. I suspect it is simply dropping the high bytes of every Unicode character to convert to a byte sequence for passing to the MessageDigest class. This does not match your Objective-C implementation where you are using a UTF-8 encoding.
Note: even if you fix your Objective-C implementation to match the encoding of your Java md5() method, your test will need some adjustment because you cannot use stringWithCString with the NSUTF8StringEncoding encoding to convert the byte sequence 0xa9 to an NSString.
UPDATE
Having now seen the Java implementation using the deprecated getBytes method, my recommendation is to change the Java implementation, if at all possible, to use a proper UTF-8 encoding.
I suspect, however, that your requirements are to match the current Java implementation, even if it is wrong. Therefore, I suggest you duplicate the bad behavior of Java's deprecated getBytes() method by using NSString getCharacters:range: to retrieve an array of unichars, then manually create an array of bytes by taking the low byte of each unichar.

A: stringWithCString requires a null terminated C-String. I don't think that kTestASCII[] is necessarily null terminated in your Objective-C code. Perhaps that is the cause of the difference.
Try:
char kTestASCII [] = {
            169,
            0
        };

A: Thanks to GBegan's explanation - here is my solution
for(int c = 0; c < [s length]; c++){
    int number = [s characterAtIndex:c];
    unsigned char c[1];
    c[0] = (unsigned char)number;
    NSMutableData *oneByte = [NSMutableData dataWithBytes:&c length:1];
}


text: Q: recommend me some texts on the history of the non-western mathematics I would like to self study the detailed history of the non-western mathematics. I have started the literature of Barton (7th Ed.) but it primarily concentrated on Western and American Mathematics. Would someone recommend me some texts belonging to the domain?


text:
Q: Adding a timeslider controller to openlayers I have a database that contains some weather data in a .csv format. Each table represents the weather condition at specific point in time.
Using the geoserver, I can visualise each of these tables on my browser.
What I have been searching for a way to do, is something to add as slider to my html code, so it shows the weather condition at each minute, as I slide across the slider.
I have found some .js code here, but honestly speaking, don't know where to add to fit my purpose (or even if it really fits the purpose or not)
https://github.com/metno/openlayers-timeslider
Also, I don't know if this would be helpful, but the part of the html that shows the data on the map is as following:
var rainLayer = new ol.layer.Tile({
  source: new ol.source.TileWMS({
  url: 'http://x.x.x.x/geoserver/wms',
  params: {'LAYERS': 'storename:layername'}
});

A: You can use ImageMosaic plugin for raster time-series data of Geoserver.
Here is the documentation for implementing a time enabled ImageMosaic.
after implementing the mosaic you need to pass the time parameter to the geoserver in the openlayers like this:
var wms = new ol.layer.Tile({
            name: name,
            opacity: opacity,
            source: new ol.source.TileWMS({
                url: global.geoserverWMS2 + 'wms',
                params: {
                    'LAYERS': layer_name,
                    'TILED': true,
                    'TIME': '2017-01-01', // this is an example
                },
                serverType: 'geoserver'
            })
        });

and once you wanted to change the time parameter in order to render the corresponding weather image just use the updatePrams() on the wms layer like this:
wms.getSource().updateParams({'time': '2016-01-01'})
wms.getSource().updateParams({'time': '2015-01-01'})
wms.getSource().updateParams({'time': '2014-01-01'})

and it will refresh the data source and render the new imagery.


text:
Q: How to use multiprocessing module to iterate a list and match it with a key in dictionary? I have a list named master_lst created from a CSV file using the following code
infile= open(sys.argv[1], "r")
lines = infile.readlines()[1:]
master_lst = ["read"]
for line in lines:
 line= line.strip().split(',')
 fourth_field = line [3]
 master_lst.append(fourth_field)

This master list has the unique set of sequences. Now I have to loop 30 collapsed FASTA files to count the number of occurrences of each of these sequences in the master list. The file format of the 30 files is as follow:
>AAAAAAAAAAAAAAA
7451
>AAAAAAAAAAAAAAAA
4133
>AAAAAAAAAAAAAAAAA
2783

For counting the number of occurrences, I looped through each of the 30 file and created a dictionary with sequences as key and number of occurrences as values. Then I iterated each element of the master_lst and matched it with the key in the dictionary created from the previous step. If there is a match, I appended the value of the key to a new list (ind_lst). If not I appended 0 to the ind_lst. The code for that is as follow:
for file in files:
 ind_lst = []
 if file.endswith('.fa'):
  first = file.split(".")
  first_field = first [0]
  ind_lst.append(first_field)
  fasta= open(file)
  individual_dict= {}
  for line in fasta:
   line= line.strip()
   if line == '':
    continue
   if line.startswith('>'):
    header = line.lstrip('>')
    individual_dict[header]= ''
   else:
    individual_dict[header] += line
  for key in master_lst[1:]:
   a = 0
   if key in individual_dict.keys():
     a = individual_dict[key]
   else:
     a = 0
   ind_lst.append(a)

then I write the master_lst to a CSV file and ind_lst using the code explained here: How to append a new list to an existing CSV file?
The final output should look like this:
Read                           file1     file2 so on until file 30
AAAAAAAAAAAAAAA                 7451      4456
AAAAAAAAAAAAAAAA                4133      3624
AAAAAAAAAAAAAAAAA               2783      7012

This codes work perfectly fine when I use a smaller master_lst. But when the size of the master_lst increases then the execution time increases too much. The master_lst I am working with right now has 35,718,501 sequences(elements). When I subset 50 sequences and run the code, the script takes 2 hours to execute. So for 35,718,501 sequences it will take forever to complete.
Now I don't know how to speed up the script. I am not quite sure if there could be some improvements that can be made to this script to make it execute in a shorter time.  I am running my script on a Linux server which has 16 CPU cores. When I use the command top, I could see that the script uses only one CPU. But I am not a expert in python and I don't know how to make it run on all available CPU cores using multiprocessing module. I checked this webpage: Learning Python's Multiprocessing Module.
But, I wasn't quite sure what should come under def and if __name__ == '__main__':. I am also not quite sure what arguments should I pass to the function. I was getting an error when I try the first code from Douglas, without passing any arguments as follow:
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run

self._target(*self._args, **self._kwargs)

I have been working this for the last few days and I haven't been successful in generating my desired output. If anyone can suggest an alternative code that could run fast or if anyone could suggest how to run this code on multiple CPUs, that would be awesome. Any help to resolve this issue would be much appreciated.

A: Here's a multiprocessing version. It uses a slightly different approach than you do in your code which does away with the need for creating the ind_lst.
The essence of the difference is that it first produces a transpose of the desired data, and then transpose that into the desired result.
In other words, instead of creating this directly:
Read,file1,file2
AAAAAAAAAAAAAAA,7451,4456
AAAAAAAAAAAAAAAA,4133,3624
AAAAAAAAAAAAAAAAA,2783,7012

It first produces:
Read,AAAAAAAAAAAAAAA,AAAAAAAAAAAAAAAA,AAAAAAAAAAAAAAAAA
file1,7451,4133,2783
file2,4456,3624,7012

...and then transposes that with the built-in zip() function to obtain the desired format.
Besides not needing to create the ind_lst, it also allows the creation of one row of data per file rather than one column of it (which is easier and can be done more efficiently with less effort).
Here's the code:
from __future__ import print_function

import csv
from functools import partial
from glob import glob
from itertools import izip  # Python 2
import operator
import os
from multiprocessing import cpu_count, Pool, Queue
import sys

def get_master_list(filename):
    with open(filename, "rb") as csvfile:
        reader = csv.reader(csvfile)
        next(reader)  # ignore first row
        sequence_getter = operator.itemgetter(3)  # retrieves fourth column of each row
        return map(sequence_getter, reader)

def process_fa_file(master_list, filename):
    fa_dict = {}
    with open(filename) as fa_file:
        for line in fa_file:
            if line and line[0] != '>':
                fa_dict[sequence] = int(line)
            elif line:
                sequence = line[1:-1]

    get = fa_dict.get  # local var to expedite access
    basename = os.path.basename(os.path.splitext(filename)[0])
    return [basename] + [get(key, 0) for key in master_list]

def process_fa_files(master_list, filenames):
    pool = Pool(processes=4)  # "processes" is the number of worker processes to
                              # use. If processes is None then the number returned
                              # by cpu_count() is used.
    # Only one argument can be passed to the target function using Pool.map(),
    # so create a partial to pass first argument, which doesn't vary.
    results = pool.map(partial(process_fa_file, master_list), filenames)
    header_row = ['Read'] + master_list
    return [header_row] + results

if __name__ == '__main__':
    master_list = get_master_list('master_list.csv')

    fa_files_dir = '.'  # current directory
    filenames = glob(os.path.join(fa_files_dir, '*.fa'))

    data = process_fa_files(master_list, filenames)

    rows = zip(*data)  # transpose
    with open('output.csv', 'wb') as outfile:
        writer = csv.writer(outfile)
        writer.writerows(rows)

    # show data written to file
    for row in rows:
        print(','.join(map(str, row)))


text:
Q: Html.Action() extension method encoding the = sign in url I have a action in controller which is returning the View return type is ActionResult and in View Im calling it using Html.Action() method all is going perfectly but when page is loaded it change the query string means encode the query string like = sign with %3F but not all of = signs
How can I get rid of these encoding ???
here is code:
Controller
 public ActionResult FetchCartItemsByOrderId(int OrderId)
    {
        CartViewModel cart = new CartViewModel();

        db.Configuration.ProxyCreationEnabled = false;

        if (User.Identity.IsAuthenticated)
        {
            cart.order = db.Orders.AsEnumerable().FirstOrDefault(x => x.Id == OrderId);
             cart.listOrderDetail = db.OrderDetails.Where(x => x.OrderId == OrderId).ToList();
        }

        return View("~/Views/Generic/_ViewCart.cshtml", cart);

    }

View:
@Html.Action("FetchCartItemsByOrderId", "Generic", new { orderId = Convert.ToInt32(Request.QueryString["orderId"]) });


text:
Q: how to pass a method call to JOptionPane.showMessageDialog parameter I have a class called Person and within it there's a method to show the details of a person
public class Person
{
private int age = 12;
private double salary=12000;
public void show() {

    System.out.println("Age : " + age);
    System.out.println("Salary: "+ salary);
}

In another class Test, i would like to display the Person's details using the show() method  from Person Class via the showMessageDialog
import javax.swing.JOptionPane;

public class Test
{
public static void main(String[] args){
Person s = new Person();
    JOptionPane.showMessageDialog(null, s.show(), "Person Info", JOptionPane.PLAIN_MESSAGE);
}

The end goal is to display a person info on Joptionpane message box
I am wondering if it can be achieved **without altering the show() method
But the code failed to compile
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    The method showMessageDialog(Component, Object, String, int) in the type JOptionPane is not applicable for the arguments (null, void, String, int)
Anyone have any idea would be greatly appreciated. Many thanks

A: Person.show() is returning void. So, you are getting this error.
showMessageDialog(Component, **Object**, String, int)
(null, **void**, String, int)
You can return String from show()
public String show() {
   return "Age : " + age + " Salary: "+ salary;
}

Or define a toString() method.
public String toString() {
       return "Age : " + age + " Salary: "+ salary;
}

And then show by following
JOptionPane.showMessageDialog(null, s.toString(), "Person Info", JOptionPane.PLAIN_MESSAGE);

Or you can just show Dialog from show method.
public void show() {
JOptionPane.showMessageDialog(null, "Age : " + age + " Salary: "+ salary, "Person Info", JOptionPane.PLAIN_MESSAGE);
}


text:
Q: Uploading an image to Google Lens using Selenium I am trying to upload images using Selenium on Google lens using this link: https://lens.google.com/search?p=0
By examining the site, I've concluded that If I have copied an image I can paste it on Google lens with Ctrl+V and it automatically uploads. I tried to mimic the exact thing by trying to paste the image from my clipboard. This code does store the image on my clipboard and when I stop the execution and paste it on the browser, it uploads perfectly. However, the program is not able to do so. Code is below:
import os
import win32clipboard as clp
file_path = 'capture.png'

clp.OpenClipboard()
clp.EmptyClipboard()

wide_path = os.path.abspath(file_path).encode('utf-16-le') + b'\0'
clp.SetClipboardData(clp.RegisterClipboardFormat('FileNameW'), wide_path)
WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.CSS_SELECTOR,'#yDmH0d > div:nth-child(16) > div > ul'))).click()
actions = ActionChains(driver)
actions.send_keys(Keys.CONTROL,'v')

The second approach I tried to use was to find the input element and send file name as a key, but that too didn't work. One thing I noticed was the input element is not visible at first until you click the Upload Button and then the Computer. So I tried to mimic that as well, still not working. Code is below:
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="gb"]/div[2]/div[2]/div[2]/div/div/div[1]/div/div[1]/div/div[1]/span/div[1]/button'))).click()
time.sleep(1)
WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="yDmH0d"]/div[13]/div/ul/li[1]')))
time.sleep(1)
WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH,'//*[@id="gb"]/div[2]/div[2]/div[2]/div/div/div[2]/input'))).send_keys('capture.png')

Any idea how to make this work or better approach to upload images?

A: This is all you need :
from selenium.webdriver.common.action_chains import ActionChains
elem = driver.find_element(By.XPATH, '/html')
ac = ActionChains(driver)
ac.move_to_element(elem).move_by_offset(100, 100).click().perform()

Use this for active the page.
Good luck !


text:
Q: Convert b64 to binary and run attached to Powershell I'm trying to follow the example found here:
https://truesecdev.wordpress.com/2016/03/15/embedding-exe-files-into-powershell-scripts/
What code does: convert a base64 string to a binary file and execute/load it into the Powershell process.
What I'm trying to achieve: avoid the executable being written to the disk, this way the exe is executed only in the memory and not maintain a copy saved somewhere.
I got the function Invoke-ReflectivePEInjection from:
https://github.com/PowerShellMafia/PowerSploit/blob/master/CodeExecution/Invoke-ReflectivePEInjectio....
This is my current script:
https://codeshare.io/5PbrJY

I can't past the script here because it exceeds the characters limit.
When I run the script i got a lot of errors like:
https://pastebin.com/rtB9hP13
I have uploaded the error log here ^ (cant past it here as it exceed the character limit)
Looking for any kind of help on it.


text:
Q: How to log a true result of an Assert I am writing some tests using TestNG, WebDriver and log4j
I am trying to log the result of an assert nomatter if the result is true or false. For example, when i write this code:
Assert.assertTrue(condition)

I want to see in the log if that was a PASS or a FAIL. Right now, i can only see any log if the result is a FAIL.
Does anyone have an idea about how can achieve this?
Thanks

A: You could overwrite the Assert-Class and trigger the logger by yourself.

A: There's no way to tell Assert to log a successful assertion.  You could do this:
Assert.assertTrue(condition);
logger.info(condition ? "PASS" : "FAIL");

or subclass Assert and reimplement assertTrue to do the logging for you.  Note in this case your log line will claim to be inside Assert.assertTrue instead of the call point, so you'll have to fix that somehow.

A: I am working on redesigning TestNG's assert system, take a look at the new architecture and let me know what you think:
https://groups.google.com/group/testng-users/browse_thread/thread/4392868b7d1fd051


text:
Q: WixRemoveFoldersEx appears to be firing during both install and uninstall I'm using Wix 3.11.4510.0
During the Install we see the error in the log. It appears to be doing no harm as I don't believe that is actually firing . We are geting calls from customers asking
Thanks
Michae
    <ComponentGroup Id="UnInstallCleanUp" Directory="APPLICATIONFOLDER">
        <Component Id="UnInstallCleanUp" Guid="{908C5D26-8379-4E62-86F8-26C9F0409EAA}">
            <RegistryValue Root="HKLM" Key="Software\xxxxxxxxxsx\PublicReadable" Name="Path" Type="string" Value="[APPLICATIONFOLDER]"  KeyPath="yes"/>
            <util:RemoveFolderEx On="uninstall" Property="APPLICATIONFOLDER" />
        </Component>
    </ComponentGroup>

This occurs
Action ended 12:29:39: ValidateProductID. Return value 1.
Action start 12:29:39: WixRemoveFoldersEx.
MSI (s) (38!1C) [12:29:40:112]: Closing MSIHANDLE (7) of type 790531 for thread 5148
MSI (s) (38!1C) [12:29:40:112]: Closing MSIHANDLE (3) of type 790541 for thread 5148
MSI (s) (38!1C) [12:29:40:114]: Closing MSIHANDLE (6) of type 790531 for thread 5148
MSI (s) (38!1C) [12:29:40:114]: Closing MSIHANDLE (5) of type 790540 for thread 5148
WixRemoveFoldersEx:  Error 0x80070057: Missing folder property: APPLICATIONFOLDER for row: wrfD426C0E3317774F55FB79E7BF0E43C1F
MSI (s) (38:A8) [12:29:40:116]: Closing MSIHANDLE (2) of type 790542 for thread 8540
CustomAction WixRemoveFoldersEx returned actual error code 1603 but will be translated to success due to continue marking
MSI (s) (38:5C) [12:29:40:117]: Doing action: CostInitialize
MSI (s) (38:5C) [12:29:40:117]: Note: 1: 2205 2:  3: ActionText
Action ended 12:29:40: WixRemoveFoldersEx. Return value 1.

A: The WixRemoveFoldersEx custom action runs during every operation, to determine if it has work to do. The log message is to indicate that the property isn't set and it couldn't do any work even if there were work to do.


text:
Q: If PHP value in equation have ending zeros it get stripped Was changing my thousand decimal from "," to "." and can't solve how to not get one of my values not to strip away zeros in end of value and i can't understand why.
An example to describe me case would be this
$value_1 = '25.000';
$value_2 = '4.920';

If i echo this two values is will produce
<?php echo $value_1;?> / <?php echo $value_2;?>

25.000 / 4.920
Everything is okay this far. Then am doing an equation
$sum = $value_1 - $value_2;

And here is where it goes wrong
echo $sum;

Produce: 20.08 where the correct value should have been 20.080
But if the equation would have an sum with a value that is not a zero. For example if we change one of the values to produce a sum that contain something else then a zero it would play out like this
$value_1 = '25.000';
// Adding +1 to original code to get the sum of 2079
$value_2 = '4.921';

$sum = $value_1 - $value_2;

echo $sum;

Produce: 20.079
In my code i have been running several tests where i echo out values to make sure that everything is correct until the equation. I don't understand the logic. Or i understand that what is my thousands separator is in the sum from the equation threaten as a decimal, but then i don't understand why that is not happening anywhere else.
Worth to mention is that it's running on an Woocommerce site that is set to use "." as thousand separator and "," for decimals but with 0 decimals written out. Every where on site i get values correct.
If i run the values without thousand separator like:
 $value_1 = '25000';
 $value_2 = '4920';

The sum would be written out as 20080 so with that knowledge it can't be Woocommerce that tampers with my result.
Best would be to find the solution but because am only using this code on one place am not completely foreign to first stripping away the thousand separator "." from my values and after the equation restore it again.

A: It's working correctly.  The answer to the subtraction is a number to two decimal places.  If you want to force it to show three, use number_format:
echo number_format($sum, 3);

More info here: http://php.net/manual/en/function.number-format.php


text:
Q: calling webservice using javascript without using jQuery ajax? I have to call the web service using java script? e.g. I'm creating one app in HTML. In that I want to check user name and password in server machine(computer) and I want to collect the result from the server. Here I'm passing three arguments like user name, password and login mode(windows or others) then it's sent to server and it returns json result then I parse the json result and then I'm binding in to a list.
so I got output in jQuery.
// Make the dataobject based on the credentials
            var dataObject = {};
dataObject = {Username:uname,Password:pword,Domain:domain,WindowsUser:windowsuser};

//webservice

$.ajax({
        type: "POST",
        url:"../REST/session.aspx?_method=put",
        data: JSON.stringify(dataObject, null,4),
        cache: false,
        dataType: "json",
        success: onSuccessLogin,
        error: function (xhr, ajaxOptions){
                alert(xhr.status + " : " + xhr.statusText);
            }

    });

function onSuccessLogin(data)
{

    alert("success");
    $.mobile.pageLoading();

    //Parse the vault result
    parseResults(data);
}

then I successfully parsed. Here I want to change the web service because Non touch mobiles doesn't support the jQuery. so that I'm changing that web service.

A: I think what you are searching for is "XMLHttpRequest". You can make an asynchronous call with it to your webserver, collect the results and parse it. You don't need a special JavaScript Framework for that. In fact, every Ajax API uses the XMLHttpRequest Object.
http://www.w3.org/TR/XMLHttpRequest/
There are many easy Examples on the web how to do that.

A: If you really don't want to use ajax / XMLHttpRequest, you could make use of HTML5's WebSocket but it's not necessarily easier.


text:
Q: fetch active directory user data using C# I want to fetch data about particular user . I know the OU path of this user but I can't fetch info using that OU path . It always says that user is not found . Can anyone tell me that do I need to change search filter . Please help .
Code
path of the user abc.ds.xyz.net/fGroup/xcxc/Users/123456
abc.ds.xyz.net is domain then fGroup is OU , xcxc is OU , Users is OU , 123456 is cn .
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.DirectoryServices;
    using System.DirectoryServices.AccountManagement;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;

    namespace Ldap_authentication
    {
       public class Program
       {
         static void Main(string[] args)
         {

            Console.Write("Enter user: ");
            String username = Console.ReadLine();

            try
            {
              DirectoryEntry myLdapConnection = createDirectoryEntry();

              DirectorySearcher search = new DirectorySearcher(myLdapConnection);
              search.Filter = "(&(OU=fGroup)(OU=xcxc )(OU=Users)(cn=" + username + "))";
              SearchResult result = search.FindOne();

              if (result != null)
              {

                ResultPropertyCollection fields = result.Properties;

                foreach (String ldapField in fields.PropertyNames)
                {

                    foreach (Object myCollection in fields[ldapField])
                        Console.WriteLine(String.Format("{0,-20} : {1}",
                                      ldapField, myCollection.ToString  ()));
                }
             }

             else
             {
                // user does not exist
                Console.WriteLine("User not found!");
                Console.ReadLine();
             }
         }

        catch (Exception e)
        {
            Console.WriteLine("Exception caught:\n\n" + e.ToString());
             Console.ReadLine();
        }

    }
    static DirectoryEntry createDirectoryEntry()
    {
        DirectoryEntry ldapConnection = new DirectoryEntry("abc.ds.xyz.net");
        ldapConnection.Path = "LDAP://DC=abc,DC=ds,DC=xyz,DC=net";
        ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
        return ldapConnection;
    }
   }
  }

EDIT
    search.Filter = "(&(OU=fGroup))";
    SearchResult result = search.FindOne();

when I change  search.Filter = "(&(OU=fGroup)(OU=xcxc )(OU=Users)(cn=" + username + "))"; into search.Filter = "(&(OU=fGroup))"; I get result . Can anyone tell me how to search with multiple search input filter .

A: After hitting my head against a wall for hours and hours finally I found answer . I need to write multiple search filters like
Old code  search.Filter = "(&(OU=fGroup))"; replace this with this
   search.Filter = "(&(OU=fGroup))";
   search.Filter = "(&(OU=xcxc))";
   search.Filter = "(&(OU=Users))";
   search.Filter = "(&(cn=" + username + "))";
   SearchResult result = search.FindOne();

   Finally found my answer :) . Happy Coding guys :)


text:
Q: What is the difference between key and constraint in sql? I have referred many documents but couldn't find a supporting/compromising answer for this. Can anyone briefly describe the difference between key and constraints?

A: A key is a single or combination of multiple fields in a table. Its is used to fetch or retrieve records/data-rows from data table according to the condition/requirement. Keys are also used to create relationship among different database tables or views.
SQL constraints are used to specify rules for the data in a table.
 If there is any violation between the constraint and the data action, the action is aborted.
Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after the table is created (inside the ALTER TABLE statement).
you can check more documentation in the links below
Keys
Constraint


text:
Q: Save one by one words from string to the list I want to get words from a string (like this: "My name is Jonathan") one by one, and save each word into an elemnt on a list. I want to do it extremelly simple, without any vectors etc.
For example
I take one word from a string and save it into an element
The same
Until end of string.

A: You can do this the following way
#include <string>
#include <list>
#include <sstream>
#include <iterator>

//...

std::istringstream is( "My name is Jonathan" );

std::list<std::string> lst( ( std::istream_iterator<std::string>( is ) ),
                            std::istream_iterator<std::string>() );

Here is a demonstrative program
#include <iostream>
#include <string>
#include <list>
#include <sstream>
#include <iterator>

int main()
{
    std::istringstream is( "My name is Jonathan" );

    std::list<std::string> lst( ( std::istream_iterator<std::string>( is ) ),
                                std::istream_iterator<std::string>() );

    for ( const std::string &s : lst ) std::cout << s << ' ';
    std::cout << std::endl;

    return 0;
}

Its output is
My name is Jonathan

If you want to apply this task to your own list then you can use the following approach
std::istringstream is( "My name is Jonathan" );
std::string word;

while ( is >> word )
{
    // append your list with the word
}


text:
Q: Content of a UITableViewCell does not want to fit I have made a little sample project that reproduces my error:
TableViewBug.zip
What happens is that this code, when run under iOS 7.1, produces a UITableView with cells, whose content will not stay at the margins, where it should be according to the constraints, and where it even says it is, according to it's frame. Meaning, when I log cell.contentView.frame in tableView:cellForRowAtIndexPath:, it says it is at x:0 y:0, but when I look at the UI, most of the views have been compressed, and the last one is even too large and has been clipped, because of the longer label.
Screenshot
On iOS 8, this code executes flawlessly, I don't know what is wrong with it.

A: Found it! Just remove:
[cell.contentView setTranslatesAutoresizingMaskIntoConstraints:NO];

form:
- (void)configureCell:(TableViewCell *)cell withDictionary:(NSDictionary *)dictionary {...}


text:
Q: Can't have selected tab font color to black I am trying to design some tabs using CSS and following this post. Unfortunately, I can't manage to have the selected tab font color to black.
I have created a JsFiddle to describe the issue. What am I doing wrong?
Here is the HTML:

Tabs

This

That

The Other

Banana

Here is the CSS:
h1 {
    margin: 0;
    padding: 0 0 5px 0;
}

#header a {
    text-decoration:none;
}

#header ul {
    list-style: none;
    padding:0;
    margin:0;
}

#header li {
    float: left;
    border: 1px solid;
    border-color: black;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    padding: 2px 4px;
    /* border-bottom-width: 0; */
    margin: 2px 2px 0 0;
    background: black;
}

#header li a {
    color: white;
}

#header #selected {
    position: relative;
    /* top: 1px; */
    background: white;
}

#header #selected li a {
    color: black;
}

A: Updated jsFiddle: http://jsfiddle.net/zK7y2/1/
#header #selected li a {
    color: black;
}

this addresses a <* id="header"><* id="selected">
.
What you want to select is a <* id="header">
.
So use:
#header li#selected a {
    color: black;
}


text:
Q: Can't set headers after being sent - Node.js redirect issue with a form I have a form that makes a post request to a route. It accepts some input and saves to a database. I then, on successful save, redirect to the original page I was on. My code is below:
router.post("/save", function (request, response, next) {
    const metadata = {
        user: currentUser.name + " " + currentUser.surname
        date: <some-val>
    };
form.parse(request, function(err, fields, files){
    if(!fields.name){
        return response.status(400).send({"status": "error", "message": "The name is required" });
    }
    else if(!fields.description){
        return response.status(400).send({"status": "error", "message": "The description is" +
        " required" });
    }
    MediaH.upload(files, metadata, function (error, result) {
        if(error){
            return response.send(error);
        } else {
            Model.save(fields, result, metadata, function (error, result) {
                if(error) {
                    return response.send(error);
                }
                else{
                   return response.redirect("/pages")
                }
            });
        }
    });

});
});

The redirect is successful, however if I try and re-upload to my form again, I get a Error: Can't set headers after they are sent. error. I have no idea where I'm going wrong. I had a look at several similar questions on Stack Overflow and some suggested doing a return for the response.redirect but it's still not working.
Can anyone help?
EDIT:
Put the entire route above.


text:
Q: Violation of PRIMARY KEY constraint in Entity Framework Core I have a .NET5 Blazor Server application using EFCore5.
I have two entities that have a many-to-many relationship with each other.
Let's call them 'Books' and 'Tags'.
EFCore provides the BookTag join table.
On my page, I have a form that is populated with the book details and has a multi select box for the tags.
I include the tags when I get the book:
context.Books.Include(x=>x.Tags);
In debug mode, I see the Book item has several tags. But when I update some details of the book and save the form, calling context.Books.Update(book); I get an error because of duplicate keys in the BookTag join table.
It seems EFCore tries to insert entries in that table, but it should do a merge or insert/update.
I've read numerous articles about the many-to-many but all of them just show how to retrieve data. I can't find an example of how to update.
Edit:
I'm using the GenericRepository as explained by @carl-franklin in his excellent BlazorTrain series.
Edit2:
Here is some relevant code, I'm now not using the GenericRepo:
Startup.cs
services.AddDbContextFactory<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection")));
ApplicationDbContext.cs has only the DbSets.
Book.cs
[Key]
public string Code { get; set; }
public string Name { get; set; } = "";
public virtual ICollection<Tag> TagCollection { get; set; }

Tag.cs
[Key]
public string Code { get; set; }
public string Name { get; set; } = "";
public virtual ICollection<Book> BookCollection { get; set; }

Book.razor.cs
[Inject] private IDbContextFactory<ApplicationDbContext> contextFactory { get; set; }
private ApplicationDbContext context { get; set; }
protected IEnumerable<Book> BookList;

protected override async Task OnInitializedAsync()
{
    context = contextFactory.CreateDbContext();
    context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

    BookList = await context.Books.Include(x => x.TagCollection).ToListAsync();
}

private async Task UpdateBook(Book book)
{
    // Called after submitting form
    context.Books.Update(book);
    await context.SaveChangesAsync();
}

Even if I don't change anything, just update I get the duplicate error:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint 'PK_BookTag'. Cannot insert duplicate key in object 'dbo.BookTag'
In UpdateBook() I see the book has tags, as expected. It looks like EFCore is inserting them in the join table without checking if they already exist.

A: Change tracking must be turned on for this to work.  Otherwise, you have to track the changes yourself; Entity Framework thinks you're adding a new record, but the key is the same as an existing record, which is why you're getting the error.


text:
Q: mcmapply performance on multiple cores I have a function which I want to run on around 3 million datapoints. I am trying to parallelise the function using mcmapply on a Ubuntu machine with 8 cores. The function takes in a list of length 3 million as well as 3 more vectors of length 3 million and 1 constant value cutoffyearmon.
The code runs perfectly fine with 100000 rows of data within 2 minutes on a single core and throws no error. However, when I try to run the code in parallel on 6 cores of my machine using mcmapply it keeps on running for more than 5 hours.
UPDATE: This is the watered down version of my function call. There are 9 more variables which I create for time duration of 1month, 2month and 3month. I have taken variables for time 6month and 1year only.
I am using the following function call:
abc_xx_last_xxx_days=mcmapply(function(abcstrnew,sd,naflag,empflag,daysdiff,cutoffyearmon){
abcstrnew=if((!naflag) & (!empflag)){
    substring(text = abcstrnew,first = seq(from = 1,to = (nchar(abcstrnew)-2),by = 3),last = seq(from = 3,to = (nchar(abcstrnew)),by = 3))
}else{
    if(!is.na(empflag) & empflag){
        ""
    }else{
        NA_character_
    }
}

abcstrnew=if((!naflag) & (!empflag)){
    as.numeric(abcstrnew)
}else{
    if(!is.na(empflag) & empflag){
        as.numeric(0)
    }else{
        NA_real_
    }
}
if(is.na(daysdiff)){
  return(list(worst_abc_ever=NA_real_,
              times_abc=NA_real_,
              times_abc_last_180_days=NA_real_,
              times_abc_last_365_days=NA_real_,
              times_abc30_last_365_days=NA_real_,
              times_abc30_last_180_days=NA_real_,
              times_abc60_last_365_days=NA_real_,
              times_abc60_last_180_days=NA_real_,
              abc_last_180_days=NA_real_,
              abc_last_365_days=NA_real_
  ))
}else{
  if((!naflag)&(!empflag)){
    abcstrlen=length(abcstrnew)
    worst_abc_ever=max(abcstrnew)
    times_abc=as.numeric(length(which(abcstrnew>0)))

    if(daysdiff>365){
      abc_last_365_days=as.numeric(0)
      times_abc30_last_365_days=as.numeric(0)
      times_abc60_last_365_days=as.numeric(0)
      times_abc_last_365_days=as.numeric(0)
    }else{
      abcmonthstwelve=12-round(round(difftime(time1 = cutoffyearmon,time2 = as.yearmon(sd)))/30)

      if(abcstrlen>=abcmonthstwelve){
        abc_last_365_days=(max(abcstrnew[1:abcmonthstwelve]))
      }else{
        abc_last_365_days=(max(abcstrnew[1:abcstrlen]))
      }

      if(abcstrlen>=abcmonthstwelve){
        times_abc30_last_365_days=as.numeric(length(which(abcstrnew[1:abcmonthstwelve]>=30)))
      }else{
        times_abc30_last_365_days=as.numeric(length(which(abcstrnew[1:abcstrlen]>=30)))
      }

      if(abcstrlen>=abcmonthstwelve){
        times_abc60_last_365_days=as.numeric(length(which(abcstrnew[1:abcmonthstwelve]>=60)))
      }else{
        times_abc60_last_365_days=as.numeric(length(which(abcstrnew[1:abcstrlen]>=60)))
      }

      if(abcstrlen>=abcmonthstwelve){
        times_abc_last_365_days=as.numeric(length(which(abcstrnew[1:abcmonthstwelve]>0)))
      }else{
        times_abc_last_365_days=as.numeric(length(which(abcstrnew[1:abcstrlen]>0)))
      }
    }

    if(daysdiff>180){
      abc_last_180_days=as.numeric(0)
      times_abc30_last_180_days=as.numeric(0)
      times_abc60_last_180_days=as.numeric(0)
      times_abc_last_180_days=as.numeric(0)
    }else{
      abcmonthssix=6-round(round(difftime(time1 = cutoffyearmon,time2 = as.yearmon(sd)))/30)

      if(abcstrlen>=abcmonthssix){
        abc_last_180_days=(max(abcstrnew[1:abcmonthssix]))
      }else{
        abc_last_180_days=(max(abcstrnew[1:abcstrlen]))
      }

      if(abcstrlen>=abcmonthssix){
        times_abc30_last_180_days=as.numeric(length(which(abcstrnew[1:abcmonthssix]>=30)))
      }else{
        times_abc30_last_180_days=as.numeric(length(which(abcstrnew[1:abcstrlen]>=30)))
      }

      if(abcstrlen>=abcmonthssix){
        times_abc60_last_180_days=as.numeric(length(which(abcstrnew[1:abcmonthssix]>=60)))
      }else{
        times_abc60_last_180_days=as.numeric(length(which(abcstrnew[1:abcstrlen]>=60)))
      }

      if(abcstrlen>=abcmonthssix){
        times_abc_last_180_days=as.numeric(length(which(abcstrnew[1:abcmonthssix]>0)))
      }else{
        times_abc_last_180_days=as.numeric(length(which(abcstrnew[1:abcstrlen]>0)))
      }

    }

    return(list(worst_abc_ever=worst_abc_ever,
                times_abc=times_abc,
                times_abc_last_180_days=times_abc_last_180_days,
                times_abc_last_365_days=times_abc_last_365_days,
                times_abc30_last_365_days=times_abc30_last_365_days,
                times_abc30_last_180_days=times_abc30_last_180_days,
                times_abc60_last_365_days=times_abc60_last_365_days,
                times_abc60_last_180_days=times_abc60_last_180_days,
                abc_last_180_days=abc_last_180_days,
                abc_last_365_days=abc_last_365_days
    ))
  }else{
    return(list(worst_abc_ever=NA_real_,
                times_abc=NA_real_,
                times_abc_last_180_days=NA_real_,
                times_abc_last_365_days=NA_real_,
                times_abc30_last_365_days=NA_real_,
                times_abc30_last_180_days=NA_real_,
                times_abc60_last_365_days=NA_real_,
                times_abc60_last_180_days=NA_real_,
                abc_last_180_days=NA_real_,
                abc_last_365_days=NA_real_
    ))
  }
}
},lst,sd,naflag,empflag,daysdiff,cutoffyearmon,mc.cores=6, mc.preschedule=TRUE, mc.cleanup=TRUE)

You can use the following set of inputs to run the function and check it's output.
lst=list("000050000032","000000340000000000000")
sd=c(as.Date.character("2017-05-22"),as.Date.character("2017-04-23"))
empflag=c(FALSE,FALSE)
naflag=c(FALSE,FALSE)
daysdiff=difftime(time1 = as.Date.character("2017-06-30"),time2 = sd)
cutoffyearmon=as.yearmon("2017-06-30")

I am assuming the code will divide the data almost equally between 6 cores by assigning mc.preschedule=TRUE. But I am not able to see any significant performance in the processing speed. I am expecting the processing to be completed in around 1.5 hours when run on 6 cores of the machine.
Any suggestions if I have missed something.
When using pbmcmapply with mc.cores=6 I am getting an ETA of 06:01:32:57


text:
Q: Scrape Google Trending Stories Page (Python) I would like to scrape all the top 50 searches on the Google Trending Stories page found here: https://www.google.com/trends/
However, when I run the following code, none of the searches show up and it looks like I am only getting Tags:
wikis = ["https://www.google.com/trends/"]
for wiki in wikis:
    website = requests.get(wiki)
    soup = BeautifulSoup(website.content, "lxml")
    text = ''.join([element.text for element in soup.body.find_all(lambda tag:    tag != 'script', recursive=False)])
    new =  re.sub(r'[^a-zA-Z \n]','',text)

Output:
MyAccountSearchMapsYouTubePlayNewsGmailDriveCalendarTranslatePhotosMoreShoppingWalletFinanceDocsBooksBloggerContactsEven more from GoogleSign inYou are using unsupported browser Some features may not work correctly Upgrade to a modern browser such as Google ChromeTrends has upgraded to a newer version which is not supported by this devicedismiss

Any help?

A: Your problem is that https://www.google.com/trends/ is Javascript generated. So you can't use requests that is an http lib.
To test web sites in your browser with Javascript disabled : example for firefox :
about:config

javascript.enabled = false

Check google/SO to find Javascript capable libs

A: *

*Open Dev Tools Network Tab.

*Click on Fetch/XHR.

*Find Name with the response you want (click on some name and hit Preview), in my case, it was: topdailytrends?hl=en-US&tz=-180&geo=UA.

*Make a requests.get() to that URL that you'll see in the Headers tab after clicking on the name, in my case, it was: https://trends.google.com/trends/api/topdailytrends?hl=en-US&tz=-180&geo=UA.
Example code:
import requests, json

response = requests.get('https://trends.google.com/trends/api/topdailytrends?hl=en-US&tz=-180&geo=UA').text.replace(")]}',", "").strip()

json_data = json.loads(response)
trending_searches = json_data['default']['trendingSearches']

print(json.dumps(trending_searches, indent=2, ensure_ascii=False))

----------
'''
[
  {
    "title": "З днем Ангела Марії",
    "formattedTraffic": "10K+",
    "trendingSearchUrl": "/trends/trendingsearches/daily?geo=UA#%D0%97%20%D0%B4%D0%BD%D0%B5%D0%BC%20%D0%90%D0%BD%D0%B3%D0%B5%D0%BB%D0%B0%20%D0%9C%D0%B0%D1%80%D1%96%D1%97",
    "country": "Ukraine"
  }
...
]
'''


text:
Q: react redux / react thunks api Hello I am trying to consume my api
using react redux and thunks
but without success
my code so far:
my actions:
import {FETCHING_PRODUCTS_SUCESS, FETCHING_PRODUCTS_FAIL, FETCHING_PRODUCTS_REQUEST} from '../constants/ActionsFetch';
import api from '../../services/api'

export const fetchingProductsRequest = () => ({type: FETCHING_PRODUCTS_REQUEST});

export const fetchingProductsSucess = (json) => ({
  type: FETCHING_PRODUCTS_SUCESS,
  payload: json
});

export const fetchingProductsFail = (error) => ({
  type: FETCHING_PRODUCTS_FAIL,
  payload: error
})

export const fetchProducts = () => dispatch => {
    return async dispatch => {
      dispatch (fetchingProductsRequest ());
      try {
        let response = await api.get ('/ subcategory');
        console.log (response);
        let json = await response.json ();
        dispatch (fetchingProductsSucess (json));
      } catch (error) {
        dispatch (fetchingProductsFail (error));
      }
    }
}

my reducer:
const INITIAL_STATE = {
    isFetching: false,
    products: [],
    errorMessage: '',
};

export default (state = INITIAL_STATE, action) => {
    switch (action.type) {
      case FETCHING_PRODUCTS_REQUEST:
        return {... state,
                isFetching: true
                }
      case FETCHING_PRODUCTS_SUCESS:
        return {... state,
                isFetching: true,
                products: action.payload
                }
      case FETCHING_PRODUCTS_FAIL:
        return {... state,
                isFetching: false,
                errorMessage: action.payload
              }
      default:
        return state
    }
  }

my store:
import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore (rootReducer, applyMiddleware (thunk));

export default store;

and my component:
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {fetchProducts} from '../../store/actions/ProductsFetch';
class index extends Component {

  componentDidMount () {
    this.props.fetchProducts ();
  }

  render () {
    console.log (this.props.Products);
    if (this.props.Products.isFetching) {
      console.log ('a');
    }
    return (
      <div>

      </div>
    )
  }
}

const mapStateToProps = state => {
  return {
    Products: state
  };
}

export default connect (mapStateToProps, {fetchProducts}) (index);

I gave a .log console to my render:
and received it:

{productsFetch: {…}} productsFetch: {isFetching: false, products:
  Array (0), errorMessage: ""} __ proto__: Object

by giving console.log in my action
do not pass that part:
    return async dispatch =>

A: Your mistake is that you're returning too many functions from fetchProducts.
Correct fetchProducts should be
export const fetchProducts = () => async dispatch => {
  dispatch (fetchingProductsRequest ());
  try {
    let response = await api.get ('/ subcategory');
    console.log (response);
    let json = await response.json ();
    dispatch (fetchingProductsSucess (json));
  } catch (error) {
    dispatch (fetchingProductsFail (error));
  }
}


text:
Q: RTSPPlay does not run I am trying to use the RTSPPlay, project of mooncatventures. But it shows me error like this.
Ld /Users/name/Library/Developer/Xcode/DerivedData/RtspPlay1-eiclkyfwtlgulpcbdsuhpovfaaia/Build/Products/Debug-iphonesimulator/RtspPlay1Play.app/RtspPlay1Play normal i386
    cd "/Users/name/Desktop/LIVE TV/try/RTSPPlay-master"
    setenv IPHONEOS_DEPLOYMENT_TARGET 4.3
    setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.1.sdk -L/Users/devubhamanek/Library/Developer/Xcode/DerivedData/RtspPlay1-eiclkyfwtlgulpcbdsuhpovfaaia/Build/Products/Debug-iphonesimulator -F/Users/user/Library/Developer/Xcode/DerivedData/RtspPlay1-eiclkyfwtlgulpcbdsuhpovfaaia/Build/Products/Debug-iphonesimulator "-F/Users/user/Desktop/LIVE TV/try/RTSPPlay-master" -filelist /Users/user/Library/Developer/Xcode/DerivedData/RtspPlay1-eiclkyfwtlgulpcbdsuhpovfaaia/Build/Intermediates/RtspPlay1.build/Debug-iphonesimulator/RtspPlay1Play.build/Objects-normal/i386/RtspPlay1Play.LinkFileList -Xlinker -objc_abi_version -Xlinker 2 -lbz2 -lm -lz -fobjc-link-runtime -Xlinker -no_implicit_dylibs -mios-simulator-version-min=4.3 -framework FFPlayer -framework FFmpegDecoder -framework SDL -framework Foundation -framework UIKit -framework CoreGraphics -framework AudioToolbox -framework QuartzCore -framework OpenGLES -framework CoreAudio -framework MediaPlayer -o /Users/user/Library/Developer/Xcode/DerivedData/RtspPlay1-eiclkyfwtlgulpcbdsuhpovfaaia/Build/Products/Debug-iphonesimulator/RtspPlay1Play.app/RtspPlay1Play

Undefined symbols for architecture i386:
  "_SDL_AddTimer", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_SDL_CloseAudio", referenced from:
      _stream_component_close in FFPlayer(main.o)
  "_SDL_CondSignal", referenced from:
      _SDL_main in FFPlayer(main.o)
      _stream_component_close in FFPlayer(main.o)
      _packet_queue_abort in FFPlayer(main.o)
      _packet_queue_put in FFPlayer(main.o)
  "_SDL_CondWait", referenced from:
      _video_thread in FFPlayer(main.o)
      _subtitle_thread in FFPlayer(main.o)
      _packet_queue_get in FFPlayer(main.o)
  "_SDL_CreateCond", referenced from:
      _SDL_main in FFPlayer(main.o)
      _packet_queue_init in FFPlayer(main.o)
  "_SDL_CreateMutex", referenced from:
      _SDL_main in FFPlayer(main.o)
      _packet_queue_init in FFPlayer(main.o)
  "_SDL_CreateRGBSurface", referenced from:
      _SDL_main in FFPlayer(main.o)
      _video_open in FFPlayer(main.o)
  "_SDL_CreateRenderer", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_SDL_CreateThread", referenced from:
      _SDL_main in FFPlayer(main.o)
      _stream_component_open in FFPlayer(main.o)
  "_SDL_CreateWindow", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_SDL_Delay", referenced from:
      _video_thread in FFPlayer(main.o)
      _subtitle_thread in FFPlayer(main.o)
      _decode_thread in FFPlayer(main.o)
  "_SDL_DestroyCond", referenced from:
      _do_exit in FFPlayer(main.o)
      _stream_component_close in FFPlayer(main.o)
  "_SDL_DestroyMutex", referenced from:
      _do_exit in FFPlayer(main.o)
      _stream_component_close in FFPlayer(main.o)
  "_SDL_DestroyTexture", referenced from:
      _video_display in FFPlayer(main.o)
  "_SDL_EventState", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_SDL_FillRect", referenced from:
      _video_display in FFPlayer(main.o)
  "_SDL_FreeSurface", referenced from:
      _SDL_main in FFPlayer(main.o)
      _do_exit in FFPlayer(main.o)
  "_SDL_GL_SetAttribute", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_SDL_Init", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_SDL_LockSurface", referenced from:
      _video_thread in FFPlayer(main.o)
  "_SDL_MapRGB", referenced from:
      _video_display in FFPlayer(main.o)
  "_SDL_OpenAudio", referenced from:
      _stream_component_open in FFPlayer(main.o)
  "_SDL_PauseAudio", referenced from:
      _stream_component_open in FFPlayer(main.o)
  "_SDL_PixelFormatEnumToMasks", referenced from:
      _SDL_main in FFPlayer(main.o)
      _video_open in FFPlayer(main.o)
  "_SDL_PollEvent", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_SDL_PushEvent", referenced from:
      _sdl_refresh_timer_cb in FFPlayer(main.o)
      _video_thread in FFPlayer(main.o)
      _decode_thread in FFPlayer(main.o)
  "_SDL_RenderPresent", referenced from:
      _video_display in FFPlayer(main.o)
  "_SDL_SendQuit", referenced from:
      -[SDLUIKitDelegate quitSdl] in SDL_uikitappdelegate.o
      -[SDLUIKitDelegate applicationWillTerminate:] in SDL_uikitappdelegate.o
      -[SDLUIKitDelegate applicationDidEnterBackground:] in SDL_uikitappdelegate.o
  "_SDL_UnlockSurface", referenced from:
      _video_thread in FFPlayer(main.o)
  "_SDL_WaitEvent", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_SDL_WaitThread", referenced from:
      _do_exit in FFPlayer(main.o)
      _stream_component_close in FFPlayer(main.o)
  "_SDL_mutexP", referenced from:
      _SDL_main in FFPlayer(main.o)
      _stream_component_close in FFPlayer(main.o)
      _video_thread in FFPlayer(main.o)
      _subtitle_thread in FFPlayer(main.o)
      _packet_queue_get in FFPlayer(main.o)
      _packet_queue_abort in FFPlayer(main.o)
      _packet_queue_flush in FFPlayer(main.o)
      ...
  "_SDL_mutexV", referenced from:
      _SDL_main in FFPlayer(main.o)
      _stream_component_close in FFPlayer(main.o)
      _video_thread in FFPlayer(main.o)
      _subtitle_thread in FFPlayer(main.o)
      _packet_queue_get in FFPlayer(main.o)
      _packet_queue_abort in FFPlayer(main.o)
      _packet_queue_flush in FFPlayer(main.o)
      ...
  "_av_audio_convert", referenced from:
      _sdl_audio_callback in FFPlayer(main.o)
  "_av_audio_convert_alloc", referenced from:
      _sdl_audio_callback in FFPlayer(main.o)
  "_av_audio_convert_free", referenced from:
      _stream_component_close in FFPlayer(main.o)
      _sdl_audio_callback in FFPlayer(main.o)
  "_av_bitstream_filter_next", referenced from:
      _show_formats in cmdutils.o
  "_av_close_input_file", referenced from:
      _decode_thread in FFPlayer(main.o)
  "_av_codec_next", referenced from:
      _show_formats in cmdutils.o
  "_av_dup_packet", referenced from:
      _packet_queue_put in FFPlayer(main.o)
  "_av_find_input_format", referenced from:
      _opt_format in FFPlayer(main.o)
  "_av_find_opt", referenced from:
      _opt_default in cmdutils.o
  "_av_find_stream_info", referenced from:
      _decode_thread in FFPlayer(main.o)
  "_av_free", referenced from:
      _SDL_main in FFPlayer(main.o)
      _free_subpicture in FFPlayer(main.o)
      _video_thread in FFPlayer(main.o)
      _packet_queue_get in FFPlayer(main.o)
  "_av_free_packet", referenced from:
      _sdl_audio_callback in FFPlayer(main.o)
      _video_thread in FFPlayer(main.o)
      _subtitle_thread in FFPlayer(main.o)
      _packet_queue_flush in FFPlayer(main.o)
      _decode_thread in FFPlayer(main.o)
  "_av_freep", referenced from:
      _free_subpicture in FFPlayer(main.o)
      _packet_queue_flush in FFPlayer(main.o)
  "_av_get_bits_per_sample_format", referenced from:
      _sdl_audio_callback in FFPlayer(main.o)
  "_av_get_int", referenced from:
      _video_thread in FFPlayer(main.o)
  "_av_get_string", referenced from:
      _set_context_opts in cmdutils.o
  "_av_gettime", referenced from:
      _SDL_main in FFPlayer(main.o)
      _get_master_clock in FFPlayer(main.o)
      _video_display in FFPlayer(main.o)
      _get_video_clock in FFPlayer(main.o)
      _stream_component_open in FFPlayer(main.o)
      _sdl_audio_callback in FFPlayer(main.o)
      _stream_pause in FFPlayer(main.o)
      ...
  "_av_iformat_next", referenced from:
      _show_formats in cmdutils.o
  "_av_init_packet", referenced from:
      _SDL_main in FFPlayer(main.o)
      _decode_thread in FFPlayer(main.o)
  "_av_log", referenced from:
      _decode_thread in FFPlayer(main.o)
  "_av_malloc", referenced from:
      _packet_queue_put in FFPlayer(main.o)
  "_av_mallocz", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_av_metadata_get", referenced from:
      _decode_thread in FFPlayer(main.o)
  "_av_oformat_next", referenced from:
      _show_formats in cmdutils.o
  "_av_open_input_file", referenced from:
      _decode_thread in FFPlayer(main.o)
  "_av_protocol_next", referenced from:
      _show_formats in cmdutils.o
  "_av_read_frame", referenced from:
      _decode_thread in FFPlayer(main.o)
  "_av_read_pause", referenced from:
      _decode_thread in FFPlayer(main.o)
  "_av_read_play", referenced from:
      _decode_thread in FFPlayer(main.o)
  "_av_realloc", referenced from:
      _opt_default in cmdutils.o
  "_av_register_all", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_av_set_string3", referenced from:
      _opt_default in cmdutils.o
      _set_context_opts in cmdutils.o
  "_av_strdup", referenced from:
      _parse_options in cmdutils.o
  "_av_strlcat", referenced from:
      _show_help_options in cmdutils.o
  "_av_strlcpy", referenced from:
      _show_help_options in cmdutils.o
      _SDL_main in FFPlayer(main.o)
  "_avcodec_alloc_context2", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_avcodec_alloc_frame", referenced from:
      _video_thread in FFPlayer(main.o)
  "_avcodec_close", referenced from:
      _stream_component_close in FFPlayer(main.o)
  "_avcodec_decode_audio3", referenced from:
      _sdl_audio_callback in FFPlayer(main.o)
  "_avcodec_decode_subtitle2", referenced from:
      _subtitle_thread in FFPlayer(main.o)
  "_avcodec_decode_video2", referenced from:
      _video_thread in FFPlayer(main.o)
  "_avcodec_find_decoder", referenced from:
      _stream_component_open in FFPlayer(main.o)
  "_avcodec_flush_buffers", referenced from:
      _sdl_audio_callback in FFPlayer(main.o)
      _video_thread in FFPlayer(main.o)
      _subtitle_thread in FFPlayer(main.o)
  "_avcodec_open", referenced from:
      _stream_component_open in FFPlayer(main.o)
  "_avcodec_register_all", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_avcodec_thread_init", referenced from:
      _stream_component_open in FFPlayer(main.o)
  "_avcodec_version", referenced from:
      _print_all_lib_versions in cmdutils.o
  "_avdevice_register_all", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_avdevice_version", referenced from:
      _print_all_lib_versions in cmdutils.o
  "_avfilter_version", referenced from:
      _print_all_lib_versions in cmdutils.o
  "_avformat_alloc_context", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_avformat_seek_file", referenced from:
      _decode_thread in FFPlayer(main.o)
  "_avformat_version", referenced from:
      _print_all_lib_versions in cmdutils.o
  "_avpicture_alloc", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_avutil_version", referenced from:
      _print_all_lib_versions in cmdutils.o
  "_dump_format", referenced from:
      _decode_thread in FFPlayer(main.o)
  "_parse_date", referenced from:
      _parse_time_or_die in cmdutils.o
  "_sws_getCachedContext", referenced from:
      _video_thread in FFPlayer(main.o)
  "_sws_getContext", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_sws_scale", referenced from:
      _video_thread in FFPlayer(main.o)
  "_swscale_version", referenced from:
      _print_all_lib_versions in cmdutils.o
  "_url_feof", referenced from:
      _decode_thread in FFPlayer(main.o)
  "_url_ferror", referenced from:
      _decode_thread in FFPlayer(main.o)
  "_url_ftell", referenced from:
      _SDL_main in FFPlayer(main.o)
  "_url_set_interrupt_cb", referenced from:
      _decode_thread in FFPlayer(main.o)
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Can someone plz help me, thanx guys. I have checked that SDL.Framework and I dont see any problem in it. Does I have to add some library in my project to run this project or in mac.

A: The version of ffmpeg in ffmpegdecoder.framework is not built for the simulator. this indicates that you are building for simulator.
Undefined symbols for architecture i386:
Change project settings to release , remove armv7s from your arch and it should build just fine.
Running on the simulator is not a good representation of a project that makes use of the iPhone GPU like these do.
If you have issues building or you absolutely must run on the simulator please contact michelle@mooncatventures.com , we can definitely help you with those changes.


text:
Q: MySQL reports: Documentation #1064 - There is something wrong in the syntax used with "" on rule 3 I am currently working on an assignment for school, where I have to write a query, but I am experiencing an error.
The assingment goes as follows:
If customer A visits branch 1, and customer B visits branch 1 and 2, and customer C visits branch 2, then you can say that customer A and B 0 branches are separated from each other, and customer A and C 1 branch. Find how many branches two random customers are apart from each other.
I get this error
SQL-query: Documentatie
SELECT DISTINCT a.klant_idklant AS "KLANT A", b.klant_idklant AS "KLANT B", a.filiaal_idfiliaal AS "FILIAAL A", b.filiaal_idfiliaal AS "FILIAAL B", ABS(a.filiaal_idfiliaal - b.filiaal_idfiliaal) AS "FILIALEN VAN ELKAAR VERWIJDERD"
FROM aankoop a, aankoop b
WHERE a.klant_idklant = FLOOR(RAND()(SELECT MAX(idklant) FROM klant) - (SELECT MIN(idklant) FROM klant) + (SELECT MIN(idklant) FROM klant))
AND b.klant_idklant = FLOOR(RAND()(SELECT MAX(idklant) FROM klant) - (SELECT MIN(idklant) FROM klant) + (SELECT MIN(idklant) FROM klant)) LIMIT 0, 25

MySQL reports: Documentation
#1064 - There is something wrong in the syntax used with '(SELECT MAX(idklant) FROM klant) - (SELECT MIN(idklant) FROM klant) + (SELECT MI' on rule 3

This is my current query
SELECT DISTINCT a.klant_idklant AS "KLANT A"
              , b.klant_idklant AS "KLANT B"
              , a.filiaal_idfiliaal AS "FILIAAL A"
              , b.filiaal_idfiliaal AS "FILIAAL B"
              , ABS(a.filiaal_idfiliaal - b.filiaal_idfiliaal) AS "FILIALEN VAN ELKAAR VERWIJDERD"
           FROM aankoop a
              , aankoop b
          WHERE a.klant_idklant = FLOOR(RAND()(SELECT MAX(idklant) FROM klant) -
                                              (SELECT MIN(idklant) FROM klant) +
                                              (SELECT MIN(idklant) FROM klant)
                                       )
            AND b.klant_idklant = FLOOR(RAND()(SELECT MAX(idklant) FROM klant) -
                                              (SELECT MIN(idklant) FROM klant) +
                                              (SELECT MIN(idklant) FROM klant)
                                       )

This is the
Database Structure

A: The problem is your not multiplying the result of the subqueries with RAND().
You should have:
SELECT DISTINCT a.klant_idklant AS "KLANT A"
              , b.klant_idklant AS "KLANT B"
              , a.filiaal_idfiliaal AS "FILIAAL A"
              , b.filiaal_idfiliaal AS "FILIAAL B"
              , ABS(a.filiaal_idfiliaal - b.filiaal_idfiliaal) AS "FILIALEN VAN ELKAAR VERWIJDERD"
           FROM aankoop a
              , aankoop b
          WHERE a.klant_idklant = FLOOR(RAND()*(SELECT MAX(idklant) FROM klant) -
                                              (SELECT MIN(idklant) FROM klant) +
                                              (SELECT MIN(idklant) FROM klant)
                                       )
            AND b.klant_idklant = FLOOR(RAND()*(SELECT MAX(idklant) FROM klant) -
                                              (SELECT MIN(idklant) FROM klant) +
                                              (SELECT MIN(idklant) FROM klant)


text:
Q: View database records via listview itemclick I am new to Android and I want to know how to view mySQL database records in another activity via listview itemclick but it depends on the database primary key of the selected item in the listview.
In other words, since the items in the listview are parsed from a database, each item will have a primary key. When you click that item, the user will go to another activity to view details about that particular item based on its primary key. How can I start a new activity based on the primary key of the list item selected? Sample code would be much appreciated.

A: This answer may depend on what kind of adapter you're using. If you're using a CursorAdapter, you'll have to get the cursor at the position clicked, and read the id value:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Cursor cursor = (Cursor) mAdapter.getItem(position);
        long id = cursor.getLong(cursor.getColumnIndex("_id");
    }
});

If you're not using a cursor adapter, you can just change those two lines to match whatever object you're using:
Object myObject = (Object) mAdapter.getItem(position);
long id = myObject.getIdentifier();

Once you have this information, you can use it as Extras to an Intent to start another activity to do the stuff you've mentioned. From what you've described you're looking for a master-detail flow, there are plenty of resources out there explaining it.


text:
Q: Containerized logic app not working when deployed to AKS We are trying to deploy a logic app as containerized workload in AKS. Following is our Docker file:
FROM mcr.microsoft.com/azure-functions/dotnet:3.0.14492-appservice

ENV AzureWebJobsStorage=<StorageAccount connection string>
ENV AZURE_FUNCTIONS_ENVIRONMENT Development
ENV AzureWebJobsScriptRoot=/home/site/wwwroot
ENV AzureFunctionsJobHost__Logging__Console__IsEnabled=true
ENV FUNCTIONS_V2_COMPATIBILITY_MODE=true

COPY ./bin/release/netcoreapp3.1/publish/ /home/site/wwwroot

Following is our deployment manifest file:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: pfna-pgt-sf-pdfextract
  namespace: canary
  labels:
    app: pfna-pgt-sf-pdfextract
spec:
  replicas: 1
  selector:
    matchLabels:
      app: pfna-pgt-sf-pdfextract
  template:
    metadata:
      labels:
        app: pfna-pgt-sf-pdfextract
    spec:
      nodeSelector:
        beta.kubernetes.io/os: linux
      containers:
        - name: pfna-pgt-sf-pdfextract
          image: "image_link"
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 250m
              memory: 256Mi
          ports:
            - containerPort: 80
          env:
            - name: AzureBlob_connectionString
              value: <connection_string>
            - name: AzureWebJobsStorage
              value: <connection_string>
      imagePullSecrets:
        - name: sbx-acr-secret
---
apiVersion: v1
kind: Service
metadata:
  name: pfna-pgt-sf-pdfextract
  namespace: canary
  labels:
    app: pfna-pgt-sf-pdfextract
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 80
    protocol: TCP
    name: http-pfna-pgt-sf-pdfextract
  selector:
    app: pfna-pgt-sf-pdfextract

Following is connections.json:
{
  "serviceProviderConnections": {
    "AzureBlob": {
      "parameterValues": {
        "connectionString": "@appsetting('AzureWebJobsStorage')"
      },
      "serviceProvider": {
        "id": "/serviceProviders/AzureBlob"
      },
      "displayName": "localAzureBlob"
    }
  },
  "managedApiConnections": {}
}

Following is the host.json:
{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle.Workflows",
    "version": "[1.*, 2.0.0)"
  },
  "extensions": {
    "workflow": {
       "settings": {
          "Runtime.Backend.VariableOperation.MaximumStatelessVariableSize": "5000000"
       }
    }
 }
}

The image is running successfully in docker desktop but when deployed to AKS we are getting 'Function host is not running'.
Please help resolve this.

A: You need to specify WEBSITE_HOSTNAME as well (doesn't matter what it is, just needs to be specified)
That being said, as of today there is another issue that is causing the function host to not start (libadvapi32.dll).


text:
Q: Go to previous cue in a texttrack element when current track id is empty I'm trying to implement a way to navigate through the subtitles of a video that has subtitles in WebVTT format.
Task:
I would like to click on a button to make the video go to the beginning of the previous cue, but sometimes the video is between two cues, so when evaluating texttrack.activeCues the result is an empty element.
Problem:
I can think of several ways to do this, but none of them seem the most efficient or logical. Let's say the video is currently at minute 100, where there is no active cue, how do I know what the previous cue is when I don't have a reference id?
I don't know if there is some element inside the TextTrackCueList that will help me without having to make an algorithm that goes through all the cues and evaluate them. There should be a simpler way I think. I appreciate any help you can give me.


text:
Q: Upgrading XCode caused warning for hex Format Specifier The following line of code:
[colHeader appendFormat:@"%C", 0x2193];

throws this warning:
Format specifies type 'unsigned short' but the argument has type 'int'
This started appearing when I upgraded to Xcode 4.4 (upgraded compiler?).  The warning will drive me nuts...any suggestions on how to remove it?  Thanks.

A: Well, the easiest thing is just to cast it, I guess:
[colHeader appendFormat:@"%C", (ushort) 0x2193];

You can specify that a value is unsigned by appending a "u", e.g., 0x2193u. However, the constant will then be an unsigned int, not an unsigned short, so that won't help you here as you would still get a warning.


text:
Q: How to deploy custom style changes to a bunch of master pages in SharePoint I'm working in SharePoint 2010 and I was wondering is there a way to deploy a single css change to masterpage for every child site in my site collection? I'm using a team site and I'm using the v4.master.

A: I'm assuming that all your subsites are referencing a single masterpage at the root of your site collection.
I'm also assuming that since you're using an OOTB masterpage (v4.master), that it remains "untouched" and so doesn't have any custom CSS in it.
If this is correct so far, you've got three options:

*

*RELATIVE CSS. You can create a custom CSS file and add a reference to it in the head of your masterpage. This change only has to made once and will be reflected on all pages in all sites, however it does mean that you'll need to edit the HTML in the masterpage, so I wouldn't recommend this if you are using one of the OOTB files such as v4.master.

<SharePoint:CssRegistration
  runat="server" Name="custom.css"
  After="corev4.css"
  EnableCssTheming="false">

*

*THEME. Create a new site theme which contains your custom CSS file, then simply assign it to your site via the Site Settings UI. This doesn't require any changes to the masterpage, however themes are not automatically applied to new subsites when they're created. The only way to automate this would be through a feature or feature receiver.

*ALTERNATE CSS. Create your own custom CSS file, upload it to your site's Style Library folder and then appoint it as the Alternate CSS. This setting simply allows a designer to specify a URL to a CSS file which will be loaded AFTER the default SP styles. The Alternate CSS setting is inherited automatically by all child sites (by default), however if you don't have the publishing features enabled then you can't set it via the Site Settings UI, you'll have to do it through code or a Powershell script.
I hope that helps.


text:
Q: Scribbled out crossed out text How would one be able to reproduce the scribbling of text in LaTeX?
Something like this superimposed on text:

Ideally:
latex code:
% using the four scribble patterns (top to bottom)

\bigscribble{Can} \mediumscribble{this} \smallscribble{be} \flatscribble{done}

Output:


text:
Q: How can I save data (score) from my first viewcontroller to the second? I am creating a quiz app for ios for a big project at my school, but it is my first time making something with xcode and swift. I've run into a problem which i can't seem to figure out on my own. At the moment I am trying to keep score across multiple ViewControllers; I've tried a lot of different stuff, but it still doesn't work.
I am, like I said, a noob to xcode and actually all coding.
At first i have the code for the score:
@IBOutlet weak var scoreLabel: UILabel!
var score = 0

In my app, when someone answers the right question, the score gets 1 point (score += 1). After 4 questions of the first theme, 4 questions of a different theme, on a different ViewController are showed.
this is my code at the end of the first ViewController (MultipleChoice 2 is my second vc):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.destination is MultipleChoice2 {
        let vc = segue.destination as? MultipleChoice2
        vc?.score = score
    }
}

Code for my second vc:
var score = Int()

@IBOutlet weak var scoreLabel: UILabel?

override func viewDidLoad() {
    super.viewDidLoad()
    scoreLabel?.text = String(score)
}

I might be doing this all wrong, but I expect the app to save the score from my first ViewController to my second, so that, when someone has score 3 points in the first vc, he still has 3 points in the second vc.
The other things that i have tried didn't work at all, but with this code i get the message Thread 1: signal SIGABRT, at class AppDelegate, after clicking on the button that sends me to the second viewcontroller.
I honestly have no clue on how to save my score to the next vc and it would be great if someone had a solution to this..

A: Check if all the outlets are connected. After that check whether segue is connected or not.
Change
var score = Int()

to
var score: Int = 0

in secondVC and try again.

A: Try following and let me know if you face any trouble getting it working :
First of all change declaration of score variable in secondVC to
var score : Int = 0

then in prepare for segue method you can try these :
first set segue identifier from storyboard as it is more convenient to use :
then you can check if we are in proper condition by
if segue.identifier == "showSecondVC" {
    let vc = segue.destination as! MultipleChoice2
    vc.score = score
}

Also use breakpoint to check whether everything is executing properly
One more thing is you can set label text by using following code also :
scoreLabel?.text = "\(score)"

A: *

*Change var score = Int() to var score: Int? in second view controller.

*Set segue identifier to second view controller in storyboard.

*Modify segue method as below in first view controller
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showSecondVC" {
        let vc = segue.destination as! MultipleChoice2
        vc.score? = score
    }
}


text:
Q: Does the Where Statement matter if the tables are joined? I would like to know if both queries will always return the same results. are they equal?
SELECT OT_ACC_NO , ACC_NO FROM ACCOUNTS
JOIN OTHER_TABLE ON OT_ACC_NO = ACC_NO
WHERE ACC_NO IS NOT NULL

SELECT OT_ACC_NO , ACC_NO FROM ACCOUNTS
JOIN OTHER_TABLE ON OT_ACC_NO = ACC_NO
WHERE OT_ACC_NO IS NOT NULL

A: The two are equivalent.  Perhaps even more surprising is that the WHERE clause is unnecessary.  So, this is equivalent:
SELECT OT_ACC_NO, ACC_NO
FROM ACCOUNTS JOIN
     OTHER_TABLE
     ON OT_ACC_NO = ACC_NO;

Why?  Because an INNER JOIN returns rows only when the ON condition is true.  If either value is NULL, then the comparison returns NULL, which is treated as false.
I should note that although the final result will be the same, the execution plan for the queries may not be the same.

A: This where condition doesn't make any logical impact.
INNER JOIN ensures that records must exist in both tables and they cannot be NULL values.

A: Lets take a small step backwards and consider the equality operator and NULL values:
SELECT CASE WHEN NULL = NULL THEN 'Equal' ELSE 'Not Equal' END FROM DUAL;

Now, surprisingly for some, this will return Not Equal.
If you consider NULL to stand for an unknown value then you are asking if an unknown value is equal to another unknown value and the answer is false.
For your query:
SELECT OT_ACC_NO,
       ACC_NO
FROM   ACCOUNTS
       JOIN OTHER_TABLE
       ON OT_ACC_NO = ACC_NO

This will join the tables when OT_ACC_NO = ACC_NO and, as we saw above, if either of those variables is NULL (unknown) then the result of the equality comparison will always be false and the rows will be excluded from the join result.
So, adding a where clause to test whether either OT_ACC_NO or ACC_NO are NULL will never exclude any rows as they will already have been excluded by the join condition.

A: The question is marked with the Oracle, so the answers should be somehow carefull with topics a no logical impact, equivalent and same result.
Below sample data for case where the seconds query returns no data, but the first query fails with ORA-01722: invalid number
create table ACCOUNTS as
select '1-1'  ACC_NO from dual;

create table OTHER_TABLE as
select cast(null as number) OT_ACC_NO from dual;


text:
Q: A question on finite fields. Suppose you have a finite field $\mathbb{F}$, where $|\mathbb{F}|=p^n$ and $p$ is a prime number. Also suppose that $f(x)=x^2+b\in \mathbb{F}[x]$ is an irreducible polynomial over $\mathbb{F}$ and $r$ is a root of $f(x)$ in an extension of $\mathbb{F}$.
How can I prove that $p\neq 2$?

A: Let $K$ be a finite field of characteristic $2$. For any $a\in K$, let $f(a)=a^2$. Note that $f$ is one to one. For if $a^2=y^2$, then $(a-y)(a+y)=0$, so $y=a$ or $y=-a=a$.
Since $K$ is finite, and $f$ is one to one, it is onto. Thus everything is a square, and in particular $x^2+b$ is never irreducible.


text:
Q: JFrame Paint having click-sensitive areas of the screen I was making a program and I wanted to know how to make certain areas of a JFrame activate something when clicked, although without a button, like you clicked in the upper-right quarter of a picture to activate something.

A: Create an List of Shape objects to represent the areas that you want to click on:
List<Shape> shapes = new ArrayList<Shape>();

Then you can add different shapes to the List:
areas.add( new Rectangle(5, 5, 10, 10) );

Then you add a MouseListener to the frame and in the mousePressed event you would do something like:
for (Shape shape: shapes)
{
    if (shape.contains(theMousePointFromTheMouseEvent)
        // do something
}

A: create a JLabel object and set its icon to the image you want to display. Then add a mouse listener to the label object and implement all of its abstract classes especially the mouse clicked method to do what you want to do when clicked. Then when you click your JLabel you will see what you want.
The below code is an example to print "hello" when label is clicked:-
java.awt.event.MouseListener ml = new java.awt.event.MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("hello");
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        };

       jLabel1.addMouseListener(ml);