text:
Q: Question about Drawing a graph with networkx I am using NetworkX for drawing graph, when I searching in NetworkX documentation I saw a code from Antigraph class that was confusing and I can't understand some line of this code. Help me for understanding this code, please.
I attached this code:
import networkx as nx
from networkx.exception import NetworkXError
import matplotlib.pyplot as plt

class AntiGraph(nx.Graph):
    """
    Class for complement graphs.

    The main goal is to be able to work with big and dense graphs with
    a low memory footprint.

    In this class you add the edges that *do not exist* in the dense graph,
    the report methods of the class return the neighbors, the edges and
    the degree as if it was the dense graph. Thus it's possible to use
    an instance of this class with some of NetworkX functions.
    """

    all_edge_dict = {"weight": 1}

    def single_edge_dict(self):
        return self.all_edge_dict

    edge_attr_dict_factory = single_edge_dict

    def __getitem__(self, n):
        """Return a dict of neighbors of node n in the dense graph.

        Parameters
        ----------
        n : node
           A node in the graph.

        Returns
        -------
        adj_dict : dictionary
           The adjacency dictionary for nodes connected to n.

        """
        return {
            node: self.all_edge_dict for node in set(self.adj) - set(self.adj[n]) - {n}
        }

    def neighbors(self, n):
        """Return an iterator over all neighbors of node n in the
           dense graph.

        """
        try:
            return iter(set(self.adj) - set(self.adj[n]) - {n})
        except KeyError as e:
            raise NetworkXError(f"The node {n} is not in the graph.") from e

    def degree(self, nbunch=None, weight=None):
        """Return an iterator for (node, degree) in the dense graph.

        The node degree is the number of edges adjacent to the node.

        Parameters
        ----------
        nbunch : iterable container, optional (default=all nodes)
            A container of nodes.  The container will be iterated
            through once.

        weight : string or None, optional (default=None)
           The edge attribute that holds the numerical value used
           as a weight.  If None, then each edge has weight 1.
           The degree is the sum of the edge weights adjacent to the node.

        Returns
        -------
        nd_iter : iterator
            The iterator returns two-tuples of (node, degree).

        See Also
        --------
        degree

        Examples
        --------
        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
        >>> list(G.degree(0))  # node 0 with degree 1
        [(0, 1)]
        >>> list(G.degree([0, 1]))
        [(0, 1), (1, 2)]

        """
        if nbunch is None:
            nodes_nbrs = (
                (
                    n,
                    {
                        v: self.all_edge_dict
                        for v in set(self.adj) - set(self.adj[n]) - {n}
                    },
                )
                for n in self.nodes()
            )
        elif nbunch in self:
            nbrs = set(self.nodes()) - set(self.adj[nbunch]) - {nbunch}
            return len(nbrs)
        else:
            nodes_nbrs = (
                (
                    n,
                    {
                        v: self.all_edge_dict
                        for v in set(self.nodes()) - set(self.adj[n]) - {n}
                    },
                )
                for n in self.nbunch_iter(nbunch)
            )

        if weight is None:
            return ((n, len(nbrs)) for n, nbrs in nodes_nbrs)
        else:
            # AntiGraph is a ThinGraph so all edges have weight 1
            return (
                (n, sum((nbrs[nbr].get(weight, 1)) for nbr in nbrs))
                for n, nbrs in nodes_nbrs
            )

    def adjacency_iter(self):
        """Return an iterator of (node, adjacency set) tuples for all nodes
           in the dense graph.

        This is the fastest way to look at every edge.
        For directed graphs, only outgoing adjacencies are included.

        Returns
        -------
        adj_iter : iterator
           An iterator of (node, adjacency set) for all nodes in
           the graph.

        """
        for n in self.adj:
            yield (n, set(self.adj) - set(self.adj[n]) - {n})

# Build several pairs of graphs, a regular graph
# and the AntiGraph of it's complement, which behaves
# as if it were the original graph.
Gnp = nx.gnp_random_graph(20, 0.8, seed=42)
Anp = AntiGraph(nx.complement(Gnp))
Gd = nx.davis_southern_women_graph()
Ad = AntiGraph(nx.complement(Gd))
Gk = nx.karate_club_graph()
Ak = AntiGraph(nx.complement(Gk))
pairs = [(Gnp, Anp), (Gd, Ad), (Gk, Ak)]
# test connected components
for G, A in pairs:
    gc = [set(c) for c in nx.connected_components(G)]
    ac = [set(c) for c in nx.connected_components(A)]
    for comp in ac:
        assert comp in gc
# test biconnected components
for G, A in pairs:
    gc = [set(c) for c in nx.biconnected_components(G)]
    ac = [set(c) for c in nx.biconnected_components(A)]
    for comp in ac:
        assert comp in gc
# test degree
for G, A in pairs:
    node = list(G.nodes())[0]
    nodes = list(G.nodes())[1:4]
    assert G.degree(node) == A.degree(node)
    assert sum(d for n, d in G.degree()) == sum(d for n, d in A.degree())
    # AntiGraph is a ThinGraph, so all the weights are 1
    assert sum(d for n, d in A.degree()) == sum(d for n, d in A.degree(weight="weight"))
    assert sum(d for n, d in G.degree(nodes)) == sum(d for n, d in A.degree(nodes))

nx.draw(Gnp)
plt.show()

I can't understand in these 2 lines:
(1) for v in set(self.adj) - set(self.adj[n]) - {n}
(2) nbrs = set(self.nodes()) - set(self.adj[nbunch]) - {nbunch}

A: To understand these lines, lets break each term carefully. For the purpose of explaination, I will create the following Graph:
import networkx as nx

source = [1, 2, 3, 4, 2, 3]
dest = [2, 3, 4, 6, 5, 5]
edge_list = [(u, v) for u, v in zip(source, dest)]

G = nx.Graph()

G.add_edges_from(ed_ls)

The Graph has the following edges:
print(G.edges())
# EdgeView([(1, 2), (2, 3), (2, 5), (3, 4), (3, 5), (4, 6)])

Now lets understand the terms in the above code:
set(self.adj)
If we print this out, we can see it is the set of nodes in the Graph:
print(set(self.adj))
# {1, 2, 3, 4, 5, 6}

set(self.adj[n])
This is the set of nodes adjacent to node n:
print(set(G.adj[2]))
# {1, 3, 5}

Now lets look at the first line that you asked in your question
for v in set(self.adj) - set(self.adj[n]) - {n}

This can be translated as follows:
for v in set of all nodes - set of nodes adjacent to node N - node N

So, this set of all nodes - set of nodes adjacent to node N returns the set of nodes that are not adjacent to node N (and this includes node N itself). (Essentially this will create the complement of the Graph).
Lets, look at an example:
nodes_nbrs = (
                (
                    n,
                    {
                        v: {'weight': 1}
                        for v in set(G.adj) - set(G.adj[n]) - {n}
                    },
                )
                for n in G.nodes()
            )

This will have the following value:
Node 1: {3: {'weight': 1}, 4: {'weight': 1}, 5: {'weight': 1}, 6: {'weight': 1}}
Node 2: {4: {'weight': 1}, 6: {'weight': 1}}
Node 3: {1: {'weight': 1}, 6: {'weight': 1}}
Node 4: {1: {'weight': 1}, 2: {'weight': 1}, 5: {'weight': 1}}
Node 6: {1: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}, 5: {'weight': 1}}
Node 5: {1: {'weight': 1}, 4: {'weight': 1}, 6: {'weight': 1}}

So if you look closely, for each node, we get the a list of nodes that were not adjacent to the node.
For say, node 2, the calculation would look something like this:
{1, 2, 3, 4, 5, 6} - {1, 3, 5} - {2} = {4, 6}

Now lets come to the second line:
nbrs = set(self.nodes()) - set(self.adj[nbunch]) - {nbunch}

Here set(self.adj[nbunch]) is basically the set of nodes adjacent to nodes in nbunch. nbunch is nothing but an iterator of nodes, so instead of set(self.adj[n]) where we get neighbors of a single node, here we get neighbors of multiple nodes.
So the expression can be translated as follows:
Set of all nodes - Set of all nodes adjacent to each node in nbunch - Set of nodes in nbunch
Which is same as the first expression that you asked except that this one is for multiple nodes, i.e. This will also return the list of nodes that are not adjacent to nodes in nbunch


text:
Q: Insert a column of non-numeric data into a cell's column at arbitrary location and shift old data to the right I need to insert a column (vector) with non-numeric data cells (one or multiple strings) into a cell of non-numeric data at an arbitrary location and retain old data columns by shifting them to the right.
my_word =
's'    'i'    'p'
's'    'i'    'p'
's'    'i'    'p'
's'    'i'    'p'
's'    'i'    'p'

my_column =
'a'
'b'
'c'
'd'
'e'

result_cell_1 =
's'    'a'    'i'    'p'
's'    'b'    'i'    'p'
's'    'c'    'i'    'p'
's'    'd'    'i'    'p'
's'    'e'    'i'    'p'

result_cell_2 =
's'    'i'    'a'    'p'
's'    'i'    'b'    'p'
's'    'i'    'c'    'p'
's'    'i'    'd'    'p'
's'    'i'    'e'    'p'

The major problem is that I want to insert a column at the second and the third location. In addition, I am not limited to the length in the example, so the solution should allow me to loop over a row of any length and insert a column at each location incrementally. Also, I have a solution for substitution each column, including the first and the last one, so they are not the problem. The problem is in the middle, where the length is not always the same.

A: Manipulating cell arrays is very similar to normal matrices. If i were the column to insert,
result = [my_word(:,1:i-1) my_column my_word(:,i:end)]

would accomplish your goal. It breaks my_word into the first and second half, and concatenates them back together with my_column in the middle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPA_supplicant authentication implementation I need help from someone that have some experience in playing with wpa_supplicant code.
What i understand is that wpa_supplicant dose everything in order for a supplicant to connect to an AP (if that what you what). Hence the steps are as:

*

*Scan

*Get scan results

*AUTH

*ASSOC

*4-hand shake

*data exchange

As i understand this then the first 4 steps are only managed by wpa_supplicant. That is, wpa_supplicant simply calls the under laying driver to perform these steps and after the main event loop receives the EVENT_ASSOC msg. it starts the 4-handshake.
For my part, it is fine with the first two steps are carried out at the driver, ie., wpa_supplicant send a scan req, the driver perform the scan and feed the scan results.
My question is, is it correct that wpa_supplicant cannot generate the necessary packet and use, e.g., layer 2 (rawsocket) to send authentication request to the AP ? and followed by an associate request ?... shall one simply provides these as a handle from the driver layer ?
as i can see from the code in wpa_supplicant.c
(void wpa_supplicant_associate(struct wpa_supplicant *wpa_s,
                  struct wpa_bss *bss, struct wpa_ssid *ssid))
that this function calls a function pointer to the selected driver eg. ".associate = wpa_driver_nl80211_associate" and here the driver then send this down to the udnerlaying nl80211 driver code ? .... so wpa_supplicant can not generate these packet by it self ?
I hope that this make any sens, if not please ask :)

A: Yes, your understanding is correct. To send auth/assoc req, the wpa_supplicant should construct the corresponding NL80211 commands in following different scenarios:
a) in case the SME is maintained in wpa_supplicant

*

*NL80211_CMD_AUTHENTICATE

*NL80211_CMD_ASSOCIATE

b) in case the SME is maintained by driver

*

*NL80211_CMD_CONNECT

And these commands will trigger the corresponding cfg80211_ops hooks (.auth, .assoc, .connect) registered by the wifi driver to be called to construct the frames and then send out the frames.


text:
Q: HID report descriptor (with iPhone) I am trying to send keystrokes via bluetooth to my iPhone4 from ubuntu.
I.e., developing a very primitive virtual keyboard.
Problem Have my application talk to iPhone (i.e. using report protocol, that's all iPhone supports). As it is, my write(interruptChannelFD) calls return no errors, but
no text appears on iPhone side. The l2cap channels have been opened using blueZ library.
Question 1: Given that no virtual keyboard exists that does that, just how hard is it?
I am at the stage where iPhone and my linux box connect and stay connected, no problem.
Also, all the perror() calls are telling me that control and interrupt channel sockets connect just fine. (What I do is hciconfig my dongle to Keyboard device class and use the
well-known code by Collin Mulliner with slight modification  -- I had to enter a passcode once, as all smartphones require).
Question 2:  I should be able to just write() into interrupt socket without worrying about encryption, right? I've entered the passcode and the phone trusts the keyboard. (Collin was pondering a possible hid attack, but I connect honestly)
Also, it is my understanding that in boot protocol of a HID device, the exact report
descriptor
specfied in SPD is hardly relevant -- the report format is fixed anyway. So...
Question 3: Do I miss something major about the report protocol.
What I do is modify the Apple keyboard report descriptor and write
into the socket (see below).
const uint8_t hid_spec[] = {
    0x05, 0x01, // usage page
    0x09, 0x06, // keyboard
    0xa1, 0x01, // collection (Application)
    0x85, 0x01, // report id (0x01)
    0x05, 0x07, // usage page(keyboard)
    0x19, 0xe0, // usage min
    0x29, 0xe7, // usage max
    0x15, 0x00, // logical min
    0x25, 0x01, // logical max
    0x75, 0x01, // report size
    0x95, 0x08, // report count
    0x81, 0x02, // input (dat var abs)

    0x75, 0x08, // report size
    0x95, 0x01, // report count
    0x81, 0x01, // input (const)

            // The following two outputs I don't seem to receive
    0x75, 0x01, // report size
    0x95, 0x05, // report count
    0x05, 0x08, // usage page (LEDs)
    0x19, 0x01, // usage min
    0x29, 0x05, // usage max
    0x91, 0x02, // OUTPUT1 (dat var abs)

    0x75, 0x03,
    0x95, 0x01,
    0x91, 0x01, // OUTPUT2 (arr,const)

    0x75, 0x08, // report size
    0x95, 0x06, // report count
    0x15, 0x00, // logical min
    0x26, 0xff, 0x00 // logical max

    0x05, 0x07
    0x19, 0x00
    0x2a, 0xff, 0x00,
    0x81, 0x00,

            // A total of 9 bits sent by now
            // I tried remove the following fields
            /********** BEGIN SNIP
    0x75, 0x01,
    0x95, 0x01,
    0x15, 0x00,
    0x25, 0x01,

    0x05, 0x0c,
    0x09, 0xb8,
    0x81, 0x06,

    0x09, 0xe2,
    0x81, 0x06,

    0x09, 0xe9,
    0x81, 0x02,
    0x09, 0xea,
    0x81, 0x02,
    0x75, 0x01,
    0x95, 0x04,
    0x81, 0x01,
            **** END SNIP/

    0xc0         // end coll

};
After this, I write the following 10 bytes into the interrupt channel:
                    pkg[0] = 0xa1;   // BT HDR (DATA)
                    pkg[1] = 0x01;   // REPORT ID 0x1 == kbd
                    pkg[2] = modifiers; // Ctrl, Shift, etc
                    pkg[3] = 0x00;    // constant 0 (see descr)
                    // pkg[4] = 0x00; // the key code - entered before this point, according to HID usage tables.
                    pkg[5] = 0x00;
                    pkg[6] = 0x00;
                    pkg[7] = 0x00;
                    pkg[8] = 0x00;
                    pkg[9] = 0x00;

                    if (write(is, pkg, 10) <= 0) {
                        perror("write");
                        exit(-1);
                    }

A: Good day, sir.
Let me kindly point to you to a humble holiday timewaster of mine that actually is able to be used with a piece of junk called iPad, whose software stack should be reasonable close to iPhone of yours: https://github.com/lkundrak/virtkbd
Aside from the actual implementation, I'll try to answer your questions.
Question 1:
Given the quality and length of Bluetooth HID profile specification, USB HID one and tooling available and actual device specifics, I guess trial and error will take you further. Have an actual Bluetooth keyboard, and write a simple protocol repeater and dumper to let you observe what do they do -- refer to documentation to decrypt what's going on.
Question 2:
Right. For my iPad, I first need to pair the devices with my computer not being of a Keyboard class (my guess is that iPad otherwise attempts to make me enter a PIN, which can not be done with Bluez). Then I need to change the class to Keyboard (by running my bithdd program) and force iPad to reconnect, so that it grabs the protocol descriptor from SDP and attempts to connect to L2CAP ports 17 and 19.
Question 3:
Yes, it's pretty much like that -- I don't think you miss anything important.
Have a nice day!


text:
Q: Trouble building multi-project .sln via command line Also seems the documentation is somewhat conflicted.
devenv /? :
/Project        Specifies the project to build, clean, or deploy.
                Must be used with /Build, /Rebuild, /Clean, or /Deploy.

https://msdn.microsoft.com/en-us/library/b20w810z(VS.80).aspx :
Devenv SolutionName /build SolnConfigName [/project ProjName [/projectconfig ProjConfigName]]

Arguments
SolutionName
Required. The full path and name of the solution file.
SolnConfigName
Required. The name of the solution configuration that will be used to build the solution named in SolutionName.
/project ProjName
Optional. The path and name of a project file within the solution. You can enter a relative path from the SolutionName folder to the project file, or the project's display name, or the full path and name of the project file.

If I run devenv "C:\[PATH]\[SINGLE-PROJECT-SOLUTION].sln" /rebuild "Release|Win32" it works fine (no /project) however if I run the same command with a different solution that has multiple projects, it fails with:
The selected file is not a valid solution file.
The operation could not be completed. Unspecified error

Is it possible to run a single command to build a multi-project solution via command line in VS2005? (Ideally with parallelization)


text:
Q: How do I make each box of the Tabs panel coloured when selected? I need to make the individual tab bar light up (or coloured) when each is selected, however, I do not know how to do it. Can someone teach me please?:)
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';

const useStyles = makeStyles({
  root: {
    flexGrow: 1,
  },
});

export default function CenteredTabs() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <Paper className={classes.root}>
      <Tabs
        value={value}
        onChange={handleChange}
        indicatorColor="primary"
        textColor="primary"
        centered
      >
        <Tab label="Item One" />
        <Tab label="Item Two" />
        <Tab label="Item Three" />
      </Tabs>
    </Paper>
  );

Result:

A: This is answered in the Material UI React Documentation here: https://material-ui.com/components/tabs/
Click the <> icon to show the full source on the example.


text:
Q: Swift3: Live UiLabel update on user input I've searched everywhere and can't seem to find a clear answer on updating a label in real-time.
How do i go about updating a UILabel (real-time) without the use of a button. For example, i have a text field and a UIlabel connected to the view controller.
As soon as the user starts typing in the textfield, the same text is being displayed in real time on the UI label. As a result,this eliminates the use of a button to update the label. How do i go about doing this?

A: Use the delegate method:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    label.text = textField.text
    return true
}

A: You are update your label in textField shouldChangeCharactersInRange Delegate method :
   func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

      // Update Your label here......

     YourLabel.text = textField.text
     return true
 }

A: option 1: Directly you can make action of textfield with value changed

@IBAction func textFieldValueChange(_ sender: UITextField) {
        self.label.text = sender.text
    }

option 2: Give Delegate to TextField
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

     label.text = textField.text
     return true
 }

A: step 1:Extend class to UITextFieldDelegate
class ViewController: UIViewController,UITextFieldDelegate

In ViewDidLoad()

Step 2: Add Following code into ViewDidLoad()
txtDemo.delegate = self

txtDemo.addTarget(self, action: #selector(LabelChanged(_:)), for:.editingChanged)

step 3: Make new Function as below:
func LabelChanged(_ sender:Any) {
    lblDemo.text = txtDemo.text
}

Or Also use delegate method:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    lblDemo.text = txtDemo.text
    return true
}

Here lblDemo is UILabel outlet and txtDemo is UITextField outlet


text:
Q: Running report on JasperServer from C# Jasper Reports is a superb open source alternative to Crystal Reports. It's great for single page PDF pages such as letters & invoices to multi-page reports. However it's not very .NET friendly, and getting C#/Mono to play nice with JasperServer has not been fruitful.
Has anyone got any code samples of how to run a report on JasperServer from C#, and attach an XML dataset with the SOAP request?  It needs to work on Mono, so Microsoft.Web.Services2 is out of the question.
I had a go at trying to roll my own soap request.  Jasper Server seems to accept it, but I cant seem to get any response back other than a server 500 error. I didn't get as far as attaching a MTOM attachment.
var sb = new StringBuilder();

sb.AppendLine("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">");
sb.AppendLine("<s:Body s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
sb.AppendLine("<q1:runReport xmlns:q1=\"http://axis2.ws.jasperserver.jaspersoft.com\">");

sb.AppendLine("<requestXmlString xsi:type=\"xsd:string\">");
sb.AppendLine("<request operationName=\"runReport\" locale=\"en\">");
sb.AppendLine("    <argument name=\"RUN_OUTPUT_FORMAT\">PDF</argument>");
sb.AppendFormat("    <resourceDescriptor name=\"\" wsType=\"\" uriString=\"{0}\" isNew=\"false\">", "/JourneyReport");
sb.AppendLine("      <label>null</label>");
sb.AppendLine("      <parameter name=\"testparam\">1</parameter>");
sb.AppendLine("    </resourceDescriptor>");
sb.AppendLine("  </request>");
sb.AppendLine("</requestXmlString>");
sb.AppendLine("</q1:runReport>");
sb.AppendLine("</s:Body></s:Envelope>");

var webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:8080/jasperserver/services/repository");
webRequest.Credentials = new NetworkCredential("jasperadmin","jasperadmin");
webRequest.PreAuthenticate = true;

webRequest.Headers.Add("SOAPAction","");

//Set HttpWebRequest properties
byte[]  bytes = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
webRequest.Method = "POST";
webRequest.ContentLength = bytes.Length;
webRequest.ContentType = "text/xml; encoding='utf-8'";

//Get Stream object
var objRequestStream = webRequest.GetRequestStream();
objRequestStream.Write(bytes, 0, bytes.Length);
objRequestStream.Close();

var response = (HttpWebResponse)webRequest.GetResponse();

A: Jasper gives a Web Services API which you already have found, I suppose. For that being a Web Services using XML, it can be accessed through any language, like C# in this case, when you convert the service description (WSDL) to a service stub on that language.
On that given link there can be found Jasper Reports wsdl file locations and after having access to them your task is to create the stub, which is a code level access to the given XML interface. For Mono this can be done with a simple command line command according to this tutorial and the rest of the work is to use this code how ever you want to use it.
The exact command can be found through these two links with not much magic, but it is something as easy as one command running wsdl.exe with the given path (eg. http://localhost:8080/jasperserver/services/repository?wsdl) as argument and then compiling the result with a command similar to mcs /target:library SomeService.cs -r:System.Web.Services where you replace SomeService.cs with the name of the file that was the output of the previous command.
That's it!

A: I ran into the same problem not in mono but using Visual Studio. I always get error 500. That's because the answer of jasperserver according to the microsoft/mono code is not SOAP complient. ASP.NET expects a text/xml structure, and jasperserver sends a multipart structure back with the xml as the first part and the report as an attachment in the second part.
ASP.NET gives an exception on that. I am now trying to do a similar thing using REST, but I've not succeeded so far.
Addition: 2012-03-09
Figured out using REST, see Get report from jasperserver using REST webservice and asp.net C#
By the way, that is also working in Mono! (I develop in Visual Studio, but deploy on Mono)


text:
Q: Why is (/ 1/2) in Clojure equal to 2N? Just playing around in the Clojure repl the other day and I came across this.
user=> (/ 1/2)
2N

So I tried this:
user=> (type (/ 1/2))
clojure.lang.BigInt

Anybody know what's going on here?

A: 1/2 creates a Ratio and the / function ends up calling (clojure.lang.Numbers/divide 1 1/2). If you look at that definition it eventually ends up calling (clojure.lang.Numbers$RatioOps/divide 1 1/2). This lifts 1L into a ratio, performs the ratio division and then simplifies the result of 2/1 into the BigInt 2.


text:
Q: iOS error notification when upload to apple store finish I'm trying to make iOS apps using phonegap, but when I finish upload to the apple store, all going well I just got an email notification with error :
Version Mismatch - Neither CFBundleVersion ['2.0.0'] nor CFBundleShortVersionString [''] in the Info.plist match the version of the app set in iTunes Connect ['2.0'].
What causes this error? Is there anything wrong in the config.xml settings in phonegap?
My config.xml :
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.joriscorp.xxxx" version="2.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>Baca Berita</name>
    <description>
        Aplikasi android untuk mendapatkan informasi terkini dari situs www.bacaberita.com.
    </description>
    <author email="bertho_joris@yahoo.co.id" href="http://www.berthojoris.com/">
        Bertho Joris
    </author>
    <feature name="http://api.phonegap.com/1.0/device" />
    <preference name="phonegap-version" value="3.3.0" />
    <preference name="permissions" value="none" />
    <preference name="orientation" value="portrait" />
    <preference name="target-device" value="universal" />
    <preference name="fullscreen" value="false" />
    <preference name="webviewbounce" value="true" />
    <preference name="prerendered-icon" value="true" />
    <preference name="stay-in-webview" value="false" />
    <preference name="detect-data-types" value="true" />
    <preference name="exit-on-suspend" value="false" />
    <preference name="show-splash-screen-spinner" value="true" />
    <preference name="auto-hide-splash-screen" value="true" />
    <preference name="disable-cursor" value="false" />
    <preference name="ios-statusbarstyle" value="black-opaque" />
    <icon src="icon.png" />
    <icon src="icons/ios/icon.png" gap:platform="ios" width="57" height="57" />
    <icon src="icons/ios/icon-72.png" gap:platform="ios" width="72" height="72" />
    <icon src="icons/ios/icon_at_2x.png" gap:platform="ios" width="114" height="114" />
    <icon src="icons/ios/icon-72_at_2x.png" gap:platform="ios" width="144" height="144" />
    <gap:splash src="splash/ios/Default.png" gap:platform="ios" width="320" height="480" />
    <gap:splash src="splash/ios/Default_at_2x.png" gap:platform="ios" width="640" height="960" />
    <gap:splash src="splash/ios/Default_iphone5.png" gap:platform="ios" width="640" height="1136" />
    <gap:splash src="splash/ios/Default-Landscape.png" gap:platform="ios" width="1024" height="748" />
    <gap:splash src="splash/ios/Default-Portrait.png" gap:platform="ios" width="768" height="1004" />
    <gap:splash src="splash/ios/Default-Landscape_at_2x.png" gap:platform="ios" width="2048" height="1496" />
    <gap:splash src="splash/ios/Default-Portrait_at_2x.png" gap:platform="ios" width="1536" height="2008" />
    <access origin="*" />
</widget>

What should I do to handle this error?
Thanks....

A: According to the email, it seems as if you need to change your Version number in the General section of your Target from "2.0.0" to "2.0" and your Bundle version string in your Info.plist from " " to "2.0" since "2.0" is the version listed in iTunes Connect.
This line, for example, should be:
<widget id="com.joriscorp.xxxx" version="2.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">


text:
Q: C Exploit using Environment Variable in execve In C programming language, for execve:
int execve(const char *filename, char *const argv[],
                  char *const envp[]);

How can we use envp for exploiting?
Secondly, when passing values through envp, do we need to terminate it with a NULL?
Lastly, where is envp placed on stack?
Thanks in advance!

A: Shellcode on Linux tends to use syscalls to exec. Are you perhaps thinking of ret2libc? Your question is mixing c code and shellcode and its not clear what you are asking.

A: This example could help you understand the usage of execve() argv and envp
$ cat a.sh
#!/bin/sh
echo "value of PWDIR is $PWDIR"
echo "first arg = $1"
echo "second arg = $2"
printenv

/* execve.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    char *newargv[] = { NULL, "hello", "world", NULL };
    char *newenviron[] = {"PWDIR=/home/root" };

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <file-to-exec>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    newargv[0] = argv[1];

    execve(argv[1], newargv, newenviron);
    perror("execve");   /* execve() only returns on error */
    exit(EXIT_FAILURE);
}

Compiling the code
$ cc execve.c -o execve
Executing the code and output as follows
$ ./execve a.sh
value of PWDIR is /home/root
first arg = hello
second arg = world
PWDIR=/home/root
PWD=/home/arul/work/images/samples

Environment variable passed in execve is used in the shell script.
Also note when script is executed, separate shell will be spawned here.


text:
Q: SQL Server 2008: Multiple joined columns to rows? Someone is trying to extract data from SQL Server into a format that is more Excel-manipulable.  Here is sample data from SQL Server. Note: I changed the text from our industry-specific stuff to a car analogy, but that's all:
Table: Products
products_id | products_model
============================
100         | Saturn Vue
200         | Toyota Prius
300         | Ford Focus

Table: Categories
categories_id | categories_name
===============================
1             | Leather Seats
2             | Heated Seats
3             | Tapedeck
4             | Heater
5             | Hybrid
6             | Sunroof
7             | Cruise Control

Table: Products_Categories
products_id | categories_id
===========================
100         | 3
200         | 1
200         | 4
200         | 5
300         | 4
300         | 7

This is what they want the results/output to look like:
products_id | products_model | Leather Seats | Heated Seats | Tapedeck | Heater | Hybrid | Sunroof | Cruise Control
===================================================================================================================
100         | Saturn Vue     | N             | N            | Y        | N      | N      | N       | N
200         | Toyota Pruis   | Y             | N            | N        | Y      | Y      | N       | N
300         | Ford Focus     | N             | N            | N        | Y      | N      | N       | Y

I can't figure out how to get it to work. I tried playing with PIVOT, but it got too complex for me. I'll accept any type of solution so long as the final result looks like the one above.
The create script is in SQLFiddle.

A: You can use the PIVOT function to transform this data:
select products_id,
  products_model,
  Isnull([Leather Seats], 'N') [Leather Seats],
  Isnull([Heated Seats], 'N') [Heated Seats],
  Isnull([Tapedeck], 'N') [Tapedeck],
  Isnull([Heater], 'N') [Heater],
  Isnull([Hybrid], 'N') [Hybrid],
  Isnull([Sunroof], 'N') [Sunroof],
  Isnull([Cruise Control], 'N') [Cruise Control]
from
(
  select p.products_id,
    p.products_model,
    c.categories_name,
    'Y' flag
  from products p
  left join Products_Categories pc
    on p.products_id = pc.products_id
  left join Categories c
    on pc.categories_id = c.categories_id
) src
pivot
(
  max(flag)
  for categories_name in ([Leather Seats], [Heated Seats],
                          [Tapedeck], [Heater],
                          [Hybrid], [Sunroof],
                          [Cruise Control])
) piv

See SQL Fiddle with Demo.
If the categories_name values are unknown or not fixed, then you can use dynamic sql:
DECLARE @cols AS NVARCHAR(MAX),
    @colsNull AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(categories_name)
                    from Categories
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

select @colsNull = STUFF((SELECT ',IsNull(' + QUOTENAME(categories_name)+', ''N'')'+' as '+QUOTENAME(categories_name)
                    from Categories
                    group by categories_name, categories_id
                    order by categories_id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT products_id,
                  products_model,' + @colsNull + ' from
             (
                select p.products_id,
                  p.products_model,
                  c.categories_name,
                  ''Y'' flag
                from products p
                left join Products_Categories pc
                  on p.products_id = pc.products_id
                left join Categories c
                  on pc.categories_id = c.categories_id
            ) x
            pivot
            (
                max(flag)
                for categories_name in (' + @cols + ')
            ) p '

execute(@query)

See SQL Fiddle with Demo
The result of both queries is:
| PRODUCTS_ID | PRODUCTS_MODEL | LEATHER SEATS | HEATED SEATS | TAPEDECK | HEATER | HYBRID | SUNROOF | CRUISE CONTROL |
-----------------------------------------------------------------------------------------------------------------------
|         300 |     Ford Focus |             N |            N |        N |      Y |      N |       N |              Y |
|         100 |     Saturn Vue |             N |            N |        Y |      N |      N |       N |              N |
|         200 |   Toyota Prius |             Y |            N |        N |      Y |      Y |       N |              N |

A: easier to understand version
select distinct
  p.products_id
  ,p.products_model
  ,case when pc_ls.products_id is null then 'N' else 'Y' end as 'Leather Seats'
  ,case when pc_hs.products_id is null then 'N' else 'Y' end as 'Heated Seats'
  ,case when pc_td.products_id is null then 'N' else 'Y' end as 'Tapedeck'
  ,case when pc_ht.products_id is null then 'N' else 'Y' end as 'Heater'
  ,case when pc_hy.products_id is null then 'N' else 'Y' end as 'Hybrid'
  ,case when pc_sr.products_id is null then 'N' else 'Y' end as 'Sunroof'
  ,case when pc_cc.products_id is null then 'N' else 'Y' end as 'Cruise Control'
from products p
left join products_categories pc_ls on pc_ls.products_id = p.products_id and pc_ls.categories_id= 1
left join products_categories pc_hs on pc_hs.products_id = p.products_id and pc_hs.categories_id= 2
left join products_categories pc_td on pc_td.products_id = p.products_id and pc_td.categories_id= 3
left join products_categories pc_ht on pc_ht.products_id = p.products_id and pc_ht.categories_id= 4
left join products_categories pc_hy on pc_hy.products_id = p.products_id and pc_hy.categories_id= 5
left join products_categories pc_sr on pc_sr.products_id = p.products_id and pc_sr.categories_id= 6
left join products_categories pc_cc on pc_cc.products_id = p.products_id and pc_cc.categories_id= 7


text:
Q: Small PHP MVC framework with namespaces I'm looking for a very small MVC framework, or just sample architecture, that makes use of namespaces. I'm a bit curious on how to do it and would like to see a small example of that. Thanks! Any tips or links?

A: This is a one page mvc framework Fat-Free

A: https://github.com/Shaneprrlt/AtomicPHP
You can watch the development step by step on youtube:
Part 1
Part 2
Part 3
And it sure would help to take a look at the manual.


text:
Q: Как собрать в список последние элементы списка списков сгрупировав их по другим элементам? Есть список со списками, максимальное количество элементов в списке 3:
inp = [
    ['A1', 'B1', 'A1'],
    ['A1', 'B1', 'A2'],
    ['A1', 'B1', 'A3'],
    ['A1', 'B2', 'A4'],
    ['A1', 'B2', 'A5'],
    ['A2', 'B1', 'A6'],
    ['A2', 'B1', 'A7']
]

Первый и второй элемент списка часто дублируется, а 3й элемент разный.
Надо, чтобы первый и второй элемент списка не дублировались, а третьи элементы собирались в список.
В результате должен получиться вот такой список списков:
out = [
    ['A1', 'B1', ['A1', 'A2', 'A3']],
    ['A1', 'B2', ['A4', 'A5']],
    ['A2', 'B1', ['A6', 'A7']]
]

Не понимаю, как это можно сделать?

A: Вариант 1 - используем itertools.groupby(...):
from itertools import groupby

inp = [
    ['A1', 'B1', 'A1'],
    ['A1', 'B1', 'A2'],
    ['A1', 'B1', 'A3'],
    ['A1', 'B2', 'A4'],
    ['A1', 'B2', 'A5'],
    ['A2', 'B1', 'A6'],
    ['A2', 'B1', 'A7']
]

res = [[k[0], k[1], [t[2] for t in c]]
        for k,c in groupby(sorted(inp), key=lambda x: (x[0], x[1]))]

print(res)

результат
[['A1', 'B1', ['A1', 'A2', 'A3']],
 ['A1', 'B2', ['A4', 'A5']],
 ['A2', 'B1', ['A6', 'A7']]]

Вариант 2 - используем модуль Pandas:
import pandas as pd  # pip install pandas

df = pd.DataFrame(inp)
res = df.groupby([0,1])[2].apply(list).reset_index().to_numpy().tolist()

A: Можно сгруппировать с помощью словаря, используя кортеж со значениями первых двух столбцов в качестве ключа.
inp = [
    ['A1', 'B1', 'A1'],
    ['A1', 'B1', 'A2'],
    ['A1', 'B1', 'A3'],
    ['A1', 'B2', 'A4'],
    ['A1', 'B2', 'A5'],
    ['A2', 'B1', 'A6'],
    ['A2', 'B1', 'A7']
]

dct = {}

for *first_two_cols, third in inp:
    key = tuple(first_two_cols)
    dct.setdefault(key, [])
    dct[key].append(third)

# Переводим словарь в список.
out = [[*first_two_cols, third] for first_two_cols, third in dct.items()]
# Или так
#out = [[first, second, third] for (first, second), third in dct.items()]

from pprint import pprint
pprint(out)

Результат
[['A1', 'B1', ['A1', 'A2', 'A3']],
 ['A1', 'B2', ['A4', 'A5']],
 ['A2', 'B1', ['A6', 'A7']]]


text:
Q: SQL yyyymm date formatting I have a month column in YYYYMM-Example 201204 format and I need to break it into two column year(2012) and month(04)????
I've tried using Ltrim & Rtrim to break apart but not really working.

A: This requires string manipulations, which differ by database.  A typical method is:
select substr(col, 1, 4) as yyyy, substr(col, 5, 2) as mm

In some databases, the function would be substring().  Most databases support either substr() or substring().

A: Try
select yyyy = datepart( year  , t.datetime_column ) ,
       mm   = datepart( month , t.datetime_column ) ,
       ...
from dbo.some_table t

Or
select yyyy = year(  t.datetime_column ) ,
       mm   = month( t.datetime_column ) ,
       ...
from dbo.some_table t

Or, if the column is a string:
select yyyy = convert(int, left(  t.some_column , 4 ) ) ,
       mm   = convert(int, right( t.some_column , 2 ) ) ,
       ...
from dbo.some_table t
where t.some_column like '[0-9][0-9][0-9][0-9][0-9][0-9]'

A: Assuming Oracle (since none is specified) and varchar/char this would be another option:
select
    extract(year from (to_date('201204', 'yyyymm'))) year,
    extract(month from (to_date('201204', 'yyyymm'))) month
from dual;

First, convert to date and then get the month and year using extract function. Assumes month is always two chars and year four.


text:
Q: upload to google cloud store using json api from javascript I am trying to use gapi to upload an image to google cloud storage.The current code I have is
<script src="https://apis.google.com/js/api.js"></script>
<script type="text/javascript">
var imgData = null;

function getImage() {
    navigator.camera.getPicture(onSuccess, onFailure, {
        destinationType: navigator.camera.DestinationType.FILE_URI,
        sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
    });

    function onSuccess(imageURI) {
        imgData = encodeImageUri(imageURI);
        var contentLen = imgData.length;
        gapi.load('client', start);
    }

    function onFailure(message) {
        alert("Get image failed: " + message);
    }
}

function start() {
    // 2. Initialize the JavaScript client library.
    console.log('firing google storage api');
    gapi.client.init({
        'apiKey': 'XXX-XX'
    }).then(function() {
        // 3. Initialize and make the API request.
        console.log('api initialized');
        var request = gapi.client.request({
            'path': 'https://www.googleapis.com/upload/storage/v1/b/visionapibucket/o?uploadType=media&name=myObject',
            'method': 'POST',
            'headers': {
                'Content-Type': 'image/jpeg'
            },
            'body': imgData
        });

        try {
            //Execute the insert object request
            console.log('executing call');
            request.execute(function(resp) {
                alert(resp);
            });

        } catch (e) {
            console.log('An error has occurred: ' + e.message);
        }
    }).then(function(response) {
        console.log(response.result);
    }, function(reason) {
        console.log('Error: ' + reason.result.error.message);
    });
};
</script>

I can see that the code is hitting
the statement in console is: api initialized
but I don't see the gapi.client.request being called or even printing any error etc.
I am not sure what is wrong here. Please advise

A: You cannot upload files to Google storage by using just API key. You must have an oauth token.

If the request requires authorization (such as a request for an individual's private data), then the application must provide an OAuth 2.0 token with the request. The application may also provide the API key, but it doesn't have to.
If the request doesn't require authorization (such as a request for public data), then the application must provide either the API key or an OAuth 2.0 token, or both—whatever option is most convenient for you.

https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing
In your case, you want to upload so you must have an oauth token.
You have several workaround:

*

*You can upload the file to your server, and upload it using you server credentials by using service account.
https://cloud.google.com/compute/docs/access/service-accounts

*You can create a token on your server, and send it to your client. Then the client can upload one file to your Google Storage account without a permanent access token

*You can upload to the Google Storage account of your users. For do so, they must login to your app.
https://developers.google.com/identity/protocols/OAuth2

*The last method is, you can upload the files to your server, and copy it to the cloud by executing gutil mv command. In this case all you have to do is to login once to your Google cloud account by using  gcloud auth
gustil mv,
gcloud mv command
More info about gcloud utility, and to download it: https://cloud.google.com/sdk/


text:
Q: How to get multiple text entries from GUI and use those in a main python script? I have a python file that extracts tweets, get their geo-coordinates and sentiment and finally plots those tweets/sentiment as colored circles on a map.
The following inputs (text entries) are needed to get it to work:
An example user-input is also shown next to each input prompt:
 Enter the maximum number of tweets: *100*

 Do you want to search by topic? type: y or n: *y*

 Enter topic: *MoSalah*

 Enter visulaization/projection type:
 1. Mercator
 2. orthographic
 3. melloweide
 >>  *Mercator*

 Zoom in to a conteninent of choice:
 1. world
 2. africa
 3. asia
 4. north america
 5. south america
 6. europe
 7. usa
 >>  *world*

 Enter symbol shape:
 1. square
 2. circle
 >> *circle*

Now in order to make the user experience more exciting, I want to build a simple GUI that asks the user for all those inputs and store them into their respective variables, but I don't know how to create one and more importantly link the GUI to the python code running behind it.
Do I have to have separate retrieval function for each one of the required inputs shown above?
For example, is this how the retrieval function for max no. of tweets should look like using a tkinter GUI :
from tkinter import *
root = Tk()

root.geometry('200x100')

# Retrieve to get input form user and store it in a variable

# Retrieve maximum number of tweets

def retrieveMaxTweets():
    maxTweets = textBox.get()

    return maxTweets

textBox = Text(root, height = 2, width = 10)
textBox.pack()

buttonComment = Button(root, height=1, width=10, text='Enter max no. of tweets', command = lambda: retrieveMaxTweets())

buttonComment.pack()

mainloop()

And then in the part of the code where I initially asked for the limit, I do this:
limit = retrieveMaxTweets()

instead of this:
limit = int(input(" Enter the maximum number of tweets: "))

A: You could store the results of the different GUI 'questions' in to a dictionary ready for the other parts of the code to use. That way you would only have one function that 'collects/validates/stores' the responses.
For example
import tkinter as tk

class App(tk.Frame):
    def __init__(self,master=None,**kw):
        #Create a blank dictionary
        self.answers = {}
        tk.Frame.__init__(self,master=master,**kw)

        tk.Label(self,text="Maximum number of Tweets").grid(row=0,column=0)
        self.question1 = tk.Entry(self)
        self.question1.grid(row=0,column=1)

        tk.Label(self,text="Topic").grid(row=1,column=0)
        self.question2 = tk.Entry(self)
        self.question2.grid(row=1,column=1)

        tk.Button(self,text="Go",command = self.collectAnswers).grid(row=2,column=1)

    def collectAnswers(self):
        self.answers['MaxTweets'] = self.question1.get()
        self.answers['Topic'] = self.question2.get()
        functionThatUsesAnswers(self.answers)

def functionThatUsesAnswers(answers):
    print("Maximum Number of Tweets ", answers['MaxTweets'])
    print("Topic ", answers['Topic'])

if __name__ == '__main__':
    root = tk.Tk()
    App(root).grid()
    root.mainloop()

When the button is pressed, each of the 'answers' are added to a dictionary which is then passed to the function that does the main part of your code.


text:
Q: ffmpeg need to run this command for 360 times FFmpeg need to run this command for 360 times but it fails after 200
or any optimization for this command.
for (int i = 0; i < 360; i++) {
     commandStr = "ffmpeg -y -i /sdcard/videokit/bgimage.jpg -i /sdcard/videokit/disk_round.png -
     filter_complex [1:v]scale=800:800,setsar=1,rotate=" +
     i + "*PI/180:c=none:ow=rotw(iw):oh=roth(ih)[s];[0][s]overlay=(W-w)/2:(H-h)/2[out] -pix_fmt bgra -
     strict experimental -s 720x720 -map [out] /sdcard/videokit/image-spin/"+ i + ".png";

     vk.run(GeneralUtils.utilConvertToComplex(commandStr), workFolder, getApplicationContext());
}


text:
Q: how to use use load_file in mysql ? I get a wrong message " Can't get stat of 'D:\w.ini' " ! like the title.
I guess it is the matter of file's name. But I try "D://w.init" and "file:///D:\w.ini", I util get this wrong message.

A: My wild guess is that you are running this command on a remote mySQL server, and trying to LOAD INFILE a file on your local D:\ drive.
This cannot work, as the mySQL on server side can't access your local D: drive.
You will need to upload the file to your server first.


text:
Q: Faster way/better idea to display QR code? At the moment I'm using this to generate and display my QR code in my android app:
    try {
        BitMatrix bm = qrwriter.encode(b.toString(), BarcodeFormat.QR_CODE,
                QRCODE_WIDTH, QRCODE_HEIGHT);
        final Bitmap mBitmap = Bitmap.createBitmap(bm.getWidth(),
                bm.getHeight(), Bitmap.Config.ARGB_4444);
        for (int i = 0; i < QRCODE_HEIGHT; i++) {
            for (int j = 0; j < QRCODE_WIDTH; j++) {
                mBitmap.setPixel(i, j, bm.get(i, j) ? Color.BLACK
                        : Color.WHITE);
            }
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                imgqrcode.setImageBitmap(mBitmap);
            }
        });
    } catch (WriterException e) {

    }

It works fine, but it's very slow to use that nested loop. I have to set QRCODE_WIDTH and QRCODE_HEIGHT to very small values (which generates very blurry images on high dpi devices) just to get it to generate in a reasonable amount of time. Ideally I'd like to get the device's resolution and base the size of the QR code on that so it always looks clear.
Am I taking the wrong approach with this? Is there a faster way?

A: Are you sure from profiling that this is the slow part? You can try creating an array of pixels then setting them all at once but this takes more memory.
You should make the QR code small and let the UI scale it up. Dont render at full size. If it looks blurry then you need to disable anti aliasing.


text:
Q: Is sqlparse required and if yes, how do you install it? I have two different Django projects. One uses PostgreSQL and one uses MySQL.
In the postgres version, this worked.
    migrations.RunSQL('''CREATE OR REPLACE view skill_ranked_by_person_view AS
    SELECT link.id
    , skill.id skill_id
    , person.id person_id
    , concat( skill_rank.rank, ' — ', replace(
        concat(first_name,' ', middle_name, ' ' , last_name)
    , '  ', ' '), ' (', skill_rank.name, ')' ) person
    -- , *
    FROM people_personskill link
    INNER JOIN people_skill skill
    ON link.skill_id = skill.id
    INNER JOIN people_skillrank skill_rank
    ON skill_rank.id = link.skill_rank_id
    INNER JOIN people_person person
    ON link.person_id = person.id
    ORDER BY skill.rank desc, skill_rank.rank DESC'''),

In the MySQL version, this failed.
    migrations.RunSQL('''
    create or replace view client_view as
    select IDAutoInteger as id
    , concat(IDText,' - ', NameText) `client`
    from clients
    where IDText is not null
    order by concat(IDText,' - ', NameText) ;
    '''),

with
"sqlparse is required if you don't split your SQL "
django.core.exceptions.ImproperlyConfigured: sqlparse is required if you don't split your SQL statements manually.

Neither project has sqlparse in the requirements.txt file.
Is sqlparse required and if yes, how do you install it?

A: The solution was simple.
pip install sqlparse

I added sqlparse to requirements.txt in the MySQL project.
I checked if sqlparse was installed in the project that did not require it and it wasn't installed. I'm not sure why one project required it and one did not but the resolution of the issue was to just install sqlparse via pip.

A: As per the documentation of Django:

There are several optional Django features that require third-party Python packages that (intentionally) aren't specified as install_requires dependencies in setup.py, since not everyone would want them installed.

And then they listed sqlparse:

*

*sqlparse for multi-line SQL statements for migrations RunSQL

Source


text:
Q: To get a parameter value which is passed inside a URL to a variable in a servlet I want to get a parameter value which is passed inside a URL to a variable in a servlet.
I wrote the service as below.
@Path("/hello")
public class HelloWorldService {

    @GET
    @Path("/{name}")
    public Response getUserDetails(@PathParam("name") String email){
        String output = "User info ..  "+name ;
       // String queryParamStr = request.getQueryString();
        return Response.status(200).entity(output).build();
    }
}

I used below URL to test the service.
...//localhost:8080/Jersey-Rest/rest/hello/hansi
It shows the output as User info ..hansi
now I want to pass this parameter value to a servlet. I wrote a servlet as below.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {

        String parameter=request.getParameter("name");
        System.out.println("##########parameter############"+parameter);

    } finally {
        out.close();
    }
}

Below is my web.xml
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Restful Web Application</display-name>

    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.mkyong.rest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

I want to get the value "hansi" to the parameter variable. But I can't get. I am very new to java web.

A: You can use request.getRequestUri()
If you call the servlet with localhost:8080/Jersey-Rest/rest/hello/hansi, getRequestUri will return /Jersey-Rest/rest/hello/hansi. Then you can retrieve the 'hansi' from this string.
Example code:
String uri = request.getRequestUri();
String[] params = uri.Split("/");
String name = params[params.length()-1];

PrintWriter out = response.getWriter();
out.println( "Name : " + name);


text:
Q: Get list of cases in switch statement I use a PHP Switch statement to determine the pages of my website.  So here is an example:
switch($page) {
    case "about":
        $title_name = "About Us";
        $page_content = "includes/about-us.php";
        include("inner.php");
    break;
    case "services":
        $title_name = "Services";
        $page_content = "includes/services.php";
        include("inner.php");
    break;
}

And my file structure is index.php?page=about which converts to /about/ using htaccess.
What I want to do is take all of my pages in that switch statement and automatically grab it and put it in a list so I can automatically have it write to my footer page where I will have all of the links.
So instead of manually typing in all of the links in the footer like: Home  |  About Us |  Services |  FAQ , it will pull it automatically based on the pages I provided in the Switch statement.
Is there a way to do this?  It would also be good to automatically be able to add new pages and it will add a new case for the new page, and automatically create the page in the includes folder.
If anyone can point me in the right direction I would really appreciate it.  From my understanding, I don't believe you can do this with a switch statement, I would have to re-work the way I call the pages, right?

A: $pages = array('about'=> 'About Us', 'services' => 'Services');

if (array_key_exists($page, $pages)) {
   $title_name = $pages[$page];
   $page_content = "includes/$page.php";
   include('inner.php');
}

For your footer you can just iterate over the list of pages. To add a new page, just add it to the array and create the corresponding file.
But to answer your question: No, you can't analyze code-statements during runtime.

A: Nope, it's not possible using switch - but you could store those informations in an array:
$page_list = array(
    'about' => array(
        'title' => 'About Us',
        'content' => 'includes/about-us.php',
    ),
    'services' => array(
        'title' => 'Services',
        'content' => 'includes/services.php',
    ),
);

if(isset($page_list[$page])) {
    $page_info = $page_list[$page];

    $title_name = $page_info['title'];
    $page_content = $page_info['content'];

    include("inner.php");
} else {
    // 404 - file not found
}

// create links
foreach($page_list as $link_name => $page_ent) {
    echo "{$page_ent['title']}
"
}

// output
// About Us

// Services

A: You have this backwards. What you want is to have an array of the pages, and then loop over it once for the switch statement and once for the footer. Or, better yet, get rid of the switch statement altogether and instead use an associative array mapping pages to the info you might need to construct that particular page (there's a lot of common behavior between the switches, so knowing what your page is, you can likely just construct the proper URLs/etc from that).

A: You definitely can't get all values from a switch statement, you will have to redesign your code. Of course there are many ways to achieve this, but I normally do something like the below, which is both shorter and easier to extend than your method.
<?php

$pages = array('home', 'about', 'services', 'faq');
$titles = array('Home', 'About us', 'Services', 'FAQ');

$index = array_search($_POST['p'], $pages);
if ($index !== false) {
   $page_content = 'includes/' . $pages[$index] . '.php';
   $title_name = $titles[$index];
} else {
   print 'Page not found';
}

?>

Hope this helped.


text:
Q: iOS Login Prompt Uses Bundle Name Unfollow When using Unity Facebook SDK version 7.18 on iOS, the login permission prompt on iOS seems to be using the Bundle Name (CFBundleName) instead of Bundle Display Name (CFBundleDisplayname) in Info.plist.  The FacebookDisplayName is also set, but it is not using that.  Bundle Name by default is set to $(PRODUCT_NAME), but I don't think we'd want to change PRODUCT_NAME or Bundle Name.  What is the proper way to change or localize the app name shown in this dialog?
FB Login Dialog text:
"App Name" Wants to Use "facebook.com" to Sign In.
This allows the app and website to share information about you.
Cancel   Continue


text:
Q: Draw a complex circle (Has border only on the left half of it) using Android Shapes I'm trying to draw a complex circle with the right half different from the second one using the XML description of Android.
The final circle should have border on the left and no border on the right.
I though about creating two different circles (One with border, the other without) and merge them but I did not manage to do it.
Any ideas?
first_circle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/holo_red_dark"/>
</shape>

second_circle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/black"/>
    <stroke android:width="6dp" android:color="@color/lectra_black" />
</shape>

final_circle.xml
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp" android:drawable="@drawable/first_circle">
    </item>
    <item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp" android:drawable="@drawable/second_circle">
    </item>
</layer-list>

A: I'm answering my question : half circle with counter, the other half without.
drawable contains circle_grey.xml, counter_black.xml, counter_black_clip.xml.
layout contains activity_main.xml.
circle_grey.xml
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#A0A0A0"/>
</shape>

counter_black.xml
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval" xmlns:android="http://schemas.android.com/apk/res/android">
    <size android:width="80sp" android:height="80dp" />
    <stroke android:width="4dp" android:color="#000000" />
</shape>

counter_black_clip.xml
<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/counter_black"
    android:clipOrientation="horizontal"
    android:gravity="left" />

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:background="@drawable/circle_grey"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/layout_half_cercle"
            android:weightSum="7"
            android:background="@drawable/counter_black_clip"
            android:orientation="horizontal"/>

    </LinearLayout>
</RelativeLayout>

activity_main.java
package app.test.com.myapplication;

import android.graphics.drawable.ClipDrawable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.LinearLayout;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout layoutDate = (LinearLayout) findViewById(R.id.layout_half_cercle);
        ClipDrawable drawable = (ClipDrawable) layoutDate.getBackground();
        drawable.setLevel(drawable.getLevel() + 5000);
    }
}

A: Thanks a lot. This is the best example of how to simply implement a ClipDrawable - using 2 shapes (drawable resources) to create a new one using  for those using it for purposes other than for a progress bar.


text:
Q: Alternative to __del__ for final result & killing processes in a class? This dummy class is similar to a current project of mine:
class EndProcess(object):

    def __init__(self):
        self._Q = multiprocessing.Queue()

        self.p1 = multiprocessing.Process(target=self.worker, args=("p1",))
        self.p2 = multiprocessing.Process(target=self.worker, args=("p2",))
        self.p3 = multiprocessing.Process(target=self.worker, args=("p3",))
        self.p1.start()
        self.p2.start()
        self.p3.start()

    def worker(self, name):
        while True:
            rnd = random.randint(0, 100)
            self._Q.put((name, rnd))
            print(name, rnd)
            time.sleep(1)

    def __del__(self):
        # "log" final state of Queue
        while not self._Q.empty():
            print(self._Q.get())

        # free resources
        ...

        # clean up workers
        self.p1.terminate()
        self.p2.terminate()
        self.p3.terminate()

if __name__ == "__main__":
    ep = EndProcess()

The problem is that __del__ is not guaranteed to be always called, especially at important points in time, since __del__ is only called by Python's garbage collector when the reference count of the object reaches zero.
How can I assure that resources always get set free and the workers always get terminated?

A:
How can I assure that resources always get set free and the workers always get terminated?

You can accomplish this by implementing the context manager methods __enter__ and __exit__. You can then use your EndProcess class with the context manger statement with. This way, your clean-up logic will executed even if an error occurs:
class EndProcess(object):
    def __init__(self):
        self._Q = multiprocessing.Queue()
        self.p1 = multiprocessing.Process(target=self.worker, args=("p1",))
        self.p2 = multiprocessing.Process(target=self.worker, args=("p2",))
        self.p3 = multiprocessing.Process(target=self.worker, args=("p3",))
        self.p1.start()
        self.p2.start()
        self.p3.start()

    def worker(self, name):
        while True:
            rnd = random.randint(0, 100)
            self._Q.put((name, rnd))
            print(name, rnd)
            time.sleep(1)

    def __enter__(self):
        # Add your setup logic here. Initialize any data structures.
        # set any threads, etc.
        pass

    def __exit__(self, exc_type, exc_value, traceback):
        # The three arguments to `__exit__` describe the exception
        # caused the `with` statement execution to fail. If the `with`
        # statement finishes without an exception being raised, these
        # arguments will be `None`.
        #
        # These arguments may be useful for things such as logging, or
        # debugging.
        while not self._Q.empty():
            print(self._Q.get())
        ...
        self.p1.terminate()
        self.p2.terminate()
        self.p3.terminate()
        ...

Now you can use EndProcess instances in a context manager statement:
end_process = EndProcess()
...
with end_process as ep:
    # Use ep like you would normally. `__enter__` and `__exit__` will be
    # automatically.
    pass


text:
Q: SalesForce SmartStore not working above android version 2.2 please help me to implement Smartstore using Salesforce sdk for above android version 2.2. I have tried to run SmartStore app on android version 4.0 device, but it gives me exception
        "info.guardianproject.database.sqlcipher.SQLiteException: not an error"
I think i am using old SqlChipper jar file or maybe some other reason. But app is working fine on 2.2 or below devices.
Thanks in Advance!


text:
Q: Using sect and slots in Scheme I am trying to learn the beginnings of FP, with the help of "Algorithms for Functional Programming". At chapter 2 the writer introduces the sect and <> keywords. One of the procedures in the book would be:
(define add1 (sect + <> 1))

I used Repl.it to compute the procedure. But sadly enough, it throws following error:
Error: execute: unbound symbol: "<>" []

Then I tried Racket, because I read here Repl.it uses BiwaScheme which doesn't fully support any Scheme standard. But then I got another error:
sect: undefined;
cannot reference an identifier before its definition

So am I doing something wrong? Or is there another editor / IDE that I should use?

A: I was wrong, both sect and <> are not Scheme keywords. In the preface it is mentioned the author uses the (afp primitives) library for primitive procedures and syntax extensions. By using this library you get a bunch of extra procedures at your disposel.
You can download it here.

A: Racket comes with an add1 function; no need to define your own.
And it supports SRFI-26 cut, which is what that sect looks to be by another, more common name:
> (require srfi/26)
> ((cut + 1 <>) 2)
3


text:
Q: Fractional Number. how to fix this error. . when user input whole number and multipy it there's no problem in this part of my code
but when user input a fractional number(negative or positive) like "1/2,-2/3 ETC" there is an error
the error  is pointing in: new1 = CDbl(txta1.Text) * CDbl(txtb2.Text) * CDbl(txtc3.Text)
Error Message: Conversion from string "1/2" to type 'Double' is not valid.
view plaincopy to clipboardprint?
Dim new1, new2, new3, new4, new5, new6, add1, add2, minus1 As Double
    new1 = CDbl(txta1.Text) * CDbl(txtb2.Text) * CDbl(txtc3.Text)
    new2 = CDbl(txta2.Text) * CDbl(txtb3.Text) * CDbl(txtc1.Text)
    new3 = CDbl(txta3.Text) * CDbl(txtb1.Text) * CDbl(txtc2.Text)

    new4 = CDbl(txtc1.Text) * CDbl(txtb2.Text) * CDbl(txta3.Text)
    new5 = CDbl(txtc2.Text) * CDbl(txtb3.Text) * CDbl(txta1.Text)
    new6 = CDbl(txtc3.Text) * CDbl(txtb1.Text) * CDbl(txta2.Text)

A: Please activate Option strict ON, which will help you to prevent rookie mistakes like trying to use a textfield like txta1.text as a number:
http://support.microsoft.com/kb/311329
You have to try to parse a value from text to a number like so:
Dim number1 As Double

If Double.TryParse(txta1.Text, number1) Then
 // do something
Else
   Console.WriteLine("{0} is outside the range of a Double.", _
                   value)
// report error
End If

Otherwise it is very hard to debug your code.
As to fractions: I would be very hard to parse a fraction reliably by hand. I would somethink prebuild, like a mathematic expression library. Take a look: https://ncalc.codeplex.com/

A: "1/2" is a string and must be parsed and converted into a numeric by your code.
Here is an example.
For use with simple fractions (as shown in your example), decimals and negative numbers.
Note: You should add error checking. For brevity, I did not include any error checking.
    Dim strInput As String = "-1/2"
    Dim dblValue As Double = Nothing

    If strInput.Contains("/") Then ' A fraction
        Dim strArray() As String = strInput.Split(CChar("/"))
        dblValue = CDbl(strArray(0)) / CDbl(strArray(1))
    Else
        dblValue = CDbl(strInput)
    End If
    Console.WriteLine(dblValue)


text:
Q: Unison sync of sshfs mount - what can go wrong if the connection breaks? I am syncing a local directory (say "/local") with a cloud storage server  using Unison. The cloud storage is mounted to, say, "/mnt" via sshfs (with no-cache option), and I sync the two directories /local and /mnt with Unison locally.
[I don't have root access to the server, and Unison is not installed on the server, so a genuine remote sync with Unison is not possible.]
In short, I am looking for a safe way to sync the local directories of multiple computers with the server (including the correct handling of removed files).
I assume that the Unison sync between local directories is safe in principle, as long as nothing happens to the connection. But what if the sshfs connection breaks while Unison is working? Unfortunately I don't understand well enough how sshfs connections work in order to judge whether there is a data loss risk.
Assume Unison is in the process of writing a modified file to /mnt when the connection breaks. Will it quit with an error (which I assume would be safe)?
My fear is that it keeps writing to /mnt although the connection is broken, and then marks a file as successfully transferred in its archive although the file has not actually been written to the server. Could this happen?
How about read processes? It seems that when I disconnect while Unison is reading /mnt it always fails with the error message that /mnt has been emptied completely (good!). But is there any situation in which it might get the information that only part of the data in /mnt is missing and then wrongly assumes that these files have been deleted?
EDIT: Reading the Unison manual again, I got aware of the "mountpoint" parameter. However, the way the manual makes it sound, Unison checks for the existence of the mountpoint only once, after detecting updates. So I still see the risk of something going wrong if the connection breaks during file transfer.
EDIT2: Essentially, my question is the same as this - seemingly unanswered - question in the fuse sourceforge mailing list: https://sourceforge.net/p/fuse/mailman/message/1605382/


text:
Q: How do I determine if adding 2 numbers will involve regourping / carryover or subracting 2 numbers will involve borrowing? I need to create a function that will generate 2 random numbers between x and y (e.g. x = 1, y = 20) which when added will not involve regrouping / carryover or which when subracted will not involve borrowing.
For example,
18 + 1 = good
14 + 5 = good
18-7 = good
29 - 8 = good

15 + 6 = bad
6 + 7 = bad
21 - 3 = bad
36 - 8 = bad etc.

I want to create a simple worksheet generator that will generate sample problems using the requirements above.
I guess I could always convert the number to string, get the right most digit for each of the 2 numbers, convert them back to integer, and test if one is greater than the other. Repeat for all the digit. Only thing is, that is so damn ugly (read inefficient). I am sure that there is a better way. Anyone have any suggestions? Thanks

A: Generate them one digit at a time.  e.g
a1 = rand(9)
a2 = rand(9 - a1)

b1 = rand(9)
b2 = rand(9 - b1)

x = b1*10 + a1
y = b2*10 + a2

From the construction you know that x+y will not involve any carry, because a1+a2 <= 9 and b1 + b2 <= 9.
You can do similar for subtraction.
If you want to restrict the overall range to be [1..20] instead of [1..99], just adjust the range for the leftmost digit:
b1 = rand(1)
b2 = rand(1 - b1)

A: Breaking up the numbers into digits is indeed exactly what you need to do.  It does not matter whether you do that by arithmetic manipulation (division and modulus by 10) or by converting the numbers into strings, but fundamentally your question is precisely about the individual digits of the numbers.

*

*For the subtraction x − y, no borrows are required if and only if none of the digits in y are greater than the corresponding digit in x.

*For the addition x + y, there will be no carries if and only if the sum of each pair of corresponding digits is less than 10.
Here's some pseudo-C# for checking these conditions:
bool CanSubtractWithoutBorrow (uint x, uint y) {
    while (y > 0) {
        if ((x % 10) < (y % 10)) return False;
        x /= 10; y /= 10;
    }
    return True;
}

bool CanAddWithoutCarry (uint x, uint y) {
    while (x > 0 && y > 0) {
        if ((x % 10) + (y % 10) >= 10) return False;
        x /= 10; y /= 10;
    }
    return True;
}

A: using System;

class Sample {
    static void Main() {
        var rnd = new Random();
        var x = 1;
        var y = 20;
        var a = rnd.Next(x, y);
        var b = rnd.Next(x, y);
        var op = '+';
        Console.WriteLine("{0} {2} {1} = {3}", a, b, op , isValid(a, b, op)? "good":"bad");
        op = '-';
        Console.WriteLine("{0} {2} {1} = {3}", a, b, op , isValid(a, b, op)? "good":"bad");
    }
    static bool isValid(int x, int y, char op){
        int a = x % 10;
        int b = y % 10;
        switch (op){
        case '+':
            return a + b < 10;
        case '-':
            return x >= y && a - b >= 0;
        default:
            throw new Exception(String.Format("unknown operator '{0}'", op));
        }
    }
}

A: You need to look at each pair digit in turn, and see if adding or subtracting them involves carries.
You can get the rightmost digit by taking the value modulo 10, x%10, and you can erase the right most digit by dividing by 10.
No string conversions are necessary.


text:
Q: authentication failure on new arch install I'm setting up a new machine running Arch and after going through the beginner's guide I rebooted into the machine and when trying to log in as my user or as root with correct passwords I get back the "Login Incorrect" error.
How I can debug this? All I see in journalctl is this (I tried logging in 3 times, twice for root and once for my user)
login[285]: pam_unix(login:auth): authentication failure; logname=LOGIN uid=0 euid=0 tty=tty1 ruser= rhost= user=root
login[285]: FAILED LOGIN 1 tty1 FOR root, authentication failure
login[285]: FAILED LOGIN 2 tty1 FOR root, authentication failure
login[285]: pam_unix(login:auth): authentication failure; logname=LOGIN uid=0 euid=0 tty=tty1 ruser= rhost= user=dillon
login[285]: FAILED LOGIN 3 tty1 FOR dillon, authentication failure

A: It seemed that the issue was my password contained symbols. In particular it contained the symbols "#" and "!". I'm assuming it was the "!" that was causing issues, but after changing the password to "hi" it seemed to let me log in.
EDIT: I found out what the real issue was.
My keymapping was set to something like "de-latin" instead of "us" and the "#" in my password was looking like this in the tty <77777777><77777777>. I didn't see this before because the password field does not show any characters.
tl;dr If you are having trouble logging in with your correct username and password make sure your keymaps are set correctly!


text:
Q: PHP MySQL building a 3 Tier multi dimensional array So I have my query, its returning results as expect all is swell, except today my designer through in a wrench. Which seems to be throwing me off my game a bit, maybe its cause Im to tired who knows, anyway..
I am to create a 3 tier array
primary category, sub category (which can have multiples per primary), and the item list per sub category which could be 1 to 100 items.
I've tried foreach, while, for loops. All typically starting with $final = array(); then the loop below that.
trying to build arrays like:
$final[$row['primary]][$row['sub']][] = $row['item]
$final[$row['primary]][$row['sub']] = $row['item]

I've tried defining them each as there own array to use array_push() on. And various other tactics and I am failing horribly. I need a fresh minded person to help me out here. From what type of loop would best suit my need to how I can construct my array(s) to build out according to plan.
The Desired outcome would be
array(
   primary = array
             (
                sub = array
                      (
                        itemA,
                        itemB,
                        itemC
                      ),
                sub = array
                      (
                        itemA,
                        itemB,
                        itemC
                      ),
             ),
   primary = array
             (
                sub = array
                      (
                        itemA,
                        itemB,
                        itemC
                      ),
                sub = array
                      (
                        itemA,
                        itemB,
                        itemC
                      ),
             ),
)

A: Something like this....
$final =
array(
    'Primary1'=>array(
        'Sub1'=>array("Item1", "Item2"),
        'Sub2'=>array("Item3", "Item4")
    ),
    'Primary2'=>array(
        'Sub3'=>array("Item5", "Item6"),
        'Sub4'=>array("Item7", "Item8")
    ),
);

You can do it using array_push but it's not that easy since you really want an associative array and array_push doesn't work well with keys. You could certainly use it to add items to your sub-elements
array_push($final['Primary1']['Sub1'], "Some New Item");

A: Something like this during treatment of your request :
if (!array_key_exists($row['primary'], $final)) {
    $final[$row['primary']] = array();
}
if (!array_key_exists($row['sub'], $final[$row['primary']])) {
    $final[$row['primary']][$row['sub']] = array();
}
$final[$row['primary']][$row['sub']][] = $row['item'];

A: If I understand you correctly, you want to fetch a couple of db relations into an PHP Array.
This is some example code how you can resolve that:
<?php

$output = array();

$i = 0;
// DB Query
while($categories) { // $categories is an db result

    $output[$i] = $categories;

    $ii = 0;
    // DB Query
    while($subcategories) { // $subcategories is an db result

        $output[$i]['subcategories'][$ii] = $subcategories;

        $iii = 0;
        // DB Query
        while($items) { // $items is an db result

            $output[$i]['subcategories'][$ii]['items'][$iii] = $items;

            $iii++;
        }
        $ii++;
    }
    $i++;
}

print_r($output);

?>


text: Q: Transcendence of algebraic numbers with Transcendental power It is known $\log\alpha$ is a transcendental number if $\alpha\neq0,1$ is algebraic. I am wondering if $$\beta^{\log\alpha}\notin\bar{\mathbb{Q}}$$ is also transcendental when $\beta$ is algebraic. Is this question still open or any reference/progress for this question ? Thank you!


text:
Q: Is there a native way to do deffered promises in Javascript in 2019? This question here - from 2014 - outlines various ways to do a deferred promise:
Resolve Javascript Promise outside function scope
There is this MDN documentation about Deferred object does say that there is Promise.defer() - but that it is obsolete.
Is there a standard way to do a deferred Promise in Javascript now? I'm otherwise likely to implement one of the Deffered objects in that original question.

A:
Is there a standard way to do a deferred Promise in Javascript now? I'm otherwise likely to implement one of the Deffered objects in that original question.

No.  There is no standard way of doing this in the current versions of Javascript.  Apparently, those shepherding the Promise specification believe the actual need for it (cases where the Promise executor function simply won't work) is rare enough that they'd rather not add it to the standard.  There may also be a belief that if they add it to the standard, too many people would use it for situations where it shouldn't be used (cases where using the promise executor would make for better code).  Obviously, that's all someone's opinion, but those who work on those standards get to decide what opinion to go with.
As you appear to know there are some pretty simple work-arounds to just define your own.  As I previously indicated in the comments, here are a couple of relevant posts on the subject, including code for work-arounds:  When would someone need to create a deferred and Deferred object in ES6.


text:
Q: C# - Create a hash of a string to an integer between a particular range I am trying to implement a form of random colour generator.
What i am planning on doing, is to create a hash of a string (Employee's name) to generate a hexadecimal value (#0 to #FFFFFF), therefore causing that employee to always correspond to the same colour.
Does anybody have an approach to do this that may work?
Thanks in Advance
EDIT
            MD5 hasher = MD5.Create();
            var hashed = hasher.ComputeHash(Encoding.UTF8.GetBytes(r.Employee.Name));
            var intColor = BitConverter.ToInt32(hashed, 0);
            color = intColor.ToString("X");

This is what i have so far, however there seems to be an issue with it somewhere as it displays the standard blue colour for everything

A: Since #0 to #FFFFFF range is 3 bytes, we can compute the hash as usual and then take, say, first 3 bytes:
public static String md5_hash3(String value) {
  using (var hash = MD5.Create()) {
    return String.Concat(hash
      .ComputeHash(Encoding.UTF8.GetBytes(value))
      .Take(3)
      .Select(item => item.ToString("X2")));
  }
}

...
 String result = md5_hash3(r.Employee.Name);

A: You can try to do it this way:
int maxValue = int.Parse("FFFFFF", System.Globalization.NumberStyles.HexNumber);
var intColor = BitConverter.ToInt32(hashed, 0);
intColor = intColor % maxValue;
var color = intColor.ToString("X");

Also it will not definitely guarantee you nice colors.


text:
Q: Why the java script loop is not running after if statement in this code? I want to print the year between 2014 and 2050 when the date is 1, day is 0 (Sunday) and month is 0 (Jan) this is the code, where I'm doing wrong?
//Write a JavaScript program to find 1st January is being a Sunday between 2014 and 2050.

for (var year = 2014; year <=2050; year++){
    var today = new Date();
    var month =  today.getMonth();
    var date  =  today.getDate();
    var year1  =  today.getFullYear();
    var day   =  today.getDay();
    // console.log(year);
if (date === 1 && day === 0 && month == 0){
    console.log(year);
}    else{
    alert("error");
}; break

};

A: I had reviewed your code and here is the analysis of your code

*

*The following line of code
}; break
Exits your loop after the first iteration, so that is not required.

*Your line of code
new Date();
Always returns the today's date.

*So instead you need to call it like:
new Date(year, 0, 1);
So , this gives you the 1st January for each year in the loop .

Hence, you just need to validate if that is a Sunday or not with the following If condition :
let date = new Date(year, 0, 1);
// checks if 1st Jan for the specific year is === 0 (sunday)
if ( date.getDay() === 0 ) {

Here is the final working code:

//Write a JavaScript program to find 1st January is being a Sunday between 2014 and 2050.
var year;
for (year = 2014; year <=2050; year++){
  let date = new Date(year, 0, 1);
// checks if 1st Jan for the specific year is === 0 (sunday)
if ( date.getDay() === 0 ) {
    console.log(year);
} else{
    // console.log("error");
};

};

References :
Syntax : new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

A: You have to create a new Date(year, 0, 1) after every iteration and then, check if it is Sunday or not.
new Date(year, 0, 1)

* year will feed the variable

* 0 represents the index of January

* 1 represents 1st of January

var date;
for (var year = 2014; year <= 2050; year++) {
  date = new Date(year, 0, 1);
  if (date.getDay() === 0) console.log(year);
};

A: This might help.
for (var year = 2014; year <= 2050; year++) {
  var d = new Date(year, 0, 1);
  if (d.getDay() === 0){
    console.log(year);
  }
}


text:
Q: Convert C++ COM class to C# for invocation by C++ executable Apologies but this is a C++ integration with C# question from a C# person!
I have a C++ EXE which invokes methods from an COM DLL which is registered as an InProcServer32 with a specific class ID.
The EXE is invoked thus:
EXENAME --UseClassId {CLSID}

The COM DLL is built in C++ at this moment and the core ".h" file looks like this:
class DECLSPEC_UUID("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX1}") ImplementationClass : public ComClass<IInterfaceMain>
{
public:
    IFACEMETHODIMP Method1(IInterfaceSub1 **param1) _NOEXCEPT override { return 1; }
    IFACEMETHODIMP Method2(IInterfaceSub1** param2) _NOEXCEPT override { return 1; }
};

CoCreatableClass(ImplementationClass)
}}}

The interface it uses is defined thus:
MIDL_INTERFACE("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX2")
    IInterfaceMain : public IUnknown
    {
    public:
        virtual HRESULT STDMETHODCALLTYPE Method1(IInterfaceSub1 **param1) = 0;
        virtual HRESULT STDMETHODCALLTYPE Method2(IInterfaceSub2 **param2) = 0;
    };

... and the interfaces used by the above are defined in a similar way.
Now, I want to create this COM DLL in .Net instead.  So the code currently looks like this:
[ComVisible(true), Guid("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX1"), ClassInterface(ClassInterfaceType.None)]
public class ImplementationClass : IInterfaceMain
{
    public ImplementationClass() {}

    public int Method1(IInterfaceSub1 param1) { return 1; }
    public int Method2(IInterfaceSub2 param2) { return 1; }
}

I have created the main interface in C# also, like this (but without any MIDL_INTERFACE / Guid):
public interface IInterfaceMain
{
    int Method1(IInterfaceSub1 param1);
    int Method2(IInterfaceSub2 param2);
}

Invoking the main EXE (the code of which isn't available) returns these two errors depending on the build architecture (top is "x64" bottom is "Any CPU").
0x80004002 No such interface supported
0x800401f9 Error in the DLL.

As I said, I'm not fluent with C++ but to my mind this should work.

A: Courtesy of Hans Passant, the answer is to decorate the interfaces with the correct [ComVisible], [Guid] and [InterfaceType] attributes.


text:
Q: How to resize Image according to parent element? How do you guys keep an image size according to the height and width of parent element ? From my current code the I get image overflow error. I haven't specified any height/width for grid I was hoping for a way that it covers the entire grid space resizing itself.
Right now the Grid has automatically divided itself into columns and rows.
GridView.builder(
      controller: _scrollController,
      scrollDirection: Axis.vertical,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
      ),
      itemCount: snapitem.length,
      itemBuilder: (context, int index) {
        return InkWell(
          child: Card(
            child: Column(
              children: <Widget>[
                GridTile(
                  child: CachedNetworkImage(
                    imageUrl: snapitem[index].poster.toString(),
                    placeholder: Center(
                      child: CircularProgressIndicator(),
                    ),
                    errorWidget: Icon(Icons.broken_image),
                    fit: BoxFit.fill,
                  ),
                ),
                ButtonTheme.bar(
                  child: ListTile(
                    title: Text(
                      snapitem[index].title,
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
          splashColor: Colors.deepPurpleAccent,
        );
      },
    );

What I want to achieve is
I want the Grid a cards, within each card there is an image above and ListTile at the bottom

A: It's not MediaQuery(), that tells you the device screen size.
First question, if you aren't using a header or footer, why are you using a GridTile at all? From grid_tile.dart :
if (header == null && footer == null)
  return child;

So get rid of the GridTile unless you plan to add a header or footer. Next...
Since your CachedNetworkImage is now a direct child of the Column, you can wrap it in an Expanded. This will ignore any size information from the CachedNetworkImage and just fit it into the space available.
See
https://docs.flutter.io/flutter/widgets/Expanded-class.html
and
Image Scale type center crop on flutter?
For more help with Flutter be sure to check out Flutter Community on Medium https://medium.com/flutter-community and our live help sessions every Wednesday at https://medium.com/flutter-community/flutterqanda/home

A: Use mediaquery
if you want your image to be half the width of the device you can use this as :
width: Mediaquery.of(context).size.width / 2


text:
Q: How (do i need to?) do i balance cells during discharge? i have a 4s4p 18650 lithium ion pack and i balance during charge (from 4 to 4.2V) down to ~5mv difference
on discharge i still see >100 mV difference at the end (2.5V). is it worth it to add a balancing circuit for discharge?
all cells are individually protected for under/over voltage.
where would i purchase such a board and how do i wire it with the main circuit?
ty for your time

A: You don't usually try to balance during discharge, just shut down when the lowest cell gets to the minimum voltage level.
Think about it.  What exactly would you to do "balance" cells on discharge?  On charging you turn on shunts across the cells that have higher voltage than the pack median.  That slows down their charging, allowing the other cells to catch up.
Turning on a shunt during discharge makes no sense.  That would only discharge the high cells to the same level as the low cells.  The pack is still limited by the lowest cell, so you get no extra output energy.
You could, in theory, open the connection to any cell that hits the minimum voltage on discharge, then turn on a bypass around it.  That would suddenly decrease the pack voltage as cells hit the minimum voltage, eventually going to 0 pack voltage when the last cell hits the limit.  Such a thing would be complicated to do and probably of little use to the load.  With cells reasonably matched in the first place, the extra energy available from the pack using this method compared to just shutting down the whole pack when the first cell hits the limit is minimal.

A: The amount of energy available between 3.25 and 3.0 V is only 2.6% of the total cell energy capacity.  I suspect that between 3.0 and 2.5 V, there is only 1.0% energy available.  There is no point running a cell below 3.25 V and below 3.0 V you are damaging the cell.
A 0.1 V mismatch between banks of 4P cells is not a big deal at 3.3 V (preferred cutoff).  At 2.5 V, you are bound to get .1 V mismatch, but you should not be there in the first place.
The energy capacity between 3.4 V and 3.3 V is about 1.9% of the total cell energy capacity.  And only 1.3% between 3.3 V and 3.2 V.  You could conceivably cut off the lowest bank at 3.2 V instead of 3.3 V to capture this energy, which in a 4S configuration will be about 3/4 at 1.9% and 1/4 at 1.3% for an average of 1.75%.  However, I do not think it is worth the effort to balance at discharge - you are only capturing 1.43% of the total system energy.  If the 4P banks are so mismatched that at 3.4 V one of them is way below 3.3 V, then I would open the banks and rotate some cells, so at 3.3 V, no two banks are more than 0.1 V apart.
90% of the energy is between 4.05 V and 3.5 V.  80% of the energy is between 4.0 V and 3.55 V.
Note:  All of the above voltages are running un-relaxed voltages at 0.5 A drain.  Add 0.05 V to get the relaxed voltages.


text:
Q: Detect and pull all github branches Can i detect all branches in my github repos?
I'd like to write a .sh script that loops thru the branches and pulls each one.

A: The github2 module for Python provides an API library with commands for listing the branches in a repo, see this documentation.
If Python isn't your thing, take a look at the list of libraries for other languages.

A: git fetch will bring down all branches from the remote repo.  Note that it will not pull the branches, pull is fetch + merge, which is probably not what you want to do.


text:
Q: Get editorWidgetV2 type and config from field index I want to duplicate properties of fields (widget, type, lenght etc.)
I cannot figure out why when I try to get the widget value, I always get TextEdit widget type and no configuration. I changed it under layer properties but no change appear on log. How can I get the properties value I have set ?
from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from PyQt4.QtCore import QVariant

##input_layer=vector
##field_to_duplicate=field input_layer

layer=QgsVectorLayer(input_layer, "tmpName", 'ogr')
pr = layer.dataProvider()
caps = pr.capabilities()

fields = layer.pendingFields()

for field in fields:
    if field.name() == field_to_duplicate:
        FieldIdx = fields.indexFromName(field.name())
        field_widget = layer.editorWidgetV2(FieldIdx)
        field_widgetConfig = layer.editorWidgetV2Config(FieldIdx)
        QgsMessageLog.logMessage(str(FieldIdx)+str(field_widget)+str(field_widgetConfig), tag="Processing", level=QgsMessageLog.INFO)

here the message log output :
5TextEdit{}

A: You are not applying the changes to the loaded layer as you are using:
layer = QgsVectorLayer(input_layer, "tmpName", 'ogr')

Because you are referencing the shapefile itself, all fields are read as default which is Text Edit.
Instead, use:
layer = processing.getObject(input_layer)

This should give you the correct widget information.

A: Add little example using @joseph suggestion.
from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from PyQt4.QtCore import QVariant
import processing

##input_layer=vector
##field_to_duplicate=field input_layer

layer = processing.getObject(input_layer)

for field_index, field in enumerate(layer.pendingFields()):
    if field.name() == field_to_duplicate:
        field_widget = layer.editorWidgetV2(field_index)
        field_widgetConfig = layer.editorWidgetV2Config(field_index)
        QgsMessageLog.logMessage(str(FieldIdx)+str(field_widget)+str(field_widgetConfig), tag="Processing", level=QgsMessageLog.INFO)

and result is correct.
0TextEdit{}
1TextEdit{}
2TextEdit{}
3TextEdit{}
4Hidden{}


text:
Q: An integral with the Gamma function Let $c$ be a positive constant. Can you evaluate the following integral?
$$
\int_0^{\infty} \frac{x^{cx+1}}{\Gamma(1+cx)}\mathrm{e}^{-x}\,\mathrm{d}x
$$
Ps. Do you have some advices or tricks to solve this type of integrals, or variants of the above one?


text:
Q: Rasa roles of entities My team is building a bot for hotel reservations and we have recently decided to migrate from Wit.ai to Rasa. In Wit.ai, we used the build-in entities:
 - datetime - with roles check-in and check-out
-  number - with roles number of people, number of rooms, and length of stay.
How can  I put roles to datetime and number entities in Rasa? I've seen entity roles are not supported: https://github.com/RasaHQ/rasa_nlu/issues/1169. Any ideas for a workaround? I guess I need something like double named-entity recognition.
Thanks in advance.