text:
Q: swithcing to next textview Ok im making  app and it have 15 button's and 6 textview's.I want when I press first button to change value of first textview(value is "") to something (number one for example).But problem is when i press second button if first textview is already set to some value to set set second textview to second value.
If you need something else ask in comments (sorry for bad English)
here is what I was doing(this is under onclick)when i press second button
if(textview1.equals("1")){
            textview2.setText("2");}
            else if (textview1.equals("")){
            textview1.setText("2");
            }

A: Since you're concerned with the text inside of your text view, you should be using the object's getText method:
if( textview1.getText().equals("1") ){ // Edited
    textview2.setText("2");
} else if (textview1.getText().equals("")){ //Edited
    textview1.setText("2");
}

A: It sounds like you wish to show last 6 buttons pressed.
Store all pressed buttons in a List (i.e. LinkedList) of size 6. Initially, it will be empty.
Then whenever any button is pressed do two things:
1) add it to the List and delete old elements if size exceeds six.
2) set button values from List.
Second step can be achieved like this:
// all TextViews should be in a list
private List<TextView> textViews;

// declare as field
private List<String> memoryQueue = new ArrayList<String>();

public void update() {
    //set fields for the pressed buttons
    for (int i=0; i<6 && i<memoryQueue.size(); i++) {
        String text = memoryQueue.get(i);
        textViews.get(i).setText(text);
    }

    // set empty fields
    for (int i = memoryQueue.size(); i<6; i++) {
        textViews.get(i).setText("");
    }
}

This code snippet assumes that you store your TextViews in a List.
And Easiest way to keep track of last six button:
public void buttonPressed(Button button) {
    //get text based on your button
    String text = button.getText();

    if (memoryQueue.contains(text)) {
         return;
    }

    memoryQueue.add(text);
    if (memoryQueue.size() > 6) {
        memoryQueue.remove(0);
    }
}

A: At first, you have to get the String text from TextView using getText() method then you can compare that String with another String. Now, change your condition as follows...
if(textview1.getText().toString().equals("1")){
    textview2.setText("2");}
else if (textview1.getText().toString().equals("")){
    textview1.setText("2");
}


text:
Q: How to connect to HTTPS via proxy with WinINet i'm trying to connect to the HTTPS service via Proxy using WinINet. My code looks like this:
hInternet = InternetOpenW(L"Test", INTERNET_OPEN_TYPE_PROXY,L"PROXY_IP:PROXY_PORT", L"<local>", 0);

if (hInternet == NULL)
{
    printf("InternetOpenW failed! Error code: %d\n", GetLastError());
}
else
{
    HINTERNET hConnect = InternetConnectW(hInternet, L"HTTPS_SERVICE_IP", 443, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
    if (hConnect == NULL)
    {
        printf("InternetConnectW failed! Error code: %d\n", GetLastError());
    }
    else
    {
        HINTERNET hRequest = HttpOpenRequestW(hConnect, NULL, L"", NULL, NULL, NULL, 0, 0);
        if (hRequest == NULL)
        {
            printf("HttpOpenRequestW failed! Error code: %d\n", GetLastError());
        }
        else
        {
            BOOL bRequestSent = HttpSendRequestW(hRequest, NULL, 0, NULL, 0);
            if (!bRequestSent)
            {
                printf("HttpSendRequestW failed! Error code: %d\n", GetLastError());
            }
            else
            {
                printf("Connection ok!\n");
            }

            InternetCloseHandle(hRequest);
        }

        InternetCloseHandle(hConnect);
    }

    InternetCloseHandle(hInternet);
}

It sends GET request to the proxy, perform ntml authentication, but  connection fails. Proxy expect the client to send CONNECT request. How can I send CONNECT method with that code?

A: You need to add the INTERNET_FLAG_SECURE flag in your HttpOpenRequestW call, such as here:
HINTERNET hRequest = HttpOpenRequestW(hConnect, NULL, L"", NULL, NULL, NULL, INTERNET_FLAG_SECURE, 0);

Obviously, the application code on your side needs to recognize whether you're dealing with HTTP or HTTPs and add this flag only when needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check if item of a dataframe is inside another dataframe I'm trying to compare a little subset of a dataframe to check if exists in other dataframe with pandas.
For example:
Dataframe1
id     state
1111   M
2222   A
3333   A
4444   M
5555   A
6666   M

Dataframe2
ids    status
8888   M
2222   A
3333   A
4444   M
5555   C
6666   M

As you can see, the headers are different between these dataframes.
I would like get the each row of Dataframe1, and check if both columns (id and state) exists in Dataframe2, in its corresponding columns (id -> ids, state -> status)
I'm starting with pandas right now, so i'm so sorry if this question has been aswered before.
I was trying with the following code, but I'm only able to compare one column, and not the rest.
first_data = pandas.read_csv(first_csv, usecols=["id", "state"])
second_data = pandas.read_csv(second_csv, usecols=["ids", "status"])
print first_data["id"].isin(second_data["ids"])

Is this the correct method to do it?
Thanks in advance!


text:
Q: Unix Command Line Current Directory Let's say I have a folder structure like this:
mygame
 play.command
 otherstuff
  code.py

I want play.command to cd to mygame no matter where mygame is and run code.py from there. How do I do that?

A: Put that code.py in /bin folder. Then you can access it from anywhere.

A: From your question it seems you want to go to the parent directory. You do this via
cd ..
otherstuff/code.py

(with the space after 'cd')
or call code.py more directly with
../otherstuff/code.py

A: I think you are trying something like this,
You have two ways to run scripts:

*

*absolute path:
python /path/to/script.py

*none-absolute path:
cd ../to/your/directory && python script.py

A: First cd to the directory where the script is stored in, and then execute the python script
#!/bin/bash
cd "$(dirname "${BASH_SOURCE[0]}")"
otherstuff/code.py


text:
Q: Schedule a Task to delete another task I have a scheduled task in EC2 windows server 2019 that runs on start and I would like to delete after it finishes.
I tried to schedule a task to delete it but the task kept running without deleting the other one, but the scripts work from Powershell directly.
SCHTASKS /Delete /TN AfterRestartSetup /F

I tried to add /z to delete the task right after it is done but it did not work.
schtasks /create /tn "AfterRestartSetup" /sc onstart /z /rl highest /ru system /tr "powershell.exe -file C:\scripts\setup\AfterRestartSetup.ps1"

I also tried to unregister but it didn't work also:
Unregister-ScheduledTask -TaskName "AfterRestartSetup"  -Confirm:$false

A: You can disable a task like this:
Disable-ScheduledTask -TaskPath "\your-user\" -TaskName "your-task-name"

Add the above line to a text file and save it with ps1 extension. Then create a task on Task Scheduler. In the General tab (of properties window), make sure you check Run with highest privileges. The Action should be Start a program where the Program/script is Powershell.exe and the argument has a complete path to the ps1 file you created earlier (e.g. C:\Scripts\myTask.ps1).


text:
Q: What is the meaning of flag -s in this command? I have met a command to load nvm environment in .zshrc, but I don't know what it exactly does with flag -s. I know that the square bracket is condition to check whether folder in this command exists or not. But don't know what -s does.
[ -s "/usr/local/opt/nvm/nvm.sh" ] && . "/usr/local/opt/nvm/nvm.sh"  # This loads nvm
Does anyone know the flag -s in this command? Thank in advance.

A: [ is the same as test. Checking test's manpage:
-s file       True if file exists and has a size greater than zero.

Update: Actually, using man '[' works, too.


text:
Q: See inferred types in complex OCaml code I'm a OCaml newbie working with some pretty complex (at least for me) OCaml code I didn't write. It would help a lot to understand it if I could see the inferred types for some of the values, as I can do with F# and Visual Studio by hovering over any value, e.g.:

(screenshot borrowed from http://theburningmonk.com/2010/01/learning-f-part-1/)
I guess I could break down the code and feed it to the toplevel to get the types, but is there any other, simpler way?

A: First, you must compile your file (foo.ml) with the -annot flag. This generates the annotation file (foo.annot) that contains type information about all identifiers inside. You can include this as part of your makefile or build process.
Then, you need to rely on your IDE to display that information. I do this in Tuareg (the emacs mode) using Ctrl+C, Ctrl+T, which highlights the current expression and displays its type.

A: OcaIDE which is an O'Caml plug-in for Eclipse displays the inferred types on the fly while editing your code.
Example:

A: You could enter the code into the ocaml toplevel.  Yeah, it's not as pretty, but it'll show the types.

A: What works for me when reading OCaml code is to begin with the .mli files to see what the overall structure of the project is. From there, and having an idea of what are the dependencies, you can explore from the toplevel.
Alternatively, you can ocamlc -i the file in question for an overview of all the declared types and values, or use Tuareg mode in Emacs as replied elsewhere, if you are of that persuasion.


text:
Q: Keep the emacs BROWSE file up to date while editing I'm trying to use a source browser for a c++ project without using a big IDE.
My current favorite text editor is emacs.
I found a solution that fit well to my needs which is the ebrowse (not intrusive, can very easily add sources of third part dependancy...).
My problem is that it does not stay up to date while I edit a file already ebrowsed.
eg if I add a method, it will not appear in the tree, and I didn't find a command to update it.
I tried to do a script that execute the ebrowse command line with an (global-auto-revert-mode t) t try to automatically keep the open BROWSE file updated, but it complain about editing externally modificated file.
There is a solution or should I quit to redo the BROWSE file each time then reload it ?
Thanks a lot
PS: I already saw ecb, it is a bit heavy from my point of view, and there is an annoying known bug that force me to trick by an ugly way ecb permission denied bug http://blog.gmane.org/gmane.emacs.code-browser/page=2


text:
Q: Блокировать клавишу в linux (Insert) Как можно блокировать клавишу INS в Linux?
Пишу книгу, иногда мешает то, что время от времени, случайно нажимаю клавишу INS, переходя в режим замены и затираю ранее набранный текст. Есть ли способ блокировать эту клавишу (чтобы никогда не переходить в режим замены)?


text:
Q: Configuring IPtables to mirror traffic in CentOS I'm trying to set up iptables to mirror traffic coming into eth2 and send to 10.1.4.4.  I have been reading a lot of documentation on this but am having some issues.
Here is the command I am trying to use:
[root@test]# iptables -t mangle -A PREROUTING -i eth2 -j TEE -gateway 10.1.4.4
iptables v1.4.7: multiple -j flags not allowed

I'm currently testing this on CentOS 6.5 and using iptables v1.4.7. Any ideas on why this isn't working?

A: You have a syntax error, you should use two dashes is gateway option, like this:
iptables -t mangle -A PREROUTING -i eth2 -j TEE --gateway 10.1.4.4

EDIT: on CentOS 6.x iptables userspace is not correctly patched. TEE was added in 1.4.8 and CentOS 6 runs 1.4.7, and I guess you'll need to patch and rebuild RPM. I can check the code and offer a solution if you wish.
EDIT: Problem is a little bit more complicated. I've tried backporting various versions of iptables to get it work, and, it's not only iptables problem per se. It's also kernel problem. CentOS version from EL7 works ok (1.4.21) and some Fedora versions too. So, what you can do is:
# rpm -Uvh http://mirrors.nic.cz/fedora-archive/fedora/linux/releases/14/Everything/x86_64/os/Packages/iptables-1.4.9-1.fc14.x86_64.rpm
Retrieving http://mirrors.nic.cz/fedora-archive/fedora/linux/releases/14/Everything/x86_64/os/Packages/iptables-1.4.9-1.fc14.x86_64.rpm
warning: /var/tmp/rpm-tmp.NDCBn2: Header V3 RSA/SHA256 Signature, key ID 97a1071f: NOKEY
error: Failed dependencies:
    libxtables.so.4()(64bit) is needed by (installed) iproute-2.6.32-32.el6_5.x86_64

Now, if you want to install it you'll need to add --force --nodeps, which will render iproute inoperable because of missing dependency. Then you'll have to extact libxtables.so.4 from original iptables rpm and keep it manually on system to fix iproute :)
And after all of that, you will get the following error:
# /sbin/iptables -t mangle -A PREROUTING -i eth2 -j TEE --gateway 10.1.4.4
iptables: No chain/target/match by that name.

This is a kernel problem - module xt_TEE.ko is missing from standard CentOS/RHEL EL6 kernels:
# rpm -ql kernel | grep xt_TEE

You can work around that by using the ELrepo kernel:
# rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org
# rpm -Uvh http://www.elrepo.org/elrepo-release-6-6.el6.elrepo.noarch.rpm
# yum --enablerepo=elrepo-kernel install kernel-lt
# rpm -ql kernel-lt | grep xt_TEE
/lib/modules/3.10.69-1.el6.elrepo.x86_64/kernel/net/netfilter/xt_TEE.ko

To read more about kernel-lt (LongTerm) packages and what are their limitations/benefits, please visit: http://elrepo.org/tiki/kernel-lt.
If you plan on using this in production, please try it and test it thoroughly and try to backport stuff into EL standard kernels and into standard iptables 1.4.7 :)
It can be done but it's a can of worms which I'm not sure you wanna open. Is it worth it?


text:
Q: Set group owner to individual or another group? I am working on creating an intranet for a company where I have each project be a group and inside that group there are smaller groups that are more specific. The project group is owned by a project lead group that will also have control over the project subsite. My question is who should own the project lead group, another group that is composed of all the project leads or have the actual project lead be the owner?

A: If you use a Group it will be easier to add more users as well as remove users.
So I would prefer to use Group instead of a single user.
For example, Member group owner can be set to Owners group.


text:
Q: How to allow scrolling only in the main section? (HTML and CSS) I'm building a To-Do List with only HTML and CSS, I want only the content of the main section of the site to be moved by the side scroll.
The page is divided into 3 sections, which are contained within a flexbox container, and a header. In the image you can see a model representing the idea.

The main section is the one in the middle, the vertical scroll must be allowed only for it, all other elements such as the header and the secondary sections must remain fixed on the screen.
I made a reduced version of the code to simplify my situation and make it easier to understand:
HTML CODE:
 <!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="style.css" />
        <title>To-do list</title>

To-Do List

Secondary Section

Main Section

Secondary Section

CSS CODE
 * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    header {
      background-color: black;
      width: 100%;
      padding: 20px;
      text-align: center;
      color: white;
    }

    .flex-container {
      display: flex;
      flex: 1 1 0;
      text-align: center;
      height: 1000px;
    }

    .flex-container h2 {
      margin-top: 30px;
      font-size: 2rem;
    }

    .main-section {
      background-color: rgb(255, 222, 144);
      width: 100%;
    }

    .secondary-section {
      background-color: rgb(114, 181, 245);
      width: 100%;
    }

I've been trying to use "position: fixed" and configure the sections overflow, but I was not successful, what would be the correct way to keep these flex elements fixed on the screen without the scroll moving them?

A: You can use position: sticky for this example. I have made the two secondary section full height as the screen (height: 100vh) and added position property to it.
Like so -

 * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    header {
      background-color: black;
      width: 100%;
      padding: 20px;
      text-align: center;
      color: white;
    }

    .flex-container {
      display: flex;
      flex: 1 1 0;
      text-align: center;
      height: 1000px;
    }

    .flex-container h2 {
      margin-top: 30px;
      font-size: 2rem;
    }

    .main-section {
      background-color: rgb(255, 222, 144);
      width: 100%;
    }

    .secondary-section {
      background-color: rgb(114, 181, 245);
      width: 100%;
      /* added */
      height: 100vh;
      position: sticky;
      top: 0;
    }
 <!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="style.css" />
        <title>To-do list</title>

To-Do List

Secondary Section

Main Section

Secondary Section

A:

   body{
        overflow: hidden;
      }
      * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    header {
      background-color: black;
      width: 100%;
      padding: 20px;
      text-align: center;
      color: white;
    }

    .flex-container {
      display: flex;
      flex: 1 1 0;
      text-align: center;
      height: 1000px;
    }

    .flex-container h2 {
      margin-top: 30px;
      font-size: 2rem;
    }

    .main-section {
      background-color: rgb(255, 222, 144);
      width: 100%;
      height: 700px;
      max-height: 900px;
      overflow: auto;
    }

    .secondary-section {
      background-color: rgb(114, 181, 245);
      width: 100%;
    }
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="style.css" />
        <title>To-do list</title>

To-Do List

Secondary Section

Main Section

                Hi there Need to add content to this to get the scroll

                Hi there Need to add content to this to get the scroll
                Hi there Need to add content to this to get the scroll
                Hi there Need to add content to this to get the scroll
                Hi there Need to add content to this to get the scroll
                Hi there Need to add content to this to get the scroll
                Hi there Need to add content to this to get the scroll
                Hi there Need to add content to this to get the scroll
                Hi there Need to add content to this to get the scroll
                Hi there Need to add content to this to get the scroll
                Hi there Need to add content to this to get the scroll
                Hi there Need to add content to this to get the scroll

                Hi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scrollHi there Need to add content to this to get the scroll

Secondary Section

A: Try this instead,
For fixed header by adding
header {
  position: fixed;
  height:80px;
  top: 0;
}

Fixed secondary-section
.secondary-section {
  width: calc(100% / 3);
  height: 100vh;
  position: fixed;
  top: 80px; // height of header
}

Scrollable main-section
.main-section {
  width: calc(100% / 3);
  position:absolute;
  bottom:0;
  right:calc(100% / 3);
  left:calc(100% / 3);
  top: 80px; // height of header
  height: inherit;
  z-index: -1;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
header {
  background-color: black;
  width: 100%;
  padding: 20px;
  text-align: center;
  color: white;
  position: fixed;
  top: 0;
  height:80px;
}

.flex-container {
  display: flex;
  flex: 1 1 0;
  text-align: center;
  height: 1000px;
  top:80px;
}

.flex-container h2 {
  margin-top: 30px;
  font-size: 2rem;
}

.main-section {
  background-color: rgb(255, 222, 144);
  width: calc(100% / 3);
  position:absolute;
  bottom:0;
  right:calc(100% / 3);
  left:calc(100% / 3);
  top: 0px;
  height: inherit;
  z-index: -1;
  top:80px;
}

.secondary-section {
  background-color: rgb(114, 181, 245);
  width: calc(100% / 3);
  height: 100vh;
  position: fixed;
  top:80px;
}
.secondary-section.right{
  right:0;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>To-do list</title>

To-Do List

Secondary Section

Main Section

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Secondary Section

A:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  text-align: center;
}

h1 {
  font-size: 20px;
}

h2 {
  font-size: 16px;
}

header {
  color: white;
  width: 100%;
  height: 50px;
  padding: 10px;
  background: black;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1;
}

.flex-container {
  display: flex;
  justify-content: center;
  min-height: 100vh;
}

.flex-container [class$="-section"] {
  width: 33.33%;
  height: 100%;
  padding: 60px 10px 10px;
}
.secondary-section {
  background: #78a4ad;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
}

.secondary-section ~ .secondary-section {
  left: auto;
  right: 0;
}

.main-section {
  background: #f1ba77;
}

HEADER

Secondary Section

Main Section

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Secondary Section


text:
Q: Format json data for Flotcharts I am using Flowcharts and need to format JSON data from PHP post. The format I need is as follows:
[2, 16, 0, 12, 22, 5, -10, 5, 15, 2, 11, 55]

The javascript command to render the charts:
_initSparklineChart($('#kt_chart_sales_by_apps_1_2'), [2, 16, 0, 12, 22, 5, -10, 5, 15, 2, 11 , 66], KTApp.getStateColor('danger'), 2);

I am getting the data using a post like this:
for ($y = 1; $y <= 4; $y++) {
    for ($x = 1; $x <= 12; $x++) {
        $array[$y][$x] = rand(1,100);
    }
}

$returnArray["message"]     = "Data Retrieved";
$returnArray["data"]        = $array;
$returnArray["count"]       = $count;

echo json_encode($returnArray);

So the javascript code would be something like this. Can anybody help me with this?
$.ajax({
    type: "POST",
    url: "./demo2/widgets/functions/production.php",
    data: {mode:mode,date:date},
    cache: false,
    dataType: "json",
    success: function(response){
        var dataset1 = response["data"];

        var dataset2 = [];
        for (var i = 0; i < dataset1.length; i++) {
            console.log(dataset1[i]);
            dataset2.push([dataset1[i]]);
        }

        _initSparklineChart($('#kt_chart_sales_by_apps_1_1'), [dataset2], KTApp.getStateColor('success'), 2);
    }
});

Working JS
var DataSet1    = {};
var DataSet2    = {};

$.each(response["data"], function( index, value ) {

    $.each(value, function( key, val ) {

        DataSet1[key] = val;

    });

    DataSet2[index] = Object.values(DataSet1);

});

$.each(DataSet2, function( index, value ) {

    _initSparklineChart($('#kt_chart_sales_by_apps_1_'+index), value, KTApp.getStateColor('success'), 2);

});

A: I'm still not entirely sure what you're asking, but from what I gather you want to initialise several charts, e.g. #kt_chart_sales_by_apps_1_1, #kt_chart_sales_by_apps_1_2, #kt_chart_sales_by_apps_1_3, etc.
If so, the following should work in your success callback:
success: function(response) {
    var datasets = response["data"];

    for (var set in datasets) {
        _initSparklineChart($('#kt_chart_sales_by_apps_1_'+set), datasets[set], KTApp.getStateColor('success'), 2);
    }
}

Small example:

var datasets = {
    "1": [2, 16, 0, 12, 22, 5, -10, 5, 15, 2, 11 , 66],
    "2": [12, 11, 5, 22, 16, -10, 66, 5, 2, 2, 15, 0],
    "3": [5, 0, 11, 2, 15, 12, 2, 66, 5, -10, 22, 16],
    "4": [5, -10, 0, 2, 16, 22, 66, 12, 5, 15, 2, 11]
}

for (var set in datasets) {
    console.log("Using ID: #kt_chart_sales_by_apps_1_" + set, "with data set:", datasets[set]);
}


text:
Q: Silverlight 4.0 : How to get DatagridTemplateColumn Header in code behind have in XAML a datagridtemplate column
<sdk:DataGridTemplateColumn x:Name="Urgency">
                <sdk:DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal" VerticalAlignment="Center">
                            <Image Source="{Binding UrgencyUri}"
                            VerticalAlignment="Stretch"
                            Stretch="UniformToFill"
                            Height="10" Width="10" Margin="0,0,5,0"/>
                            <TextBlock Text="{Binding Urgency}"/>
                        </StackPanel>
                    </DataTemplate>
                </sdk:DataGridTemplateColumn.CellTemplate>
                <sdk:DataGridTemplateColumn.HeaderStyle>
                    <Style TargetType="primitive:DataGridColumnHeader">
                        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                        <Setter Property="ContentTemplate">
                            <Setter.Value>
                                <DataTemplate>
                                    <Grid HorizontalAlignment="Stretch">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="*" />
                                            <ColumnDefinition Width="Auto" />
                                        </Grid.ColumnDefinitions>
                                        <TextBlock Text="{Binding Path=Urgency, Source={StaticResource MHVWindowResources}}" Grid.Column="0" HorizontalAlignment="Left" />
                                        <filter:DataGridColumnFilter Grid.Column="1" HorizontalAlignment="Right" />
                                    </Grid>
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </sdk:DataGridTemplateColumn.HeaderStyle>
            </sdk:DataGridTemplateColumn>

I used this code below however it returns null
DataGridTemplateColumn templateColumn = dataGrid.Columns[columnIndex] as DataGridTemplateColumn;
            if (templateColumn != null)
            {

                string header = templateColumn.Header as string;

                if (header == null)
                {
                    return null;
                }
                bindingPath = header;
            }

Is their anything that I missed out? Thanks
I want to know how to get the column header in code behind.

A: Add this line:
 var header = templateColumn.Header

place a break point here debug and check what the type is in the quick watch.
My bet is the header is probably never a string so it always null when you use:
string header = templateColumn.Header as string;

hope that helps


text:
Q: Unique Identifier in Obligation Cordapp I have replicated the Obligation Cordapp Transfer functionality and i am struck with the linearId of Unique Identifier. I have successfully exercised the Issue Cordapp and for transfer of Obligation, i have provided the flow command with linearId of generated Obligation. The parameter which i am passing through linearId is interpreted as the External id [argument in UniqueIdentifier] instead of id and so it is unable to find the Obligation to transfer.
Here are reference for issue.
The generated id for the Obligation created is
**linearId : externalId: null
id: "4799c549-8c2b-401f-90dd-1dc115fbcfba"
Thu Mar 29 18:41:02 IST 2018>>> flow start TransferObligation$Initiator newLender: "O=PartyC,L=Paris,C=FR",anonymous: false,linearId: "4799c549-8c2b-401f-90dd-1dc115fbcfba

The passed argument, linearId has to take as id [argument in UniqueIdentifier and is randomly generated if external id is not equal to null] as per Obligation Cordapp and has to do required transfer functionality. Instead it is taking linearId passed as externalId [argument in UniqueIdentifier] and so total linearId becoming externalId_id.
>Linear Id parameter is:4799c549-8c2b-401f-90dd-1dc115fbcfba_ace60f85-b360-4cf7b198-4d3d471f9d63
>Obtaining IOU from vault.
>States Size:0

Observing that ace60f85-b360-4cf7b198-4d3d471f9d63 is appended as id which is randomly generated and unable to find the Obligation generated.
How corda will interpret linearId passed? as externalId/Id as default?
In Obligation Cordapp it demonstrated in samples took as Id and required job is done.But the cordapp which i am exercising takes the passed parameter as externalId.
Or any changes has to be done in code level to take the linearId parameter as id?
Edit 1:
We are developing the code in java The transfer obligation for reference.Although it is just a replicate.Please have a look at it
  package com.example.flow;

import co.paralleluniverse.fibers.Suspendable;
import com.example.contract.ActivityContract;
import com.example.state.Activity;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import net.corda.confidential.IdentitySyncFlow;
import net.corda.confidential.SwapIdentitiesFlow;
import net.corda.core.contracts.Command;
import net.corda.core.contracts.StateAndRef;
import net.corda.core.contracts.UniqueIdentifier;
import net.corda.core.flows.*;
import net.corda.core.identity.AbstractParty;
import net.corda.core.identity.AnonymousParty;
import net.corda.core.identity.Party;
import net.corda.core.transactions.SignedTransaction;
import net.corda.core.transactions.TransactionBuilder;
import net.corda.core.utilities.ProgressTracker;
import net.corda.core.utilities.ProgressTracker.Step;

import java.security.PublicKey;
import java.util.*;

import static com.example.contract.ActivityContract.Activity_Contract_ID;

public class ActivityTransferFlow {

    @StartableByRPC
    @InitiatingFlow
    public static class Initiator extends ActivityBaseFlow{

    public final UniqueIdentifier linearId;
    public final Party newLender;
    public final Boolean anonymous;

    private final Step INITIATION = new Step("Obtaining IOU from vault.");
    private final Step BUILDING = new Step("Building and Verifying Transaction");
    private final Step SIGNING = new Step("Signing gathered transaction");
    private final Step SYNCING = new Step("Syncing gathered identities "){

        @Override
        public ProgressTracker childProgressTracker() {
            return IdentitySyncFlow.Send.Companion.tracker();
        }
    };

    private final Step GATHERING = new Step("Gathering counterparty signatures"){

        @Override
        public ProgressTracker childProgressTracker() {
            return CollectSignaturesFlow.Companion.tracker();
        }
    };

    private final Step FINALISING = new Step("Finalising transaction"){

        @Override
        public ProgressTracker childProgressTracker() {
            return FinalityFlow.Companion.tracker();
        }
    };

       private final ProgressTracker progressTracker = new ProgressTracker(
               INITIATION,
               BUILDING,
               SIGNING,
               SYNCING,
               GATHERING,
               FINALISING
       );

        public Initiator(UniqueIdentifier linearId, Party newLender, Boolean anonymous) {

            this.linearId = linearId;
            this.newLender = newLender;
            this.anonymous = anonymous;
        }

        @Override
        public ProgressTracker getProgressTracker() {
            return progressTracker;
        }

        @Suspendable
        @Override
        public SignedTransaction call() throws FlowException {

            // step1:Retrieve Activity specified by linear id from the vault
            progressTracker.setCurrentStep(INITIATION);

            final StateAndRef<Activity> activityToTransfer= getObligationByLinearId(linearId);
            }

            final Activity inputActivity=activityToTransfer.getState().getData();

            //step2:This flow can only be initiated by current recipient
            final AbstractParty lenderIdentity =getLenderIdentity(inputActivity);

            //step3:Abort if the borrower started this flow
            if(!getOurIdentity().equals(lenderIdentity))
            {
             throw new IllegalStateException("Activity transfer can only be initiated by the lender.");
            }

            //step4:Creating the new obligation state reflecting a new lender
             progressTracker.setCurrentStep(BUILDING);
             final Activity transferredActivity =createOutputActivity(inputActivity);

             //step4:Create transfer command
             final List<PublicKey> signerKeys = new ImmutableList.Builder<PublicKey>()
                     .addAll(inputActivity.getParticipantKeys())
                     .add(transferredActivity.getLender().getOwningKey()).build();

            final Command transferCommand = new Command<>(new ActivityContract.Commands.ActivityTransfer(), signerKeys);

            //step5:Create a transaction builder and then add states and commands.
            final TransactionBuilder builder = new TransactionBuilder(getNotary())
                    .addInputState(activityToTransfer)
                    .addOutputState(transferredActivity, Activity_Contract_ID)
                    .addCommand(transferCommand);

            //step6:Verify and sign the transaction
            progressTracker.setCurrentStep(SIGNING);
            builder.verify(getServiceHub());
            final SignedTransaction ptx=getServiceHub().signInitialTransaction(builder, inputActivity.getLender().getOwningKey());

            //step7:Getting party object from the borrower
            progressTracker.setCurrentStep(SYNCING);
            final Party borrower=getBorrowerIdentity(inputActivity);

            //step8:Send any keys or certificates so the signers can verify each other identity
            Set<FlowSession> sessions=new HashSet<>();
            Set<Party> parties= ImmutableSet.of(borrower,newLender);
            for (Party party:parties) {

                  sessions.add(initiateFlow(party));

            }
            subFlow(new IdentitySyncFlow.Send(sessions,ptx.getTx(),SYNCING.childProgressTracker()));

            //step9:Gathering signatures from the borrower and the new lender
             progressTracker.setCurrentStep(GATHERING);
             final SignedTransaction stx=subFlow(new CollectSignaturesFlow(
                     ptx,
                     sessions,
                     ImmutableList.of(inputActivity.getLender().getOwningKey()),
                     GATHERING.childProgressTracker()
             ));

            //Step10:Notarise and record the transaction into vault and broadcast the transaction

            progressTracker.setCurrentStep(FINALISING);
            return subFlow(new FinalityFlow(stx,ImmutableSet.of(getOurIdentity())));
        }

        @Suspendable
        private AbstractParty getLenderIdentity(Activity inputObligation) {
            if (inputObligation.getLender() instanceof AnonymousParty) {
                return resolveIdentity(inputObligation.getLender());
            } else {
                return inputObligation.getLender();
            }
        }

        @Suspendable
        private Activity createOutputActivity(Activity inputActivity) throws FlowException {
            if (anonymous) {
                final HashMap<Party, AnonymousParty> txKeys = subFlow(new SwapIdentitiesFlow(newLender));
                if (!txKeys.containsKey(newLender)) {
                    throw new FlowException("Couldn't get lender's conf. identity.");
                }
                final AnonymousParty anonymousLender = txKeys.get(newLender);
                return inputActivity.withNewLender(anonymousLender);
            } else {
                return inputActivity.withNewLender(newLender);
            }
        }

        @Suspendable
        private Party getBorrowerIdentity(Activity inputActivity) {
            if (inputActivity.getBorrower() instanceof AnonymousParty) {
                return resolveIdentity(inputActivity.getBorrower());
            } else {
                return (Party) inputActivity.getBorrower();
            }
        }
    }

    @InitiatedBy(Initiator.class)
    public static class Responder extends FlowLogic<SignedTransaction> {
        private final FlowSession otherFlow;

        public Responder(FlowSession otherFlow) {
            this.otherFlow = otherFlow;
        }

        @Suspendable
        @Override
        public SignedTransaction call() throws FlowException {
            subFlow(new IdentitySyncFlow.Receive(otherFlow));
            SignedTransaction stx = subFlow(new ActivityBaseFlow.SignTxFlowNoChecking(otherFlow, SignTransactionFlow.Companion.tracker()));
            return waitForLedgerCommit(stx.getId());
        }
    }

}

Edit 2:
The getObligationByLinearId method in ActivityBaseFlow
and the command we use is

flow start ActivityTransferFlow$Initiator linearId: d21827b7-e4be-4874-9383-e9f339d7c9ea,newLender: "O=PartyC,L=Paris,C=FR",anonymous: false

StateAndRef<Activity> getObligationByLinearId(UniqueIdentifier linearId) throws FlowException {
    System.out.println("Linear Id parameter is:"+linearId);
    QueryCriteria queryCriteria = new QueryCriteria.LinearStateQueryCriteria(
            null,
            ImmutableList.of(linearId),
            Vault.StateStatus.UNCONSUMED,
            null);
    List<StateAndRef<Activity>> obligations = getServiceHub().getVaultService().queryBy(Activity.class, queryCriteria).getStates();
    if (obligations.size() != 1) {
        System.out.println("Linear Id 1:"+linearId);
        throw new FlowException(String.format("Obligation with id %s not found.", linearId));
    }
    //System.out.println("Linear Id 2:"+linearId);
    return obligations.get(0);
}

A: The UniqueIdentifier constructor is taking the string input from flow start as the externalId.
Change your flow to accept a string instead and manually parse it using UniqueIdentifier.fromString(inputString). i.e
public Initiator(String inputString, Party newLender, Boolean anonymous) {

            this.linearId = UniqueIdentifier.fromString(inputString);
            this.newLender = newLender;
            this.anonymous = anonymous;
        }


text:
Q: How do I move the sending and receiving of messages to a server thread? I have a class Game that uses a class TCPServer. I would like to seperate all the low level sending and receiving in TCPServer. So I give TCPServer a separate thread that constantly reads incoming messages. I would like to return these messages to Game. But I dont know how to do this. Game should also react on these messages bij responding by sending a message to the clients.
I think/know it is possible by moving the thread from TCPServer to Game but is this the best way to solve this? Isn't it better to keep the 2 classes separate.
I have the following pseudocode.
public class Game{
   TCPServer tcpServer = new TCPServer();

   public void execute(){
       // do something
       Object o = new Object;
       send(o);

       if(receive(o)){  // WRONG
          // do something with the receive object
       }
   }

   private void send(Object o){
      tcpServer.send(o);
   }

   private Object receive(Object o){
      return tcpServer.receive(o);
}

public class TCPServer extends Thread{
   private ServerSocket serverSocket;
   Socket client = new Socket;

   public void run(){
     Object o = receive();
     // How do I get this object o in the Server class in function execute()?
   }

   private Object receive(){
      return serverSocket.listen();

   }

   public void send(Object o){
      client.send(o);
}

A: I think the right way to do this would be by using BlockingQueues.  Instead of sending the messages in the current thread, Game would just add them to a sendQueue.  The TCPServer would then have a receiving thread which would add things to the readQueue and another thread which wrote things from the sendQueue to the socket.
I don't quite understand your thread model right now.  Typically you have a thread calling accept() on a ServerSocket and then forking a client handler thread.  If Game is maintaining a number of these client connections then you'd have something like this:

*

*TCPServer has a thread which calls accept().

*When it gets a connection is creates a ClientHandler object and adds this to the collection of clients being handled by the game.

*Each ClientHandler has a sendQueue and receivedQueue -- maybe each are LinkedBlockingQueue

*Each ClientHandler forks a reading thread receiving from the client and adding to the  receivedQueue and a writing thread which is waiting on the sendQueue and writes to the client socket.

There's a lot of work here to get this right.  How to properly shutdown both reader and writer threads when the client socket closes is going to be a challenge.
Hope something here helps.


text:
Q: Redirect stdin and stdout in child in c I need to create a client-server app (using sockets), the basic idea is:

*

*client sends string

*server receives string and sends it as stdin of another app

*server reads stdout of the app

*server sends answer to client.

The "other app" is a closed source calc (a calculator which reads from stdin the sort of 4 5 + and prints 9).
I'm trying to create a double pipe on the server, fork, and use this pipes to redirect stdin and stdout of the calc:
if(!fork())
{

    close(STDOUT_FILENO);
    close(STDIN_FILENO);

    dup2(outfd[0], STDIN_FILENO);
    dup2(infd[1], STDOUT_FILENO);

    close(outfd[0]); /* Not required for the child */
    close(outfd[1]);
    close(infd[0]);
    close(infd[1]);

    system("./calc/calc ");
    exit(0);
}

and from the server write on one pipe and read the other
    close(outfd[0]); /* These are being used by the child */
    close(infd[1]);

    char c;
    do
    {
        c=getchar();
        write(outfd[1],&c,1);
    }while(c!='\n');
    input[read(infd[0],input,100)] = 0; /* Read from child's stdout */

    printf("%s",input);

    close(outfd[1]);
    close(infd[0]);

I know this is very incomplete, but I think it should at least print the output of the first line in calc.
(Full code)
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{

int outfd[2];
int infd[2];

pipe(outfd); /* Where the parent is going to write to */
pipe(infd); /* From where parent is going to read */

if(!fork())
{

    close(STDOUT_FILENO);
    close(STDIN_FILENO);

    dup2(outfd[0], STDIN_FILENO);
    dup2(infd[1], STDOUT_FILENO);

    close(outfd[0]); /* Not required for the child */
    close(outfd[1]);
    close(infd[0]);
    close(infd[1]);

    //system("/usr/bin/bc -q");
    system("./calc/calc ");
    exit(0);
}
else
{

    char input[100];

    close(outfd[0]); /* These are being used by the child */
    close(infd[1]);

    //write(outfd[1],"2^32\n",5); /* Write to child's stdin */
    //write(outfd[1],"2 4 +\n",6);
    char c;
    do
    {
        c=getchar();
        write(outfd[1],&c,1);
    }while(c!='\n');
    input[read(infd[0],input,100)] = 0; /* Read from child's stdout */

    printf("%s",input);

    close(outfd[1]);
    close(infd[0]);

}
return 0;

It's very basic, but it's just for testing. When I execute it, it does nothing.
If I ps -e | grep calc during the execution, I can see it is running, but whatever I type doesn't seems to do anything.

A: Try moving:
close(outfd[1]);

between the do-while loop and input[read(infd[0],input,100)] = 0;.
This will send EOF on calc's stdin. It will exit, and this will flush its output buffer, so there will be something to read.
Your code is deadlocked: you're waiting for output before you close the pipe, but it's waiting for you to close the pipe before it sends output.


text:
Q: How do I make a *.ppk file let me into SSH (Ubuntu) I have a *.ppk file given to me so I can SSH into a server.
I'm using Ubuntu 10.x.
What commands do I need to run so I have permission to SSH?
I found something that said to do
ssh-add some_file.ppk

But then, I got this:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0777 for 'foofoofoo.ppk' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.

How can I change permissions on that file so Ubuntu will ssh-ify my .ppk file?
Thanks

A: From the error message, I'd say do chmod 600 some_file.ppk and try again.  This sets the permission on the file so that only you can read and write it (0777 means any user on the system can read or write to the file).
As a side note, private keys should always have a password.  You'll only be prompted for the password when adding it to the SSH agent.

A: The .ssh directory needs to be read/writeable/executabe by the owner only:
chmod 700 .ssh

authorized_keys and authorized_keys2 need to be read/writeable by the owner only:
chmod 600 .ssh/authorized_key*

As I don't use Ubuntu I cannot verify that this will work, but that is the required setup for RHEL/CentOS.

A: This will remove all permissions for other users in the file's group and all other users:

$ chmod g=,o= some_file

(Note depending on your system's configuration, you may be the only user in your group, which should be the same group that owns the file.)
View file permissions with ls -l:
$ ls -l some_file
-rw-r--r-- 1 user group 0 2010-7-14 23:29 some_file
$ chown g=,o= some_file
$ ls -l some_file
-rw------- 1 user group 0 2010-7-14 23:29 some_file

A: You've two options:

*

*fix the permissions (chmod 600 some_file.ppk && ssh-add some_file.ppk)

*add the key via the standard input (ssh-add - <some_file.ppk)


text:
Q: error looping thru input tags using vbscript If I open IE and go to the page I need this works
LocationURL = "https://secure4.billerweb.com/smg/BillerConsole/inetSrv?sessionHandle=oGWmOV1RQAkSijIxSWs8IjcShm7x4dZir/nuGysZmGsoWXrUY2w9NzE5MTMwNzAw&client=719130700&type=ApplicationMenu&action=Menu"
Set ie = GetIEApp(LocationURL)
Set aHTML = IE.document
Set frames = aHTML.getElementsByTagName("frame")
For Each frame In frames
    Set inputs = frame.contentwindow.document.getElementsByTagName("input")
    For Each obj In inputs
        If obj.name = "serviceSelection.inputFieldList[0].accountNumber" Then
            obj.value = "123"
        End If
        If obj.name = "serviceSelection.inputFieldList[0].reEnterAccountNumber" Then
            obj.value = "123"
        End If
        If obj.value = "Continue" Then
            obj.click
        End If
    Next
Next
Public Function GetIEApp(Location)
    Dim objShell
    Dim objWindows
    Dim objWindow
    Set objShell = CreateObject("Shell.Application")
    Set objWindows = objShell.Windows
    For Each objWindow In objWindows
        If LCase(Left(objWindow.LocationURL,4)) = "http" Then
            If LCase(Right(objWindow.FullName, 12)) = "iexplore.exe" Then
                If InStr(objWindow.LocationURL,Location) Then
                    Set GetIEApp = objWindow
                End If
            End If
        End If
    Next
    Set objWindow = Nothing
    Set objWindows = Nothing
    Set objShell = Nothing
End Function

If I use the script to open IE and login then go to the page I get an error

Object doesnt support this property or method 'frame.contentwindow.document.getElementsByTagName("input")'

Set IE = CreateObject("InternetExplorer.Application")
Set WshShell = WScript.CreateObject("WScript.Shell")
IE.Navigate "https://secure4.billerweb.com"
IE.Visible = True
While ie.Busy : WScript.Sleep 100 : Wend
IE.Document.All.Item("loginid").Value = "myid"
IE.Document.All.Item("password").Value = "mypass"
IE.Document.getElementsByName("Login").Item(0).Click
While ie.Busy : WScript.Sleep 100 : Wend
WScript.Sleep 1000
Call IE.document.parentWindow.execScript("top.header.selectGroup('1', 1)", "JavaScript")
WScript.Sleep 500
Call IE.document.parentWindow.execScript("top.header.preSubmit('inetSrv?type=WizardService&" & client & "&newBean=true')", "JavaScript")
While ie.Busy : WScript.Sleep 100 : Wend
WScript.Sleep 1000
Set aHTML = IE.document
Set iframes = aHTML.getElementsByTagName("frame")
For Each frame In iframes
    Set inputs = frame.contentwindow.document.getElementsByTagName("input")
    For Each obj In inputs
        If obj.name = "serviceSelection.inputFieldList[0].accountNumber" Then
            obj.value = "123"
        End If
        If obj.name = "serviceSelection.inputFieldList[0].reEnterAccountNumber" Then
            obj.value = "123"
        End If
        If obj.value = "Continue" Then
            obj.click
        End If
    Next
Next

A: I figured it out.
Changed
    Set inputs = frame.contentwindow.document.getElementsByTagName("input")
to
    Set inputs = frame.contentDocument.getElementsByTagName("input")


text:
Q: App and library in qbs: one project multiple products or vice-versa A question about best practices when using Qt and Qbs:  I have a static library and an app that uses it.  It looks like I can have a single qbs project with two products or two projects with one product each.  Which is better?  [And why?]
Thanks!

A: I just pulled down the qbs source which contains nice examples.  qbs itself is built, unsurprisingly, by qbs so that serves as a good example, too.
It seems that a single project with multiple products, often referenced from other qbs files is the intended usage.  Not sure why that way is better.


text:
Q: difference between df.loc[:, reversed(colnames)] and df.loc[:, list(reversed(colnames))] df.loc[:, reversed(colnames)] can retrieve a slice from df, but can not be used to assign to df. In order to assign to that slice of df, I have to use df.loc[:, list(reversed(colnames))]
Observe the following code and output for clarification:
import pandas as pd
import numpy as np

df = pd.DataFrame(
        {'a':list('asdf'), 'b':range(4)}
        )

print('df==', df, sep='\n')

colnames = ['a', 'b']

print('\ndf.loc[:, reversed(colnames)]:', df.loc[:, reversed(colnames)], sep='\n')

df.loc[:, reversed(colnames)] = np.nan
print('\ndf after df.loc[:, reversed(colnames)]=np.nan:', df, sep='\n')

df.loc[:, list(reversed(colnames))] = np.nan
print('\ndf after df.loc[:, list(reversed(colnames))]=np.nan:', df, sep='\n')

and the output:
df==
   a  b
0  a  0
1  s  1
2  d  2
3  f  3

df.loc[:, reversed(colnames)]:
   b  a
0  0  a
1  1  s
2  2  d
3  3  f

df after df.loc[:, reversed(colnames)]=np.nan:
   a  b
0  a  0
1  s  1
2  d  2
3  f  3

df after df.loc[:, list(reversed(colnames))]=np.nan:
    a   b
0 NaN NaN
1 NaN NaN
2 NaN NaN
3 NaN NaN

This behavior is new. I didn't have to list() to do assignment when I was using Anaconda 2018.12, I recently upgraded to Anaconda 2019.03.
I wonder what changed and caused this.


text:
Q: How to find the source of a message, output by Qt? When running my qt application, that is updated from qt 5.9 to qt 5.15, I get the following application output:
Using QByteRef with an index pointing outside the valid range of a QByteArray

The application is quite big and has plenty qbytearrays and qbyterefs.  The project is a few thousand files big so I do not want to search for it manually.  Is there an easy way to find the location of the application output. e.g. show the line/file that generates the output.
The line is generated by qt and not a custom qdebug or anything.

A: I would suggest you to check Stop when qWarning() is called under the Debugger section of the Qt Creator's Options:

By default, this option is off, as shown in the screenshot.


text:
Q: Как вывести в div результат ajax? Получаю ответ в json от ajax запроса и пытаюсь вывести в

 success: function (data) {
      $(".writeinfo").html(data);
    }

Как мне распарсить и вывести значения циклом, сейчас только выводит в div
[object Object],[object Object],[object Object],[object Object],[object Object]

Json приходит такой
[[{"id":1,"date_event":"2020-01-17","created_at":"2020-01-23 23:00:00","updated_at":null,"user_id":15}]]

A: array = JSON.parse(data)

далее можно работать как с обычным массивом


text:
Q: dbHasCompleted always returns TRUE I'm using R to do a statistical analysis on a SQL Server 2008 R2 database. My database client (aka driver) is JDBC and thereby I'm using RJDBC package.
My query is pretty simple and I'm sure that query would return a lot of rows (about 2 million rows).
SELECT * FROM [maindb].[dbo].[users]

My R script is as follows.
library(RJDBC);

javaPackageName <- "com.microsoft.sqlserver.jdbc.SQLServerDriver";
clientJarFile <- "/home/abforce/mystuff/sqljdbc_3.0/enu/sqljdbc4.jar";
driver <- JDBC(javaPackageName, clientJarFile);
conn <- dbConnect(driver, "jdbc:sqlserver://192.168.56.101", "username", "password");

query <- "SELECT * FROM [maindb].[dbo].[users]";
result <- dbSendQuery(conn, query);
dbHasCompleted(result)

In the codes above, the last line always returns TRUE. What could be wrong here?

A: The fact of function dbHasCompleted always returning TRUE seems to be a known issue as I've found other places in the Internet where people were struggling with this issue.
So, I came with a workaround. Instead of function dbHasCompleted, we can use conditional statement nrow(result) == 0.
For example:
result <- dbSendQuery(conn, query);
repeat {
    chunk <- dbFetch(result, n = 10);
    if(nrow(chunk) == 0){
        break;
    }
    # Do something with 'chunk';
}
dbClearResult(result);


text:
Q: Detect not contemplated values in a CASE statement evaluation Is there a way in T-SQL to collect all not contemplated values in a CASE condition and insert them in a table?
For example:
A SELECT that reads a table that has in Col1 the values A,B,C. This SELECT has a CASE that goes like this: CASE WHEN Col1 = 1 THEN ... WHEN Col1 = B THEN ... ELSE NULL END AS NewCol1
I would like to detect values like C, values that are not contemplated in Col1.
I could get them like this:  (...) ELSE Tabl1.Col1 but I need the CASE statement to end with ELSE NULL.

A: You can get a list of these values like this:
SELECT DISTINCT Col1
FROM Table
WHERE Col1 not in (1,...,B)

A: As @avery_larry suggested, I used a debug flag, giving my query two behaviours. I could call a function/stored with the parameter and if it's up INSERT the values into a desired output.


text:
Q: Transpose row value to additional pre-defined field when value is less than specified value I have a table that contains two identifying columns, a date, and a value.  This value can be up to 100.  What I want to do is where [ID] and [DATE] is the same across subsequent rows and the values are less than 100 (which also means [ID_SECONDARY] is always different), I want a query to place each one of these values in a column '[VALUE_1]...[VALUE_N]' along with the Value Description ([ID_SECONDARY]-->[VALUE_1_DESC]...[VALUE_N_DESC]). Ultimately each row should contain a unique [ID], [DATE], and an aggregation of the different [ID_SECONDARY] descriptions along with their values [VALUE_1]...[VALUE_N].  The number of unique [ID_SECONDARY] will not surpass 4, but could be from 1 to 4.
My initial inclination is to approach this using a cursor, but am hopeful there is a better alternative.
The first image is a sample of the information provided in the table, the second image is the output I'm looking for.  Any help is greatly appreciated.

.
As far as I can tell this is different from the various dynamic pivot posts out there because the columns are independent of the secondary ID and are fully dependent on the VALUE column to determine if the value itself belongs in columns 1-4.

A: Try this
WITH a AS (
    SELECT
        ID
        , [DATE]
        , ID_SECONDARY
        , VALUE
        , ROW_NUMBER() OVER (PARTITION BY ID, DATE ORDER BY ID) AS RNUM
)
SELECT
    a.ID
    , a.[DATE]
    , MAX (
        CASE a.RNUM
            WHEN 1 THEN a.VALUE
            ELSE NULL
      ) AS VALUE_1
    , MAX (
        CASE a.RNUM
            WHEN 1 THEN a.ID_SECONDARY
            ELSE NULL
    ) AS VALUE_1_DESC
    , MAX (
        CASE a.RNUM
            WHEN 2 THEN a.VALUE
            ELSE NULL
      ) AS VALUE_2
    , MAX (
        CASE a.RNUM
            WHEN 2 THEN a.ID_SECONDARY
            ELSE NULL
    ) AS VALUE_2_DESC
    , MAX (
        CASE RNUM
            WHEN 3 THEN a.VALUE
            ELSE NULL
      ) AS VALUE_3
    , MAX (
        CASE RNUM
            WHEN 3 THEN a.ID_SECONDARY
            ELSE NULL
    ) AS VALUE_3_DESC
    , MAX (
        CASE RNUM
            WHEN 4 THEN a.VALUE
            ELSE NULL
      ) AS VALUE_4
    , MAX (
        CASE RNUM
            WHEN 4 THEN a.ID_SECONDARY
            ELSE NULL
    ) AS VALUE_4_DESC
FROM a
GROUP BY a.ID, a.[DATE]


text:
Q: The type or namespace name "MyBindingLib" does not exist in the namespace (are you missing an assembly reference?) I have xamarin.ios binding project for ios library. When I reference it in some xamarin.ios project, it shows lots of errors like:
The type or namespace name "MyBindingLib" does not exist in the namespace (are you missing an assembly reference?)

Is there any possible workaround to get rid of it? (Except using "build only" option in error list window, which is useless for the actual code)
It compiles and works successfully, though.
Any help is appreciated. Thanks in Advance.

A: This sounds like a bug I filed a while ago:
https://bugzilla.xamarin.com/show_bug.cgi?id=42448
If so, the workaround is to reference the binding project's .dll instead of the binding project itself. IOW, build the binding project and then add a reference to that .dll from your X.iOS project.


text:
Q: sigqueue() to send a signal to process group I create process tree with fork() (about 3 child). I can easly send a signal to all of them by kill(-getpgrp(), signal_number), but how to do the same with sigqueue?
The sigqueue() function sends a signal to a process or a group of processes, they said, but unlike kill(), i can't use sigqueue() to send a signal to an entire process group by specifying a negative value in pid.
So how to do that ?
EDIT:
Code:
s1.c is a program where i "catch" the signals to take control over them.
So the couple of s1 ( with the same group id) waits for signal from sigqueue().
int main (int argc,char *argv[])
{

    int i=0;
    char *do=argv[1];
    int b=atoi(argv[2]);
    int y=fork();
    if(argc !=3)
    {
        printf("wrong arg number\n");
        exit(0);
    }

do{

switch(fork())
    {
    case -1:
            perror("error \n");
            exit(1);
            break;
    case 0:
            execl("s1","s1.c",argv[1],argv[2], NULL);
            break;
    default:
            sleep(2);
            break;
}
i++;
}
while(i<3);
    sleep(2);
    printf("ssignal %d send to gpid : %d\n",b,getpgrp());

    union sigval value;
    value.sival_int = 0;
    value.sival_ptr = 0;

    if(sigqueue(getpgrp(), b, value) == 0) {
            printf("signal sent successfully!!\n");
    } else {
            perror("SIGSENT-ERROR:");
    }
    return 0;

while(wait(0) != -1){}

return 0;
}

A: If your implementation does in fact support process group signaling in sigqueue, then you probably need to do exactly what you would do for the pid argument to kill:
sigqueue(-getprgp(), signo, value);  // Nonstandard. Remember to _negate_ the PGID
sigqueue(0, signo, value);           // Nonstandard. Shorthand to signal my own PGID

By the strict standard, however, you are out of luck.  sigqueue supports neither the null signal (0) nor the ability to signal groups of processes:

The standard developers required that sigqueue() have the same semantics with respect to the null signal as kill(), and that the same permission checking be used. But because of the difficulty of implementing the "broadcast" semantic of kill() (for example, to process groups) and the interaction with resource allocation, this semantic was not adopted. The sigqueue() function queues a signal to a single process specified by the pid argument.


text:
Q: PHP submit a form at every end of month automatically I have a form with hidden fields that i whant to submit every end of month (exemple: 30 September at 23:55) automatically without accessing the page and press a submit button. How i achieve this? Now my form is submitting only if i access the page and press the "Save" button.
My php code:
if(isset($_POST['btnSavee'])){
        $product_name = $_POST['product_name'];
        $percentage = $_POST['percentage'];
        $qty_reqliz = $_POST['qty_reqliz'];
        $trg_cantit = $_POST['trg_cantit'];
        $trg_val_realiz = $_POST['trg_val_realiz'];
        $agent_name = $_POST['agent_name'];
        $agent_id = $_POST['agent_id'];
        $the_bonus = $_POST['the_bonus'];
        $realizat_total = $_POST['realizat_total'];
        $prod_over_60 = $_POST['prod_over_60'];

        // create array variable to handle error
        $error = array();

        for($i=0;$i<count($product_name);$i++) {
            if($product_name[$i]!="" && $percentage[$i]!="") {

                $sql_queryes = "INSERT INTO tbl_stats_history (Product_name, Percentage, Qty_realiz, Trg_cantit, Trg_val_realiz, Ag_name, Ag_id)
                            VALUES(?, ?, ?, ?, ?, ?, ?)";

                $stmtes = $connect->stmt_init();
                if($stmtes->prepare($sql_queryes)) {
                    $stmtes->bind_param('sssssss',
                        $product_name[$i],
                        $percentage[$i],
                        $qty_reqliz[$i],
                        $trg_cantit[$i],
                        $trg_val_realiz[$i],
                        $agent_name[$i],
                        $agent_id[$i]
                    );
                    // Execute query
                    $stmtes->execute();
                    // store result
                    $resultest = $stmtes->store_result();
                    $stmtes->close();
                }

                if($resultest){
                    $error['update_data'] = "

                                                    Date salvate cu succes!

";
                    }else{
                        $error['update_data'] = " ".$stmtes->error."";
                    }
            }
        }

        $sql_querye = "INSERT INTO tbl_stats_bonus (Bonus, Realiz_total, Prod_over_60, Age_id)
                            VALUES(?, ?, ?, ?)";

                $stmts = $connect->stmt_init();
                if($stmts->prepare($sql_querye)) {
                    $stmts->bind_param('ssss',
                        $the_bonus,
                        $realizat_total,
                        $prod_over_60,
                        $ID
                    );
                    // Execute query
                    $stmts->execute();
                    // store result
                    $resulte = $stmts->store_result();
                    $stmts->close();
                }
    }

And my html form (it is with submit button):

<form method="post">
  <input class="form-control" name="product_name[]" value="Prod1" type="hidden" />
  <input class="form-control" name="product_name[]" value="Prod2" type="hidden" />
  <input class="form-control" name="percentage[]" value="50%" type="hidden" />
  <input class="form-control" name="percentage[]" value="12%" type="hidden" />
  <button class="btn bg-green btn-primary waves-effect pull-right" type="submit" name="btnSavee">Save</button></form>

A: You need to be learn cron job for automatic work in php after some time.
you can see this question also..


text:
Q: log4j:WARN Please initialize the log4j system properly. not working The log4j setting does not work. I don't know why.
The current tomcat war structure is as follows:
drwxr-x--- 6 root root      4096 2022-09-21 10:32 ROOT
-rw-r----- 1 root root 221852486 2022-09-21 10:30 admin
drwxr-x--- 6 root root      4096 2022-09-21 12:12 api
-rw-r----- 1 root root 125701373 2022-09-21 12:11 ROOT.war
drwxr-x--- 4 root root      4096 2022-09-21 10:32 admin.war
-rw-r----- 1 root root  38811606 2022-09-21 10:31 api.war

The log4j setting information is as follows:
web.xml
<listener>
    <listener class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

<context-param>
    <param-name>log4jExposeWebAppRoot</param-name>
    <param-value>api.root</param-value>
</context-param>
<context-param>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>300000</param-value>
</context-param>
<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:/config/log/log4j.xml</param-value>
</context-param>

log4j.xml
<logger name="jdbc.sqlonly">
    <level value="info" />
    <appender-ref ref="console" />
</logger>
<logger name="jdbc.connection">
    <level value="off" />
    <appender-ref ref="console" />
</logger>
<logger name="jdbc.sqltiming">
    <level value="off" />
    <appender-ref ref="console" />
</logger>
<logger name="jdbc.resultsettable">
    <level value="info" />
    <appender-ref ref="console" />
</logger>
<logger name="jdbc.resultset">
    <level value="off" />
    <appender-ref ref="console" />
</logger>
<logger name="jdbc.audit">
    <level value="off" />
    <appender-ref ref="console" />
</logger>

No matter how hard I try, it just says I can't find the location.
I think the war file located in Tomcat is the problem, is there any way to solve the problem?


text:
Q: Warning: implicit declaration of function 'calloc' #include<stdio.h>

int *arr;

int main()
{
   arr = calloc(1, sizeof(int));

   free(arr);
   return 0;
}

As far as I understand, this warning occurs because I did not declare the function in header (In this case I should've included stdlib.h). My questions are:

*

*Why doesn't the GCC give an error? Because as far as I understand, calloc is located at stdlib.h, but I didn't include it in my program. Why does my program still know what is calloc?

*Should we close our eyes at the warning? Because my program works well even without include of stdlib.h.

A:
As far as I understand, this warning occurs because I did not declare the function in header (In this case I should've included <stdlib.h>).

You are correct. The compiler complains that you are calling a function for which it has not seen a declaration. Including <stdlib.h> does provide a proper declaration for the function calloc.  Note that you could also have provided a declaration yourself by adding the line: void *calloc(size_t, size_t);. Yet it is recommended to use the standard include files to get the exact declarations for library functions.

Why doesn't the GCC give an error?

Because the compiler is lenient in order to compile older programs that were written before the C Standard was even published. It used to not be an error to call functions without a declaration or a definition in scope. The compiler would just infer the prototype from the types of the arguments provided. In your case the prototype is inferred as int calloc(int, size_t), which is obviously incorrect and will cause undefined behavior.  To avoid such problems, the compiler issues a warning about calloc being undeclared.

Why does my program still know what is calloc?

It does not, the prototype is inferred from the call statement and this guess falls short.  As a matter of fact, the compiler should also complain about the int return value being implicitly converted to an int * when stored to arr.  If int * and int have a different representation on the target system (as is the case on 64-bit systems), the value of arr will be invalid and free(arr) will definitely have undefined behavior too.
The compiler produces an executable because the function calloc is found in the C library, which is linked to all C programs implicitly. The argument and return types are not checked at link time for C programs.

Should we close our eyes at the warning?

Definitely not. You should compile your program with all warnings enabled using gcc -Wall -Wextra -Werror, and gcc will consider all warnings like fatal errors and refuse to produce an executable until they are corrected.  This will save you many hours of debugging time. It is a pity this behavior is not the default one.

my program works well even without include of <stdlib.h>.

Well it appears to work on your system, but it fails on mine (assuming I remove my default compiler options that prevent gcc from making an executable). The program has undefined behavior.  Do not rely on chance.
Here is a proper version:
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = calloc(1, sizeof(*arr));  /* use object type for consistency */

    printf("pointer value is %p\n", (void *)arr);

    free(arr);
    return 0;
}

A: *

*The function is not located at stdlib.h, it is in the same shared library object, libc.so so your linker has no problem finding the symbol. If you tried to call a made up function, you also wouldn't get a compiler error, rather your linker would complain about being unable to resolve a symbol.

*You technically can, but you absolutely shouldn't. If you wouldn't you wouldn't be warned about argument errors. The Linker does not (and can not) check, if you supplied the right amount and types of arguments.
Example:
// a.c
int asdf(int b){
   return b+1;
}

// main.c
int main(void) {
   asdf();
   return 0;
}

If you compile now: gcc main.c a.c
You will only get a warning, while if you had included a header you would get an error. This is BAD, since it can lead to undefined behavior that can lead to unexpected crashes, memory corruption, security issues, etc.
You should always give your compiler a fair opportunity to help you.
EDIT: Clarify, that ignoring is bad

A: calloc is not in stdlib.h. Nothing is in stdlib.h. Nothing is in any .h (or nothing should).
What is in stdlib.h is just (about calloc I mean)
extern void *calloc(size_t nmemb, size_t size);

calloc is in the libc. That is where your program will find it when it will call it.
Strictly speaking, you don't need anything else (I mean, from an execution point of view) to be able to call a function.
All .c codes are compiled to do their task. libc has been compiled long ago. And at linking time (for static libraries, and for dynamic to point to them) and then at run time, all functions from all compiled code are loaded. So your main from your code and calloc will find each other at that time.
The problem is not there.
The problem is that in order to compile your main, the compiler need to know how calloc is supposed to be called.
It needs to know it to check for syntax error. Otherwise you could pass 3 arguments, or only one, to calloc, and the compiler would have no way to know that this is not correct.
You could pass arguments of the wrong type, and likewise.
It needs to know also to know how many bytes it is supposed to push as an argument, and even how it is supposed to pass arguments.
See for example these two codes
one.c
#include <stdio.h>

void printInt(int a, int b){
    printf("ints %d %d\n", a, b);
}

void printFloat(float a, float b){
    printf("floats %f %f\n", a, b);
}

void printDouble(double a, double b){
    printf("doubles %f %f\n", a, b);
}

two.c
#include <stdio.h>
int main(void) {
    printInt(1,2);
    printInt(1.0, 2.0);

    printFloat(1,2);
    printFloat(1.0,2.0);

    printDouble(1,2);
    printDouble(1.0,2.0);
}

Compile them with (depending on your compiler)
gcc -std=gnu99 -o main one.c two.c # There is an implicit -lc here including libc, that contains printf

On my computer it prints
ints 1 2
ints 1034078176 -2098396512
floats 0.000000 0.000000
floats 0.000000 0.000000
doubles 0.000000 0.000000
doubles 1.000000 2.000000

See that it works as intended only for printInt called with ints, and printDouble called with doubles. It fails to cast 1.0 as an int to call printInt, or on the contrary to cast 1 as a double to call printDouble. And For printFloat it fails in all cases, because the compiler assumed wrongly the size of the arguments to be pushed.
But other than that, those 3 functions are called. It is not the the code of the function that is missing. It is the ability of the compiler, when calling them, to call them correctly.
Just add, in two.c the declarations
extern void printInt(int, int);
extern void printFloat(float, float);
extern void printDouble(double, double);

(Or create a one.h containing those, and #include "one.h" in two.c, it leads to the same result)
And now the output is as expected
ints 1 2
ints 1 2
floats 1.000000 2.000000
floats 1.000000 2.000000
doubles 1.000000 2.000000
doubles 1.000000 2.000000

And I haven't even started with types declarations.
#include are not meant to provide libraries, and the functions that are in them. That you do while linking, adding .o and -lsomelib to the liking command line (or using other way, depending on your compiler).
#include are there to provide codeless declarations that the compiler needs to know how to call those functions.

A:

*

*Why doesn't the GCC give an error? Because as far as I understand, calloc is located at stdlib.h, but I didn't include it in my program. Why does my program still know what is calloc?

For compatibility with legacy code, this is not an error, so compilation cannot be aborted, and so, you get a warning instead.  In old legacy C code, you can use a function without a declaration if it returns an int result (which is assumed if you don't specify a prototype for the function).  Old K&R code is still valid in C98 (I cannot ensure about later standard editions, but at least I have tested K&R code and it compiles with at most some warnings that can be ignored) and so it must be compiled into working code (but still probably invalid code, as the code generated to call calloc will consider an int is being returned---while calloc indeed returns a void * pointer type, which in 64bit architectures is 64bit)
Just try this code, and see :)
main(argc, argv)
char **argv;
{
    int i;
    char *sep = "";
    for (i = 0; i < argc; i++) {
        printf("%s[%s]", sep, *argv++);
        sep = ", ";
    }
    puts("");
}

The code above compiles without any problem in a pdp11 runing unix v7 (just tested before posting) and in gcc last version.  Is shows you the argv command parameter list on stdout.
$ make pru$$
Make:  Don't know how to make pru31.  Stop.
[tty2]lcu@pdp-11 $ cc -o pru$$ pru$$.c
[tty2]lcu@pdp-11 $ pru$$ a b c d e f
[pru31], [a], [b], [c], [d], [e], [f]
[tty2]lcu@pdp-11 $

This is pdp11/45 UNIX(tm) V7
(C) 1978 AT&T Bell Laboratories.  All rights reserved.

Restricted rights: Use, duplication, or disclosure
is subject to restrictions stated in your contract with
Western Electric Company, Inc.

login:

*Should we close our eyes at the warning? Because my program works well even without include of stdlib.h.

I think you should never close your eyes at any warning.  If you just #include <stdlib.h>, the compiler will compile correctly the source code without a warning.  The important thing about warnings is that YOU SHOULD READ THEM, AND UNDERSTAND THEM (and the consequences of ignoring them) BEFORE CONTINUING.  A waning is just an advisory message, it doesn't interrupt the compilation because this can be the intended purpose of the compiler run (simply to compile old, legacy code, that will produce a valid program, but written a long time ago)
In the case above, you had better to do the proper #include <stdio.h>, because if you don't, your code will be erroneous.  It will assume the calloc() function returns an int (which is not the same size in 64bit architectures) and the value will probably will be a truncated pointer (a pointer in which some part of it has been truncated by the conversion to an int) and will not work (but this happens recently, with 64bit architectures, it was fine on 32bit ones, incorrect but working)  So, you can obey or disobey, but you are on your own.


text:
Q: Incrementing nested list in multiprocessing manager from multiprocessing import Manager
manager = Manager()

managerdict = manager.dict()

managerdict["first"]= {"stat" : [0,1]}

managerdict["first"]["stat"][0] += 1
managerdict["first"]["stat"][1] += 1

print(managerdict)

anotherdict = {}
anotherdict['foo'] = {"stat" : [0, 1]}
anotherdict['foo']["stat"][0] += 1
anotherdict['foo']["stat"][1] += 1

print(anotherdict)

Which outputs:
{'first': {'stat': [0, 1]}}
{'foo': {'stat': [1, 2]}}
What am I doing wrong?
The First entry never gets incremented.
Whereas a normal dict does.
I have tried various other entities like switching the nested list to a nested dict.All the same.
Seems to be an old known issue: https://bugs.python.org/issue6766

A: I guess the manager.dict() has some tricks to monitor item assignments (i.e. directly getting, setting, deleting keys of the dict)
But, as you found out, they aren't able to watch for changes to nested data structures within the managed dict.
This suggests you need to do something like this:
# get a reference to the data structure you want to update
inner_data = managerdict["first"]
# update the data
inner_data["stat"][0] += 1
inner_data["stat"][1] += 1
# assign it back to the managed dict:
managerdict["first"] = inner_data
# now you can observe it updated
print(managerdict)

{'first': {'stat': [1, 2]}}


text:
Q: SQL server partitioning I have a table that has millions of records and we are looking at implementing table partitioning. Looking at it we have a foreign key "GroupID" that we would like to partition on. Is this possible?
The Group will have more entries added to it, so as new GroupID's are added can the partition's be made dynamically?

A: Yes you can use partitioning, yes new partitions can be made dynamically.  It's easiest to use a partitioning scheme that does not need to be updated though.
SQL Enterprise 2005 & up:
SQL 2005 and up has built in transparent support for partitioning if you are using SQL development edition or enterprise edition. Dynamically adding more partitions means that you'd have to create a new partitioning function, new partition schemes and probably new file groups.
You can alter a partition function by using SPLIT:
ALTER PARTITION FUNCTION MyPartitionFunction ()
SPLIT RANGE (2);

SQL 2000 or SQL 2005 & up non-enterprise:
Otherwise you can still use partitioning but you need to do it the old MS SQL 2000 way.  In the old way  you have to physically create many tables, and then a view that is a UNION ALL of each of the tables.  So you need knowledge of the schema before hand.
The good news about the old partitioning way is it's even easier to create new partitions dynamically.  You just need to create a new table with a new constraint and update your view.
There are some limitations though, your partitioning column must be part of your primary key.  And to do inserts directly into your View you'll need to NOT have an Identity column (one that is auto incremented by MS SQL)

A: Group ID may not be the best item to partition on, partitioning suits a rolling window effect and is designed more for removing of outdated data and the rolling in of new data.
By Grouping on ID you only allow yourself to add / remove groups, e.g. no element of time / longevity of data. There is also a hard limit of 1000 partitions per parrtitioned table, limiting you to 1000 groups. Since you intend on add group ID's and it is not indicated as a static number you will potentially hit this hard limit.
The only option to extend that limit of 1000 is to place a partitioned view across multiple partitioned tables.
The question I would ask is what causes new data to be added / older data to be removed and on what basis is that made. Just because the table is millions of rows does not make it an immediate candidate for partitioning, which is why I would ask the question.
In terms of dynamically adding them - that feature does not exist you would have to write the stored procedures and logic to handle the allocation of new filegroups / set next used and splitting of the partition function. It can be done, but SQL is not going to do it for you.


text:
Q: Is there any method to justify text in Unity 2D? I need to add a text field in my unity scene with the justified alignment. But the problem is that I'm not getting any syntax of the method to justify the text in unity 2D. Need your help!

A: Just use TextMeshPro for 2d TextMeshPro inspector settings
There is the link to text mesh pro manual TextMesh Pro Manual


text: Q: Fetch notifications by using spring-social I am developing an application to fetch comments,notifications,updates etc of a user from Facebook by using spring-social.But I am not getting any api to fetch notifications of the user.


text:
Q: how to had conditional class in a method helper? I'd like to had a conditional class in a method helper
product_helper.rb
def product_icon
  ...
  elsif product.sent?
    '<div class="green-text  <%= 'middle' if current_action?(controller: 'products', action: 'index')" %> >
'.html_safe
end

But I get this ERROR :
syntax error, unexpected keyword_class, expecting keyword_end
 '<div <%= 'class="middle if current_acti...
                  ^

A: You are in the helper, so you cannot use <%= ... %> but need to use #{....}
Your helper should return this:
return "<div class='green-text <%= 'middle' if current_action?(controller: 'products', action: 'index')'%>>
".html_safe


text:
Q: oAuth1.0a doesn't work for wordpress API from Python using requests, although call works from Postman I am fairly new to programming and Python and I tried to POST to the wordpress REST API with OAuth1.0a to create a post to my blog.
In Postman it all works well, so the credentials are ok. But my Python code below returns 401 - rest_cannot_create.
I have been trying to make this work for 5 hours now. I hope you can help a newbie!
Thank you!
import requests
from requests_oauthlib import OAuth1
import json

url = "https://example.com/wp-json/wp/v2/posts/"
oauth_consumer_key = "1234567"
oauth_consumer_secret = "ABCDEFG"
oauth_token = "9876543"
oauth_token_secret = "HIJKLMNOP"

auth = OAuth1(oauth_consumer_key, oauth_consumer_secret, oauth_token, oauth_token_secret)

post = {'date': '2017-06-19T20:00:35',
        'title': 'Testing API via Python',
        'slug': 'rest-api-1',
        'status': 'draft',
        'content': 'this is the content post',
        'excerpt': 'this is the excerpt',
        'format': 'standard',
        'author': "1"
        }

r = requests.post(url, auth=auth, json=post)
print(json.loads(r.content))

A: I had to replace the last two lines with the following and it worked for me -
r = requests.post(url, auth=auth, data=post)
  print(r.content)


text:
Q: How to correctly use the Scatter-Gather pattern? I am still pretty new when it comes to Spring Integration, I am trying to use IntetrationFlowDefinition.scatterGather() with no avail. The general idea is to:

*

*take a String as an input

*use a splitter to tokenize it using the space character

*send each token to a set of services, each returning a value

*aggregate responses from each service

*aggregate previously aggregated responses to a List

*transform the list to a single String
I am using a messaging gateway as my input/output:
@MessagingGateway(name = "gateway")
public interface TestGateway {

  @Gateway(requestChannel = "input")
  String process(String input);

}

and invoking it via:
final TestGateway gateway = (TestGateway) ctx.getBean("gateway");
System.out.println(gateway.process("this is a test"));

My IntegrationFlows are:
@Bean
public IntegrationFlow soutFlow() {
  return f -> f.handle(m -> System.out.println(m.toString()));
}

@Bean
public IntegrationFlow flow() {
  return IntegrationFlows.from("input")
    .split(s -> s.delimiters(" "))
    .wireTap(soutFlow())
    .scatterGather(
      sc -> sc.recipientFlow(m -> true, f1 -> f1.handle((p, h) -> p + " - flow 1").wireTap(soutFlow()))
        .recipientFlow(m -> true, f2 -> f2.handle((p, h) -> p + " - flow 2").wireTap(soutFlow()))
        .applySequence(true),
      ga -> ga.outputProcessor(mg -> mg.getMessages()
        .stream()
        .map(m -> m.getPayload().toString())
        .collect(Collectors.joining(", "))),
      sg -> sg.gatherTimeout(1_000))
    .wireTap(soutFlow())
    .aggregate()
    .wireTap(soutFlow())
    .transform((List<String> source) -> source.stream()
      .map(s -> "- " + s)
      .collect(Collectors.joining("\n")))
    .get();
}

I am expecting to see output formatted as something like this:
- this - flow 1, this - flow 2
- is - flow 1, is - flow 2
- a - flow 1, a - flow 2
- test - flow 1, test - flow 2

Unfortunately, this doesn't work and gatherer always times out after 1 second. Wire-tapping debug output shows the following messages:
GenericMessage [payload=this, headers={replyChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceNumber=1, errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceSize=4, correlationId=7c9653a7-55eb-72e4-ff74-62b10782cc3b, id=6c81a1ce-9a7c-83c3-3b69-7fb2f8b3112c, timestamp=1538668173435}]
GenericMessage [payload=this - flow 1, headers={replyChannel=org.springframework.integration.channel.FixedSubscriberChannel@78aea4b9, sequenceNumber=1, gatherResultChannel=ac418949-6ade-4db5-bd4c-3cbbbb7e9a49:1, sequenceDetails=[[7c9653a7-55eb-72e4-ff74-62b10782cc3b, 1, 4]], errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceSize=2, correlationId=8d29aea7-3ec7-2c15-5b92-fbb0af002a3f, id=7ca4de30-f801-ad14-6452-249c85e9ab36, timestamp=1538668173446}]
GenericMessage [payload=this - flow 2, headers={replyChannel=org.springframework.integration.channel.FixedSubscriberChannel@78aea4b9, sequenceNumber=2, gatherResultChannel=ac418949-6ade-4db5-bd4c-3cbbbb7e9a49:1, sequenceDetails=[[7c9653a7-55eb-72e4-ff74-62b10782cc3b, 1, 4]], errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceSize=2, correlationId=8d29aea7-3ec7-2c15-5b92-fbb0af002a3f, id=71b22112-8e7b-c2c5-057f-2a91c49af8c8, timestamp=1538668173446}]
GenericMessage [payload=is, headers={replyChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceNumber=2, errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceSize=4, correlationId=7c9653a7-55eb-72e4-ff74-62b10782cc3b, id=9da2f181-82de-d50e-51bb-229a3e32b998, timestamp=1538668174448}]
GenericMessage [payload=is - flow 1, headers={replyChannel=org.springframework.integration.channel.FixedSubscriberChannel@78aea4b9, sequenceNumber=1, gatherResultChannel=ac418949-6ade-4db5-bd4c-3cbbbb7e9a49:2, sequenceDetails=[[7c9653a7-55eb-72e4-ff74-62b10782cc3b, 2, 4]], errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceSize=2, correlationId=0abfd6a8-713d-e0cb-bc59-a111a85429df, id=d5102417-f6c2-cbac-197a-b9c4f3f51a74, timestamp=1538668174448}]
GenericMessage [payload=is - flow 2, headers={replyChannel=org.springframework.integration.channel.FixedSubscriberChannel@78aea4b9, sequenceNumber=2, gatherResultChannel=ac418949-6ade-4db5-bd4c-3cbbbb7e9a49:2, sequenceDetails=[[7c9653a7-55eb-72e4-ff74-62b10782cc3b, 2, 4]], errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceSize=2, correlationId=0abfd6a8-713d-e0cb-bc59-a111a85429df, id=d9b31390-d3d1-9b61-43fc-45c06ac86931, timestamp=1538668174449}]
GenericMessage [payload=a, headers={replyChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceNumber=3, errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceSize=4, correlationId=7c9653a7-55eb-72e4-ff74-62b10782cc3b, id=f109f368-6859-ac8d-0e0c-3beb563f9594, timestamp=1538668175451}]
GenericMessage [payload=a - flow 1, headers={replyChannel=org.springframework.integration.channel.FixedSubscriberChannel@78aea4b9, sequenceNumber=1, gatherResultChannel=ac418949-6ade-4db5-bd4c-3cbbbb7e9a49:3, sequenceDetails=[[7c9653a7-55eb-72e4-ff74-62b10782cc3b, 3, 4]], errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceSize=2, correlationId=0e347381-a6e2-891a-72ff-c862565d6a1e, id=e0270063-6e19-5827-7674-21fa047ab11d, timestamp=1538668175451}]
GenericMessage [payload=a - flow 2, headers={replyChannel=org.springframework.integration.channel.FixedSubscriberChannel@78aea4b9, sequenceNumber=2, gatherResultChannel=ac418949-6ade-4db5-bd4c-3cbbbb7e9a49:3, sequenceDetails=[[7c9653a7-55eb-72e4-ff74-62b10782cc3b, 3, 4]], errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceSize=2, correlationId=0e347381-a6e2-891a-72ff-c862565d6a1e, id=b08aab99-10ce-4dac-2f3c-b48b4514fd35, timestamp=1538668175451}]
GenericMessage [payload=test, headers={replyChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceNumber=4, errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceSize=4, correlationId=7c9653a7-55eb-72e4-ff74-62b10782cc3b, id=52feeb27-8da4-70c4-889e-f482d2922e40, timestamp=1538668176453}]
GenericMessage [payload=test - flow 1, headers={replyChannel=org.springframework.integration.channel.FixedSubscriberChannel@78aea4b9, sequenceNumber=1, gatherResultChannel=ac418949-6ade-4db5-bd4c-3cbbbb7e9a49:4, sequenceDetails=[[7c9653a7-55eb-72e4-ff74-62b10782cc3b, 4, 4]], errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceSize=2, correlationId=53e7fd2c-d3a4-0c0a-1296-2a14ef5e90ab, id=9152e603-e436-c0a4-abde-1f7e5ae654bf, timestamp=1538668176454}]
GenericMessage [payload=test - flow 2, headers={replyChannel=org.springframework.integration.channel.FixedSubscriberChannel@78aea4b9, sequenceNumber=2, gatherResultChannel=ac418949-6ade-4db5-bd4c-3cbbbb7e9a49:4, sequenceDetails=[[7c9653a7-55eb-72e4-ff74-62b10782cc3b, 4, 4]], errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@649725e3, sequenceSize=2, correlationId=53e7fd2c-d3a4-0c0a-1296-2a14ef5e90ab, id=a7357efd-d34a-6a05-159e-5860e3bc5281, timestamp=1538668176454}]

I must be missing something obvious but Spring documentation is very scarce when it comes to good Java DSL examples.
UPDATE:
Using wireTap() does, in fact, affect the flow. I have removed it and set up some breakpoints. It appears that the gatherer is correctly processing the scattered and processed messages, the problem seems to be in sending them further down the stream. The exception is:
org.springframework.messaging.MessagingException: Failed to handle Message; nested exception is org.springframework.messaging.core.DestinationResolutionException:
 failed to look up MessageChannel with name '27cf1bec-7e06-424e-80f8-9f2f67ebaf87:2' in the BeanFactory.;
 nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named '27cf1bec-7e06-424e-80f8-9f2f67ebaf87:2' available,
 failedMessage=GenericMessage [payload=is - flow 1, is - flow 2, headers={replyChannel=org.springframework.integration.channel.FixedSubscriberChannel@4bafe935, sequenceNumber=2, gatherResultChannel=27cf1bec-7e06-424e-80f8-9f2f67ebaf87:2, sequenceDetails=[[2baa7135-5c02-932f-6b5d-cfd4052a965b, 2, 4]], errorChannel=org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@87b5b49, sequenceSize=2, correlationId=c04f280d-83b7-74e9-a0a6-0f89efdf795c, id=ffec13cf-531e-0721-1484-e8b26b705330, timestamp=1538735548924}]

I would imagine that these intermediate channels would be created automatically by Spring when using IntegrationFlow. Is that not the case?

A: The problem is an incorrect/incorrectly set-up gatherer. My assumption was that if the input of the scatter-gather is a single String (a tokenized word), the output should also be a single String. Unfortunately, the aggregator created this way was not restoring sequence/correlation headers correctly causing the aggregator which is next in line to wait indefinitely to complete the group. Providing a null gatherer restores the default behavior. The downside is that the scatter-gather output is now a List. This can be easily mitigated by putting a transformer that flattens the list before the next aggregator. The working code below:
@Bean
public IntegrationFlow flow() {
  return IntegrationFlows.from("input")
    .split(s -> s.delimiters(" "))
    .scatterGather(
      sc -> sc
        .applySequence(true)
        .recipientFlow(m -> true, f1 -> f1.handle((p, h) -> p + " - flow 1"))
        .recipientFlow(m -> true, f2 -> f2.handle((p, h) -> p + " - flow 2")),
      null
    )
    .transform((List<String> l) -> l.stream().collect(Collectors.joining(", ")))
    .aggregate()
    .transform((List<String> source) -> source.stream()
      .map(s -> "- " + s)
      .collect(Collectors.joining("\n")))
    .get();
}

And the output is now exactly how it was expected to be:
- this - flow 1, this - flow 2
- is - flow 1, is - flow 2
- a - flow 1, a - flow 2
- test - flow 1, test - flow 2


text:
Q: How to enable email Autocomplete in Material UI React I have the following Material UI TextField to capture emails. However, when the user starts typing, emails on the browser are not been suggested as I thought. How can I ensure, email addresses on the browser are suggested as the user types in his/her email.
<OutlinedInput
                type="email"
                disabled={authStarted}
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="name@example.com"
                autoComplete={"on"} //This part isn't working
                className={classes.emailField}
            />