text:
Q: TStringList splitting bugs Recently I've been informed by a reputable SO user, that TStringList has splitting bugs which would cause it to fail parsing CSV data. I haven't been informed about the nature of these bugs, and a search on the internet including Quality Central did not produce any results, so I'm asking. What are TStringList splitting bugs?
Please note, I'm not interested in unfounded opinion based answers.
What I know:
Not much... One is that, these bugs show up rarely with test data, but not so rarely in real world.
The other is, as stated, they prevent proper parsing of CSV. Thinking that it is difficult to reproduce the bugs with test data, I am (probably) seeking help from whom have tried using a string list as a CSV parser in production code.
Irrelevant problems:
I obtained the information on a 'Delphi-XE' tagged question, so failing parsing due to the "space character being considered as a delimiter" feature do not apply. Because the introduction of the StrictDelimiter property with Delphi 2006 resolved that. I, myself, am using Delphi 2007.
Also since the string list can only hold strings, it is only responsible for splitting fields. Any conversion difficulty involving field values (f.i. date, floating point numbers..) arising from locale differences etc. are not in scope.
Basic rules:
There's no standard specification for CSV. But there are basic rules inferred from various specifications.
Below is demonstration of how TStringList handles these. Rules and example strings are from Wikipedia. Brackets ([ ]) are superimposed around strings to be able to see leading or trailing spaces (where relevant) by the test code.
Spaces are considered part of a field and should not be ignored.

Test string: [1997, Ford , E350]
Items: [1997] [ Ford ] [ E350]

Fields with embedded commas must be enclosed within double-quote characters.

Test string: [1997,Ford,E350,"Super, luxurious truck"]
Items: [1997] [Ford] [E350] [Super, luxurious truck]

Fields with embedded double-quote characters must be enclosed within double-quote characters, and each of the embedded double-quote characters must be represented by a pair of double-quote characters.

Test string: [1997,Ford,E350,"Super, ""luxurious"" truck"]
Items: [1997] [Ford] [E350] [Super, "luxurious" truck]

Fields with embedded line breaks must be enclosed within double-quote characters.

Test string: [1997,Ford,E350,"Go get one now
they are going fast"]
Items: [1997] [Ford] [E350] [Go get one now
they are going fast]

In CSV implementations that trim leading or trailing spaces, fields with such spaces must be enclosed within double-quote characters.

Test string: [1997,Ford,E350," Super luxurious truck "]
Items: [1997] [Ford] [E350] [ Super luxurious truck ]

Fields may always be enclosed within double-quote characters, whether necessary or not.

Test string: ["1997","Ford","E350"]
Items: [1997] [Ford] [E350]

Testing code:
var
  SL: TStringList;
  rule: string;

  function GetItemsText: string;
  var
    i: Integer;
  begin
    for i := 0 to SL.Count - 1 do
      Result := Result + '[' + SL[i] + '] ';
  end;

  procedure Test(TestStr: string);
  begin
    SL.DelimitedText := TestStr;
    Writeln(rule + sLineBreak, 'Test string: [', TestStr + ']' + sLineBreak,
            'Items: ' + GetItemsText + sLineBreak);
  end;

begin
  SL := TStringList.Create;
  SL.Delimiter := ',';        // default, but ";" is used with some locales
  SL.QuoteChar := '"';        // default
  SL.StrictDelimiter := True; // required: strings are separated *only* by Delimiter

  rule := 'Spaces are considered part of a field and should not be ignored.';
  Test('1997, Ford , E350');

  rule := 'Fields with embedded commas must be enclosed within double-quote characters.';
  Test('1997,Ford,E350,"Super, luxurious truck"');

  rule := 'Fields with embedded double-quote characters must be enclosed within double-quote characters, and each of the embedded double-quote characters must be represented by a pair of double-quote characters.';
  Test('1997,Ford,E350,"Super, ""luxurious"" truck"');

  rule := 'Fields with embedded line breaks must be enclosed within double-quote characters.';
  Test('1997,Ford,E350,"Go get one now'#10#13'they are going fast"');

  rule := 'In CSV implementations that trim leading or trailing spaces, fields with such spaces must be enclosed within double-quote characters.';
  Test('1997,Ford,E350," Super luxurious truck "');

  rule := 'Fields may always be enclosed within double-quote characters, whether necessary or not.';
  Test('"1997","Ford","E350"');

  SL.Free;
end;

If you've read it all, the question was :), what are "TStringList splitting bugs?"

A: I'm going to go out on a limb and say that the most common failure case is the embedded linebreak.  I know most of the CSV parsing I do ignores that.  I'll use 2 TStringLists, 1 for the file I'm parsing, the other for the current line.  So I'll end up with code similar to the following:
procedure Foo;
var
    CSVFile, ALine: TStringList;
    s: string;

begin
    CSVFile := TStringList.Create;
    ALine := TStringList.Create;
    ALine.StrictDelimiter := True;
    CSVFile.LoadFromFile('C:\Path\To\File.csv');
    for s in CSVFile do begin
        ALine.CommaText := s;
        DoSomethingInteresting(ALine);
    end;
end;

Of course, since I'm not taking care to make sure that each line is "complete", I can potentially run into cases where the input contains a quoted linebreak in a field and I miss it.
Until I run into real world data where it's an issue, I'm not going to bother fixing it.  :-P

A:
Not much... One is that, these bugs show up rarely with test data, but not so rarely in real world.

All it takes is one case. Test data is not random data, one user with one failure case should submit the data and voilà, we've got a test case. If no one can provide test data, maybe there's no bug/failure?

There's no standard specification for CSV.

That one sure helps with the confusion. Without a standard specification, how do you prove something is wrong? If this is left to one's own intuition, you might get into all kinds of troubles. Here's some from my own happy interaction with government issued software; My application was supposed to export data in CSV format, and the government application was supposed to import it. Here's what got us into a lot of trouble several years in a row:

*

*How do you represent empty data? Since there's no CSV standard, one year my friendly gov decided anything goes, including nothing (two consecutive commas). Next they decided only consecutive commas are OK, that is, Field,"",Field is not valid, should be Field,,Field. Had a lot of fun explaining to my customers that the gov app changed validation rules from one week to the next...

*Do you export ZERO integer data? This was probably an bigger abuse, but my "gov app" decided to validate that also. At one time it was mandatory to include the 0, then it was mandatory NOT to include the 0. That is, at one time Field,0,Field was valid, next Field,,Field was the only valid way...

And here's an other test-case where (my) intuition failed:

1997, Ford, E350, "Super, luxurious truck"

Please note the space between , and "Super, and the very lucky comma that follows "Super. The parser employed by TStrings only sees the quote char if it immediately follows the delimiter. That string is parsed as:
[1997]
[ Ford]
[ E350]
[ "Super]
[ luxurious truck"]

Intuitively I'd expect:
[1997]
[ Ford]
[ E350]
[Super luxurious truck]

But guess what, Excel does it the same way Delphi does it...
Conclusion

*

*TStrings.CommaText is fairly good and nicely implemented, at least the Delphi 2010 version I looked at is quite effective (avoids multiple string allocations, uses a PChar to "walk" the parsed string) and works about the same as Excel's parser does.

*In the real world you'll need to exchange data with other software, written using other libraries (or no libraries at all), where people might have miss-interpreted some of the (missing?) rules of CSV. You'll have to adapt, and it'll probably not be a case of right-or-wrong but a case of "my clients need to import this crap". If that happens, you'll have to write your own parser, one that adapts to the requirements of the 3rd party app you'd be dealing with. Until that happens, you can safely use TStrings. And when it does happen, it might not be TString's fault!

A: Another example... this TStringList.CommaText bug exists in Delphi 2009.
procedure TForm1.Button1Click(Sender: TObject);
var
  list : TStringList;
begin
  list := TStringList.Create();
  try
    list.CommaText := '"a""';
    Assert(list.Count = 1);
    Assert(list[0] = 'a');
    Assert(list.CommaText = 'a'); // FAILS -- actual value is "a""
  finally
    FreeAndNil(list);
  end;
end;

The TStringList.CommaText setter and related methods corrupt the memory of the string that holds the a item (its null terminator character is overwritten by a ").

A: Already tried use TArray<String> split?
var
text: String;
arr: TArray<String>;
begin
text := '1997,Ford,E350';
arr := text.split([',']);

So arr would be:
arr[0] = 1997;
arr[1] = Ford;
arr[2] = E350;


text:
Q: send whatsapp message to specific number programmatically I'm developing an app, and I want to send a WhatsApp message to a specific number
I used this code and make corrections.
but the users who installed both WhatsApp messenger and business WhatsApp, this code send a message into business WhatsApp directly, it didn't show options to allow the users to choose between two apps
in android 5 it shows options but android 7 and 8 it didn't show options. it sends to business WhatsApp only.
can you help me to allow to give options to choose between both apps in android 7 and 8?
private void openWhatsApp (String phoneNumber) {

    boolean isWhatsappInstalled = whatsappInstalledOrNot("com.whatsapp");

    if (isWhatsappInstalled) {

        Intent intent = new Intent(Intent.ACTION_VIEW);

        intent.setData(Uri.parse("http://api.whatsapp.com/send?phone="+phoneNumber));

        startActivity(intent);

    } else {
        Uri uri = Uri.parse("market://details?id=com.whatsapp");
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        Toast.makeText(getActivity(), "WhatsApp not Installed",
                Toast.LENGTH_SHORT).show();
        startActivity(goToMarket);
    }
}

private boolean whatsappInstalledOrNot(String uri) {
    PackageManager pm = getActivity().getPackageManager();
    boolean app_installed = false;
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        app_installed = true;
    } catch (PackageManager.NameNotFoundException e) {
        app_installed = false;
    }
    return app_installed;
}

A: i am sending whatapp message from my app with the help of this code:-
private void sendMsgOnSavedWhatsappNumber(String mobile) {
        Intent sendIntent = new Intent("android.intent.action.MAIN");
        sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
        sendIntent.putExtra("jid",
                PhoneNumberUtils.stripSeparators("91" + mobile) + "@s.whatsapp.net");
        startActivity(sendIntent);
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: how do we convert (a ∧ b) ↔ c into CNF form? After making a truth table, what I came up with was:
(¬ (a ∧ b ) ∨ c ) ∧ ( (a ∧ b ) ∨ c ) ∧ ( (a ∧ b ) ∨ ¬ c )
But now I find it difficult to convert this into CNF. I have no idea how to change the ∧ such that they become ∨ within the clauses.
What I am doing is using the (a ∧ b) and c to form the CNF. But this is getting me nowhere.
I consulted my coursemates, who said I should instead be using a, b, and c to form the CNF. I think they're right, but I don't know why I am wrong.
Should I be using just the atomic propositions, instead of using the compound proposition? Is this why I am hitting a brick wall here?
If I use the atomic propositions, wouldn't that be a different meaning than using compound proposition (a ∧ b)?
Please help. Thanks so much.

A: $(a\land b)\leftrightarrow c$ becomes
$$(a\land b\land c)\lor(\neg a\land\neg c)\lor(\neg b\land\neg c)$$
This is the DNF. To get the CNF we distribute OR over AND, removing combinations containing things like $a\lor\neg a$ and clauses contained in other clauses:
$$(a\lor\neg c)\land(b\lor\neg c)\land(c\lor\neg a\lor\neg b)$$


text:
Q: x86 Assembly - Add Two 64 Bit Numbers I am trying to write this code in x86 assembly (X[i] and C are 64 bit numbers). Assume memory address to A[i] is stored in ebx and C is stored in edx.
for(int i = 0; i <= 100; i++) {
    A[i] = A[i] + C
}

I have a pretty good grasp on how to access the values in memory. Because I have 32 bit registers, I believe I need to do two additions: one for the lower 32 bits of each operand and one for the upper 32 bits.
So something like:
mov rax, [A[i]_bits0_15]
add rax, [C_bits0_15]
mov [A[i]_bits0_15], rax

mov rbx, [A[i]_bits16_31]
adc rbx, [C_bits16_31]
mov [A[i]_bits16_31], rbx

Am I on the right track? I am not sure how to do the proper notation for adding the lower/upper 32 bits from memory so that would be helpful to see as well.

A: No different than grade school.
 011
 1234
+5678
=====
 6912

break it into halves
 11
  34
+ 78
=====
 112

 12
+56
=====
 68

you need to move the carry over to the upper addition
 11   <--- carry out hanging off the left
  34
+ 78
=====
  12

  1  <--- carry in from lower level addition
 12
+56
=====
 69

and there is the 6912.
X86 has a carry out bit and should have an add with carry instruction to include that bit (zero or one) into the next level addition.
You can obviously add numbers that are as wide as you have storage for 8, 16, 32, 64 bits at a time depending on the instruction you choose. 1 million bits, one billion bits, etc...


text:
Q: What regularization of singularity means? I have this function,
$$F(r) =  \frac{1}{r^{6}-1}$$
What does regularization of the singularity mean? I think we can add a small imaginary part to remove the singularity like given below.
$$F(r) = \frac{1}{r^{6}-1+i 0^{+}}$$
How this helps when evaluating following integral.
$$\int_{-1}^{1} \frac{1}{r^{6}-1+i 0^{+}}dr$$


text:
Q: Restricting public access of server I have 2 servers which I run as front-end and back-end server. I use rest api for calls and nginx as reverse proxy in both servers.
I want to restrict public access of back-end server (direct access), and allow access only to front-end server for api calls. Both servers have unique domain. By default if someone tries to get the url of backend server and opens, It should show some error 400 message.
I tried nginx deny and allow but not working.
What may be the best way to do this ?


text:
Q: Preg_match doesn't work right I have spent a while to search around the internet but still couldn't find out why my script didn't work :(
Here is my string ($title) which I need to check
Nanatsu no Taizai – Chương 071: Tồn tại trong bóng đêm

And and list of regular expression I used but always returned false
"/^([a-z\ ]+)[\-]{1,}/i"

"/^([a-z\ ]+)[\ ]{0,1}[\-]{1,}/i"

"/^([a-z\ ]+)[\-]{1,}/ui"

And the code I used is
preg_match($regex,$title,$matches)

Please help me . Thank you in advance.

A: If you're just trying to extract everything up to the first -, the best way to do that is not to use a regular expression at all. strtok and trim, might be ideal for you:
$result = trim(strtok($title, '-'));

If you want the result to include the - then, you can do:
$result = strtok($title, '-') . '-';

A: Maybe this works for you
$t = "Nanatsu no Taizai - Chương 071: Tồn tại trong bóng đêm";

preg_match('/(.*) - (.* [0-9]{1,}:) (.*)/i', $t, $matches);

print_r($matches);

Result
Array
(
    [0] => Nanatsu no Taizai - Chương 071: Tồn tại trong bóng đêm
    [1] => Nanatsu no Taizai
    [2] => Chương 071:
    [3] => Tồn tại trong bóng đêm
)

Better?

A: Take a look at Unicode character properties, find your language from the table and use it like \p{Thai}


text:
Q: Python3 kill a blocked Thread So I am working on an task that can only be performed for an estimated total of 10 seconds.
I made a list of threading.Thread, that all access a queue.Queue to pull the tasks but after the 10 seconds are up I want to kill the threads and move on but, if I finish first I want to move on before 10 seconds.
I have a "manager" thread blocked on a call on queue.Queue this way I can see if the queue is complete before the 10 seconds are up.
self._task_queue.join()

How can I have the main execution thread stop that thread if the timeout has been reached? Note I am using threading.Thread as the task these threads are doing is checking operating system tasks.
example:
timeout_dt = datetime.utcnow() + timedelta(seconds=self._timeout) if self._timeout else None
while True:
    try:
        current_time = datetime.utcnow()
        if self._manager.event.is_set():
            logger.info(f'manager complete event {self._manager.event.is_set()}')
            break
        if timeout_dt and current_time > timeout_dt:
            logger.info(f'timeout complete current {current_time} timeout {timeout_dt}')
            # TODO: kill the manager thread waiting for queue.Queue.join()
            break
        time.sleep(1)
    except Exception as e:
        # An exception happened in the main execution thread
        logger.exception(e)

A: How I solved it
class MyQueue(Queue):

    def timeout_join(self, timeout=None):
        '''Blocks until all items in the Queue have been gotten and processed.
        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer thread calls task_done()
        to indicate the item was retrieved and all work on it is complete. If
        optional args 'timeout' is a non-negative number, it blocks at most
        'timeout' seconds and raises the TimeoutError exception if the number
        of unfinished tasks is not equal to the task_done in the available time.
        When the count of unfinished tasks drops to zero or timeout is reached,
        join() unblocks.
        '''
        with self.all_tasks_done:
            if timeout is None:
                while self.unfinished_tasks:
                    self.all_tasks_done.wait()
            elif timeout and timeout < 0:
                raise ValueError("'timeout' must be a non-negative number")
            else:
                endtime = time.time() + timeout
                while self.unfinished_tasks:
                    remaining = endtime - time.time()
                    if remaining <= 0.0:
                        raise TimeoutError
                    self.all_tasks_done.wait(remaining)


text:
Q: DNS wildcard: make all subdomains unresolvable Here's the situation:

*

*before I bought the domain, all of its subdomains were resolving to some IP address (let's call it WRONG IP)

*after I bought it - nothing changed. I could add my own records, but any non-existing subdomains would still point to WRONG IP

*to counteract this, I created a wildcard subdomain to point to my server (let's call it RIGHT IP).

*now all non-existing subdomains point to RIGHT IP

But all I want is a couple of A records ... that's all. I don't want all of the non-existing subdomains to point anywhere. I just want them to not resolve at all.
How could I do this?
Thanks for your thoughts

A: The answer to my question was one of those things you think would be too simple to actually try. After waiting a while for the wildcard record to propogate all over the world, i removed that record completely. And the hosting provider's dns servers are now correctly not resolving non-existing domains instead of pointing to a marketing page.

A: What are the "dns suffix" settings on your machine/router/dhcp?
I could only explain this behavior when, on your machine there's a DNS suffix that has a wildcard record, and if you go to nonexisting.domain.com, in fact it is resolved as nonexisting.domain.com.dns-suffix.other-domain.com (which is resolvable to your WRONG IP).

A: You can try to add the following A record:
@ IN A 127.0.0.1
It's not a perfect solution but it is a solution.
I believe that will solve your problem.


text:
Q: $\varphi(x)=\int_{[\xi_0,\xi]}f(x+t)d\mu_t$ absolutely continuous and summable on $\mathbb{R}$ Let $f\in L_1(-\infty,\infty)$ be a Lebesgue-summable function on $\mathbb{R}$. I read that the function$$\varphi(x)=\int_{[\xi_0,\xi]}f(x+t)d\mu_t$$is absolutely continuous on any real closed interval. I knew that if $g\in L_1[a,b]$ then $\int_{[a,x]}g(t)d\mu_t$ is absolutely continuous as a function of $x$, but I cannot prove the absolute continuity of $\varphi$ to myself.
Moreover, it is said that it is Lebesgue-integrable on $\mathbb{R}$.
How can we prove those two statements?
As to the Lebesgue-integrability, I see that it would follow, because of Fubini's theorem, from the measurability of $\int_{\mathbb{R}}|f(x+t)|d\mu_x$ as a function of $t$, but I have no idea of how to prove it, if it is true.
I $\infty$-ly thank you all!!!

A: Regarding the integrability of $\varphi$, rather than showing the measurability of
$$t \mapsto \int_\mathbb{R} \lvert f(x+t)\rvert\,d\mu_x,$$
use the mesurability of
$$(x,t) \mapsto f(x+t)$$
which is for example shown here. Then we can compute
\begin{align}
\int_\mathbb{R} \lvert \varphi(x)\rvert\,d\mu_x &= \int_\mathbb{R} \left\lvert \int_{[\xi_0,\xi]} f(x+t)\,d\mu_t\right\rvert\,d\mu_x\\
&\leqslant \int_\mathbb{R} \int_{[\xi_0,\xi]} \lvert f(x+t)\rvert\,d\mu_t\,d\mu_x\\
&= \int_{[\xi_0,\xi]}\int_{\mathbb{R}} \lvert f(x+t)\rvert\,d\mu_x\,d\mu_t\\
&= \int_{[\xi_0,\xi]} \lVert f\rVert_{L^1(\mathbb{R})}\,d\mu_t\\
&= (\xi-\xi_0)\lVert f\rVert_{L^1(\mathbb{R})}\\
&< +\infty
\end{align}
to see that $\varphi \in L^1(\mathbb{R})$.
For the absolute continuity of $\varphi$, write (for $x < y$ to avoid dealing with signs)
\begin{align}
\varphi(y) - \varphi(x) &= \int_{[\xi_0,\xi]} f(y+t)\,d\mu_t - \int_{[\xi_0,\xi]} f(x+t)\,d\mu_t\\
&= \int_{y+\xi_0}^{y+\xi} f(u)\,d\mu_u - \int_{x+\xi_0}^{x+\xi} f(u)\,d\mu_u\\
&= \int_{x+\xi}^{y+\xi} f(u)\,d\mu_u - \int_{x+\xi_0}^{y+\xi_0} f(u)\,d\mu_u\\
&= \int_{x}^y f(\xi+t)\,d\mu_t - \int_x^y f(\xi_0+t)\,d\mu_t\\
&= \int_x^y f(\xi+t) - f(\xi_0+t)\,d\mu_t.
\end{align}
Thus we see that $\varphi$ is the integral of the integrable function
$$t \mapsto f(\xi + t) - f(\xi_0+t),$$
and hence $\varphi$ is absolutely continuous.


text:
Q: Show events in the middle of day in month-timline view in FullCalendar I would need to show events in month-timeline view in FullCalendar from the middle of the day, as you can see on the picture below.
Every event starts in the middle of the day and ends just like that. If another event starts the same day, is on the same line and it starts in the middle of day as well.
At the top of my head is to specify hours in "start" and "end" parameters of every event, but it is not used in month-timline view (in header, there are only days, not hours).
Is here a way to how to do it?

A: set
slotDuration : '12:00' and
slotLabelInterval  : '24:00'


text:
Q: How to change Wordpress Logo URL in Genesis Block Theme So, there is a random function called genesis_block_theme_title_logo() that is supposed to display the logo and have the url for the logo when clicked on, but I can't seem too ion the function.
I need to just change the url the logo is pointing to. I cloned this website from another one, so it's still pointing to a previous one.


text:
Q: Combine files using Pillow and Python
*

*I need to run a python script inside a folder.

*the script count    files    ( image ) number create an image for
every 64 images.
example: if the    folder containing 640 images, I will get 10
images as a combination    of 64 images/outputimage

just, before adding  "for" instruction, I can get a result, but manually and only with the same image ( a duplication of image ).
any idea?
so I proceed as follows:
import os
import os.path

from PIL import Image

list = os.listdir(".")  # current directory
number_files = len(list)
print (number_files)

for x in range(0, number_files):

    # files = ['x.png']

        # opens an image: here I can't find how
    im = Image.open("1.png") # here I tried to

# creates a new empty image, RGB mode, and size 800 by 800.
new_im = Image.new('RGB', (800, 800))

# Here I resize my opened image, so it is no bigger than 100,100
im.thumbnail((100, 100))
# Iterate through a 8 by 8 grid with 100 spacing, to place my image
for i in xrange(0, 800, 100):
    for j in xrange(0, 800, 100):
        # paste the image at location i,j:
        new_im.paste(im, (i, j))
        new_im.save(os.path.expanduser('outputimage.png'))

update :
import os
import os.path

from PIL import Image

def drange(start, stop, step):
    while start < stop:
        yield start
        start += step

list = os.listdir(".")  # directory path
number_files = len(list)
print (number_files)

new_im = Image.new('RGB', (800, 800))

for x in drange(0, number_files, 64):

    im = Image.open(list[x])
    im.thumbnail((100, 100))

    for i in xrange(0, 800, 100):
        for j in xrange(0, 800, 100):

            new_im.paste(im, (i, j))

new_im.save(os.path.expanduser('out.png'))

other update based on Sven solution :
import os.path

from PIL import Image

fileList = [] where_to_look = "png/"
  for f in os.listdir(where_to_look):
        if os.path.isfile(os.path.join(where_to_look, f)):
            fileList.append(f)
             print (len(fileList))

target_img = None n_targets = 0 collage_saved = False

for n in range(len(fileList)):
    img = Image.open(fileList[n])
    img.thumbnail((100, 100))

    if n % 64 == 0:
        # create an empty image for a collage
        target_img = Image.new("RGB", (800, 800))
        n_targets += 1
        collage_saved = False

    # paste the image at the correct position
    i = int(n / 8)
    j = n % 8
    target_img.paste(img, (100*i, 100*j))

    if (n + 1) % 64 == 0 and target_img is not None:
        # save a finished 8x8 collage
        target_img.save("{0:04}.png".format(n_targets))
        collage_saved = True

# save the last collage if not collage_saved:
    target_img.save("{0:04}.png".format(n_targets))

A: Based on your update, I quickly sketched a solution. Please beware that I did not test it:
import os
from PIL import Image

image_dir = os.path.abspath("png")
# list all files in directory
files = os.listdir(image_dir)
# get all PNGs
png_files = filter(lambda x: x.endswith(".png"), files)
# make file paths absolute
image_files = map(lambda x: os.sep.join([image_dir, x]), png_files)

n_files = len(image_files)

target_img = None
n_targets = 0
collage_saved = False
for n in range(n_files):
    img = Image.open(image_files[n])
    img.thumbnail((100, 100))

    if n % 64 == 0:
        # create an empty image for a collage
        target_img = Image.new("RGB", (800, 800))
        n_targets += 1
        collage_saved = False

    # paste the image at the correct position
    i = int(n / 8)
    j = n % 8
    target_img.paste(img, (100*i, 100*j))

    if (n + 1) % 64 == 0 and target_img is not None:
        # save a finished 8x8 collage
        target_img.save("{0:04}.png".format(n_targets))
        collage_saved = True

# save the last collage
if not collage_saved:
    target_img.save("{0:04}.png".format(n_targets))

This will iterate over all your images and assemble them in a 8x8 grid (I call it collage in the script). Whenever the grid is filled, the collage is saved as a file with the naming pattern 0001.png, 0002.png and so on.
Note that there are some points to improve:

*

*os.listdir(".") will give you all files in the directory, not only images. You would have to filter the output for image files.

*This only works in the current working directory.

*The output is also saved to the current working directory.

UPDATE: filter PNGs and use absolute paths


text:
Q: Strange occurrences with controlling multiple keys being held down With the below code, when a key is pressed its keycode is pushed to the keymap array if it's not already there and when a key is let up its keycode is taken out of the array. When testing this out by constantly shoving the keymap array to the console, I found some strange things.
var keymap = [];

$(window).keydown(function(e) {
    if($.inArray(e.keyCode,keymap) == -1) {keymap.push(e.keyCode);}
});

$(window).keyup(function(e) {
    for(i = 0;i < keymap.length;i++) {
        if(keymap[i] = e.keyCode) {keymap.splice(i,1);}
    }
});

setInterval(function() {console.log(keymap);},100);

*

*If I hold down a and d at the same time their keycodes are present in keymap, then if I hold down w all three of their keycodes are present. Now when I let go of w it's removed from the array, but so is d even though I'm still holding down d.

*I then found that I can hold down a, w, and d and they'll all be put into keymap, but it will not put w, a, and s in keymap when I hold them down. A combination of two of these will be put in, but the third will not.
Can anyone tell me what's going on?

A: Your comparison is an assignment actually. Change if(keymap[i] = e.keyCode) to
if (keymap[i] == e.keyCode)
//             ^

Also, you should use local variables:
for(var i = 0; …
//  ^^^

And while it shouldn't matter for your array where items are supposed to be unique, you need to decrease the counter variable i after you remove an item or you skip to check the next one otherwise:
keymap.splice(i--,1)
//             ^^


text:
Q: How do I select a single row from duplicate resultsets? I think I may be on the right track but something is missing from my select statement

I am trying select the unique items in the level column. Is there a better way write this?
This is the desired output:

A: I may have found a work-around solution. By using a loop, I was able to supply the level and id:
I knew the Men slope/rating had the lower of the two srid. So I wrote the sql to limit the  results to the first one for the level, in this case white.
For the Female slope/rating, I just reversed the sql results and limit to 1 using ORDER BY DESC LIMIT 1. To get all 4 levels (White, Red, Black, Blue) I used Php array_push in a for loop to get the desired slope and rating for both Men and Women for all levels.


text:
Q: Unable to use make_index_sequence as a default argument to a function (instantiation of undefined template) I have the following C++ code, which correctly prints out the 3 values of the tuple, comma-separated.
#include <iostream>
#include <utility>
#include <tuple>

std::tuple<int, const char*, float> t(10, "ten", -0.0);

#define SEQ std::make_index_sequence<std::tuple_size_v<decltype(t)> >{}

template <typename... Ts, size_t... Is>
void print_tuple(const std::tuple<Ts...>& t, std::index_sequence<Is...>) {
    ((
        std::cout << (Is == 0 ? "" : ", ") << std::get<Is>(t)
    ), ...);
}

int main() {
    print_tuple(t, SEQ);
}

However, if I want to just call print_tuple(t), I would want to make a default argument.
#include <iostream>
#include <utility>
#include <tuple>

std::tuple<int, const char*, float> t(10, "ten", -0.0);

#define SEQ std::make_index_sequence<std::tuple_size_v<decltype(t)> >{}

template <typename... Ts, size_t... Is>
void print_tuple(const std::tuple<Ts...>& t, std::index_sequence<Is...> = SEQ) {
    ((
        std::cout << (Is == 0 ? "" : ", ") << std::get<Is>(t)
    ), ...);
}

int main() {
    print_tuple(t);
}

The problem is that this code produces an error -
implicit instantiation of undefined template 'std::tuple_size<const
      std::tuple<int, const char *, float> &>'
    inline constexpr size_t tuple_size_v = tuple_size<_Tp>::value;
                                           ^
main.cpp:10:75: note: in instantiation of variable template specialization
      'std::tuple_size_v<const std::tuple<int, const char *, float> &>'
      requested here

I tried using std::remove_cv & std::remove_reference to remove const &, but I got the same error.

A: You can overload the print_tuple-function:
#include <iostream>
#include <utility>
#include <tuple>

std::tuple<int, const char*, float> t(10, "ten", -0.0);

template <typename... Ts, size_t... Is>
void print_tuple(const std::tuple<Ts...>& t, std::index_sequence<Is...>) {
    ((
        std::cout << (Is == 0 ? "" : ", ") << std::get<Is>(t)
    ), ...);
}
template <typename... Ts>
void print_tuple(const std::tuple<Ts...>& t) {
    print_tuple(t, std::make_index_sequence<sizeof...(Ts)>{});
}

int main() {
    print_tuple(t);
}


text:
Q: Prepending all linkable items in a textview with http:// I have a textview that displays html.
> textview.setText(html.fromhtml(document))
> textview.setMovementMethod(LinkMovementMethod.getInstance());

When i go to click on some of the links, some open in browser, others don't.
Logcat says this:
> No Activity found to handle Intent { act=android.intent.action.VIEW
> dat=law.fordham.edu/ (has extras) }

Seems like a simple fix. Just have to add "http://" to every link in the doc.
If all of the links started with "www", things would be easy. I would just do:
> replaceAll("www", "http://www")

That does work for some of the links. But not all of them start with 'www' and therefore, I need a different method to prepend them with http://
What is the best way to do this?
EDIT:
paragraphs = doc.select("div.sectionContent>*");
       set =  paragraphs.toString().replaceAll("\\\\n", "\n").trim();
       links = doc.select("a");
           for (Element i: links){
                  String relHref = i.attr("abs:href");
                  if (!relHref.contains("http")){
                       set = set.replace(relHref, "http://"+relHref);
                  }
                                 }

I'm using jsoup to do all this but I keep getting:
java.lang.OutOfMemoryError

A: Process the HTML, look for <a> tags and then if the start of the url inside the anchor is not what you want then adjust it.
A regex search should be able to find the anchors for you.


text:
Q: How to extract the n-th elements from a list of tuples in Java? Basically I try to extract only the 2nd element from the list of tuples.
Scala has a  very nice solution to this (which somewhat looks like
this x._2) but I don't know how I can do this in Java.
public static ArrayList<House> house = new ArrayList<>(Arrays.asList(new House(321321, 2.5),
                                                                     new House(456544, 3.0),
                                                                     new House(789687, 4.0));

A: Assuming your House class has getters for these values e.g.:
public class House {
    private final int value1;
    private final double value2;

    public House(final int value1, final double value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    public int getValue1() {
        return value1;
    }

    public double getValue2() {
        return value2;
    }
}

You can do a map and collect to get the second value:
final List<Double> value2s = house.stream().map(House::getValue2).collect(Collectors.toList());


text:
Q: How to remove moved items from a Jlist? I'm trying to remove the items that I moved to my second Jlist. I've been trying to do this using two different codes, one using HashSet and the other using Arrays and For loops.
HashSet method:
//So far my code moves the items.

Set<Integer> keepThese = new HashSet<>();
int sel[] = lstLista1.getSelectedIndices();
for (int x : sel) {
    keepThese.add(x);
}
for (int i=0 ; i< modelo1.getSize() ; i++) {
    if(keepThese.contains(i)) {

    } else {
        if(modelo2.contains(modelo1.getElementAt(i))) {
        } else {
            modelo2.addElement(modelo1.getElementAt(i));
        }
    }
}

Arrays and For loops
int indices[] = lstLista1.getSelectedIndices();
String arreglo[] = new String[indices.length];
for (int i = 0; i < indices.length; i++) {
   arreglo[i] = modelo1.getElementAt(indices[i]).toString();
}
for (int i = indices.length-1; i >= 0; i--) {
    if(modelo2.contains(modelo1.getElementAt(indices[i]))) {

    } else {
        modelo1.remove(indices[i]);
    }
}
for (int i = 0; i < modelo1.getSize(); i++) {
    if(!modelo2.contains(modelo1.getElementAt(i))) {
        modelo2.addElement(modelo1.getElementAt(i));
    }
}
modelo1.removeAllElements();
for (int i = 0; i < arreglo.length; i++) {
    modelo1.addElement(arreglo[i]);
}

A: I'm not sure why you have 4 loops?
You need to do it in two steps (ie two loops):

*

*copy the data from the first JList to the second JList

*remove the rows from the first JList

Step 1 should be straight forward. Just create a loop to get the data at each index and add it to the other ListModel. Assuming you are using the DefaultListModel the code would be something like:
for (int i = 0; i < indices.length; i++) {
    model2.addElement( model1.getElementAt(indices[i]) );

Here is an example for step 2. It demonstrates the logic for both  a JList and a JTable:
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.*;
import javax.swing.table.*;

public class ItemDeletion extends JPanel
{
    private JList<String> list;
    private JTable table;

    public ItemDeletion()
    {
        setLayout( new BorderLayout(5, 5) );

        String[] items =
        {
            "One",
            "Two",
            "Three",
            "Four",
            "Five",
            "Six",
            "Seven",
            "Eight",
            "Nine",
            "Ten"
        };

        //  Add the list

        DefaultListModel<String> listModel = new DefaultListModel<String>();

        for (String item: items)
            listModel.addElement( item );

        list = new JList<String>( listModel );

        JButton listDelete = new JButton( "Delete From List" );
        listDelete.addActionListener( new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                DefaultListModel model = (DefaultListModel)list.getModel();
                int row = list.getSelectedIndex();

                while (row != -1)
                {
                    model.removeElementAt( row );
                    row = list.getSelectedIndex();
                }
            }
        });

        JPanel listPanel = new JPanel( new BorderLayout(5, 5) );
        listPanel.add(new JScrollPane( list ), BorderLayout.CENTER);
        listPanel.add(listDelete, BorderLayout.PAGE_END);

        //  Add the table

        DefaultTableModel tableModel = new DefaultTableModel(0, 1);
        List<String> tableItems = Arrays.asList( items );
        Collections.shuffle( tableItems );

        for (String item: tableItems)
        {
            System.out.println( item );
            tableModel.addRow( new String[]{item} );
        }

        table = new JTable( tableModel );

        table.setAutoCreateRowSorter(true);
        ((DefaultRowSorter)table.getRowSorter()).toggleSortOrder(0);

        JButton tableDelete = new JButton( "Delete From Table" );
        tableDelete.addActionListener( new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                DefaultTableModel model = (DefaultTableModel)table.getModel();
                int row = table.getSelectedRow();

                while (row != -1)
                {
                    int modelRow = table.convertRowIndexToModel( row );
                    model.removeRow( modelRow );
                    row = table.getSelectedRow();
                }
            }
        });

        JPanel tablePanel = new JPanel( new BorderLayout(5, 5) );
        tablePanel.add(new JScrollPane( table ), BorderLayout.CENTER);
        tablePanel.add(tableDelete, BorderLayout.PAGE_END);

        add(listPanel, BorderLayout.LINE_START);
        add(tablePanel, BorderLayout.LINE_END);
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Multiple Item Deletion");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ItemDeletion(), BorderLayout.NORTH);
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}


text:
Q: No error or warning for trying to print to an already closed filehandle In the following small code, I do not get an error or a warning for lines [09] and [18]. The only warning I get is with line [21]:
use strict;                                              # [01]
use warnings FATAL => 'unopened';                        # [02]
                                                         # [03]
open(my $outHandleA, ">outputA.txt") or die ("A: $!\n"); # [04] Opened $outHandleA
print $outHandleA "FILE A\n";                            # [05]
close $outHandleA;                                       # [06] Closed $outHandleA
                                                         # [07]
print $outHandleA;                                       # [08]
print $outHandleA "ABC\n";                               # [09] <---
print $outHandleA;                                       # [10]
print "-----";                                           # [11]
                                                         # [12]
open(OUT, ">outputB.txt") or die ("B: $!\n");            # [13] Opened OUT
print OUT "FILE B\n";                                    # [14]
close OUT;                                               # [15] Closed OUT
                                                         # [16]
print OUT;                                               # [17]
print OUT "DEF\n";                                       # [18] <---
print OUT;                                               # [19]
                                                         # [20]
print DOES_NOT_EXIST_HANDLE "GHI\n";                     # [21] Raises a FATAL warning
                                                         # [22]
print "JKL";                                             # [23] Does not reach here (as expected)

However, shouldn't lines [09] and [18] also raise an error or a warning like the following since it is closed (unopened)?

*

*ERROR:  print() on closed filehandle $outHandleA at printingToClosedHandle.pl line 9.

*WARNING: print() on unopened filehandle $outHandleA at printingToClosedHandle.pl line 9.
This might be an issue with my version of Perl which is "perl 5, version 28, subversion 1 (v5.28.1) built for MSWin32-x64-multi-thread". Furthermore, here is the output of the program I get below:

outputA.txt
outputB.txt
STDOUT

FILE A
FILE B
GLOB(0xfeb428)GLOB(0xfeb428)-----

The STDOUT output in above table is from lines [08], [10], and [11]. Please note that the value between the parenthesis (...) in the above table might change with each execution.

A: There is a difference between a filehandle that has been opened (initialized) and got closed, and one that has not been opened at all; attempting to print to them draws different warnings. One of 'unopened' entries in perldiag says

%s() on unopened %s
(W unopened) An I/O operation was attempted on a filehandle that was never initialized. You need to do an open(), a sysopen(), or a socket() call, or call a constructor from the FileHandle package.

while an entry for print() on closed filehandle says

print() on closed filehandle %s
(W closed) The filehandle you're printing on got itself closed sometime before now. Check your control flow.

They both get the warnings though.
When use warnings FATAL => 'unopened' alone is enabled then printing to a filehandle that had been initialized but then closed does not get a warning.
use warnings;
#use warnings FATAL => 'unopened';
use strict;
use feature 'say';

open my $stdout, '>&', *STDOUT;    # a copy

say $stdout "hi";
close $stdout;
say $stdout "to lexical, closed";  # it warns (l.10)

FATAL_warnings_unopened: {
    no warnings;                   # change to FATAL for 'unopened'
    use warnings FATAL => 'unopened';

    say $stdout "with FATAL to closed fh";      # no warning
    close STDOUT;
    say "with FATAL to STDOUT";                 # no warning

    say NON_EXISTENT_FH "no such filehandle!";  # l.20
};

say STDERR 'done';

This prints

hi
say() on closed filehandle $stdout at warnings_FATAL.pl line 10.
say() on unopened filehandle NON_EXISTENT_FH at warnings_FATAL.pl line 20.

It does exit, per FATAL and an unopened filehandle NON_EXISTENT_FH inside the block, but there is no warnings for the print to $stdout right above it.  There is a warning for the first such print. A print to STDOUT which just got closed doesn't get a warning either.
If we uncomment the use warnings FATAL... line in the very beginning (and remove other warnings lines) then no warnings are issued for printing to closed handles, at all.
A very close reading of the docs for the warnings pragma is helpful.  In short, I'd suggest to always first have use warnings; on its own, and then add a statement for categories wanted to be made FATAL (where multiple categories may be added in the same statement).

A: You've run afoul of a detail of use and the importing mechanism behind it.  Namely, if you use Foo 'bar';, then only Foo::bar will be imported, even if Foo normally exports other things.
In the same way, use warnings FATAL => 'unopened'; does not turn all warnings.  It turns on only 'unopened' warnings:
$ perl -E 'use warnings FATAL => "unopened" ; print $x;'
$ perl -E 'use warnings; use warnings FATAL => "unopened" ; print $x;'
Name "main::x" used only once: possible typo at -e line 1.
Use of uninitialized value $x in print at -e line 1.


text:
Q: How to set zoom level in google map Here is the code I have written to add a marker to the google map by providing latitude and longitude. The problem is that I get a very highly zoomed google map. I have tried setting the zoom level to 1 but this has no effect to the very highly zoomed map.

How can i decrease the level of zoom for this case?

A: Here is a function I use:
var map =  new google.maps.Map(document.getElementById('map'), {
            center: new google.maps.LatLng(52.2, 5),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            zoom: 7
        });

function zoomTo(level) {
        google.maps.event.addListener(map, 'zoom_changed', function () {
            zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function (event) {
                if (this.getZoom() > level && this.initialZoom == true) {
                    this.setZoom(level);
                    this.initialZoom = false;
                }
                google.maps.event.removeListener(zoomChangeBoundsListener);
            });
        });
    }

A: map.setZoom(zoom:number)
https://developers.google.com/maps/documentation/javascript/reference#Map

A: What you're looking for are the scales for each zoom level. The numbers are in metres. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

A: These methods worked for me, it maybe useful for anyone:
MapOptions interface
set min zoom: mMap.setMinZoomPreference(N);
set max zoom: mMap.setMaxZoomPreference(N);
where N can equal to:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000

A: For zooming in your map two levels, add this small line of code,
map.setZoom(map.getZoom() + 2);

A: Your code below is zooming the map to fit the specified bounds:
addMarker(27.703402,85.311668,'New Road');
center = bounds.getCenter();
map.fitBounds(bounds);

If you only have 1 marker and add it to the bounds, that results in the closest zoom possible:
function addMarker(lat, lng, info) {
  var pt = new google.maps.LatLng(lat, lng);
  bounds.extend(pt);
}

If you keep track of the number of markers you have "added" to the map (or extended the bounds with), you can only call fitBounds if that number is greater than one.  I usually push the markers into an array (for later use) and test the length of that array.
If you will only ever have one marker, don't use fitBounds.  Call setCenter, setZoom with the marker position and your desired zoom level.
function addMarker(lat, lng, info) {
  var pt = new google.maps.LatLng(lat, lng);
  map.setCenter(pt);
  map.setZoom(your desired zoom);
}

html,
body,
#map {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}


text:
Q: Can $\Pr(t<\infty)=1$ follow from $\Pr(t1-\delta$? If we know that $\forall \delta>0, \exists N \in \mathbb{N} $, s.t.
$
\Pr(t<N)>1-\delta
$, does it follow that $\Pr(t<\infty)=1$?

A: Yes, $P(t=\infty) \leq P(t \geq N)=1-P(t<N) <1-(1-\delta)=\delta$. Since $\delta$ is arbitrary we get $P(t=\infty)=0$.


text:
Q: How do you change the screen resolution in FreeBSD11 as a hyper-v guest? I'm running FreeBSD11 x64 as a Hyper-V guest and I'm having trouble finding information on how to increase the resolution to my monitor size (2560x1440 @ 144hz).
dmesg: http://pastebin.com/raw/UbbwHeBS
I've tried running
cvt 2560 1440 144

xrandr --newmode "2560x1440_144.00" 808.75 2560 2792 3072 3584 1440 1442 1448 1568 -hsync -vsync

xrandr --admode default 2560x1440_144.00

xrandr -s 2560x1440

but the output is "Failed to change the screen configuration!"
I've also tried setting up a custom resolution setting in xorg.conf.d to no avail.


text:
Q: Parent child relationship model in pyspark using Graphx/Spark I have a data-set which contains the (child, parent) entities. I need to find the ultimate parent of every child from the data-set. My data-set has 1.3 million records. Sample data is given below.
c-1, p-1
p-1, p-2
p-2, p-3
p-3, p-4

In the above sample data the ultimate parent of c-1 is p-4, ultimate parent of p-1 is p-4 and so on.
Some times to find the ultimate parent of a child i need to traverse multiple levels recursively.
This is what i have tried so far.

*

*I tried to create a spark DF and tried to recursively find the
        parent of every child. But this approach is taking very long time.

*I tried to create
        a UDF which can be applied on every row of the data-set. But i need
        to call the DF (lookup data-set) in the UDF. But spark does not
        support having DF in the UDF. So even this approach did not help me.

Any suggestions on to how to approach this problem?

A: To address both the problems cited by you, implementing CTE's in spark is using Graphx Pregel API could come to your rescue.
Here is a sample code below.
//setup & call the pregel api
def calcTopLevelHierarcy(vertexDF: DataFrame, edgeDF: DataFrame): RDD[(Any,(Int,Any,String,Int,Int))] = {

// create the vertex RDD
// primary key, root, path
val verticesRDD = vertexDF
  .rdd
  .map{x=> (x.get(0),x.get(1) , x.get(2))}
  .map{ x => (MurmurHash3.stringHash(x._1.toString).toLong, ( x._1.asInstanceOf[Any], x._2.asInstanceOf[Any] , x._3.asInstanceOf[String]) ) }

// create the edge RDD
// top down relationship
val EdgesRDD = edgeDF.rdd.map{x=> (x.get(0),x.get(1))}
  .map{ x => Edge(MurmurHash3.stringHash(x._1.toString).toLong,MurmurHash3.stringHash(x._2.toString).toLong,"topdown" )}

// create graph
val graph = Graph(verticesRDD, EdgesRDD).cache()

val pathSeperator = """/"""

// initialize id,level,root,path,iscyclic, isleaf
val initialMsg = (0L,0,0.asInstanceOf[Any],List("dummy"),0,1)

// add more dummy attributes to the vertices - id, level, root, path, isCyclic, existing value of current vertex to build path, isleaf, pk
val initialGraph = graph.mapVertices((id, v) => (id,0,v._2,List(v._3),0,v._3,1,v._1) )

val hrchyRDD = initialGraph.pregel(initialMsg,
  Int.MaxValue,
  EdgeDirection.Out)(
  setMsg,
  sendMsg,
  mergeMsg)

// build the path from the list
val hrchyOutRDD = hrchyRDD.vertices.map{case(id,v) => (v._8,(v._2,v._3,pathSeperator + v._4.reverse.mkString(pathSeperator),v._5, v._7 )) }

  hrchyOutRDD

}

In the method, calcTopLevelHierarcy(), you can pass-in DataFrame (which addresses your second point).
Here is a very good link with some sample code. Please take a look.
Hope, this helps.


text:
Q: Service Fabric Local Cluster "unable to route request to..." - After upgrading Windows 10 May 2019 Upgraded Windows 10 today. PC restarted and had to start my local cluster again. Now I receive a 502 code and "Unable to route request to... ". There are no exceptions thrown in the cluster gateway and the service appears to be receiving requests despite not making it into the controller.
Has anyone else experienced Service Fabric issues after this May 2019 Windows update?


text:
Q: memcopy and 2d arrays struct item_CHECK_LIST_data
{

    char    list[MAX_CHECK_LIST_OPTIONS + 1][MAX_ITEM_TEXT_LEN];
    char    checkeditems[MAX_CHECK_LIST_OPTIONS + 1];//which are checked

    char    number_of_options;
};

can i copy this with memcopy?
I have a weird bug that would be explained by memcopy not being able to...

A: Yes, you can memcpy two-dimensional arrays in C, provided that they're actually 2D arrays and not a 1D array of pointers.  Two-dimensional arrays are laid out contiguously in memory, so memcpy will correctly read all the blocks.  However, if your array is a 1D-array of pointers to more 1D arrays, then the memcpy will only copy the pointers and you'll end up with a shallow copy rather than a deep copy.

A: Did you use sizeof() to find how much to copy? The elements of the struct may be padded so the size is bigger than the sum of the parts

A: If it is just the struct as a whole that you want to copy, don't use memcpy. Just do an assignment, the = token is made for this.


text:
Q: bifunctor in haskell after the least fixed type I am not sure how to derive the functor instance after making a fixed point :
data FreeF f a next  = PureF a | FreeF (f next)  deriving (Functor)

data Mu f  = In { out :: f ( Mu f ) }

newtype Free f a = Free(  Mu (FreeF f a)  )

instance Functor f => Functor (Free f) where
     fmap h (Free (out -> PureF a))  = Free (In (PureF (h a)))
     fmap h (Free (out -> FreeF fn)) = Free (In (fmap undefined undefined)) --stuck

If I modify Mu to accept an extra type parameter, I can progress until... :
data Mu f a  = In { out :: f ( Mu f a )  } deriving (Functor)

newtype Free f a = Free(  Mu (FreeF f a) a )

instance Functor f => Functor (Free f ) where
     fmap h (Free (out -> PureF a))  = Free . In . PureF $ h a
     fmap h (Free (out -> FreeF fn)) = Free . In . FreeF $ fmap undefined fn

Here I need to have undefined :: Mu (FreeF f a) a -> Mu (FreeF f b) b but mu f is a functor for the same f and here it varies in type.
What is the correct way to tackle this ?

A:
mu f is a functor for the same f and here it varies in type.

Fortunately we're defining Functor (Free f), and we actually use this Functor instance to map over the a's in the PureF constructors. Functor (Free f) abstracts over all "internal" occurrences of a.
So, whenever we want to map over both occurrences of a, for example when we want to implement FreeF f a (Mu (FreeF f a)) -> FreeF f b (Mu (FreeF f b)), we can do that by wrapping everything up all the way back to Free, mapping, then unwrapping again.
The following checks out with your original data definitions:
newtype Free f a = Free {unFree :: Mu (FreeF f a)} -- add "unFree"

instance Functor f => Functor (Free f) where
     fmap h (Free (In (PureF a)))  = Free (In (PureF (h a)))
     fmap h (Free (In (FreeF fn))) =
       Free (In (FreeF (fmap (unFree . fmap h . Free) fn)))

Some testing:
{-# LANGUAGE UndecidableInstances, StandaloneDeriving #-}

deriving instance Show (f (Mu f)) => Show (Mu f)
deriving instance Show (Mu (FreeF f a)) => Show (Free f a)

foo :: Free [] Int
foo = Free $ In $ FreeF [ In $ PureF 100, In $ PureF 200 ]

> fmap (+100) foo
Free {unFree = In {out = FreeF [In {out = PureF 200},In {out = PureF 300}]}}

A: I haven't done this construction before, but I think I'm seeing something. Your intuition about adding an argument to Mu is good, but you need to pass it along so that Free f fits, i.e. so that f takes two arguments instead of one:
newtype Mu f a = In { out :: f (Mu f a) a }

Mu f ought to be a Functor under suitable conditions, which would give you the instance you're looking for.  What are those conditions?  We need:
fmap' :: (a -> b) -> f (Mu f a) a -> f (Mu f b) b

We expect f to be functorial in its second argument, so that's no problem.  So what we really need a way to get
f (Mu f a) b -> f (Mu f b) b
           ^               ^
           +--not varying--+

We can use the instance recursively to get Mu f a -> Mu f b, so it looks like we just need f to be a functor in its first argument too.  Hence:
class Bifunctor f where
    bimap :: (a -> c) -> (b -> d) -> f a b -> f c d

Then you should be able to write the suitable instances
instance (Functor f) => Bifunctor (FreeF f) ...
instance (Bifunctor f) => Functor (Mu f) ...


text:
Q: How to display String created in textArea to maintain formatting in Grails? I'm wondering what's the proper way to display a String, created by user using textArea input field?
When using fieldValue everything is in single line :/
Thanks,
Krystian

A: you must place the variable you get from the database into a "pre" tag

${variable}

A: You'll have to convert characters to HTML.  For example, new line characters (\n) would need to be converted to
, etc.
You could also provide a RTE instead of the TextArea which generally give you HTML instead of plain text via JavaScript.  Google Search Results.

A: I tried with grails textArea property
<g:textArea escapeHtml="true" />

But it didn't work, so I found there's a property in textArea fields (html and gsp) that you should use when creating.
It's:
<g:textArea wrap="hard" rows="5" cols="20" />

That did the trick for me, and now everytime I call that field, from everywhere (textArea, textField, td, etc) it creates all the corresponding lines.
http://www.w3.org/wiki/HTML/Elements/textarea


text:
Q: undefined method `scope' for PaperTrail::VersionConcern:Module (NoMethodError) I have the following gems in my gem file
   gem 'paper_trail'
   gem 'paper_trail-association_tracking'

When I am running my rails server I am getting the error " undefined method `scope' for PaperTrail::VersionConcern:Module (NoMethodError)"
Below is the full the full trace
41: from bin/rails:4:in `<main>'
40: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
39: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
38: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
37: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
36: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
35: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/railties-6.0.3.6/lib/rails/commands.rb:18:in `<main>'
34: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/railties-6.0.3.6/lib/rails/command.rb:46:in `invoke'
33: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/railties-6.0.3.6/lib/rails/command/base.rb:69:in `perform'
32: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/thor-1.1.0/lib/thor.rb:392:in `dispatch'
31: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/thor-1.1.0/lib/thor/invocation.rb:127:in `invoke_command'
30: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/thor-1.1.0/lib/thor/command.rb:27:in `run'
29: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/railties-6.0.3.6/lib/rails/commands/server/server_command.rb:138:in `perform'
28: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/railties-6.0.3.6/lib/rails/commands/server/server_command.rb:138:in `tap'
27: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/railties-6.0.3.6/lib/rails/commands/server/server_command.rb:141:in `block in perform'
26: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/activesupport-6.0.3.6/lib/active_support/dependencies.rb:324:in `require'
25: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/activesupport-6.0.3.6/lib/active_support/dependencies.rb:291:in `load_dependency'
24: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/activesupport-6.0.3.6/lib/active_support/dependencies.rb:324:in `block in require'
23: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
22: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
21: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
20: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
19: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
18: from /Users/devi/Desktop/all_projects/zensuper/zen_super_admin/config/application.rb:8:in `<main>'
17: from /Users/devi/.rvm/rubies/ruby-2.7.2/lib/ruby/2.7.0/bundler.rb:174:in `require'
16: from /Users/devi/.rvm/rubies/ruby-2.7.2/lib/ruby/2.7.0/bundler/runtime.rb:58:in `require'
15: from /Users/devi/.rvm/rubies/ruby-2.7.2/lib/ruby/2.7.0/bundler/runtime.rb:58:in `each'
14: from /Users/devi/.rvm/rubies/ruby-2.7.2/lib/ruby/2.7.0/bundler/runtime.rb:69:in `block in require'
13: from /Users/devi/.rvm/rubies/ruby-2.7.2/lib/ruby/2.7.0/bundler/runtime.rb:69:in `each'
12: from /Users/devi/.rvm/rubies/ruby-2.7.2/lib/ruby/2.7.0/bundler/runtime.rb:74:in `block (2 levels) in require'
11: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
10: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
 9: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
 8: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
 7: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
 6: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/paper_trail-association_tracking-2.1.1/lib/paper_trail-association_tracking.rb:22:in `<main>'
 5: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/paper_trail-association_tracking-2.1.1/lib/paper_trail-association_tracking.rb:51:in `<module:PaperTrail>'
 4: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/paper_trail-association_tracking-2.1.1/lib/paper_trail-association_tracking.rb:52:in `<module:VersionConcern>'
 3: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/paper_trail-association_tracking-2.1.1/lib/paper_trail-association_tracking.rb:52:in `include'
 2: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/activesupport-6.0.3.6/lib/active_support/concern.rb:122:in `append_features'
 1: from /Users/devi/.rvm/gems/ruby-2.7.2/gems/activesupport-6.0.3.6/lib/active_support/concern.rb:122:in `class_eval'
 /Users/devi/.rvm/gems/ruby-2.7.2/gems/paper_trail-association_tracking-2.1.1/lib/paper_trail_association_tracking/version_concern.rb:19:in `block in <module:VersionConcern>': undefined method `scope' for PaperTrail::VersionConcern:Module (NoMethodError)

Following are the version details
 ruby version: 2.7.2
 rails version 6.0.3.6

A: Ran into this problem with paper_trails upgrading to version 12. Temporary fix is to downgrade to 11 whilst they fix the issue on the latest version

A: My suggestion is to remove paper_trail-association_tracking from your gem file and remove any initializer and other related code. For more info refer this link https://github.com/paper-trail-gem/paper_trail/pull/1281


text:
Q: WPF - GridSplitter with three columns I have an app with grid with 3 columns.  The grid splitter between the first and second columns works just fine.  To get the splitter over to be between the second and third columns I made a column for the splitter.  (So now the the third column is really the fourth.)
When I resize the other columns also shrink.  I assume that is because I have them set to be relative sized.  But I don't know how to fix it.
Here is a XAML Pad Ready example of my issue.  Plug this into XAML pad and then try to resize the last column to be smaller.
<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="1*" />
        </Grid.ColumnDefinitions>
        <StackPanel Background="#feca00" Grid.Column="0">
            <TextBlock FontSize="35" Foreground="#58290A"
                   TextWrapping="Wrap">Left Hand Side</TextBlock>
        </StackPanel>
        <GridSplitter Width="10" />
        <Border CornerRadius="10" BorderBrush="#58290A"
              BorderThickness="5" Grid.Column="1">
            <TextBlock FontSize="25" Margin="20" Foreground="#FECA00"
                   TextWrapping="Wrap">Right Hand Side</TextBlock>
        </Border>
        <GridSplitter Grid.Column="2" HorizontalAlignment="Right"  VerticalAlignment="Stretch" Width="5"></GridSplitter>
        <TabControl Grid.Column="3" Name="tabControl1">
            <TabItem Header="Add Links" Name="tabAddLinks">
                <Grid></Grid>
            </TabItem>
        </TabControl>
    </Grid>
</Page>

Thanks for the help!

EDIT:
It was suggested that having both splitters in their own columns might fix it.  I tried that and now the first splitter also shrinks the columns like the second splitter does.
Here is the XAML Pad code for that example:
<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="1*" />
        </Grid.ColumnDefinitions>
        <StackPanel Background="#feca00" Grid.Column="0">
            <TextBlock FontSize="35" Foreground="#58290A"
                   TextWrapping="Wrap">Left Hand Side</TextBlock>
        </StackPanel>
        <GridSplitter Grid.Column="1" HorizontalAlignment="Right"  VerticalAlignment="Stretch" Width="5"></GridSplitter>
        <Border CornerRadius="10" BorderBrush="#58290A"
              BorderThickness="5" Grid.Column="2">
            <TextBlock FontSize="25" Margin="20" Foreground="#FECA00"
                   TextWrapping="Wrap">Right Hand Side</TextBlock>
        </Border>
        <GridSplitter Grid.Column="3" HorizontalAlignment="Right"  VerticalAlignment="Stretch" Width="5"></GridSplitter>
        <TabControl Grid.Column="4" Name="tabControl1">
            <TabItem Header="Add Links" Name="tabAddLinks">
                <Grid></Grid>
            </TabItem>
        </TabControl>
    </Grid>
</Page>

A: A GridSplitter should be placed within its own Column in a Grid. I'm not sure I understand your issue entirely, but I suggest you try creating a Grid with 5 ColumnDefinitions. Use columns 1 and 2 to place the GridSplitters and columns 0, 2 and 4 for content.
The GridSplitter MSDN doc has a sample on how to do this.
<Grid.ColumnDefinitions>
  <ColumnDefinition/>
  <ColumnDefinition Width="Auto" />
  <ColumnDefinition/>
</Grid.ColumnDefinitions>
...
<GridSplitter Grid.Column="1"
          HorizontalAlignment="Center"
          VerticalAlignment="Stretch"
          Background="Black"
          ShowsPreview="True"
          Width="5"
          />

A: Try setting HorizontalAlignment="Center" for both splitters - no idea why having it set to "Right" should cause the behaviour to go so screwy, but changing it worked for me :)


text:
Q: Push Notifications in iOS 8 ( Parse ) After installing iOS 8 on my iDevice it does not receive push notifications from Parse anymore. I tried to send notifications from Parse, it says that sent successful, but nothing happens on device. Console says that device registered successfully to receive notifications.
I am using the following code to setup notifications.
//-- Set Notification
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
}

A: I tried out the code you did but switched [UIApplication sharedApplication] with just application and it worked fine on my iOS8 device.
//-- Set Notification
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{ [application registerUserNotificationSettings:
   [UIUserNotificationSettings settingsForTypes:
                  (UIUserNotificationTypeSound |
                   UIUserNotificationTypeAlert |
                    UIUserNotificationTypeBadge) categories:nil]];

    [application registerForRemoteNotifications];
}
else
{
    [application registerForRemoteNotificationTypes:
     (UIUserNotificationTypeBadge |
      UIUserNotificationTypeSound |
      UIUserNotificationTypeAlert)];
}


text:
Q: Why does Java's Area#equals method not override Object#equals? I just ran into a problem caused by Java's java.awt.geom.Area#equals(Area) method. The problem can be simplified to the following unit test:
@org.junit.Test
public void testEquals() {
    java.awt.geom.Area a = new java.awt.geom.Area();
    java.awt.geom.Area b = new java.awt.geom.Area();
    assertTrue(a.equals(b)); // -> true

    java.lang.Object o = b;
    assertTrue(a.equals(o)); // -> false
}

After some head scratching and debugging, I finally saw in the JDK source, that the signature of the equals method in Area looks like this:
public boolean equals(Area other)

Note that it does not @Override the normal equals method from Object, but instead just overloads the method with a more concrete type. Thus, the two calls in the example above end up calling different implementations of equals.
As this behavior has been present since Java 1.2, I assume it is not considered a bug. I am, therefore, more interested in finding out why the decision was made to not properly override the equals method, but at the same time provide an overloaded variant. (Another hint that this was an actual decision made is the absence of an overwritten hashCode() method.)
My only guess would be that the authors feared that the slow equals implementation for areas is unsuitable for comparing equality when placing Areas in Set,Map,etc. datastructures. (In the above example, you could add a to a HashSet, and although b is equal to a, calling contains(b) will fail.) Then again, why did they not just name the questionable method in a way that does not clash with such a fundamental concept as the equals method ?

A: RealSkeptic linked to JDK-4391558 in a comment above. The comment in that bug explains the reasoning:

The problem with overriding equals(Object) is that you must also
  override hashCode() to return a value which guarantees that equals()
  is true only if the hashcodes of the two objects are also equal.

but:

The problem here is that Area.equals(Area) does not perform a very
  straight-forward comparison. It painstakingly examines each and every
  piece of geometry in the two Areas and tests to see if they cover the
  same enclosed spaces. Two Area objects could have a completely
  different description of the same enclosed space and equals(Area)
  would detect that they were the same.

So basically we're left with an array of not-so-pleasant options, such as:

deprecate equals(Area) and create an alternate name for that
  operation, such as "areasEqual" so as to avoid the confusion.
  Unfortunately, the old method would remain and would be linkable and
  would trap many people who were intending to invoke the equals(Object)
  version.

or:

deprecate equals(Area) and change its implementation to be exactly
  that of equals(Object) so as to avoid semantic problems if the wrong
  method is called. Create a new method with a different name to avoid
  confusion to implement the old functionality provided by equals(Area).

or:

implement equals(Object) to call equals(Area) and implement a dummy
  hashCode() which honors the equals/hashCode contract in a degenerate
  way by returning a constant. This would make the hashCode method
  essentially useless and make Area objects nearly useless as keys in a
  HashMap or Hashtable.

or other ways to modify the equals(Area) behavior that would either change its semantics or make it inconsistent with hashCode.
Looks like changing this method is deemed by the maintainers to be neither feasible (because neither option outlined in the bug comment quite solves the problem) nor important (since the method, as implemented, is quite slow and would probably only ever return true when comparing an instance of an Area with itself, as the commenter suggests).

A: "Why does Java's Area#equals method not override Object#equals?"
Because overriding is not necessary for overloaded methods where the parameters are of differing types.

An overridden method would have the exact same method name, return type, number of parameters, and types of parameters as the method in the parent class, and the only difference would be the definition of the method.

This case does not compel us to override but it is overloading as it follows these rules:

1.) The number of parameters is different for the methods.
2.) The parameter types are different (like  changing a parameter that was a float to an int).

"why did they not just name the questionable method in a way that does not clash with such a fundamental concept as the equals method?"
Because this could trip people up going into the future.  If we had a time machine to the 90's we could do it without this concern.


text:
Q: check the if DOM has class name attached to it I want to check if a Dom has class value attached to it.. Since that DOM will be assigned a random class value dynamically, I will not know the class name specifically, so is it possible to check if it has a class element attached to irrespective of its class name.

A: That?
if($('div').prop('class').length) { }

Related docs:
http://api.jquery.com/prop/
This basically pulls out the class property from div (change that to your actualy DOM element you'd like to check for class existence) and check whether it has length > 0

A: if($('div').attr('class')!= "") { //class is there and its not empty }

A: Class in markup is an attribute so can use:
   var className=  $(selector).attr('class');
  if( className ){
      /* do Something*/
  }

attr() API Docs


text:
Q: Is there a way to get inactive products with amazon MWS API? I have quite a lot of products in the 'Inactive' section with the alert 'Potential high pricing'.
Is there a way to get these products via amazon MWS? I tried a couple of reports such as
GET_MERCHANT_LISTINGS_INACTIVE_DATA
GET_MERCHANT_CANCELLED_LISTINGS_DATA
GET_MERCHANT_LISTINGS_DEFECT_DATA
but these don't actually give me all the products and give alot of other information. Also, by navigating to Price Health I can see every products that i'm interested in, Is there a to export these or get them via MWS API?

A: Yes, I believe you can get all products including inactive products. Try these four. I'm almost positive I came across this a while ago but I'm not sure which it was:

*

*GET_FBA_MYI_UNSUPPRESSED_INVENTORY_DATA

*GET_MERCHANT_LISTINGS_DATA_LITE

*GET_FBA_FULFILLMENT_MONTHLY_INVENTORY_DATA

*GET_MERCHANT_LISTINGS_ALL_DATA


text:
Q: Instantiate model instance with manytomany field in Django I have a method that works, but it seems very clumsy, and I would think there is a better way to do this.
I have a Model that relates a user on my site (a twitter clone for learning purposes) to a list of other users.
Right now when I create a new user, I want to initialize that list with the user as a member of the list.
My model is:
class FollowerList(models.Model)
    follower = models.ForeignKey(User,related_name="follower")
    followed = models.ManyToManyField(User,related_name="followed")

The code in my view that I'm using right now is
user = User.objects.get(username=uname)
flst = FollowerList()
flst.follower = user
flst.save()
flst.followed.add(user)
flst.save()

It seems to me like there should be a method for creating this without calling save() twice, but I can't seem to find it in the docs or anywhere else.

A: Yuji's answer is correct. You can not add an object to a M2M field until it has been saved. I wanted to mention a shorter way to create instances though.
user = User.objects.get(username=uname)
flst = FollowerList(follower=user) #use key word args to assign fields
flst.save()
flst.followed.add(user)
# don't need to save after adding an object to many to many field.

I find that syntax slightly nicer than creating an empty instance and assigning fields. Though the objects.create() method (mentioned by Yuki) is nicer still.

A: A late answer to this: you could also override the constructor (__init__) as follows:
class FollowerList(models.Model):
    follower = models.ForeignKey(User,related_name="follower")
    followed = models.ManyToManyField(User,related_name="followed"

    def __init__(*args, followed=[], **kwargs):
        super(FollowerList, self).__init__(*args, **kwargs)
        self.save()
        for user in followed:
            self.followed.add(user)

ie here I've explicitly handled the followed keyword argument in the __init__ function, while passing all other args and kwargs on to the default constructor.
The call to save makes sure that the object has been registered and can thus be used in an m2m relationship.
This then allows you to do create FollowerList with one line, eg
flst = FollowerList(follower=user, followed=[user,])

Alternatively, as pointed out by Johannes, saving a model in the __init__ is not expected. The preferred approach would be to create a Manager method - see here for details: https://docs.djangoproject.com/en/1.9/topics/db/managers/
and then to create a FollowerList:
fl = FollowerList.objects.create(*args, followed, **kwargs)

A: You don't need to call save after the many2many.add()
You could also shorten the code to 2 lines:
flst = FollowerList.objects.create(follower=user)
flst.followed.add(user)


text:
Q: Getting null values in Request Body I have my Controller class as
package com.example.test.Controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.test.Model.Example;

@RestController
public class Controller {

    @PostMapping("/produce")
    public void process1(@RequestBody Example example)
    {
        System.out.println(example);
    }
}

My Json request is as follow:
{
    "master_subscriber_id": 123456,
    "request_ts": "timestamp",
    "request_uuid": "123dfrg",
    "treatments": [{
            "treatement_cd": "dsad",
            "offer_id": "dsads",
            "offer_type": "ds"
        },
        {
            "treatement_cd": "dsad",
            "offer_id": "dsad",
            "offer_type": "dsa"
        },
        {
            "treatement_cd": "tro_12345",
            "offer_id": "xyz_34567",
            "offer_type": "XYZ"
        }
    ]
}

My Model Classes are as follow:
package com.example.test.Model;

import java.util.ArrayList;
import java.util.List;

public class Example {

    private Integer masterSubscriberId;

    private String requestTs;

    private String requestUuid;

    private List<Treatment> treatments= new ArrayList<Treatment>() ;

    public Integer getMasterSubscriberId() {
        return masterSubscriberId;
    }

    public void setMasterSubscriberId(Integer masterSubscriberId) {
        this.masterSubscriberId = masterSubscriberId;
    }

    public String getRequestTs() {
        return requestTs;
    }

    public void setRequestTs(String requestTs) {
        this.requestTs = requestTs;
    }

    public String getRequestUuid() {
        return requestUuid;
    }

    public Example() {
        super();
    }

    public void setRequestUuid(String requestUuid) {
        this.requestUuid = requestUuid;
    }

    public List<Treatment> getTreatments() {
        return treatments;
    }

    public void setTreatments(List<Treatment> treatments) {
        this.treatments = treatments;
    }

    public Example(Integer masterSubscriberId, String requestTs, String requestUuid, List<Treatment> treatments) {
        super();
        this.masterSubscriberId = masterSubscriberId;
        this.requestTs = requestTs;
        this.requestUuid = requestUuid;
        this.treatments = treatments;
    }

    @Override
    public String toString() {
        return "Example [masterSubscriberId=" + masterSubscriberId + ", requestTs=" + requestTs + ", requestUuid="
                + requestUuid + ", treatments=" + treatments + "]";
    }

}

package com.example.test.Model;

public class Treatment {

    private String treatementCd;

    private String offerId;

    private String offerType;

    public String getTreatementCd() {
        return treatementCd;
    }

    public void setTreatementCd(String treatementCd) {
        this.treatementCd = treatementCd;
    }

    public String getOfferId() {
        return offerId;
    }

    public void setOfferId(String offerId) {
        this.offerId = offerId;
    }

    public String getOfferType() {
        return offerType;
    }

    public void setOfferType(String offerType) {
        this.offerType = offerType;
    }

    public Treatment() {
        super();
    }

    public Treatment(String treatementCd, String offerId, String offerType) {
        super();
        this.treatementCd = treatementCd;
        this.offerId = offerId;
        this.offerType = offerType;
    }

    @Override
    public String toString() {
        return "Treatment [treatementCd=" + treatementCd + ", offerId=" + offerId + ", offerType=" + offerType + "]";
    }

}

My output is coming like this
Example [masterSubscriberId=null, requestTs=null, requestUuid=null, treatments=[Treatment [treatementCd=null, offerId=null, offerType=null], Treatment [treatementCd=null, offerId=null, offerType=null], Treatment [treatementCd=null, offerId=null, offerType=null]]].

A: If you do not use additional annotations, the key-names in Json must match attribute names in Java classes. So in your case "master_subscriber_id" in JSON must be replaced with "masterSubscriberId" as it is in your Example class.
Or you can use this annotation @JsonProperty("master_subscriber_id") in your Example class for the mapping.
In my German blog I have written some articles about this topic:
https://agile-coding.blogspot.com/2020/10/rest-json-apis-in-java-leicht-gemacht.html


text:
Q: Abstracting .NET Core 3 Application Startup Issue I want to create a common start up process for all of my ASP.NET Core 3 projects, and so want to abstract out a working start up routine out to a class library for re-use.
I've therefore created a .NET Core 3.1 Class Library, and added all the references that are needed for it to compile and potentially run:
using Amazon.CertificateManager;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NetCore3ApplicationBase;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using UtilityCore;

(UtilityCore being an in-house library)
I added a 'startup class':
namespace NetCoreApplicationBase
{
    public static class ProgramBase
    {
         public static void ApplicationStartup(string[] args)
         {
             CreateHostBuilder(args).Build().Run();
         }
    }
}

...and modified a sample .NET Core application to call the ApplicationStartup method in Program.cs:Main.
However, when the CreateHostBuilder line is called, I get the exception:
The ConfigureServices method must either be parameterless or take only one parameter of type IServiceCollection

But this error ONLY occurs if the CreatHostBuilder code is abstracted out to another library.  If this code is embedded in the application, it works perfectly.
From some digging around this error is most commonly associated with EFCore and that suggests that on start up the application (via aspnetcore.Hosting) is searching for an appropriate DataContext to use.
But providing that in the HostBuilder using the:
services.AddDbContext<ApplicationDbContext>();

...makes no difference.
* UPDATE 1 *
The CreatHostBuilderMethod looks like this:
    public static IHostBuilder CreateHostBuilder(string[] args) =>

        Host.CreateDefaultBuilder(args)
        .UseWindowsService().ConfigureServices((hostContext, services) =>
        {
            services.AddHostedService<MyServiceName>();
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseContentRoot(AppDomain.CurrentDomain.BaseDirectory);
            webBuilder.UseStartup<Startup>();
        });

* UPDATE 2 *
Modifying the CreateHostBuilder method to only accept the services, results in the same error message.
    public static IHostBuilder CreateHostBuilder(string[] args) =>

        Host.CreateDefaultBuilder(args)

        .UseWindowsService().ConfigureServices((services) =>

        {

            services.AddHostedService<MyServiceName>();

        })

        .ConfigureWebHostDefaults(webBuilder =>

        {

            webBuilder.UseContentRoot(AppDomain.CurrentDomain.BaseDirectory);

            webBuilder.UseStartup<Startup>();

        });

Can anyone shed any light on why there is this discrepancy in start up behaviour please?

A: Thanks to the pointers in the comments, I worked out what was wrong.
  webBuilder.UseStartup<Startup>();

was pointing to a class, where I'd modified the ConfigureServices parameters and added some extra ones, meaning it no longer matched the delegate the application start up was expecting.
D'oh!


text:
Q: Get indices of matches from one array in another Given two np.arrays;
a = np.array([1, 6, 5, 3, 8, 345, 34, 6, 2, 867])
b = np.array([867, 8, 34, 75])

I would like to get an np.array with same dimensions as b, where each value is the index where the value in b appears in a, or np.nan if the value in b is not present in a.
The result should be;
[9, 4, 6, nan]

a and b will always have the same number of dimensions, but the sizes of the dimensions may differ.
something like;
(pseudo code)
c = np.where(b in a)

but which works for arrays ("in" does not)
I prefer a "one-liner" or at least a solution that is entirely on array level, and which does not require a loop.
Thx!

A: Approach #1
Here's one with np.searchsorted -
def find_indices(a,b,invalid_specifier=-1):
    # Search for matching indices for each b in sorted version of a.
    # We use sorter arg to account for the case when a might not be sorted
    # using argsort on a
    sidx = a.argsort()
    idx = np.searchsorted(a,b,sorter=sidx)

    # Remove out of bounds indices as they wont be matches
    idx[idx==len(a)] = 0

    # Get traced back indices corresponding to original version of a
    idx0 = sidx[idx]

    # Mask out invalid ones with invalid_specifier and return
    return np.where(a[idx0]==b, idx0, invalid_specifier)

Output for given sample -
In [41]: find_indices(a, b, invalid_specifier=np.nan)
Out[41]: array([ 9.,  4.,  6., nan])

Approach #2
Another based on lookup for positive numbers -
def find_indices_lookup(a,b,invalid_specifier=-1):
    # Setup array where we will assign ranged numbers
    N = max(a.max(), b.max())+1
    lookup = np.full(N, invalid_specifier)

    # We index into lookup with b to trace back the positions. Non matching ones
    # would have invalid_specifier values as wount had been indexed by ranged ones
    lookup[a] = np.arange(len(a))
    indices  = lookup[b]
    return indices

Benchmarking
Efficiency wasn't mentioned as a requirement in the question, but no-loop requirement might go there. Testing out with a setup that tries to reperesent the given sample setup, but scaling it up by 1000x :
In [98]: a = np.random.permutation(np.unique(np.random.randint(0,20000,10000)))

In [99]: b = np.random.permutation(np.unique(np.random.randint(0,20000,4000)))

# Solutions from this post
In [100]: %timeit find_indices(a,b,invalid_specifier=np.nan)
     ...: %timeit find_indices_lookup(a,b,invalid_specifier=np.nan)
1.35 ms ± 127 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
220 µs ± 30.9 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

# @Quang Hoang-soln2
In [101]: %%timeit
     ...: commons, idx_a, idx_b = np.intersect1d(a,b, return_indices=True)
     ...: orders = np.argsort(idx_b)
     ...: output = np.full(b.shape, np.nan)
     ...: output[orders] = idx_a[orders]
1.63 ms ± 59.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# @Quang Hoang-soln1
In [102]: %%timeit
     ...: s = b == a[:,None]
     ...: np.where(s.any(0), np.argmax(s,0), np.nan)
137 ms ± 9.25 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

A: You can do a broadcast:
s = b == a[:,None]
np.where(s.any(0), np.argmax(s,0), np.nan)

Output:
array([ 9.,  4.,  6., nan])

Update Another solution with intersect1d:
commons, idx_a, idx_b = np.intersect1d(a,b, return_indices=True)

orders = np.argsort(idx_b)

output = np.full(b.shape, np.nan)
output[orders] = idx_a[orders]


text:
Q: Why the jags result and depmixS4 are sometimes different? I have a data set like the following simulated data:
Pi = matrix(c(0.9,0.1,0.3,0.7),2,2,byrow=TRUE)
delta = c(.5,.5)

z = sample(c(1,2),1,prob=delta)
T = 365
for( t in 2:T){
  z[t] = sample(x=c(1,2),1,prob=Pi[z[t-1],])
}

x <- sample(x=seq(-1, 1.5, length.out=T),T,replace=TRUE)

alpha = c(-1, -3.2)
Beta = c(-4,3)

y<-NA
for(i in 1:T){
  y[i] = rbinom(1,size=10,prob=1/(1+exp(-Beta[z[i]]*x[i]-alpha[z[i]])))
}

SimulatedBinomData <- data.frame('y' = y, 'x' = x , size=rep(10,T), 'z' = z)

yy<-NA
xx<-NA
for(i in 1:dim(SimulatedBinomData)[1]){
  yy<-c(yy,c(rep(1,SimulatedBinomData$y[i]),rep(0,(SimulatedBinomData$size[i]-SimulatedBinomData$y[i]))))
  xx<-c(xx,rep(SimulatedBinomData$x[i],SimulatedBinomData$size[i]))
}
yy<-yy[-1]
xx<-xx[-1]

SimulatedBernolliData<-data.frame(y=yy,x=xx, tt=rep(c(1:T),rep(10,T)))

This is a HMM problem with two states meaning that the Hidden Markov chain z_t belongs to {1,2}. To estimate alpha and Beta in two different states I can use the package 'depmixS4' and find the Maximum Likelihood estimates or I can use MCMC in 'rjags' package.
I expect that these two estimations be almost the same while when I run the following program for different simulated data, in several times, the answers are not the same and very different!!
library("rjags")
library("depmixS4")

mod <- depmix(cbind(y,(size-y))~x, data=SimulatedBinomData, nstates=2, family=binomial(logit))
fm <- fit(mod)
getpars(fm)

n<-length(SimulatedBernolliData$y)
T<-max(SimulatedBernolliData$tt)

cat("model {

    # Transition Probability
    Ptrans[1,1:2] ~ ddirch(a)
    Ptrans[2,1:2] ~ ddirch(a)

    # States
    Pinit[1] <- 0.5 #failor
    Pinit[2] <- 0.5 #success
    state[1] ~ dbern(Pinit[2])

    for (t in 2:T) {
    state[t] ~ dbern(Ptrans[(state[t-1]+1),2])
    }

    # Parameters
    alpha[1] ~ dunif(-1.e10, 1.e10)
    alpha[2] ~ dunif(-1.e10, 1.e10)

    Beta[1] ~ dunif(-1.e10, 1.e10)
    Beta[2] ~ dunif(-1.e10, 1.e10)

    # Observations
    for (i in 1:n){
    z[i] <- state[tt[i]]
    y[i] ~ dbern(1/(1+exp(-(alpha[(z[i]+1)]+Beta[(z[i]+1)]*x[i]))))
    }
    }",
file="LeftBehindHiddenMarkov.bug")

jags <- jags.model('LeftBehindHiddenMarkov.bug', data = list('x' =  SimulatedBernolliData$x, 'y' = SimulatedBernolliData$y, 'tt' = SimulatedBernolliData$tt, T=T, n = n, a = c(1,1) ))
res <- coda.samples(jags,c('alpha', 'Beta', 'Ptrans','state'),1000)
res.median = apply(res[[1]],2,median)
res.median[1:8]
res.mean = apply(res[[1]],2,mean)
res.mean[1:8]
res.sd = apply(res[[1]],2,sd)
res.sd[1:8]
res.mode = apply(res[[1]],2,function(x){as.numeric(names(table(x))
[which.max(table(x))]) })
res.mode[1:8]

A: You are having a problem of label switching in your JAGS code, that is, states z[i]=1 is not bounded to the lower posterior value for Beta and z[i]=2 to the higher Beta. Therefore, for each iteration of the MCMC they can switch.  There are several ways to solve this problem.  One of them is the partial reordering, that is, for every MCMC iteration, draw two independent values for Beta and order them so that Beta[1] < Beta[2].
You can do that by substituting
Beta[1] ~ dunif(-1.e10, 1.e10)
Beta[2] ~ dunif(-1.e10, 1.e10)

for
Beta[1:2] <- sort(Betaaux)
Betaaux[1] ~ dunif(-1.e10, 1.e10)
Betaaux[2] ~ dunif(-1.e10, 1.e10)

Of course, the ordering could also be done on the alpha parameters instead.  The election of which parameter to use for the partial reordering depends on the problem.


text:
Q: Can the Angular Injector inject a method? In AngularJS, I know that I can inject services via the dependency injector for a provider that I define (service, controller, etc). I know that I can do something like this:
app.factory('myFactory', ['$window', function ($window) {
    // Now I can check properties on Window.

    if (!$window.sessionStorage) throw new Error("message");
}]);

But is it possible to do something like this, with the injector?
app.factory('myFactory', ['$window.sessionStorage', function ($storage) {
    // Now I can check properties on Window.

    if (!$storage) throw new Error("message");
}]);

I'm writing a service and I'd like my dependencies to be swappable on a logical basis, if at all possible, but I don't necessarily want to rely on writing a wrapper for a POJO object.
Thanks!

A: You can't do what you are trying to do. You would need to create a wrapper service. This would be very simple to do. For session storage there is ngStorage that you could use: https://github.com/gsklee/ngStorage. By using this you won't have to serialize/deserialize.

A: Actually - there is a way to do this, by using .constant or .value. (From what I understand, .constant can be used in a config block, while value cannot be.) You'd do something like the following:
angular.module('myApp', [])
    .value('storage', window.localStorage);

...and there you have it.
Alternatively, since providers in Angular kind of suck (and are pretty confusing and hard to remember), it might be easier to just use .provider and manually attach something like window.localStorage to the $get function.