text:
Q: How to uppercase first letter (without changing the others) in Snowflake I am aware of INITCAP() and this similar question, but my question is different:
How can I uppercase the first letter only in a given string, and leave the rest of the string untouched?
INITCAP() can be made to uppercase the first letter only -- however, it will lowercase everything else, as mentioned in the documentation:

<delimiters> specified as an empty string (i.e. '') instructs INITCAP to ignore all delimiters, including whitespace characters, in the input expression (i.e. the input expression is treated as a single, continuous word). The resulting output is a string with the first character capitalized (if the first character is a letter) and all other letters in lowercase.

A: Managed to do it using a few string manipulations:
SELECT INSERT(my_string, 1, 1, UPPER(LEFT(my_string, 1)));

UPPER(LEFT(my_string, 1)) will extract the first letter of the string, and uppercase it.
INSERT() will replace a portion of the string with something else -- in this case, the first letter will be replaced with its uppercase version.

A: another option is
UPPER(LEFT(my_string,1))||SUBSTR(my_string,2)
and if we use the same whitespace pattern, would win the code golf by 1:
INSERT(my_string,1,1,UPPER(LEFT(my_string,1)))


text:
Q: Find the parent of a javascript tree object array Find the bellow parent child tree object I have created. I need to find the root parent of a given child id. For example child id - 242 root parent id is 238. There are similar questions have been asked and this is the one I found very similar to my question.
Convert parent-child array to tree
I have change the original code a bit But not working for child element. The issue is here. when it comes the recursive function with rootNode.children for loop will not execute since it does not loop through children. But if I change the for loop  for (var i = 0; i < rootNode.length; i++)  to for (var i = 0; i < rootNode.children.length; i++) then it break on first loop since does not have children. I'm sure with small code change this can make work.

var getParent = function (rootNode, rootId) {

if (rootNode.id === rootId)
    return rootNode;

//for (var i = 0; i < rootNode.children.length; i++) -- original code line not working first time
for (var i = 0; i < rootNode.length; i++) {
    var child = rootNode[i];
    if (child.id === rootId)
        return child;

    if (typeof child.children !== 'undefined')
        var childResult = getParent(child, rootId);

    if (childResult != null) return childResult;
}
return null;
};

var mytree = [
{
    "id": 245,
    "parent": "0",
    "title": "project1",
    "children": [
        {
            "id": 246,
            "parent": "245",
            "title": "sub task 1"
        }
    ]
},
{
    "id": 238,
    "parent": "0",
    "title": "project2",
    "children": [
        {
            "id": 240,
            "parent": "238",
            "title": "sub task 2"
        },
        {
            "id": 242,
            "parent": "238",
            "title": "sub task 3",
            "children" : [
                {
                    "id": 241,
                    "parent": "242",
                    "title": "sub task 3.1"
                }
            ]
        }
    ]
},
{
    "id": 173,
    "parent": "0",
    "title": "project3"
}
];
console.log(JSON.stringify(getParent(mytree, 238)['title']));
console.log(JSON.stringify(getParent(mytree, 241)));

A: You need to iterate the given root node, because this is an array, not an object.

function getParent(root, id) {
    var node;

    root.some(function (n) {
        if (n.id === id) {
            return node = n;
        }
        if (n.children) {
            return node = getParent(n.children, id);
        }
    });
    return node || null;
}

var mytree = [{ id: 245, parent: "0", title: "project1", children: [{ id: 246, parent: "245", title: "sub task 1" }] }, { id: 238, parent: "0", title: "project2", children: [{ id: 240, parent: "238", title: "sub task 2" }, { id: 242, parent: "238", title: "sub task 3", children: [{ id: 241, parent: "242", title: "sub task 3.1" }] }] }, { id: 173, parent: "0", title: "project3" }];

console.log(getParent(mytree, 238));
console.log(getParent(mytree, 241));
.as-console-wrapper { max-height: 100% !important; top: 0; }

More a classical attempt

function getParent(root, id) {
    var i, node;
    for (var i = 0; i < root.length; i++) {
        node = root[i];
        if (node.id === id || node.children && (node = getParent(node.children, id))) {
            return node;
        }
    }
    return null;
}

var mytree = [{ id: 245, parent: "0", title: "project1", children: [{ id: 246, parent: "245", title: "sub task 1" }] }, { id: 238, parent: "0", title: "project2", children: [{ id: 240, parent: "238", title: "sub task 2" }, { id: 242, parent: "238", title: "sub task 3", children: [{ id: 241, parent: "242", title: "sub task 3.1" }] }] }, { id: 173, parent: "0", title: "project3" }];

console.log(getParent(mytree, 238));
console.log(getParent(mytree, 241));
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: I think my js tools can help you
https://github.com/wm123450405/linqjs

var mytree = [
{
    "id": 245,
    "parent": "0",
    "title": "project1",
    "children": [
        {
            "id": 246,
            "parent": "245",
            "title": "sub task 1"
        }
    ]
},
{
    "id": 238,
    "parent": "0",
    "title": "project2",
    "children": [
        {
            "id": 240,
            "parent": "238",
            "title": "sub task 2"
        },
        {
            "id": 242,
            "parent": "238",
            "title": "sub task 3",
            "children" : [
                {
                    "id": 241,
                    "parent": "242",
                    "title": "sub task 3.1"
                }
            ]
        }
    ]
},
{
    "id": 173,
    "parent": "0",
    "title": "project3"
}
];
//node.asEnumerable get a Tree object
//isAncestorOf to predicate the root node is or not the ancestor node of parameter
console.log(mytree.find(node => node.asEnumerable(node => node.children, node => node.id).isAncestorOf(241)));
console.log(mytree.find(node => node.asEnumerable(node => node.children, node => node.id).isAncestorOf(242)).title);
<script src="https://wm123450405.github.io/linqjs/libs/linq-js.min.js"></script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Neural Network Architecture for Graph Inputs I have an undirected graph with edges of equal distance with 7 features per node. I want to train a Neural Network with this graph as an input and output a scalar. What network architecture do I need for my network to analyse the graph locally (for example, a node and it's neighbours) and to generalise, much like Convolutional Neural Networks operate on grid data. I have heard of Graph Neural Networks however I don't know if this is what i'm looking for. Will it be able to analyse my graph much like a CNN does with an image, sharing the generalisation benefits that convolution kernels bring?
I want to implement the solution in TensorFlow, ideally with Keras.
Thank you

A: The performance will most likely depend on the exact output that you're hoping to get. From your description a 2D-CNN should be good enough and easier to implement with Keras than a GNN.
However, there are some advantages to retaining the graph structure from your data. I think this is too much to present here, but you can find a proper explanation on "Spatio-Temporal Analysis and Prediction of Cellular Traffic in Metropolis" by Wang et al.
This paper also has the benefit of describing data processing to input into the network.
If you don't want to use basic Keras models to assemble your own GNN you may also want to take a look at Spektral, which is a python library for graph deep learning.
Without any other constraints I would firstly use a CNN, because it will be faster to implement with almost ready to use models from Keras.


text:
Q: 3 or more *consecutive* layout passes to prepare to be shown. Error When I open an NSPopover I am getting the following error:
WARNING: <NSPopover: 0x618000120780> needed 3 or more *consecutive* layout
passes to prepare to be shown. Verify that nothing in your view hierarchy
is aggressively dirtying layout during layout, as this will likely
cause problems elsewhere.

This has only just started appearing in a recent build and I can not find what is causing it.  I have removed all prep code before the popover is shown so it basically calls:
- (IBAction)addClicked:(id)sender {

[[self addPopover] showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMaxYEdge];

}

I have removed all constraints from the window in IB too.  So I shouldn't be doing anything during layout that requires a repaint.
Searching the web comes up with very little info, what I could find anyway.  My popover is used for a form input so has 4 NSTextFields an NSOutlineView and an NSImage.  It also creates a hidden WebView which is not visible to the user and used for server processing.
OSX 10.7+
Any ideas?
Thanks
Geoff

A: if you ever get this error, I removed it by selecting the view effects inspector in IB and put a checkmark next to view (the entire popup view) for the Core Animation Layer. Now I can have square buttons with template images and no obscure warning.


text:
Q: Парсинг русского языка с веб Добрый вечер, произвожу пасрсинг данных на русском языке таким кодом
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
    buffer.append(line);
}
resultJson = buffer.toString();

При этом если установить эту строку в TextView, то вместо русских слов будут последовательности  из "�". Попробовал перевести из исходной(cp1251) кодировки в utf-8, но теперь просто вместо русских слов пробелы. Сам код
byte[] arr = resultJson.getBytes("cp1251") ;
Log.d("SMTH", resultJson);
String res = new String(arr, "utf-8");
resultJson = res;

Подскажите, как корректно перевести?

A: Указать кодировку для InputStreamReader при его создании:
new InputStreamReader(inputStream, "windows-1251")

Иначе в resultJson будет неправильно преобразованное значение с использованием кодировки по умолчанию. Восстановить данные вряд ли уже получится для не ASCII.

A: Можно сделать так
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(
          new InputStreamReader(inputStream, "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
    buffer.append(line);
}
resultJson = buffer.toString();


text:
Q: Display layout based on boolean from Vuex I got Vue2 app with vue-router with routings configured like that:
export default {
  path: "/",
  redirect: "/dashboard",
  component: AdminLayout,
  meta: {
    requiresAuth: true
  },
  children: [
    {
      path: "/dashboard",
      name: "Dashboard",
      component: Dashboard
    },
    {
      path: "/add/user",
      name: "InviteUser",
      component: InviteUser
    },
    {
      path: "/groups",
      name: "Groups",
      component: Groups
    },
   ...

In app, we got two different types of users - admin and normal user. Some of those routings should be accessible for both, but the problem is that user should see different layout base on its type (permission) - AdminLayout for admins and UserLayout for normal users.
Is there any way to show app which template should user see based on boolean from vuex with keeping route path?

*

*on /dashboard admin will see dashboard with AdminLayout

*on /dashboard normal user will see dashboard with UserLayout
My main routing cofig:
import Vue from "vue";
import VueRouter from "vue-router";

import SessionRoutes from "./session.js";
import AdminRoutes from "./admin.js";
import defaultRoutes from "./default";

Vue.use(VueRouter);

const routes = [AdminRoutes, SessionRoutes, defaultRoutes];

const router = new VueRouter({
  mode: "history",
  routes
});

export default router;

A: you can set a condition in the layout part on the current page for example for when you use nuxt:

but I opine you don't use Nuxt.js and I think below solution is suitable for your question:

*

*Using the meta-object in our route

*set dynamic component on app.vue page

*code for about.vue page

    import Home from '../views/Home.vue'
    import About from '../views/About.vue'
    import LayoutA from '../layouts/LayoutA.vue'
    import LayoutB from '../layouts/LayoutB.vue'
    Vue.use(VueRouter)
    const routes = [
      {
        path: '/',
        name: 'Home',
        component: Home,
        meta: { layout: LayoutA }
      },
      {
        path: '/about',
        name: 'About',
        component: About,
        meta: { layout: LayoutB }
      }
    ]
    const router = new VueRouter({
      mode: 'history',
      base: process.env.BASE_URL,
      routes
    })

    export default router;

<template>

    <component :is="this.$route.meta.layout || 'div'">
      <router-view />
    </component>

</template>

<template>

This is an about page

</template>

A: To get a different layout working for the dashboard and all child routes your layouts have to use the router view component. I use a wrapper component to handle this in one of my projects following this approach.
Excerpt from my router config:
…
  {
    component: MainFrame,
    name: 'main',
    path: '/',
    redirect: 'dashboard',
    children: [
      {
        alias: 'dashboard',
        component: Dashboard,
        name: 'dashboard',
        path: '', // Default child route → be equivalent to /dashboard
      },
      {
        path: "add/user",
        name: "InviteUser",
        component: InviteUser
      },
      {
        path: "groups",
        name: "Groups",
        component: Groups
      },
    ],
  },
…

In your MainFrame component you can wrap your layout in a dynamic component. So you can switch your layout easely based on a Vuex getter:
MainFrame.vue
<template>
  <component :is="layout">

  </component>
</template>

And your layouts have to use <router-view />. It works as a wrapper for all nested routes and therefore you have only one place to handle the layout for the dashboard and child pages:
AdminLayout.vue
<template>

    …
    …

      <transition name="fade" mode="out-in">
        <router-view />
      </transition>

    …

</template>

UserLayout.vue
<template>

    <router-view />

</template>

EDIT:
This approach can be used for deeper nesting too. Assuming your user route should have another child routes you can solve this on the router config using a <router-view /> within a render function:
…
      // Let's split down user related routes
      {
        component: { render: (h) => h('router-view') },
        name: 'usersView',
        path: 'users',
        redirect: 'ListUsers',
        children: [
          // Show users
          {
            path: '', // route: /users/
            name: 'ListUsers',
            component: ListUsers
          },
          // Show a single user
          {
            path: ':id', // route: /users/{userId}
            name: 'ViewUser',
            component: ViewUser
          },
          // Invite new users
          {
            path: 'add', // route: /users/add
            name: 'InviteUser',
            component: InviteUser
          },
        ]
      }
…


text:
Q: Cutting information correctly from a String in Java I'm reading a string in java from a .txt file says:
E 1 2 W1
(I'm having it in a string variable)
now I want to cut the information into 3 variables:
v1 = 1
v2 = 2
w = 1

problem is numbers could occupy more bytes in example:
E 12 204 W1
how do I easily take the 2nd, 3rd and 4th words into differents vars?

A: There are many solutions for this problem. Visit the String API to see all methods that can serve your needs.
I won't show you a full solution but I'll try to guide you.
If the pattern is fixed, you can easily write a method that splits the String and assign the second, third and fourth variables in a loop.
You can also build a regex that extracts the wanted fields for you, e.g. \d+\s+\d+\s+\w\d+.

A: If  this
E             12            204           W1
<token><space><token><space><token><space><token>
0              1            2             3

is your format, then you could just split your string using " " and get the elements with the index 1 and 2, from the element in index 3 remove the leading W

A:     String src = "E 12 204 W1";
    String[] numbers = src.split("\\D+");
    int v1 = Integer.parseInt(numbers[1]);
    int v2 = Integer.parseInt(numbers[2]);
    int w = Integer.parseInt(numbers[3]);

This particular version of split removes everything that's not a number. The first element (numbers[0]) is going to be an empty string so you can ignore it. The others will be the numbers, and only the numbers, so you can safely parse them into integers (unless you think there is a chance somebody will input a large number such as 98798765465498798798754, in which case you will get an exception and you should catch and handle it).


text:
Q: How to modify time format property mapping? I have a content search webpart on my SharePoint site, which I use for announcements. I would like it to show the date and time of creation, so I added a mapping that shows the date and time (see screen shot below) but the format is unfortunately not very good looking. How do I change the time format?

A: You could create a copy of the Content Search Web Part Display Template that you wanna use.
In the current site collection, go to Site Settings > under "Web Designer Galleries", click "Master pages and page layouts" > Display Templates > Content Web Parts > download a copy of "Item_Picture3Lines.html"
Open the file in notepad, notepad++ or any other text editor and change the Title so you can differ this display template from the others. A example can be <title>Custom Picture on left, 3 lines on right</title>
Scroll down to row 63 and find the following:
var line1Id = encodedId + "line1";
var line2Id = encodedId + "line2";
var line3Id = encodedId + "line3";
After these lines, add
var parseDate = new Date(line3.inputValue);
var line3Date = parseDate.format('ddd MMMM d HH:mm:ss');

keep scrolling down to row 113 and look at the end of the row before the closing div tag. Change _#= line3 =#_ to _#= line3Date =#_. Save the file as the same name you used on row 3.
Upload the HTML file to the same location from where you downloaded it. When the file has been uploaded, a javascript file should be created with the same name. Publish a major version of the HTML file and go back to the site where your content search web part is located.
Edit the web part properties and your new display template should show up under "Item". Select it and then change the property mappings, set "Created" or "DateCreated" in Line 3. Apply and save the page.

OR
You could take the easy way, by just creating a calculated column based on the Created column, or in your case DateCreated with the following formula:
=TEXT(Created, "ddd MMMM d HH:mm:ss")


text:
Q: AnkhSvn doesn't add files to SVN This is a known issue - when files are added using Ankh, they are not really added to SVN. Many a times this has caused problems, for instance when committing later through TortoiseSvn only to find missing files, or when creating a patch.
Is there a workaround, or some plans to fix this is a future Ankh release?
Edit - to clarify, when I commit using Ankh, the files are really added. But if the commit is not done using Ankh, the files are not added (unlike other SVN operations which do carry over).

A: I wouldn't say it's a "known issue", because it's not an issue in AnkhSVN in the first place:
First off all, when you commit the "new" files, they're added just in time for the commit. The reason for the "new" status vs the "added" status, is that it makes it easier/cheaper to do renames/moves, something that's very common for new files.
When you go to Tools -> Options -> Source Control -> Subversion Environment, there's a checkbox "Directly add new files to Subversion". This will automatically add new files right away, instead of giving them the "new" status.


text:
Q: Get a phone number from contacts I have a button that I click and that shows contacts. It displays the name, but not the number of a selected contact...
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, 1);
            }
        });
    }

    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            Uri contactData = data.getData();
            Cursor c = managedQuery(contactData, null, null, null, null);
            if (c.moveToFirst()) {
                String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                contactName.setText(name);

                Something here !!!!!!!!!!!!!!!!!!!!!!!!

                contactName.setText(number);
            }
        }
    }
}

It String the NAME but how can I get the phone number?
@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
        while (phones.moveToNext())
        {
            String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            contactName.setText(name);
            contactNumber.setText(number);
        }
    }

With this code it opens my contacts. I touch one, but it always display the LAST name and number that I have added to contacts.
For example, I touch Adrian (22222222) and it shows Paul (33333333) which is the last person that I have added.
What should I do?

A: String phoneNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));


text:
Q: Android Game GC Lag? How to fix It? I have created a small game and when I play it, I am experiencing very large lag spikes at certain intervals; When I look at the logcat output, I can see that the lag is caused by the garbage collector. Now I have adjusted my code to adhere with all the rules in regards to how to formulate for loops to not create garbage, and I have created all of the objects before the game starts. However, the lag is still present.
I look at games like Flappy Bird, and it has no lag whatsoever despite its simplicity. What am I doing wrong?
I'll post code if need be.
Here is the Collision code:
branchesSize = Level.branches.size();
    for (int x = 0; x < branchesSize; ++x) {
        if (yPos <= Level.branches.get(x).yPos
                + Level.branches.get(x).height
                && yPos >= Level.branches.get(x).yPos) {
            if (xPos <= Level.branches.get(x).xPos
                    + Level.branches.get(x).width
                    && xPos >= Level.branches.get(x).xPos) {
                // DEATH
                death();
            }
        }

        if (yPos + height / 2 >= Level.branches.get(x).yPos
                && yPos + height / 2 <= Level.branches.get(x).yPos
                        + Level.branches.get(x).height) {
            if (xPos + width <= Level.branches.get(x).xPos
                    + Level.branches.get(x).width
                    && xPos + width >= Level.branches.get(x).xPos) {
                // DEATH
                death();
            }
        }

        if (yPos >= Level.branches.get(x).yPos
                && yPos <= Level.branches.get(x).yPos
                        + Level.branches.get(x).height) {
            if (xPos + width <= Level.branches.get(x).xPos
                    + Level.branches.get(x).width
                    && xPos + width >= Level.branches.get(x).xPos) {
                // DEATH
                death();
            }
        }

        // Collect Nuts
        nutsSize = Level.nuts.size();
        for (int y = 0; y < nutsSize; ++y) {
            if (yPos <= Level.nuts.get(y).yPos) {
                nuts += 1;
                Level.nuts_available.add(Level.nuts.get(0));
                Level.nuts.remove(0);
                nutsSize -= 1;
            }
        }
    }

A: You should take a heap dump of your program and analyze it using MAT or JHAT and see what is your memory filled with when there is a lot of memory usage,


text:
Q: Spring Integration DefaultFtpsSessionFactory This configuration worked perfectly for me before we upgraded the spring boot to 2.4.2 version.
    DefaultFtpsSessionFactory sessionFactory = new DefaultFtpsSessionFactory();
    sessionFactory.setHost("host");
    sessionFactory.setUsername("username");
    sessionFactory.setPassword("password");
    sessionFactory.setPort(21);
    sessionFactory.setClientMode(FTPClient.PASSIVE_LOCAL_DATA_CONNECTION_MODE);
    sessionFactory.setControlEncoding("UTF-8");

Currently I am facing following exception :
javax.net.ssl.SSLException: Unsupported or unrecognized SSL message
I was not able to find anything in the documentation.
Thanks for answers.
Edit 1#:
@ArtemBilan here, is the stack trace:
Caused by: javax.net.ssl.SSLException: Unsupported or unrecognized SSL message
    at sun.security.ssl.SSLSocketInputRecord.handleUnknownRecord(SSLSocketInputRecord.java:439) ~[?:?]
    at sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:184) ~[?:?]
    at sun.security.ssl.SSLTransport.decode(SSLTransport.java:108) ~[?:?]
    at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1152) ~[?:?]
    at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1063) ~[?:?]
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:402) ~[?:?]
    at org.apache.commons.net.ftp.FTPSClient._openDataConnection_(FTPSClient.java:642) ~[commons-net-3.7.jar:3.7]
    at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:790) ~[commons-net-3.7.jar:3.7]
    at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:3456) ~[commons-net-3.7.jar:3.7]
    at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:3386) ~[commons-net-3.7.jar:3.7]
    at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:3063) ~[commons-net-3.7.jar:3.7]
    at org.springframework.integration.ftp.session.FtpSession.list(FtpSession.java:74) ~[spring-integration-ftp-5.4.3.jar:5.4.3]
    at org.springframework.integration.ftp.session.FtpSession.list(FtpSession.java:45) ~[spring-integration-ftp-5.4.3.jar:5.4.3]
    at org.springframework.integration.file.remote.session.CachingSessionFactory$CachedSession.list(CachingSessionFactory.java:225) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.listFilesInRemoteDir(AbstractRemoteFileOutboundGateway.java:948) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.ls(AbstractRemoteFileOutboundGateway.java:913) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.ftp.gateway.FtpOutboundGateway.lambda$ls$0(FtpOutboundGateway.java:209) ~[spring-integration-ftp-5.4.3.jar:5.4.3]
    at org.springframework.integration.ftp.gateway.FtpOutboundGateway.doInWorkingDirectory(FtpOutboundGateway.java:285) ~[spring-integration-ftp-5.4.3.jar:5.4.3]
    at org.springframework.integration.ftp.gateway.FtpOutboundGateway.ls(FtpOutboundGateway.java:209) ~[spring-integration-ftp-5.4.3.jar:5.4.3]
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.lsRemoteFilesForMget(AbstractRemoteFileOutboundGateway.java:1202) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.mGetWithRecursion(AbstractRemoteFileOutboundGateway.java:1182) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.mGet(AbstractRemoteFileOutboundGateway.java:1127) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.ftp.gateway.FtpOutboundGateway.lambda$mGet$3(FtpOutboundGateway.java:230) ~[spring-integration-ftp-5.4.3.jar:5.4.3]
    at org.springframework.integration.ftp.gateway.FtpOutboundGateway.doInWorkingDirectory(FtpOutboundGateway.java:285) ~[spring-integration-ftp-5.4.3.jar:5.4.3]
    at org.springframework.integration.ftp.gateway.FtpOutboundGateway.mGet(FtpOutboundGateway.java:229) ~[spring-integration-ftp-5.4.3.jar:5.4.3]
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.lambda$doMget$9(AbstractRemoteFileOutboundGateway.java:683) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:439) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.doMget(AbstractRemoteFileOutboundGateway.java:682) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.handleRequestMessage(AbstractRemoteFileOutboundGateway.java:573) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:134) ~[spring-integration-core-5.4.3.jar:5.4.3]
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:56) ~[spring-integration-core-5.4.3.jar:5.4.3]
    ... 43 more

Edit #2
[INFO] +- commons-net:commons-net:jar:3.7.2:compile
[INFO] +- org.springframework.integration:spring-integration-ftp:jar:5.4.3:compile

Edit #3 - Some exception higher in stack just for completeness
Caused by: org.springframework.messaging.MessagingException: Failed to execute on session; nested exception is javax.net.ssl.SSLException: Unsupported or unrecognized SSL message
    at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:448) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.doMget(AbstractRemoteFileOutboundGateway.java:682) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.handleRequestMessage(AbstractRemoteFileOutboundGateway.java:573) ~[spring-integration-file-5.4.3.jar:5.4.3]
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:134) ~[spring-integration-core-5.4.3.jar:5.4.3]
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:56) ~[spring-integration-core-5.4.3.jar:5.4.3]
    ... 43 more

Edit 4# Experiment with commons-net:jar:3.7.2
Following setup works fine
[INFO] +- commons-net:commons-net:jar:3.7.2:compile
[INFO] +- org.springframework.integration:spring-integration-ftp:jar:5.3.2.RELEASE:compile
[INFO] |  \- org.springframework.integration:spring-integration-file:jar:5.4.3:compile
[INFO] |     \- org.springframework.integration:spring-integration-core:jar:5.4.3:compile
[INFO] |        \- org.springframework.retry:spring-retry:jar:1.3.1:compile

A: Please, consider to use commons-net:commons-net:3.7.2 dependency.
We indeed upgraded Spring Integration starting of version 5.4 to commons-net 3.7 from an old 3.6.
See this issue for more details: https://github.com/spring-projects/spring-integration/issues/3463.
We have plans to release 5.4.4 the next week: https://calendar.spring.io/

A: After downgrading spring-integration-ftp to version 5.3.2.RELEASE it works.
<dependency>
  <groupId>org.springframework.integration</groupId>
  <artifactId>spring-integration-ftp</artifactId>
  <version>5.3.2.RELEASE</version>
</dependency>


text:
Q: Using SecRandomCopyBytes in Swift I want to generate random bytes using SecRandomCopyBytes in Swift 3.0. Here is how I did it in Swift 2.2
private static func generateRandomBytes() -> String? {
    let data = NSMutableData(length: Int(32))

    let result = SecRandomCopyBytes(kSecRandomDefault, 32, UnsafeMutablePointer<UInt8>(data!.mutableBytes))
    if result == errSecSuccess {
        return data!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
    } else {
        print("Problem generating random bytes")
        return nil
    }
}

In Swift 3, I tried to do it like this, since I know the concept of unsafemutablebytes is different now, but it doesn't allow me to return. If I comment out the return part, it still says Generic Parameter ResultType could not be inferred
fileprivate static func generateRandomBytes() -> String? {
    var keyData = Data(count: 32)
    _ = keyData.withUnsafeMutableBytes {mutableBytes in
        let result = SecRandomCopyBytes(kSecRandomDefault, keyData.count, mutableBytes)
        if result == errSecSuccess {
            return keyData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
        } else {
            print("Problem generating random bytes")
            return nil
        }
    }
    return nil
}

Does anyone know how to fix this?
Thanks

A: According to Apple Documentation it looks similar to this:
public func randomData(ofLength length: Int) throws -> Data {
    var bytes = [UInt8](repeating: 0, count: length)
    let status = SecRandomCopyBytes(kSecRandomDefault, length, &bytes)
    if status == errSecSuccess {
        return Data(bytes: bytes)
    }
    // throw an error
}

or as an additional initializer:
public extension Data {
    public init(randomOfLength length: Int) throws {
        var bytes = [UInt8](repeating: 0, count: length)
        let status = SecRandomCopyBytes(kSecRandomDefault, length, &bytes)
        if status == errSecSuccess {
            self.init(bytes: bytes)
        } else {
            // throw an error
        }
    }
}

A: You were close, but return inside the closure returns
from the closure, not from the outer function.
Therefore only SecRandomCopyBytes() should be called in the
closure, and the result passed back.
func generateRandomBytes() -> String? {

    var keyData = Data(count: 32)
    let result = keyData.withUnsafeMutableBytes {
        (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int32 in
        SecRandomCopyBytes(kSecRandomDefault, 32, mutableBytes)
    }
    if result == errSecSuccess {
        return keyData.base64EncodedString()
    } else {
        print("Problem generating random bytes")
        return nil
    }
}

For a  "single-expression closure" the closure type can inferred
automatically, so this can be shortened to
func generateRandomBytes() -> String? {

    var keyData = Data(count: 32)
    let result = keyData.withUnsafeMutableBytes {
        SecRandomCopyBytes(kSecRandomDefault, 32, $0)
    }
    if result == errSecSuccess {
        return keyData.base64EncodedString()
    } else {
        print("Problem generating random bytes")
        return nil
    }
}

Swift 5 update:
func generateRandomBytes() -> String? {

    var keyData = Data(count: 32)
    let result = keyData.withUnsafeMutableBytes {
        SecRandomCopyBytes(kSecRandomDefault, 32, $0.baseAddress!)
    }
    if result == errSecSuccess {
        return keyData.base64EncodedString()
    } else {
        print("Problem generating random bytes")
        return nil
    }
}

A: This is the simplest and "Swiftiest" way to implement your function using Swift 5:
func generateRandomBytes() -> String? {
    var bytes = [UInt8](repeating: 0, count: 32)
    let result = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)

    guard result == errSecSuccess else {
        print("Problem generating random bytes")
        return nil
    }

    return Data(bytes).base64EncodedString()
}

Generally it is best practice in Swift to use guard statements as opposed to if/else statements when the control flow of a function depends on the success or failure of an expression or the presence of a non-nil value.


text:
Q: Strip quotation marks from Wordpress shortcode inserted by text area I've added shortcode to a page via a custom textarea in my Wordpress admin, but the shortcode is seen as text and gets wrapped in quotation marks, so it doesn't work.

This is basically how I sanitize my input:
if( isset( $input['textarea_input'] ) )
        $new_input['textarea_input'] = sanitize_text_field( $input['textarea_input'] );

This is how I output it on the page:
<?php echo $options['textarea_input']; ?>

do_shortcode does not change anything
<?php echo do_shortcode($options['textarea_input']); ?>

My guess is that the Wordpress TinyMCE editor recognizes shortcode, and therefor it works. Since mine is added via a hidden text area, it's just seen as plain text. What does the TinyMCE editor what I'm not doing? I wan't

A: Your sort of right, the Wordpress editor saves content thru a filter called the_content. This filter is used to filter the content of the post after it is retrieved from the database and before it is printed to the screen. Apply this filter to simulate TinyMCE formatting.
<?php echo apply_filters( 'the_content', $options['textarea_input']); ?>


text:
Q: Python - multiprocessing using safe add function import multiprocessing
import time
from multiprocessing import Pool
import os
class Cal:
    def add( self, num):
        added = num + 3
        time.sleep(3)
        print( str(os.getppid()) + " // " + str( num) + " -> " + str( added))
        return added
class Worker:
    def __init__( self, cal):
        self.cal = cal
    def run( self, param):
        return cal.add( param)

cal = Cal()
def fun( num):
    return Worker( cal).run( num)

cpuCount = multiprocessing.cpu_count()
with Pool( cpuCount) as p:
    print( p.map(fun, range(50)))

I made code that add 3 to each number and return them in multi processing. It seems to work well, but I curious that Cal.add function is used in proper way. the cal class instance was created at once (checked by pid). is there any way to use same memory in other thread which is created by Pool?


text:
Q: Start drag outside draggable div using jQuery UI I've using the first example by this code: http://jqueryui.com/draggable/#handle like this:

$(function() {
  $("#draggable").draggable({
    handle: "p"
  });
});
 #draggable {
   width: 100px;
   height: 100px;
   padding: 0.5em;
   float: left;
   margin: 0 10px 10px 0;
 }
 #draggable p {
   cursor: move;
 }
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">

I can be dragged only by this handle

I would to start touch outside "draggable handle" and activate it when mouse passing over it.
I try to explain better with an image:

Is it possibile? How can I do this?


text:
Q: Surd factors do not auto cancel each other out Simplify[Sqrt[Pr] - (Sqrt[Pr/Ra])*Sqrt[Ra]]

The above command should give me 0 as the simplified outcome, but it keeps generating the following

However, after I manually split that fraction of surds into two separate surds, it generates the desired form

This is annoying because in lengthy expressions it always convert fraction of surds into a single square root (as the one shown in the first picture) and it then just leaves it is without further simplification. Is there any way to let it auto-split those single square roots of fractions?

A: Sqrt[a/b] == Sqrt[a]/Sqrt[b]

does only hold if b>0
Simplify[Sqrt[a/b] == Sqrt[a]/Sqrt[b], Assumptions -> b > 0]

True

So you get your result if you just write
Simplify[Sqrt[Pr] - (Sqrt[Pr/Ra])*Sqrt[Ra], Assumptions -> Ra > 0]

0


text:
Q: Nginx + Php-FPM - upstream response is buffered Running Wordpress on Nginx + Php-FPM. We are getting these kind of warning message in our error logs:
[warn] 25518#25518: *34774 an upstream response is buffered to a temporary file /var/lib/nginx/fastcgi/5/01/0000000015 while reading upstream, client: 80.94.93.51, server: domain.com, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.4-fpm.sock:"

After reading several other threads about similar issues we have modified our configuration by adding proxy_buffers as seen below but this doesn't solve the issue.
   location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        proxy_buffers 16 16k;
        proxy_buffer_size 16k;
    }


text:
Q: Loop 3 posts column wise and continue the loop into same columns I wanted some information about on how to achieve the below senario. Can anyone help me out please.
Ok so here is what i have got so far.
I have two custom post types. And i am pulling & merging those to load randomly. They load randomly and with post types alternatively.
Ex: post type 1, post type 2, post type 1, post type 2 etc..
I have achieved this so far. Now while loading posts i want them into 3 columns(masonry format).

            <?php
            // Fetch quotes
            $quotes_query = new WP_Query( array(
                'post_type'=> 'quote',
                'orderby' => 'rand',
                'posts_per_page' => 4,
            ) );

            // Fetch founders
            $founders_query = new WP_Query( array(
                'post_type'=> 'founder',
                'orderby' => 'rand',
                'posts_per_page' => 3,
            ) );

            // List of merged founder and quotes
            $mergedposts = array();

            for ( $i = 0; $i < 10; $i++ ) {
                // Add quotes to list
                if ( isset( $quotes_query->posts[ $i ] ) ) {
                    $mergedposts[] = $quotes_query->posts[ $i ];
                }

                // Add founder to list
                if ( isset( $founders_query->posts[ $i ] ) ) {
                    $mergedposts[] = $founders_query->posts[ $i ];
                }
            }

            foreach( $mergedposts as $post ) :
            setup_postdata($post);
            ?>

                    <?php if ( get_post_type( get_the_ID() ) == 'quote' ) { ?>
                      <div class="foundersnetwork_content" style="background-color: <?php the_field('background_color'); ?>;">

<?php the_field('quote_data'); ?>

                    <?php } ?>

                    <?php if(get_post_type( get_the_ID() ) == 'founder'){ ?>

<?php the_post_thumbnail('full'); ?>

                    <?php } ?>

          <?php endforeach; ?>

But the 4th post must fall into 1st column, 5th post into 2nd column, 6th post into 3rd column and so on..
example:

post 1
post 4
post 7

post 2
post 5

post 3
post 6

**** Updated ****
Found a solution. Not exactly how i wanted but this will do the trick as the 4th falls under 1st no matter of the other posts - https://bootsnipp.com/snippets/featured/pinterest-like-responsive-grid
So this is solved now. Thanks to everyone who spent time on this.

A: If that col-4 class does what your example suggests it does, then just wrapping each post in col-4 would achieve the same effect:

Post 1

Post 2

Post 3

Post 4

Post 5

Post 6

Then you don't need to do anything special with WP_Query at all.

A: You may use this as follow:-
   $query = new WP_Query( array(
        'post_type'      => 'post',
        'order'          => 'DESC',
        'post_status'    => ' publish',
        'posts_per_page' => 3
    ) );

    while ($query->have_posts()): $query->the_post();
    echo"
";
        the_title();
    echo"
";
    endwhile;
   wp_reset_postdata();

You may Please check it and let me know if you succeded in your goal.


text:
Q: ref.once() not being called I'm trying to get the username by accessing a
data value saved as a child within the uid (as the parent):
var ref = new Firebase("https://mintio.firebaseio.com");

var authData = ref.getAuth();
var username = null;
ref.on("value" , function(snapshot){
    console.log("reading initiaized");
    var usernameSnap = snapshot.child(authData.uid).child("name");
    username = usernameSnap.val();
    console.log("username read");
});

but the username stays empty and the message is never being logged into the console... as if the once() function is never being called.
The authData object holds the correct uid ("google:107739486693148575362")
and the data looks like this:

EDIT:
These are my security rules:
{
    "rules": {
      "users": {
        "$uid": {
            ".read": "auth.uid == $uid",
            ".write": "auth !== null && auth.uid == $uid"
        }
      }
    }
}

If this isn't enough information the repo can be found here: https://Minzkraut@bitbucket.org/Minzkraut/mintio.git
Am I doing something wrong here?

A: When I try to access you database, I get:

Error: permission_denied: Client doesn't have permission to access the desired data.

So it seems like you have security rules that prevent the read from succeeding.
Most likely, you have a security that ensures each user can only access their own user data:
{
  "rules": {
    "$uid": {
      ".read": "auth.uid == $uid"
    }
  }
}

If you have security rules similar to the above, when executing this query:
var ref = new Firebase("https://mintio.firebaseio.com");
ref.on("value" , function(snapshot){ ...

You are trying to read from the root of your database. The Firebase server checks this against your security rules and notes that you don't have read access to the root of the database. So it rejects the operation.
What you want is to access the user's data directly:
var ref = new Firebase("https://mintio.firebaseio.com");
ref.child(ref.getAuth().uid).on("value" , function(snapshot){ ...

With this last snippet, the read operation starts on the user's own data. The Firebase server checks against the rules and will see that "auth.uid == $uid" is true.
This is one of the two most common pitfalls with Firebase security rules:

*

*Rules are not filters

*Permissions cascade


text:
Q: Selecting all the Magasin(stores) with at least 1 product in it with also a qte_stock>0 SQL CREATE DATABASE Gestion_Magasin
GO

USE Gestion_Magasin
GO

CREATE TABLE Magasin
(
    NUM_MAG int PRIMARY KEY,
    NOM_MAG varchar(15),
    SUPERFICIE int CHECK (SUPERFICIE BETWEEN -1 AND 120),
    REF_PRODUIT int FOREIGN KEY REFERENCES PRODUIT(REF_PRODUIT)
)

CREATE TABLE PRODUIT
(
    REF_PRODUIT int PRIMARY KEY,
    DESIGNATION varchar(25),
    QTE_STOCK int DEFAULT 0,
)

SELECT * FROM Magasin
SELECT * FROM PRODUIT

Heading
//This is the view where I m facing this problem ty for your help .
CREATE VIEW vue01
AS
    SELECT *
    FROM magasin AS m
    JOIN PRODUIT AS p ON m.REF_PRODUIT = p.REF_PRODUIT
    WHERE COUNT(m.REF_Produit) > 0

A: You can't put it like this without doing an aggregate
Use having instead
SELECT p.REF_PRODUIT, NUM_MAG, NOM_MAG,SUPERFICIE
FROM magasin AS m
JOIN PRODUIT AS p ON m.REF_PRODUIT = p.REF_PRODUIT
group by p.REF_PRODUIT, NUM_MAG, NOM_MAG,SUPERFICIE
having COUNT(m.REF_Produit) > 0


text:
Q: Codeigniter + ION AUTH...Can't tell if logged in I'm building a Codeigniter application with ION Auth, which is going relatively OK. I've set up the ION Auth framework following this guide http://www.rappasoft.com/tutorials/5-building-a-simple-codeigniter-application-using-ion-auth.html#.U0Q5ufldUrU and when I log in using the default username and password I'm redirect to my homepage. So far, so good.
Problem then is that when I access one of my protected pages (i.e. a controller which extends MY_Controller), I'm redirected to the login page again.
I'm quite new to this, so just looking for some pointers of where to look. It seems I'm being logged in, but I don't really know how to check for sure.
I've tried this line of code in my view, but I get a couple of errors: user_info is undefined & trying to get property of a non object.
<?php echo $user_info->username;?>

MY_Controller in application/core:
 if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends CI_Controller {

public function __construct() {
   parent::__construct();

   if (!$this->ion_auth->logged_in()) {
        redirect('auth/login');
   } else {
        //Store user in $data
        $data->user_info = $this->ion_auth->user()->row();
        //Load $the_user in all views
        $this->load->vars($data);
   }
}
}

My 'members only' area controller class declaration:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Manage extends MY_Controller {

    function __construct()
    {
        parent::__construct();

        $this->load->database();
        $this->load->library('grocery_CRUD');
    }
//other functions omitted

A: Add this to your MY_Controller and see what is returned
var_dump($this->ion_auth->logged_in());exit;


text:
Q: "There are no fingerprint readers available at this time" error. On my windows 8 HP 64bit After a refresh of my system. I couldn't log in windows with my finger print anymore. I tried updating the driver, but it says up to date.
Please help my system make is HP envy m6 Notebook PC, 64 bit, version 6.2.9200 Build 9200.
Thanks in anticipation.

A: When you say "Updating the driver" I assume you mean "Run Windows Update".  Instead, go to the manufacturer's website and look for Support or Drivers or Downloads.  There, find your computer's model and download the appropriate drivers for it.  It will probably have multiple versions and confusing naming standards - it might be called Biometric Security or Fingerprint Reader or something else.
Windows Update only has a computer's unique drivers if both the manufacturer and Microsoft team up and both do significant amounts of work to put the unique drivers on the list.  It's a lot easier for the manufacturer to just put the drivers on their website.


text:
Q: React component overriding another when set const I am creating a chatbot and I am having a problem when the user sends a message.
The program process is as follows: There is a json where all messages exchanged with the bot are stored and another with the bot's predefined responses. That is, when a message is sent by the user, a check is made to see if there is a reply to that message.
Initially the message appears as we can see in the following image User message that was written in the text box. The message was sent and is already in json along with the reply. It is only possible to see the user's message by placing an alert before adding the bot message graphically. When I click OK, the alert disappears and the user's message is replaced by the bot's message as shown in the following image:Bot message. When the page is refreshed, the two messages appear correctly.
So the problem is that when a message is sent by the user it appears briefly but then is being replaced but only graphically. In json it appears correctly.
Part of the code in my App.js is as follows:
const [messages, setMessages] = useState([])

const AddMessage = async(text, type) => {
    const res = await fetch('http://localhost:4000/messages/', {
        method: 'POST',
        headers: {
            'content-type': 'application/json'
        },
        body: JSON.stringify(text, type)
    })
    const data = await res.json()
    //console.log(data)

    alert(JSON.stringify(data))

    setMessages([...messages, data])
}

return (

                <Messages messages={messages} onDelete={deleteMessage}/>

            <SendMessage onAddMessageUser={AddMessage} onAddMessageBot={AddMessage}/>

);

Part of the SendMessage code:
const SendMessage = ({ onAddMessageUser, onAddMessageBot }) => {

    const onSubmit = (e) => {

    e.preventDefault()

    if (!text) {
        alert('Please write a message!')
        return
    }

    setMessage('')
    addUserMessage(text)
    addBotMessage(text)

}

function addUserMessage(text) {
    type = 'question'
    onAddMessageUser({ text, type })
}

function addBotMessage(text) {

    var type = 'answer'
    var flag = true

    for (let key = 0; key < botDataLength; key++) {
        if (text === botData[key].question) {
            //console.log('true');
            //console.log(botData[key].answer)
            //alert(botData[key].answer)
            text = botData[key].answer
            flag = false

        }
    }

    text = flag ? 'Sorry I don\'t understand' : text

    onAddMessageBot({text, type})
}

A: setMessages need the previous array :
setMessages(messages => [...messages, data]);


text:
Q: Sinegy API signature, HMAC-SHA25, and encoded in base64 format Can somebody help me with sinegy API signature? This is what they are asking:

API methods that use full signed authentication requires api-key in the request header and api-signature in the request body.
API signature is an encoded message which contains:
Stringed request parameters
Method of API function
Path of API function
API secret
These attributes must be separated by the vertical
line | delimiter, hashed in HMAC-SHA25, and encoded in base64 format.

I don't have any experience with API signatures, this is what I tried so far:
secret = '$KDcKdsemlwJ6Vmj05f5NOQ4e.'

digest = hmac.new(
    secret.encode(),
    'ghjfghjfgh|fjkghkghj|ghjkghjk|ljklhjklh'.encode(),
    hashlib.sha256
)
signature = base64.b64encode(digest.digest())

This is what their example signature looks like: 8asufaol53wad,
but what I receive is: b'qCTV/psNaUdZt/F+0QMhDISb/n4yYuYrK7YG8aMCC7U='
Here is their full API doc: https://docs.sinegy.com/#tag/Authentication

A: Try this:
api_secret = "$KDcKdsemlwJ6Vmj05f5NOQ4e."
str_to_sign = "ghjfghjfgh|fjkghkghj|ghjkghjk|ljklhjklh"
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())


text:
Q: Leap year program doing wrong things for a specific input So I got this question from my friend yesterday regarding a program to check if a year is leap or not using python and decided to help. I wrote it up and it seems to run just fine until I enter 1992 as an input in which case it returns false (which shouldn't be the case). So I'm wondering where I wrong.
My code :
`
def is_leap(year):
   leap = False

   if (year % 4) == 0:
       if (year % 100) == 0:
           if (year % 400) == 0:
               leap = True
           else:
               leap = False
       else:
           leap = False
   else:
       leap = False

   return leap

year = int(input())
print(is_leap(year))

Results :
1992 - > False

A: Few problems with your code: first of all I would do checks in a partially reverse order, e.g.

*

*start checking year % 400,

*then in your line 5 you have a logical error: it has to be
if not (year % 100) == 0:

*only then check for year % 4
The code can look like:
def is_leap(year):
    leap = False

    if (year % 400) == 0:
        leap = True
    elif ((year % 100) != 0 and (year % 4) == 0):
        leap = True
    else:
        leap = False
    return leap

year = int(input())
print(is_leap(year))

A: The issue lies in the nested if statements. Leapyears are either year % 100 != 0 and year % 4 == 0 or year % 400 == 0.
Try this:
def is_leap(year):
    leap = False
    if year % 100 != 0 and year % 4 == 0 or year % 400 == 0:
        leap = True

    return leap

year = int(input())
print(is_leap(year))


text:
Q: Converting element.dataset (a DOMStringMap object) into a "real" JSON object in vanilla JavaScript? Like explained in a similar Stack Overflow question, in vanilla JavaScript, I can do the following:
var data = Object.assign({}, element.dataset);

... in order to get all data-* attributes as an object.
However, the resulting object is not a "real" JSON object, booleans and numbers are surrounded by quotes.
<div id="my-element"
    data-string="It's OK."
    data-bool="true"
    data-number="10">
</div>

Here is the comparison between vanilla JavaScript and jQuery:

I supposed that in jQuery, jQuery('#my-element').data() is doing the heavy job of "lifting" the data before returning the actual JSON.
Since I'd like to use ES6 and not jQuery, and I don't want to reinvent the wheel (parsing that values using regex/conditions), I'm asking if there is a quick way to do this job.

A: The data processing in jquery is done in getData() function in data.js
here is the code from JQuery library:
function getData( data ) {
    if ( data === "true" ) {
        return true;
    }

    if ( data === "false" ) {
        return false;
    }

    if ( data === "null" ) {
        return null;
    }

    // Only convert to a number if it doesn't change the string
    if ( data === +data + "" ) {
        return +data;
    }
    //Replaced rbrace with regex value.
    if ( /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/.test( data ) ) {
        return JSON.parse( data );
    }

    return data;
}

you can use this function and update your data.


text:
Q: $e^{\varphi -1}$ characteristic function So I am trying to figure out whether $e^{\varphi-1}$ is a characteristic function given that $\varphi$ is. I know that linear combinations of characteristic functions and the real part of a characteristic function are characteristic functions.
I would like to figure this one out by myself so just some small hints would be appreciated. How do I chose the random variable $Y$ for this function?

A: Suppose Y is an rv that has the cf $\phi$.
Then consider X = $Y1 + Y2 + ... + Y_P$ where Y1, Y2, ... are iid copies of Y and P follows Poisson(1).
Thus, $E(e^{itX}) = \sum_{k=0}^\infty E(e^{itX};P=k) \frac{e^{-1}}{k!} = \sum_{k=0}^\infty \phi^k\frac{e^{-1}}{k!} = e^{\phi-1} $
Thus, $e^{\phi-1} $ is the characteristic function of X.


text:
Q: Confused about how to set up OpenSSL for UDK2018 I'm trying to set up a UDK2018 environment. Step 3 of the instructions refers to a text file in the OpenSSl with instructions below, but then says to download a zip and extract it. None of the commands in the instructions seem to work, because the directory isn't a git depository. I'm not very experienced at this, just trying to develop a UEFI script for a test. Any help on how to set up the environment would be great. Here are the instructions from the text file I referred to above:
 "HOW to Install OpenSSL for UEFI Building
OpenSSL repository was added as one submodule of EDKII project.
The user can use the following commands to clone both main EDKII repo and
openssl submodule:
  1) Add the "--recursive" flag to the git clone command:
     $ git clone --recursive https://github.com/tianocore/edk2
or
  2) Manually initialize and update the submodules after the clone operation
     on main project:
     $ git clone https://github.com/tianocore/edk2
     $ git submodule update --init --recursive
And use the following combined commands to pull the remote submodule updates
(e.g. Updating the new supported OpenSSL release tag):
     $ git pull --recurse-submodules && \
       git submodule update --recursive --remote"
Thank you,
Simon

A: You can also access the UDK release by cloning the abovementioned github repository and checking out the UDK2018 branch. That will give you the submodule metadata, and make the above instructions work.
Note: this branch contains backported fixes above what was in the original UDK2018 release. The original released version can be obtained as the vUDK2018 tag.
More information.


text:
Q: getting object from parse into array and converting into strings I'm trying to fetch data from parse. that have 4-5 fields in string format and display them in the dropdown menu of IOS storyboard.
there are actually 9 columns including parse default columns. they create data,ACL, Object ID so and so forth.
I'm need to fetch only those fields from parse which are in string format and i want display them as a dropdown menu in UIViewController. for dropdown i'm UITableViewController.
serviceview.h
@interface ServiceViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic)NSArray *selectionArray;

@property (weak, nonatomic) IBOutlet UILabel *resultLabel;

@property (weak, nonatomic) IBOutlet UIPickerView *servicepicker;

@property (weak, nonatomic) IBOutlet UITableView *tableViewCars;

@property (strong, nonatomic)NSArray *customerCars;

- (IBAction)customerCarBtn:(id)sender;

serviceview.m
@interface ServiceViewController ()

@end

@implementation ServiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableViewCars.delegate = self;
    self.tableViewCars.dataSource = self;
     _selectionArray = @[@"Car Service", @"Brake Pads", @"Car Battery", @"Alternator",@"Starter Motor",@"Timing Belt",@"Cooling System",@"Clutch Repair",@"Repair-Others"];
    NSString *uType = [[PFUser currentUser] objectForKey:@"email"];

    PFQuery *query = [PFQuery queryWithClassName:@"customerCars"];
    [query whereKey:@"cEmail" containsString:uType];
    NSLog(@"%@",uType);
    [query findObjectsInBackgroundWithBlock:^(NSArray *customerCar, NSError *error) {
        if (customerCar) {
            NSLog(@"Successfully retrieved %lu scores.", (unsigned long)customerCar.count);
            for (PFObject *objects in customerCar) {
                NSLog(@"%@", objects.objectId);
                _customerCars = @[objects];
                self.customerCars = [[NSArray alloc]initWithObjects:@[objects], nil];
               // NSLog(@"%@",[_customerCars.objectId]);
            }
            //NSLog(customerCars);
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return [self.customerCars count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *simpleTableIdentifier = @"SimpleTableItem";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

    }

    cell.textLabel.text = [self.customerCars objectAtIndex:indexPath.row] ;

    //cell.textLabel.font = [UIFont systemFontOfSize:11.0];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [self.tableViewCars cellForRowAtIndexPath:indexPath];

    self.tableViewCars.hidden = YES;

}

- (IBAction)customerCarBtn:(id)sender {

    if (self.tableViewCars.hidden == YES) {
        self.tableViewCars.hidden = NO;
    }

    else
        self.tableViewCars.hidden = YES;

}

A: The objects being stored in your customerCars array, are of type PFObject, because that is what Parse returns.
In order to obtain the String value from one of your Parse properties of a car, access it as a dictionary key on the object.
For example, say you wanted to update the cell text label to display the 'colour' property of a car. You would use something like:
PFObject *car = [self.customerCars objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat: @"%@ - %@", car[@"make"], car[@"model"]];

A: First you have to check on parse for field that have values in string format.
Then you have to use PFQuery's selectKeys method and pass keyNames in array to fetch only selected Keys from parse like this :
PFQuery *query = [PFQuery queryWithClassName:@"customerCars"];
[query whereKey:@"cEmail" containsString:uType];
[query selectKeys:@[@"column1",@"column2",@"column3"]];


text:
Q: How to implement CommonTree class in ANTLR4 What I want to realize: Treating comment by ANTLR4 in JavaScript
Now I'm coding interpret C script by antlr4js, and I want to take comment content.
example:
/* this is my function */
int add(int a, int b);

then, I want get string "this is my function", and attach to add().
I googled and found that I can use hidden channel.
Here is the page that I refer to :
This is Stuff: Tackling Comments in ANTLR Compiler
I can code collecting comment after lexing (describing at Collecting Hidden Tokens in above page), but I can't follow next section Merging Tokens With AST because I can't find out CommonTree class what base class.
problem point
The image to code.(in above page)
public class HiddenTokenAwareTree extends CommonTree {

  private List<Token> preceding = new LinkedList<Token>();
  private List<Token> orphans = new LinkedList<Token>();
  private List<Token> following = new LinkedList<Token>();

  // ... constructors, getters and setters follow

}

This is Java code, so when implement in javascript, code will be like this:
var CommonTree = require("antlr4/PATH/TO/COMMONTREE").CommonTree;

class HiddenTokenAwareTree{

}

I can't find out this PATH/TO/COMMONTREE.
my project setting
node: 6.14.6
$ npm list --depth=0
├── antlr4@4.8.0
├── webpack@4.44.1
└── webpack-cli@3.3.12
I installed antlr4 by $ npm i antlr4.
Thanks for any advices !

A: The tutorial you're linking to is for ANTLR v3, ANTLR v4 doesn't have the ability to define a custom tree adapter.
What you could do is create a visitor or listener and retrieve hidden tokens at certain nodes in your parse tree.


text:
Q: Wonkiness with dot sourcing and powershell clases This one has me thoroughly confused. In some scenarios, running a script that dot-sources another script that defines a class does not reflect changes to the class. Here's the repro.
Script common.ps1:
class A
{
    A()
    {
        Write-Host 'hi'
    }
}

Script myscript.ps1:
. .\common.ps1
[A]::new() | out-null

In a powershell terminal, I then run
. .\common.ps1
[A]::new() | out-null
.\myscript.ps1

outputs
hi
hi

I then change common.ps1 by replacing 'hi' with 'bye', and again run
. .\common.ps1
[A]::new() | out-null
.\myscript.ps1

To get this output (my comments added):
bye # expected
hi # what?!?!

The fact that the change is not-reflected when myscript.ps1 does the dot sourcing but is when the dot sourcing is done locally blows my mind. If I don't dot-source locally, running myscript.ps1 always reflects any changes to common.ps1. And it is only when my change is to some part of the class that it does not have an effect (I can add a Write-Host outside of the class and it will show up).
What's going on? Somehow myscript.ps1 can't load the updated class even though the local shell can? I imagine this is related to this question but the inconsistency between local shell and myscript.ps1 has me scratching my head.


text:
Q: GPFlow multiple independent realizations of same GP, irregular sampling times/lengths In GPflow I have multiple time series and the sampling times are not aligned across time series, and the time series may have different length (longitudinal data). I assume that they are independent realizations from the same GP. What is the right way to handle this with svgp, and more generally with GPflow? Do i need to use coregionalization? The coregionalization notebook assumed correlated trajectories, while I want shared mean/kernel but independent.

A: Yes, the Coregion kernel implemented in GPflow is what you can use for your problem.
Let's set up some data from the generative model you describe, with different lengths for the timeseries:
import numpy as np
import gpflow
import matplotlib.pyplot as plt

Ns = [80, 90, 100]  # number of observations for three different realizations
Xs = [np.random.uniform(0, 10, size=N) for N in Ns]  # observation locations

# three different draws from the same GP:
k = gpflow.kernels.Matern52(variance=2.0, lengthscales=0.5)  # kernel

Ks = [k(X[:, None]) for X in Xs]
Ls = [np.linalg.cholesky(K) for K in Ks]
vs = [np.random.randn(N, 1) for N in Ns]
fs = [(L @ v).squeeze(axis=-1) for L, v in zip(Ls, vs)]

To actually set up the training data for the gpflow GP model:
# output indicator for the observations: which timeseries is this?
os = [o * np.ones(N) for o, N in enumerate(Ns)]  # [0 ... 0, 1 ... 1, 2 ... 2]

# now assemble the three timeseries in single data set:
allX = np.concatenate(Xs)
allo = np.concatenate(os)
allf = np.concatenate(fs)
X = np.c_[allX, allo]
Y = allf[:, None]
assert X.shape == (sum(Ns), 2)
assert Y.shape == (sum(Ns), 1)

# now let's set up a copy of the original kernel:
k2 = gpflow.kernels.Matern52(active_dims=[0])  # the same as k above, but with different hyperparameters

# and a Coregionalization kernel that effectively says they are all independent:
kc = gpflow.kernels.Coregion(output_dim=len(Ns), rank=1, active_dims=[1])
kc.W.assign(np.zeros(kc.W.shape))
kc.kappa.assign(np.ones(kc.kappa.shape))
gpflow.set_trainable(kc, False)  # we want W and kappa fixed

The Coregion kernel defines a covariance matrix B = W Wᵀ + diag(kappa), so by setting W=0 we prescribe zero correlations (independent realizations) and kappa=1 (actually the default) ensures that the variance hyperparameter of the copy of the original kernel remains interpretable.
Now construct the actual model and optimize hyperparameters:
k2c = k2 * kc

m = gpflow.models.GPR((X, Y), k2c, noise_variance=1e-5)

opt = gpflow.optimizers.Scipy()
opt.minimize(m.training_loss, m.trainable_variables, compile=False)

which recovers the initial variance and lengthscale hyperparameters pretty well.
If you want to predict, you have to provide the extra "output" column in the Xnew argument to m.predict_f(), e.g. as follows:
Xtest = np.linspace(0, 10, 100)
Xtest_augmented = np.c_[Xtest, np.zeros_like(Xtest)]
f_mean, f_var = m.predict_f(Xtest_augmented)

(whether you set the output column to 0, 1, or 2 does not matter, as we set them all to be the same with our choice of W and kappa).
If your input was more than one-dimensional, you could set
active_dims=list(range(X.shape[1] - 1)) for the first kernel(s) and active_dims=[X.shape[1]-1] for the Coregion kernel.


text:
Q: How to merge two point clouds with different view points My 3D Scanner scans some object from different angles to get a 360° surface reconstruction in the end. The point clouds of each scan have different amounts of points and need to be merged. In the PCL library, that I would like to use for the reconstruction, there are algorithms for merging point clouds with the same amount of points, using some iterative closest point method.
I would like to avoid finding out the axis of the rotation. Of course, knowing it's position and the angle of the rotation, I could just multiply all my points of one cloud with the rotation matrix and then merge the clouds. Is there any way to merge them without knowing the center of rotation? (And maybe even get it's position out of the algorithm?)

A: Well, it seems an old question, just may be help to other people :)
It won't make sense if you merge the point clouds without registration. Thus ICP should be employed.
Then you can perform transformation to the corresponding Point Cloud, and merge them after that.
Should be straight forward.

A: The only way that I have been able to figure out how to concatenate clouds of two different sizes is to pad the smaller cloud up to the same size as the larger cloud. I did it by testing which is largest then filling a temporary cloud with the smaller cloud and then filling the balance with 0 0 0.
The other way that I see is to create a temporary cloud with all  0 0 0 points and then filling the lower portion of the temporary cloud with the smaller cloud.
I think the latter is easier to implement but the former is faster. I used the former.


text:
Q: SPSS analysis: repeated design for total sum DVs I am trying to run an SPSS analysis on two dependent variables (DVs) that are part of a total group of DVs that sum to 1. That is, my research question was how people spend their time on one of the three activity categories, and I asked them to indicate the proportion of their time spent on each of these activities: A, B or C. The total should sum up to 100%.
My hypothesis is that people spend a greater proportion of their time on A than on B. But as you can see, A and B are not independent from each other, such that A+B+C always adds up to 100%. Is it okay to run an SPSS repeated measure analysis: having 2 factors? IF this is not a good idea, what is a better approach?


text:
Q: Split GeoTIFF into multiple cells with Rasterio I'd like to create training data for a machine learning pipeline. To do this I want to take a large raster and split it into multiple equal sized cells.
I have a very basic loop for generating the pixel-wise coordinates, how do I generate a cell from these when splitting up a GeoTIFF?
def splitImageIntoCells(img, filename, squareDim):
 numberOfCellsWide = img.shape[1] // squareDim
 numberOfCellsHigh = img.shape[0] // squareDim
 x, y = 0, 0
 for hc in range(numberOfCellsHigh):
     y = hc * squareDim
     for wc in range(numberOfCellsWide):
         x = wc * squareDim
         # Need some method from Rasterio here
         # to crop at the given x and y...

A: I devised the following 4 methods:
from shapely import geometry
from rasterio.mask import mask

# Takes a Rasterio dataset and splits it into squares of dimensions squareDim * squareDim
def splitImageIntoCells(img, filename, squareDim):
    numberOfCellsWide = img.shape[1] // squareDim
    numberOfCellsHigh = img.shape[0] // squareDim
    x, y = 0, 0
    count = 0
    for hc in range(numberOfCellsHigh):
        y = hc * squareDim
        for wc in range(numberOfCellsWide):
            x = wc * squareDim
            geom = getTileGeom(img.transform, x, y, squareDim)
            getCellFromGeom(img, geom, filename, count)
            count = count + 1

# Generate a bounding box from the pixel-wise coordinates using the original datasets transform property
def getTileGeom(transform, x, y, squareDim):
    corner1 = (x, y) * transform
    corner2 = (x + squareDim, y + squareDim) * transform
    return geometry.box(corner1[0], corner1[1],
                        corner2[0], corner2[1])

# Crop the dataset using the generated box and write it out as a GeoTIFF
def getCellFromGeom(img, geom, filename, count):
    crop, cropTransform = mask(img, [geom], crop=True)
    writeImageAsGeoTIFF(crop,
                        cropTransform,
                        img.meta,
                        img.crs,
                        filename+"_"+str(count))

# Write the passed in dataset as a GeoTIFF
def writeImageAsGeoTIFF(img, transform, metadata, crs, filename):
    metadata.update({"driver":"GTiff",
                     "height":img.shape[1],
                     "width":img.shape[2],
                     "transform": transform,
                     "crs": crs})
    with rasterio.open(filename+".tif", "w", **metadata) as dest:
        dest.write(img)

To use these you would simply read in an image with Rasterio, and call the first method like so:
splitImageIntoCells(myReadInImage, "my_file_name", 1000)


text:
Q: how to use addr2line in commandline how to use addr2line?
i have a program that gives the backtrace of last 10 addresses that it visited before crash. but if i use these address to addr2line like
addr2line -e test [address]

it just gives me
??:0

is there a special way to compile to use addr2line like we use ggdb to use gdb?

A: You need to have some debugging information compiled in to your executable. e.g.
$ gcc t.c                         # debug information not requested
$ gdb ./a.out
...
(gdb) break main
Breakpoint 1 at 0x400588
(gdb) q
$ addr2line -e a.out 0x400588
??:0                              # no information returned

$ gcc -g t.c                      # default debug information requested with -g
$ addr2line -e a.out 0x400588
t.c:4                             # line information returnedd
$


text:
Q: Parsing Json response with Java I have this restful web service http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2, I tested it with Advanced Rest Client plugin for Chrome and it work well. I want to parse the Json response with java code, so my code is:
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.*;

public class JsonArray {

    public JsonArray() {
        initJson();
    }
    public void initJson() {
        URL url;
        try {
            url = new URL("http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2");
            JSONObject obj = new JSONObject(url);
            String success = obj.getString("success");
            System.out.println(success+"/n");
            JSONArray arr = obj.getJSONArray("element");
            for(int i=0;i<att.length;i++){
                String doc_id = arr.getJSONObject(i).getString("doc_id");
                String doc_firstname = arr.getJSONObject(i).getString("doc_firstname");
                String doc_lastname = arr.getJSONObject(i).getString("doc_lastname");
                System.out.println("doc_id: "+doc_id+"/n"+"doc_firstname:"+doc_firstname+"/n"+"doc_lastname: "+doc_lastname);
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(JsonArray.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

But I get those exceptions:
Exception in thread "main" org.json.JSONException: JSONObject["success"] not found.
Exception in thread "main" org.json.JSONException: JSONObject["element"] not found.

A: I would recommend using a library like Apache HttpComponents or UniRest that executes the http request (GET, POST, etc.) against the external server and returns the proper response. Here's an example using UniRest:
String url = "http://firstsw.besaba.com/get_all.php";
HttpResponse<JsonNode> jsonResponse = Unirest.get(url)
    .queryString("tab", "doctor")
    .queryString("cond", "doc_id=2")
    .asJson();
String jsonContent = jsonResponse.getBody().toString();
//prints the JSON response
System.out.println(jsonContent);
//and you could create your JSON object from here
JSONObject obj = new JSONObject(jsonContent);

A: I think your problem is
            url = new URL("http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2");
        JSONObject obj = new JSONObject(url);

You must not use the url as parameter for the JSONObject(String) constructor.
You have to request the server first and get the json string of the http response
For a get request you should use code like this
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tab", "doctors"));
params.add(new BasicNameValuePair("cond", "doc_id=2"));

HttpParams httpParams = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
httpParams.setBooleanParameter("http.protocol.expect-continue", false);

final String paramString = URLEncodedUtils.format(params, "UTF-8");
final String urlRequest = "http://firstsw.besaba.com/get_all.php?" + paramString;
final HttpClient httpClient = new DefaultHttpClient(httpParams);
final HttpGet httpGet = new HttpGet(urlRequest);
final HttpResponse httpResponse = httpClient.execute(httpGet);
String jsonString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
JSONObject jo = new JSONObject(jsonString);

for post request
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tab", "doctors"));
params.add(new BasicNameValuePair("cond", "doc_id=2"));

final HttpParams httpParams = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
httpParams.setBooleanParameter("http.protocol.expect-continue", false);

final HttpClient httpClient = new DefaultHttpClient(httpParams);
final HttpPost httpPost = new HttpPost("http://firstsw.besaba.com/get_all.php");
httpPost.setEntity(new UrlEncodedFormEntity(params));
final HttpResponse httpResponse = httpClient.execute(httpPost);
String jsonString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
JSONObject jo = new JSONObject(jsonString);

A: Looking at your code the line JSONObject obj = new JSONObject(url) is problematic.
According to the javadoc the url is seen as an Object.
This will not give the desired result.
Better is to get the json content as String first.
Replace this part :
        url = new URL("http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2");

        String content = (String)url.getContent();
        JSONObject obj = new JSONObject(content);
        String success = obj.getString("success");
        System.out.println(success+"/n");
        JSONArray arr = obj.getJSONArray("element");

See the javadoc where I found this info:
json.org


text:
Q: Apollo cache local filters and pagination I have a graphql api with bunch of filters and pagination available.
Is it possible to make Apollo filter already fetched results locally and only query the server if there are pages remaining?
For example, let us have Users with Name and Role filters, and 20 results per page.
We start with filtered query (name: Alice) and get 15 results. If we add a second filter (role: Admin) the app should do the filtering locally.
Or we start with (role: Admin) and get 50 results. Now we add a second filter (name: Alice) and the app should instantly filter whatever Alices were present at the first page, yet do the second query, and update the list once it's complete. Then if we remove the first filter, the app should do another query without local filtering at all, cause there may be non-Admin Alices ordered first.


text:
Q: Django sys.path.append for project *and* app needed under WSGI Could somebody give me a pointer on why I need to add my project root path to the python path as well as the application itself in my WSGI file?
Project base is called 'djapp', the application is called 'myapp'.
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../djapp')

os.environ['DJANGO_SETTINGS_MODULE'] = 'djapp.settings'

If I omit the line with "/../djapp/" the log tells my that 'myapp' can not be imported, even though 'djapp.settings' is. (validating 'djapp' was imported)
It al runs properly with the ./manage.py command. there's a __init__ in the project folder.
For testings sake, I see the same issue using addsitedir:
site.addsitedir('/home/user/web/project/')
site.addsitedir('/home/user/web/project/djapp')

A: Since djapp (the django project folder) is in a parent folder that also belongs to the deployment I renamed the djapp folder simply to project.
Then this code is always correct:
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..' )
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../project')

os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'

The complete folder layout being:
host.example.com\
    etc\
    bin\
    project\
    logs\

And what have you. This way project can always be called project :)
Hope that helps.
GrtzG

A: Presumably you've got code within your project which is doing from myapp import foo.
Two options:

*

*change that to from djapp.myapp import foo, which is not recommended as it prevents portability;

*only add djapp in your WSGI, and set the DJANGO_SETTINGS_MODULE to just 'settings'.


text:
Q: MYSQL Removing duplicates in mixmatched order How can I remove duplicates in the following order
1 2
2 1
1 3
4 1

and only output
1 2
1 3
4 1

A: Consider the following...
DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,user1 INT NOT NULL
,user2 INT NOT NULL
);

INSERT INTO my_table (user1,user2) VALUES
(1, 2),
(2, 1),
(1, 3),
(4, 1);

SELECT x.*
  FROM my_table x
  JOIN
     ( SELECT MIN(id) id
         FROM my_table
        GROUP
           BY LEAST(user1,user2)
            , GREATEST(user1,user2)
     ) y
    ON y.id = x.id;
+----+-------+-------+
| id | user1 | user2 |
+----+-------+-------+
|  1 |     1 |     2 |
|  3 |     1 |     3 |
|  4 |     4 |     1 |
+----+-------+-------+

A: Use GROUP BY to merge duplicate.

A: You can use the DISTINCT clause to remove duplicates. The DISTINCT command in SQL retrieves unique data from your table. To remove duplicates, you can issue a statement similar to below:
SELECT DISTINCT Column_Name
FROM Table_Name

OUTPUT: 1 2 OR 2 1

Please let me know if this helps.


text:
Q: Why does this 'generic' Rust code doesn't work as expected? I've recently taken on learning Rust and I'm trying to write a small expression evaluator. I've been practicing Rust for a few days now and thought this task would be cool to work with Rust's Traits. What I tried to do is make Sum & Number structs implement Expression trait, so that I could express (pun unintended) (1 + 2) as an expression where left and right hand sides are expressions too.
I've stumbled onto the problem that you can't just use Traits as properties' types, so you instead should use &dyn Trait or Box in the Book. Following this notion a rewrote it and now it compiles, but I can't get access to values inside Sum.
Here's my code:
trait Expression {}
#[derive(Debug)]
struct Number {
    pub val: i32
}

impl Expression for Number {}

struct Sum {
    pub left: Box<dyn Expression>,
    pub right: Box<dyn Expression>
}

impl Expression for Sum {}

fn main() {
    let e = Sum{ left: Box::new(Number{ val: 2}),
                 right: Box::new(Number{ val: 2})
    };
    let sum = (2 + 2);
    println!("{:#?}", sum);
}

What I want to be able to do is get to Number's value:
e.left.val

and use nested constuctions like:
Sum{Sum{Number, Sum{Number, Number}}, Number}

I also tried to make explicit cast to Number:
let val = (e.left as Number).val;

But it fails with an error:
non-primitive cast: std::boxed::Box<(dyn Expression + 'static)> as Number
note: an as expression can only be used to convert between primitive types. Consider using the From trait.
Sorry for any language mistakes or messy explanation, English is not my first language.
I'm not an experienced programmer and very new to Rust so I would really appreciate any help, thanks!

A: Rust doesn't let you cast non primitive types.
Reference:
https://doc.rust-lang.org/rust-by-example/types/cast.html

A: I think what you're trying to do is this (complete code in the playground):
trait Expression {
    fn evaluate(&self) -> i32;
}

impl Expression for Number {
    fn evaluate(&self) -> i32 {
        self.val
    }
}

impl Expression for Sum {
    fn evaluate(&self) -> i32 {
        self.left.evaluate() + self.right.evaluate()
    }
}


text:
Q: Benefits of using inline assembly for x86 in C? I've done some googling-research on the topic "When to use ASM?" and found some useful information. Of course people mentioned vast areas of application: size and speed optimization of HL code, bootloaders, embedded systems, driver development, reverse engineering etc.
Now, I'd like to ask what can I achieve with ASM that cannot be done (or is highly ineffective) using normal C compiler (say gcc) on Intel processor (x86)?
I've heard about:

*

*implementing mutexes - direct CPU support needed (eg. lock, xchg)

*fancy bit operations - find highest/lowest bit set to 1 (bsf, bsr), test if a bit is 1 (bt, bts...), rotate a value (ror, rol)

*interrupt masking (sti, cli)

*accessing CPU-specific information (cpuid)

Some people suggest re-writing standard memory functions (eg. memcpy()) in ASM. I thought that compilers nowadays have already these operations implemented in an optimal manner, but maybe I'm wrong?
Someone also mentioned int/float conversion which I don't understand. I mean is this also much more efficient to perform such a conversion manually?

A: Using advantage of CPU architectiure that is not supported by compiler.  When your compiler is not good enought to perform vectorizations on your calculations to get a better performance, you can use assembly too. Think about doing 32 char calculations with a single instruction in AVX capable CPU.

*

*Making direct hardware access for device drivers.

*Spot-optimizing speed-critical sections of code.

*Using class-structures and elements of them freely

*Based on arch., using xmm-ymm registers for push and pop operations of EAX,EBX,... decreases function overheading.

*Putting a long NOP sequence as editable area(for self-editing)


text:
Q: SQL Select from table twice I am trying to select from the same table twice within SQL.
I have a POLICIES table that has an index (NEXTPOLICYID) that refers to itself.
I need to compare the current premium with the estimated premium.
How can I get a result that shows the following on the same result row?
t1 = Current
t2 = Future
End result should be:

t1.POLICIES_ID | t1.WRITTEN_PREMIUM | t2.POLICIES_ID | t2.ESTIMATED_PREMIUM

This is what I have right now, and I am getting an error on my join statement, but I fear that is not my only problem.
SELECT
    t1.POLICIES_ID, t1.WRITTEN_PREMIUM, t1.NEXTPOLICYID, t2.ESTIMATED_PREMIUM
FROM
    POLICIES t1 JOIN
    POLICIES t2
    ON t1.NEXTPOLICYID = t2.POLICIES_ID

I am getting the following error:
Message: odbc_exec(): SQL error: [Rocket U2][UVODBC][1401233]Error ID: 29 Severity: ERROR Facility: FPSRVERR - Line 5, column 17 (around "JOIN"): Syntax error., SQL state S1000 in SQLExecDirect

This is an ODBC Connection to a uniVerse database, I have tested this with many other functions and it works fine.  This error tells me it does not like something before the JOIN statement.
Thank you

A: This:
SELECT
    t1.POLICIES_ID,
    t1.WRITTEN_PREMIUM
    t1.NEXTPOLICYID,
    t2.ESTIMATED_PREMIUM,
    t2.POLICIES_ID
FROM
    POLICIES t1,
    JOIN POLICIES t2 ON t1.NEXTPOLICYID = t2.POLICIES_ID

has some issues with commas in the wrong places and should be:
SELECT
    t1.POLICIES_ID,
    t1.WRITTEN_PREMIUM,
    t1.NEXTPOLICYID,
    t2.ESTIMATED_PREMIUM,
    t2.POLICIES_ID
FROM
    POLICIES t1
    JOIN POLICIES t2 ON t1.NEXTPOLICYID = t2.POLICIES_ID

I'm guessing that's the reason for the error.

A: Apart from the comma, the only other issues are:

*

*You don't need to include t2.POLICIES_ID in the select list, because you have t1.NEXTPOLICYID

*You might want to consider a left outer join, to keep policies that have no next policy.

The query might be:
 SELECT t1.POLICIES_ID, t1.WRITTEN_PREMIUM, t1.NEXTPOLICYID,
        t2.ESTIMATED_PREMIUM
 FROM POLICIES t1 JOIN
      POLICIES t2
      ON t1.NEXTPOLICYID = t2.POLICIES_ID;


text:
Q: Laravel order by child in the same table I have a thread table with replies in the same table named posts:
       ID  |  PARENT_ID  | CATEGORY_ID |  CREATED_AT  | UPDATED_AT

If the "PARENT_ID" not null then is a thread otherwise is a reply.
With a "CATEGORY_ID=3" i want to get all threads with pagination ordered by "UPDATED_AT" of last reply if there is one.

A: I think the best solution is not to go in this direction but rather update the parent when creating a child using the method:
$parent->touch();

with this solution we don't need to look for the children to know the order of the parents