text:
Q: Sampling from tensor that depends on a random variable in tensorflow Is it possible to get samples from a tensor that depends on a random variable in tensorflow? I need to get an approximate sample distribution to use in a loss function to be optimized. Specifically, in the example below, I want to be able to obtain samples of Y_output in order to be able to calculate the mean and variance of the output distribution and use these parameters in a loss function.
def sample_weight(mean, phi, seed=1):
    P_epsilon = tf.distributions.Normal(loc=0., scale=1.0)
    epsilon_s = P_epsilon.sample([1])
    s = tf.multiply(epsilon_s, tf.log(1.0+tf.exp(phi)))
    weight_sample = mean + s
    return weight_sample

X = tf.placeholder(tf.float32, shape=[None, 1], name="X")
Y_labels = tf.placeholder(tf.float32, shape=[None, 1], name="Y_labels")
sw0 = sample_weight(u0,p0)
sw1 = sample_weight(u1,p1)
Y_output = sw0 + tf.multiply(sw1,X)

loss = tf.losses.mean_squared_error(labels=Y_labels, predictions=Y_output)
train_op = tf.train.AdamOptimizer(0.5e-1).minimize(loss)
init_op = tf.global_variables_initializer()
losses = []
predictions = []

Fx = lambda x: 0.5*x + 5.0
xrnge = 50
xs, ys = build_toy_data(funcx=Fx, stdev=2.0, num=xrnge)

with tf.Session() as sess:
    sess.run(init_op)
    iterations=1000
    for i in range(iterations):
        stat = sess.run(loss, feed_dict={X: xs, Y_labels: ys})

A: Not sure if this answers your question, but: when you have a Tensor downstream from a sampling Op (e.g., the Op created by your call to P_epsilon.sample([1]), anytime you call sess.run on the downstream Tensor, the sample op will be re-run, and produce a new random value. Example:
import tensorflow as tf
from tensorflow_probability import distributions as tfd

n = tfd.Normal(0., 1.)
s = n.sample()
y = s**2
sess = tf.Session()  # Don't actually do this -- use context manager
print(sess.run(y))
# ==> 0.13539088
print(sess.run(y))
# ==> 0.15465781
print(sess.run(y))
# ==> 4.7929106

If you want a bunch of samples of y, you could do
import tensorflow as tf
from tensorflow_probability import distributions as tfd

n = tfd.Normal(0., 1.)
s = n.sample(100)
y = s**2
sess = tf.Session()  # Don't actually do this -- use context manager
print(sess.run(y))
# ==> vector of 100 squared random normal values

We also have some cool tools in tensorflow_probability to do the kind of thing you're driving at here. Namely the Bijector API and, somewhat simpler, the trainable_distributions API.
(Another minor point: I'd suggest using tf.nn.softplus, or at a minimum tf.log1p(tf.exp(x)) instead of tf.log(1.0 + tf.exp(x)). The latter has poor numerical properties due to floating point imprecision, which the former are optimized for).
Hope this is some help!


text:
Q: NFC Reader Cannot Read Encrypted Card Emulation Data I'm currently using Seeed Studio's NFC Shield v2 and Arduino Uno R3. Here's the code from the sketch that I'm using to read. It based on the example provided by Seeed Studio Android HCE libraries:
void loop() {
    ...
    uint8_t response[510];
    uint8_t responseLen = sizeof(response);
    success = nfc.inDataExchange(selectApdu, sizeof(selectApdu),
              response, &responseLen);

    if(success) {
      Serial.print("Response Length: "); Serial.println(responseLen);
      // nfc.PrintHexChar(response, responseLen);
      printResponse(response, responseLen);
    } else Serial.println("Failed sending SELECT AID");
  } else Serial.println("Didn't find anything!");
  delay(1000);
}

On the Android app that I have, I'm extending Android Developer's HCE example by adding digital signatures and AES encryption. I know for a fact that the app is readable if I don't add the AES encryption, and can verify the contents using a Python script. Once I add the encryption, the Arduino reads nothing from the app even though the Android device outputs logs that show the APDU was requested.
There seems to be two culprits:

*

*Response[510] is not the right size.

*The encrypted data being sent to Arduino is too big.

I changed the Response[] to various values such as 80, 1022, 2046, 8196, etc. However, the higher the values, the more freaked out Arduino becomes. Too low of a value, and nothing happens. 510 seems to be the magic number. I've logged a length count of my data being transferred:

*

*Without AES encryption, data length was 197 bytes which outputted fine on the Arduino serial console.

*With AES encryption, data length was 268 bytes and resulted in an output of "Failed sending SELECT AID", which is a false error since I was able to retrieve the AID request and APDU header.

What seems to be the problem and how can I go about fixing it, or at least have some workaround?

UPDATE: If I were to make the data being sent less than 245 bytes, the Arduino would output the data on the Serial console. Once it made it 246 bytes, it fails and outputs "Failed sending SELECT AID".

A: I still don't know how to work around this "limitation" on the Arduino but I've found a workaround. The key is to keep the data less than 245 bytes.
What I did is, instead of encrypting both the data and the signature together, I've decided to just encrypt the data and appended the signature to the end of the data along with something that I can use to delimit with (ie. "::").
This combination resulted to be a total 206 bytes, and it is being read and passed on as serial data to my Python script.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do i need to cast here? This does not calculate properly in floats.
System.out.println(tileWidth);
System.out.println(Gdx.graphics.getWidth());
float drawPPU = 200 / Gdx.graphics.getWidth();
float drawWidth = drawPPU * tileWidth;
float drawHeight = drawPPU * tileHeight;
System.out.println(drawPPU);
System.out.println(drawWidth);

Gives this output:
125
360
0.0
0.0

But when i cast my INTS like FLOATS this it does calculate properly:
float drawPPU = 200 / (float)Gdx.graphics.getWidth();
float drawWidth = drawPPU * (float)tileWidth;
float drawHeight = drawPPU * (float)tileHeight;

I am pretty sure I never did these basic calculations like this and it took my a while until i found what was actually wrong with my viewport. I mean:
 (float = 200 / 360) == (float = 200.0 / 360.0)

So is there something wrong with my setup/compiling or am i mixing things up in some way?


text:
Q: Why is a signal handler I establish with signal() or sigaction() ignored? I've got the following issue: I would like to catch SIGINT (and later, also SIGTERM) signals while my code is running on my Raspberry Pi 3 (with the recent Raspbian) in order to do some clean-up (particularly, closing a connection to a USB device) when I stop my (C++ 11) program. First I tried out signal (), but the signal handler never kicked in. Instead, I got this message on my console after hitting ^C:
2017-02-26 17:13:17 sigHandler: Unhandled signal 2, terminating

The signal manpage recommends to use sigaction() instead. OK, I took this tutorial to replace signal() with sigaction(), but no use, the handler is never called. After reading a bunch of other tutorials (like this one), I finally ended up with this code snippet:
void OnSignalCaught (int signal)
{
  cout << "Exited." << endl;
  exit (signal);
}

int main ()
{
  struct sigaction exit_action;
  struct sigaction old_action;
  int              ret;

  sigemptyset (&exit_action.sa_mask);

  exit_action.sa_handler = OnSignalCaught;
  exit_action.sa_flags   = 0;
  ret                    = sigaction (SIGINT, &exit_action, &old_action);

  if (ret < 0) cout << "Creating signal handler failed! Error code: " << errno << "." << endl;

// remainder of the code goes here
}

A: I have been running exactly your code. I only added the missing headers, and it works, the signal hangler got called.


text:
Q: How does Pig instantiate UDF objects Can some one tell me how Pig instantiates UDF objects? I used Pig to construct a pipeline to process some data. I deployed the pipeline in multi-node Hadoop cluster And I want to save all intermediate results that is produced after each step in the pipeline. So I wrote a UDF in Java that will open a HTTP connection at initialization and transmit data in exec. Also, I will close the connection in finalize of the object.
My script can be simplified as follow:
REGISTER MyPackage.jar;
DEFINE InterStore test.InterStore('localhost', '58888');
DEFINE Clean      test.Clean();

raw = LOAD 'mydata';
cleaned = FILTER (FOREACH raw GENERATE FLATTEN(Clean(*))) BY NOT ($0 MATCHES '');
cleaned = FOREACH cleaned GENERATE FLATTEN(InterStore(*));
named = FOREACH cleaned GENERATE $1 AS LocationID, $2 AS AccessCount;
named = FOREACH named GENERATE FLATTEN(InterStore(*)) AS (LocationID, AccessCount);
grp = GROUP named BY LocationID;
grp = FOREACH grp GENERATE FLATTEN(InterStore(*)) AS (group, named:{(LocationID, AccessCount)});
sum = FOREACH grp GENERATE group AS LocationID, SUM(named.AccessCount) AS TotalAccesses;
sum = FOREACH sum GENERATE FLATTEN(InterStore(*)) AS (LocationID, TotalAccesses);
ordered = ORDER sum BY TotalAccesses DESC;
STORE ordered INTO 'result';

And the code for InterStore can be simplified like below:
class InterStore extends EvalFunc<Tuple>{
  HttpURLConnection con;  //Avoid redundant connection establishment in exec
  public InterStore(String ip, String port) throws IOException
  {
    URL url = new URL("http://" + ip + ':' + port);
    con = (HttpURLConnection)url.openConnection();
    con.setRequestMethod("PUT");
    con.setDoOutput(true);
    con.setDoInput(true);
  }
  public Tuple exec(Tuple input) throws IOException
  {
    con.getOutputStream().write((input.toDelimitedString(",")+'\n').getBytes());
    return input;
  }
  @Override
  protected void finalize() throws Throwable
  {
    con.getOutputStream().close();
    int respcode = con.getResponseCode();
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    System.out.printf("Resp Code:%d, %s\n", respcode, in.readLine());
    in.close();
  }
}

However, I found that the HTTP connection cannot transmit data successfully as it does in local mode. How to deal with that?

A: Is there a service listening on 'localhost', '58888'?
Note that the local host are differs by each execution node, you might want to do this:
%default LHOST `localhost`

and use this variable as parameter
DEFINE InterStore test.InterStore('$LHOST', '58888');

In general I would do some printouts in the UDF and double check the parameters passed to it, and test the connection (like ping and check if the port is accessible from the hadoop node)


text:
Q: Writing list in csv java using CsvPrinter I have List<String> which I'm writing to a csv file but each row is written on one cell. How can I split them through "," ? I tried to set the delimiter but still it isn't working.
Code
Writer writer = new FileWriter("D://new.csv", true);
            CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
            csvPrinter.printRecords(myList);

A: As the documentation states, when you give a List<String> it'll use it a one record, ie one row, ie each String in a cell.

If the given collection only contains simple objects, this method will print a single record like printRecord(Iterable)

You need a code that use the fact that each String is in fact a row, like

*

*passing each String splitted a separate record
List<String> myList = new ArrayList<>();
for (String row : myList)
    csvPrinter.printRecord(row.split(","));

*Split all String then pass the whole list as a list of records
List<String> myList = new ArrayList<>();
List<String[]> myListSplitted = myList.stream().map(row -> row.split(",")).collect(Collectors.toList());
csvPrinter.printRecords(myListSplitted);


text:
Q: LT8390A Resistor Power Ratings I'm very new to the world of EE and I'm attempting to build my first buck/boost converter using Linear Technology's LT8390A.
For the most part I have been able to follow the datasheets instructions; however, the one thing I'm unsure about is how to calculate the necessary power ratings for each of the resistors.
Below is a copy of the image schematic in the datasheet that I am replicating. The resistors circled in red are the ones that I am unsure of the power rating on. Any help in both calculating the maximum power ratings for each resistor and showing out the math would be greatly appreciated.

Datasheet: LT8390A

A: Are you comfortable calculating the voltage across each resistor?
If so calculating the power using \$P=V^2/R\$ should be easy.

A: On any design figure out what the worst case scenario is for a resistor.
A) I would take the max Vin and divide it by the resistance of the first resistor
\$V = I*R \$ then \$ P = I^2*R\$
28/383k= 73uA or P= 73uA*383k=0.002mW Any resistor will work
B) Look at the max voltage for the CTRL pin and do the same
C) The RT pin voltage is around 1V, Vc has less than micro amps running through it (has a 10MΩ output impedance)
D) INTVcc has a 190mA max current limit
E) Same as a but use 12V and 100k, its going to be low
You get the idea, I got all this info from the datasheet and used two equations.

A: Calculating resistor power is of course an interesting exercise. However, there are somewhat bigger hurdles in selection of right capacitors (ESR, voltage, ripple tolerance), inductors, transistors, diodes.
This converter is no way a beginner's project. Therefore I strongly advise just go to the LinearTech application page for this converter, and download all design files provided by manufacturer, which includes detailed BOM. The BOM will have all proper parts, verified by experienced application engineers. Then follow the layout and parts exactly as outlined in the demo board, just maybe edit the board shape to fit it into your project. In this way you will save yourself a lot of troubles.


text:
Q: Get multiple keys value from diferent levels object Javascript I´m new on JSON /JAVASCRIPT. This is whhat i have
JSON OBJECT
const object = {
    "id": "123412341243",
    "intent": "CAPTURE",
    "purchase_units": [
        {
            "reference_id": "PU1",
            "amount": {
                "currency_code": "EUR",
                "value": "18.98",
                "breakdown": {
                    "item_total": {
                        "currency_code": "EUR",
                        "value": "18.98"
                    },
                    "shipping": {
                        "currency_code": "EUR",
                        "value": "0.00"
                    },
                    "handling": {
                        "currency_code": "EUR",
                        "value": "0.00"
                    },
                    "tax_total": {
                        "currency_code": "EUR",
                        "value": "0.00"
                    },
                    "insurance": {
                        "currency_code": "EUR",
                        "value": "0.00"
                    },
                    "shipping_discount": {
                        "currency_code": "EUR",
                        "value": "0.00"
                    }
                }
            },
            "payee": {
                "email_address": "c...r@gmail.com",
                "merchant_id": "848UWWSMK2TC4"
            },
            "description": "InfoPosit",
            "custom_id": "1231231231",
            "invoice_id": "Iabcabc",
            "items": [
                {
                    "name": "PRODUCTO 1",
                    "unit_amount": {
                        "currency_code": "EUR",
                        "value": "8.99"
                    },
                    "quantity": "1",
                    "sku": "fi78PSRA"
                },
                {
                    "name": "PRODUCTO 2",
                    "unit_amount": {
                        "currency_code": "EUR",
                        "value": "9.99"
                    },
                    "quantity": "1",
                    "sku": "fi11PMSRA"
                },
                {
                    "name": "PRODUCTO 3",
                    "unit_amount": {
                        "currency_code": "EUR",
                        "value": "9.99"
                    },
                    "quantity": "1",
                    "sku": "fi11PMSRA"
                }
            ],
            "shipping": {
                "name": {
                    "full_name": "test buyer"
                },
                "address": {
                    "address_line_1": "15 Mary Street",
                    "admin_area_2": "North Sydney",
                    "admin_area_1": "NSW",
                    "postal_code": "2001",
                    "country_code": "AU"
                }
            }
        }
    ],
    "payer": {
        "name": {
            "given_name": "test",
            "surname": "buyer"
        },
        "email_address": "c......r@gmail.com",
        "payer_id": "AAAAAAAAAA",
        "address": {
            "country_code": "ES"
        }
    },
    "create_time": "2020-05-10T00:36:33Z",
    "links": [
        {
            "href": "https://api.sandbox.paypal.com/v2/checkout/orders/21312312",
            "rel": "self",
            "method": "GET"
        },
        {
            "href": "https://api.sandbox.paypal.com/v2/checkout/orders/123123123",
            "rel": "update",
            "method": "PATCH"
        },
        {
            "href": "https://api.sandbox.paypal.com/v2/checkout/orders/123123123/capture",
            "rel": "capture",
            "method": "POST"
        }
    ],
    "status": "APPROVED"
}

Whith this code i get the NAME value from ITEMS... but i dont know how to put each value into a INPUT.
i´m trying to Get all names (purchase_units.items.name) and values (purchase_units.items.unit_amount.value) from my obbject and insert them each one in a input HTML.
JAVSCRIPT file
var key =new Array();
var key1= object.purchase_units[0].items;
for(var i=0, len=key1.length; i<len; i++) {

   key[i] = object.purchase_units[0].items[i].name;

}
 console.log(key);

i´ve tried searchin on enternet .. but after some days of searching i tough that some one here can help me..


text:
Q: How to use Axios interceptor with typescript correctly? I have created an axios interceptor:
instance.interceptors.response.use(async (response) => {
    return response.data;
  }, (err) => {
    return Promise.reject(err);
  });

which gets the response and returns the data property.
The response object is of type AxiosResponse<any, any> and the data property is just the data of the type AxiosResponse<any, any>.data.
The problem is that when I use this axios client
const instance = axios.create({...});
// ...etc
// add interceptor

then I do:
customAxiosClient.get().then((data: /* here data is of type AxiosResponse instead of AxiosResponse.data */)

How to solve this ?

A: You have to just specify the response data type in axios get method, like so:
axios.get<never, YourDataType>(...)

A: Answer by Rechu works, but I'm going to provide an alternative.
You can create a reusable function in order to keep your axios instance global. I use this myself in production.
First off, create a folder/file named utils/http.ts in your project. Next, this is my reusable function to keep everything in one place.
import axiosClient from "axios";
import type { AxiosRequestConfig } from "axios";

/**
 * Creates an initial 'axios' instance with custom settings.
 */
const instance = axiosClient.create({
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json; charset=utf-8",
  },
});

/**
 * Handle all responses. It is possible to add handlers
 * for requests, but it is omitted here for brevity.
 */
instance.interceptors.response.use(
  (res) => res.data,
  (err) => {
    if (err.response) {
      return Promise.reject(err.response.data);
    }

    if (err.request) {
      return Promise.reject(err.request);
    }

    return Promise.reject(err.message);
  }
);

/**
 * Replaces main `axios` instance with the custom-one.
 *
 * @param cfg - Axios configuration object.
 * @returns A promise object of a response of the HTTP request with the 'data' object already
 * destructured.
 */
const axios = <T>(cfg: AxiosRequestConfig) => instance.request<any, T>(cfg);

export default axios;

Finally, use it like the following code snippet:
const login = () => {
  const creds = { username: "user", password: "pass" };

  axios<User>({ method: "POST", url: "/api/v1/auth/login", data: creds })
    .then((user) => { /* do whatever with user here */ })
    .catch((err) => { /* handle errors */);
};

It will be typed and ready for immediate usage. The any in axios function can be substituted with unknown as well.


text:
Q: Closure of operator defined by extensions I am study (first time) about closure of operator and when I was reading about it, I thought in question below. I don't know if this is true or false, I think is true, but I don't know how prove it or find a counterexample.
Please somebody help me. Thanks in advance.

Let $X,Y$ Banach and $T:\mathcal{D}(T)\subseteq X\rightarrow Y$ a linear operator. Define the operator $\overline{T}:\mathcal{D}(\overline{T})\subseteq X\rightarrow Y$ such that

*

*$\overline{T}$ is linear closed operator

*$\overline{T}$ is an extension of $T$, i.e, $\mathcal{D}(T)\subseteq\mathcal{D}(\overline{T})$ and $T(x) = \overline{T}(x)$ for all $x\in\mathcal{D}(T)$.

*If $\hat{T}:\mathcal{D}(\hat{T})\subseteq X\rightarrow Y$ is any operator with properties 1. and 2., then $\hat{T}$ is an extension of $\overline{T}$.

Show that $\mathcal{G}(\overline{T}) = \overline{\mathcal{G}(T)}$. Where $\mathcal{G}(A)$ is the graph of operator $A$.

A: We will distinguish two cases: Either $\def\cl{\mathop{\mathrm{cl}}\nolimits}\def\Gr{\mathcal G}$ $\cl_{X \times Y} \Gr(T)$ is the graph of an operator or not ;-). In the first case we will show that the operator having this graph has the properties 1.-3., in the second case we will show that no such operator exists, as in this case, $T$ does not have any closed extension.
So suppose that $G:=\cl_{X\times Y} \Gr(T)$ is the graph of an operator $\bar T \colon X \to Y$. Being the closure of a subspace, $G$ is a subspace, hence $\bar T$ is linear. To show that $\bar T$ is closed, suppose $x_n \to x$, $\bar Tx_n \to y$. Then $(x_n, \bar Tx_n) \to (x,y)$. As $G$ is closed, we have $(x,y) \in G$, hence $y = \bar Tx$ and $\bar T$ is closed. Obviously $\bar T$ is an extension of $T$. Now suppose $S \supseteq T$ is a closed extension. Let $(x,y) \in G$, then there is a sequence $(x_n) \in {}^{\mathbb N}X$ such that $(x_n, Tx_n) \to (x,y)$. So $x_n \to x$, $Sx_n = Tx_n \to y$. As $S$ is closed, we must have $Sx = y$, that is $(x,y) \in \Gr(S)$. So $S \supseteq \bar T$.
If $G$ (as above) is not a graph, there is some $x \in X$, and $y\ne y'\in Y$ such that $(x,y), (x,y') \in G$. As $G$ is a subspace, we have $(0, y) \in G$ for some $y \ne 0$, that is for some $x_n \to 0$, $Tx_n \to y$. Then $T$ has no closed extension: Suppose $S \supseteq T$ were closed. Then, as $(x_n, Sx_n) \to (0, y)$, we have $S0 = y$, but, as $T$ is linear $S0 = T0 = 0$. Contradiction.


text:
Q: How should I make a text widget supporting a simple markup language? The Torque engine has a nice markup language TorqueML (see below, copied from a post in the garagegames forum). It makes it possible to incorporate some simple layout and format information in pure text, which can be used to build a text widget for help, or dialogs, in a game.
I would like to know if one can suggest a most efficient way to build/get the same feature in Haxe (especially within the HaxeFlixel framework).
Here is the markup language info available in Torque, for reference:
 - sets the font and fontsize as indicated. Example:
<tag:???> - not sure what this does
<color:rrggbb> - sets text color in hex format. Example: <color:ff0000> will display red text
<bitmap:filePath> - displays a bitmap image indicated by the file path. Example: <bitmap:demo/client/ui/seperator>
<spush> - saves the current text formatting so that temporary changes to formatting can be made. Used with spop.
<spop> - restores the previously saved text formatting. Used with spush. See the file "3. Gui Editor.hlf" included with the TGE demo for an example of usage.
<sbreak> - not sure what this does
<just:left> - left justify
<just:right> - right justify
<just:center> - center justify
LinkTitle - inserts a hyperlink into the text which will open the user's browser.
The external URL does not need the "http://" format. Example: Garage Games Website
<lmargin: ##> - sets the left margin
<lmargin%: ##> - sets the left margin (not sure what the % does)
<rmargin: ##> - sets the right margin
<rmargin%: ##> - sets the right margin (not sure what the % does)
<clip:> - not sure what this does

 - not sure what this does
<tab:##(,##,etc)> - sets the tab stops (multiple tabs are separated by commas)
 - Breaks the current line and begins a new one.

A: As a starting point, there is a rudimentary function already available in HaxeFlixel's FlxText.hx that lets you apply simple markup:
https://github.com/HaxeFlixel/flixel/blob/dev/flixel/text/FlxText.hx#L274


text:
Q: Chrome 69 and 70 goes unresponsive after a while behind corporate proxy Many users on OSX behind a corporate firewall report that Chrome will work fine for a while, then suddenly all URLS get an infinite spinner and eventually a Page Unresponsive popup. Force quitting and restarting chrome does not fix it, only a reboot does. All other apps like Safari continue to work fine. When I inspect web traffic with Charles, I see that the HTML for google.com comes back fine, but the page never renders. This was never an issue before Chrome 69. I verified this by downgrading and chrome never saw the issue. It's so bad we've all switched to Safari or Firefox. Terrible...
Any suggestions or ways to debug this? Chrome user support is of course unresponsive.


text:
Q: install spree with rails 4.1.0 I was trying to install spree as an e-commerce solution with rails 4.1.0.
I followed the guide from https://github.com/spree/spree and installed the spree gem by adding "gem 'spree' " to my Gemfile.
'Bundle install' just worked fine but I found this in my console:
...
Using spree_api 0.30.1
Using spree_auth 0.30.1
Using spree_dash 0.30.1
Using spree_promo 0.30.1
Using spree_sample 0.30.1
Using spree 0.30.1
...
Spree 0.30.1 did not work well with my project and caused lots of bugs.
When I changed my rails version to 4.2.5 everything was ok.
The question is why spree chooses to use 0.30.1 and is there anyone has met this problem?
Many thanks to anyone who replies :)

A: Just to be sure, do you know Solidus? Solidus is a Spree's fork pretty active.
https://solidus.io/

A: Well, I will suggest you to change your version. Spree current version is now 3.0.0. As you mentioned you using spree 0.30.0 which is very old version. Please upgrade to spree 3.0.0 which is the latest lot of features are new and fewer bugs in the new version. spree_3.0.0

A: You must have followed the instructions at master branch, so you installed the 3.1.beta version.
Try installing the spree using the 3.0.7 version by  replacing the

spree install

statement with

spree install my_store --branch "3-0-stable"

This should work. If you want older versions like 2.4 stable follow the instructions from different branch.
If you want to  use the older versions like 3.0.3 you will have to change the hash of spree in Gemfile  to d1a2d1b2aa4e23a40517b6905b972b4319d332d0, or even better fork spree and reset to desired hash like for example d1a2d1b2aa4e23a40517b6905b972b4319d332d0 and change path in gemfile


text:
Q: Detecting Text in an image I am using AForge.NET library for image processing. Using this library I am able detect basic shapes within an image. How can I detect the text within an image using the AForge.NET library?

A: You will need to use Optical Character Recognition (OCR). One link I found on using it with AForge can be visited here. Some code from the link:
// "K" letter, but a little bit noised
float[] pattern = new float [] {
        0.5f, -0.5f, -0.5f,  0.5f,  0.5f,
        0.5f, -0.5f,  0.5f, -0.5f,  0.5f,
        0.5f,  0.5f, -0.5f, -0.5f, -0.5f,
        0.5f, -0.5f,  0.5f, -0.5f, -0.5f,
        0.5f, -0.5f, -0.5f,  0.5f, -0.5f,
        0.3f, -0.5f, -0.5f,  0.5f,  0.5f};

// get network's output
float[] output = neuralNet.Compute(pattern);

int i, n, maxIndex = 0;

// find the maximum from output
float max = output[0];
for (i = 1, n = output.Length; i < n; i++)
{
    if (output[i] > max)
    {
        max = output1[i];
        maxIndex = i;
    }
}

//
System.Diagnostics.Debug.WriteLine(
  "network thinks it is - " + (char)((int) 'A' + maxIndex));

The only other way I can think of doing it, is using Tessaract-OCR which can read a wide variety of image formats and convert them to text in over 40 languages. There are also many other ways of doing it out there, including using Microsoft Office, or Emgu cv.
There's one more link which might work. It detects playing cards in AForge, and while doing so reads the numbers or J, Q, and K in the corner. You may have seen it already.

A: Use  Microsoft Cognitive Services - Computer Vision API
Optical Character Recognition (OCR) detects text in an image and extracts
 the recognized words into a machine-readable character stream


text:
Q: Mongame Content Pipeline: Compile FBX with embedded texture to XNB I have a FBX with embedded texture in it. And I can view the FBX displaying its texture in Autodesk FBX Review in another computer.
When I try to use Monogame Content Pipeline tool (MGCP.exe) to compile it to XNB it got error like:

path to texture not existed

So the question is does MGCP tool support to compile FBX with embedded texture into XNB? And does it produce a single XNB file for this?
(Note that it works fine with FBX having external texture but it produces additional XNB file for the associated texture which is I don't want)
Do I need to write the custom FbxImporter to do this?

A: It appears that MonoGame is currently using an older version of the model importer library, that does not support reading embedded textures. So I'm afraid you'd have to write a custom FbxImporter or modify the MonoGame one with the latest Assimp version.
If I remember correctly, XNA produced separate files even for embedded textures. The model format was not designed to carry additional texture data. If you really need to have them in a single file, you'll have to also create a new content processor.


text:
Q: Video Create from a Image using avconv I want create a video from a image,my code is
avconv -f image2  -i test2.jpg  -s 320X240 -r 30  -pix_fmt yuv420p -qmin 10 foo.mpg

But I got a error
VBV buffer size not set, muxing may fail

How can I solve this?


text:
Q: How to plot a boxplot using aggregates in plotly? I need to plot a series of boxplots, based on results of numerical air quality model. Since this is a significant amount of data, I trigger calculation of aggregates (min, max, quartiles, etc.) every time when new model results become ready and store them in PostgreSQL. For visualization purpose I load the aggregates into pandas and I plot them using dash. I am able to plot line plots of timeseries, however I would like to get something like this example, but also interactive.
As I went through plotly examples, it looks like it always require the raw data for ploting boxplots ( https://plot.ly/python/box-plots/#basic-box-plot ). I really enjoy the concept of presentation and logic separation. Is it possible to get a plotly box plot based on aggregated data?

A: You can provide your aggreate values to a Plotly boxplot in Python by providing it in the following format:
plotly.graph_objs.Box(y=[val_min,
                         val_lower_box,
                         val_lower_box,
                         val_median,
                         val_upper_box,
                         val_upper_box,
                         val_max])

e.g.
import plotly
plotly.offline.init_notebook_mode()

val_min = 1
val_lower_box = 2
val_median = 3
val_upper_box = 4.5
val_max = 6

box_plot = plotly.graph_objs.Box(y=[val_min,
                                    val_lower_box,
                                    val_lower_box,
                                    val_median,
                                    val_upper_box,
                                    val_upper_box,
                                    val_max])
plotly.offline.iplot([box_plot])

gives you


text:
Q: Classify Data by Method Regardless of Data Range I want to apply the same classification method to multiple Rasters in ModelBuilder Reclassify tool. The task is to apply the same classification method (percentile splits) across multiple rasters without setting the data value splits manually as I will always need the same 20/20/20/20/20 split of data.
How do you input a pre-defined classification method automatically e.g. Method: Quantile with 5 classes?


text:
Q: How to decide between different robust standard errors? Specifying my model I ran into some very mild heteroscedasticity problems. Given its superior small-sample properties (my dataset contains 79 observations) I used the HC3 specification of the White heteroscedasticity robust standard errors. However it renders almost all my estimates non-significant. Playing around with the data it showed that the significance levels relied on the type of the robust standard error used (HC0 to HC3) to a large extent. Also I couldn't use HC3 on all my models, apparently because its performance relies on the size of the hat values.
Now I'm slightly confused. How can I decide between these different standard errors? I don't actually have many high leverage points so is HC3 even appropriate?
Some more information on the data:
The sample size is fixed, as I'm working within comparative political science. My dependent variable is a left skewed 0-100 index. Most of the independent variables follow a normal distribution, those that don't were logged. Further a region-dummy is included
structure(list(ID = c("Afghanistan", "Albania", "Algeria", "Angola",
                            "Azerbaijan", "Bahrain", "Bangladesh", "Belarus", "Benin", "Bolivia",
                            "Burkina Faso", "Burma/Myanmar", "Burundi", "Cambodia", "Cameroon",
                            "Central African Republic", "Chad", "China", "Cuba", "Democratic Republic of the Congo",
                            "Djibouti", "Egypt", "Eritrea", "Eswatini", "Ethiopia", "Fiji",
                            "Gabon", "Guinea", "Haiti", "Honduras", "Hungary", "Iran", "Iraq",
                            "Jordan", "Kazakhstan", "Kenya", "Kuwait", "Kyrgyzstan", "Laos",
                            "Lebanon", "Madagascar", "Malawi", "Malaysia", "Mali", "Mauritania",
                            "Morocco", "Mozambique", "Nicaragua", "Niger", "Nigeria", "Oman",
                            "Pakistan", "Papua New Guinea", "Philippines", "Qatar", "Republic of the Congo",
                            "Russia", "Rwanda", "Saudi Arabia", "Serbia", "Singapore", "Somalia",
                            "South Sudan", "Sudan", "Syria", "Tajikistan", "Tanzania", "Thailand",
                            "Togo", "Turkey", "Turkmenistan", "Uganda", "Ukraine", "United Arab Emirates",
                            "Uzbekistan", "Venezuela", "Vietnam", "Zambia", "Zimbabwe"),
                     Dep_Var = c(84.26, 89.81, 92.13, 90.74, 96.3, 78.7, 93.52,
                                 19.44, 70.83, 96.3, 89.81, 86.11, 33.33, 68.52, 71.3, 75.93,
                                 88.89, 81.94, 100, 80.56, 100, 84.26, 93.52, 89.81, 80.56,
                                 88.89, 81.48, 78.7, 87.04, 100, 76.85, 64.35, 96.3, 100,
                                 89.35, 93.52, 100, 92.13, 96.3, 85.19, 95.37, 57.41, 75,
                                 72.22, 77.78, 93.52, 80.56, 16.67, 61.11, 85.65, 100, 96.3,
                                 83.8, 100, 86.11, 97.22, 87.04, 90.74, 94.44, 100, 85.19,
                                 60.19, 86.11, 91.67, 86.11, 73.15, 50, 82.41, 73.15, 77.78,
                                 58.33, 93.52, 92.59, 89.81, 96.3, 87.04, 96.3, 70.83, 87.96
                     ), Var1 = c(4.127, 5.251, 5.296, 6.541, 6.672, 6.414, 6.78,
                                 6.062, 7.056, 5.78, 5.786, 4.552, 3.537, 5.527, 5.608, 6.275,
                                 3.147, 5.291, 6.55, 4.069, 4.996, 4.586, 4.605, 6.525, 5.409,
                                 6.302, 6.324, 5.558, 3.996, 6.325, 5.951, 4.481, 3.772, 4.786,
                                 6.746, 5.645, 6.613, 6.603, 6.306, 3.814, 5.482, 6.14, 6.521,
                                 4.924, 5.121, 5.355, 5.101, 7.214, 6.554, 6.047, 5.636, 7.175,
                                 4.735, 5.151, 6.116, 4.799, 5.495, 6.855, 6.197, 6.398, 7.468,
                                 3.565, 3.891, 5.121, 3.319, 6.826, 5.235, 5.737, 5.703, 4.748,
                                 5.693, 6.474, 5.836, 6.91, 5.616, 5.979, 5.604, 6.875, 6.48
                     ), Var2 = c(7.71, 7.85, 6.22, 6.93, 5.95, 5.98, 7.46, 1.26,
                                 3.65, 3.42, 5.84, 3.31, 8.72, 7.88, 6.46, 8.05, 8.86, 5.62,
                                 4.89, 6.42, 7.13, 5.63, 7.67, 2.84, 4.66, 4.57, 5.63, 6.62,
                                 8.63, 8.64, 5.01, 3.43, 8.81, 5.72, 6.67, 5.12, 7.09, 6.05,
                                 3.51, 7.46, 6.88, 5.64, 4.48, 5.68, 7.64, 4.56, 5.4, 7.27,
                                 3.74, 7.67, 5.2, 7.83, 8.17, 7.09, 8.66, 9.11, 4.12, 2.87,
                                 6.84, 6.36, 1.83, 8.71, 7.95, 6.59, 7.53, 6.92, 3.77, 6.72,
                                 5.77, 4.83, 8.15, 5.81, 4.23, 4.3, 5.46, 8.92, 1.94, 5.48,
                                 7.55), Var3 = c(1.51522335168878, 4.15325778828397, 2.94875838540978,
                                                 1.00628430938346, 25.4230503312376, 8.18998374332489, 1.04538591988069,
                                                 1.25351605643943, 1.03389499888613, 1.14765788536537, 1.26573001102583,
                                                 1.07401182190831, 1.02601777187271, 1.03639332007889, 1.62605356699817,
                                                 1.92725573397033, 1.01254164138481, 1.03505721838858, 3.46173219653658,
                                                 1.08295832426121, 57.2882616377008, 1.20022298864129, NA,
                                                 1.43549075453128, 1.01873682901296, 1.44946193787762, 1.64439543970553,
                                                 1.00783008956213, 1.14205709505493, 1.08208397251952, 2.40225911107622,
                                                 22.5235306849493, 1.36123323295883, 1.14848994633969, 1.27546825552435,
                                                 1.15597071197187, 48.3011823156329, 1.24779693041552, 1,
                                                 2.15232361681418, 1.10011380715122, 1.05904852323133, 1.67293114440204,
                                                 1, 1.02209604887292, 1.26595913129412, 1.57959491321159,
                                                 1.04583300104408, 1.00857974540892, 1.16022802219023, 206.447814325508,
                                                 1.3232281172556, 1.01139457132996, 1.10081706683103, 3.18921374388388,
                                                 1.0557568170143, 1.23896346376779, 1.03959784429336, 17.1956183236117,
                                                 1.80633839574657, 10.3099601319805, 1.02590186237628, 1.02711959279389,
                                                 3.88462180786233, 1.03514910690513, 6.23547964396164, 1.00861987775186,
                                                 1.87180599797356, 1.19796183444303, 24.2411476428364, NA,
                                                 1.02032998088937, 1.91697325378271, 5.22699733044137, 2.96243967880312,
                                                 3.06551946990564, 1.07671406220387, 1.1343707501751, 1.01365610166913
                                 ), Var4 = c(5.02115486913067, 53.5285741103671, 39.4834327892571,
                                             29.7359115979868, 47.9358701966989, 235.03977126673, 18.5573982408046,
                                             66.6329529282582, 12.1943267185875, 35.520687621416, 7.748396902346,
                                             14.0781314341043, 2.61247472515742, 16.4312138876475, 14.9790917560296,
                                             4.67907440636335, 7.09540310138533, 102.616791283744, 88.2181889125004,
                                             5.45216212311342, 34.0884625440838, 30.2003134971543, NA,
                                             38.3702699384472, 8.57501351042922, 62.2004642089247, 76.6736686126914,
                                             10.6413123736656, 7.5458791774842, 25.7491219067443, 164.757418389402,
                                             55.2031078932382, 59.5510901036816, 43.3032934593257, 97.3114520688729,
                                             18.165469164389, 320.319801025988, 13.0939299165512, 25.3489827724281,
                                             77.8431685692976, 5.2221980923047, 4.11552340423602, 114.148376618668,
                                             8.90737285506382, 16.7791925268633, 32.0409500313298, 4.91804723063735,
                                             19.1290374537869, 5.54600968697425, 22.2985869624463, 154.740324753635,
                                             12.8470204090039, 28.4518018574842, 34.8508421836621, 647.817331974169,
                                             20.1107239887663, 115.849953826104, 8.01656186978807, 231.397986561214,
                                             74.0235455862041, 652.332824392302, NA, NA, 4.41505603374484,
                                             NA, 8.70787589323223, 11.2212181047515, 78.0819291629949,
                                             6.75542213340634, 90.4249298288882, 69.6663541063077, 7.76768575885308,
                                             36.5903131229487, 431.033230583165, 17.248411344137, NA,
                                             27.1527603640721, 12.9134335737364, 14.6398591018054), Var5 = c(2.086,
                                                                                5.23, 4.112, 2.896, 4.8, 5.36, 3.504, 4.398, 3.868, 4.356,
                                                                                3.844, 2.862, 2.16, 3.862, 3.4, 1.56, 1.942, 5.954, 4.51,
                                                                                1.89, 3.202, 3.83, 1.544, 3.68, 3.786, 5.52, 3.376, 3.058,
                                                                                1.182, 3.758, 5.974, 4.14, 2.358, 5.226, 5.044, 4.178, 4.824,
                                                                                3.776, 3.654, 3.72, 2.694, 3.542, 7.15, 2.99, 3.546, 4.582,
                                                                                3.252, 3.396, 3.468, 2.954, 5.374, 3.732, 3.646, 5.1, 6.262,
                                                                                2.566, 4.878, 5.414, 5.646, 5.224, 9.462, 0.618, 0.102, 1.76,
                                                                                1.658, 2.804, 3.488, 5.7, 2.884, 5.012, 2.912, 3.788, 4.17,
                                                                                7.862, 3.906, 1.836, 4.994, 3.882, 2.602), Var6 = c(43.2,
                                                                                10.8, 7.5, 2.7, 21.5, 7.4, 27.4, 63.1, 1.5, 3.6, 1.1, 20,
                                                                                1.4, 18.9, 27.7, 1.9, 0.8, 38.3, 32.4, 18.8, 3.2, 5.6, 1.6,
                                                                                5, 42.2, 8.2, 14.5, 0.7, 1.6, 2.8, 41.4, 32, 5.6, 37.4, 42.8,
                                                                                20.7, 39.9, 17.2, 21, 37.4, 0.6, 19, 26.6, 0.5, 1.1, 20.5,
                                                                                18.1, 46.2, 17.1, 2.8, 26.9, 3.4, 22.7, 20.9, 52.6, 3.5,
                                                                                47.3, 20.1, 56.3, 19.4, 56.6, 1.5, 27.1, 2.7, 7.8, 16.6,
                                                                                1.4, 48.1, 1.3, 10.7, 22.2, 1.4, 28.2, 32.9, 22.7, 6.4, 24.1,
                                                                                21, 3.9), Var7 = c(0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0,
                                                                                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
                                                                                0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                                                                0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
                                                                                1, 0, 1, 0, 1, 0, 0, 0, 0), Var8 = c(0, 0, 0, 1, 0, 0, 0,
                                                                                0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0,
                                                                                1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1,
                                                                                0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1,
                                                                                0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1), Var9 = c(0,
                                                                                0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                                                                0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0,
                                                                                1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
                                                                                1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
                                                                                0, 0), Var10 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
                                                                                0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0,
                                                                                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
                                                                                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                                                                0, 0, 0, 0, 1, 0, 0, 0), Var11 = c(0, 0, 0, 0, 0, 0, 0, 0,
                                                                                0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                                                                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
                                                                                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
                                                                                1, 0, 0, 0, 0, NA, 0, 0, 0, 0, 0, 0, 0, 0), Var12 = c(1L,
                                                                                1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                                                                1L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                                                                1L, 1L, 0L, 1L, 1L, 0L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 0L,
                                                                                1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L,
                                                                                0L, 0L, 0L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 1L,
                                                                                0L, 1L, 1L)), row.names = c(1L, 2L, 3L, 5L, 11L, 12L, 13L,
                                                                                15L, 18L, 21L, 28L, 29L, 30L, 31L, 32L, 36L, 37L, 39L, 43L, 46L,
                                                                                48L, 52L, 54L, 56L, 57L, 59L, 62L, 71L, 73L, 74L, 76L, 80L, 81L,
                                                                                88L, 89L, 90L, 92L, 93L, 94L, 96L, 103L, 104L, 105L, 106L, 107L,
                                                                                113L, 114L, 119L, 120L, 121L, 123L, 124L, 127L, 130L, 135L, 136L,
                                                                                138L, 139L, 141L, 143L, 146L, 150L, 153L, 156L, 160L, 162L, 163L,
                                                                                164L, 167L, 170L, 171L, 173L, 174L, 175L, 179L, 181L, 182L, 184L,
                                                                                185L), class = "data.frame")

model <- lm(formula = Dep_var ~ Var1 + Var2 + log(Var3) +
                 Var4 + Var5 + Var6 + Var7 + Var8 +
                 Var9 + Var10 + Var11 + Var12,
                 data = subset(df, ID !="Nicaragua" &
                                   ID != "Belarus" &
                                   ID != "Burundi"),
                 na.action = na.exclude)

coeftest(model, vcov = vcovHC(model, method = "arellano", type = "HC3"))


text:
Q: Creating image table in python Here is my problem: I have n images. They have the same width and height, they are png. I want to make an image(png) that contains a table out of them that have 5x(n/5) images in it by simply putting them next to each other.
I never tried creating images in Python, so could you help me what package and functions to use?

A: It seems like this is so trivial everyone knows how to vote down but no one knows the answer, right?
OK, so the package is Image, to create a canvas we need Image.new(colour_mode, size=(x,y), colour)
to put an image into this image we need
Image.paste(image, (left, up, right, down))
Thanks a lot for nothing.


text: Q: When the test execution is failed, can we rerun the failed test case immediately using Specflow If an element is not found in a test case, then it is failed. again it should run from the failed step that is finding the element again immediately instead of moving to next step. Is it possible using Selenium with C# specflow. kindly let me know if possible with example


text:
Q: Capitalize input text in Javascript In a form, I have two buttons to transform text to uppercase and lowercase. I am using this function to transform input text to upper case:
document.xyz.textinput.value=document.xyz.textinput.value.toUpperCase()

Now, I want to add a new button to capitalize each word. Is it possible to achieve this with the following code?
document.xyz.textinput.value=document.xyz.textinput.value.capitalize()

Thanks

A: CSS has some text-transform properties too: https://developer.mozilla.org/en/CSS/text-transform
If that isnt an option, you can simply split your string by each whitespace and capitalize that word.

A: String.prototype.capitalize = function (strSentence) {
        return strSentence.toLowerCase().replace(/\b[a-z]/g, convertToUpper);

        function convertToUpper() {
            return arguments[0].toUpperCase();
        }
}

Use this:
"hello world".capitalize();  // "Hello World"

A: Try This:
document.xyz.textinput.value = document.xyz.textinput.charAt(0).toUpperCase() + document.xyz.textinput.slice(1);

If you want a capitalize functions, See here.


text:
Q: Lightswitch V2: Datagrid Columns not auto-resizing Hi I have noticed that in Lightswitch v2 (Visual Studio 2012), the Auto Size mode for data grid columns doesn't seem to be working. That is, the columns do not re-size to accommodate my content. If I remember correctly, this used to work in Visual Studio Lightswitch v1...
Does anyone know how to make the data grid columns re-size to accommodate content in Lightswitch v2?
Note that I am able to manually stretch my columns - this is not what I'm looking for...

A: If I recall correctly, they have changed that feature to improve speed and reduce any annoying glitches.
Preferably, I would also like to see the columns stretch to fit all information within a cell, but I don't think it is currently possible. I would consult the dev's on this issue; it may be temporary.


text:
Q: Hyphenation problem with --- versus \textemdash While investigating problems with hyphenation and em-dashes, I came across this:
a piece---perhaps an installation---, involving structural feedback

The document class is article. The problem was that installation was not hyphenated, and an overfull line was produced, with installation--- moving over the right margin, and the next line beginning with the comma.
Now I happened to try this, and it fixed the problem:
a piece---perhaps an installation\textemdash, involving structural feedback

properly breaking the line such as
...instal-
lation---, involving...

This seems counter-intuitive to me, and I really prefer to see the triple hyphens in my source code, much more readable. Is there a way to fix this problem?

It looks clearly like a latex error to me, because standard usage of em-dash states: "According to most American sources [...] and some British sources [...], an em dash should always be set closed, meaning it should not be surrounded by spaces."

A: Instead of the traditional --- ligature, I use the Unicode character —, which is equivalent to \textemdash. In my opinion, there should be no line break at the em dash, but hyphenation within the adjacent words seems acceptable to me. To achieve this, I patch \textemdash as follows:
\documentclass{article}

\usepackage{etoolbox}

\usepackage[utf8]{inputenc}

\makeatletter

\apptocmd{\textemdash}{%
  \nobreak\hskip\z@skip%
}{%
}{%
}

\robustify\textemdash

\makeatother

\begin{document}

\showhyphens{hyphenation—hyphenation}

\end{document}

A: In case of strange behavior or foreign languages, you can manually instruct LaTeX to hyphenate your word like this
in\-stal\-la\-tion

\- shows a possible hyphen.

A: You have, at least, three possible options:

*

*Use \textemdash instead of ---. You already mentioned this in your question and it seems counter-intuitive for you.

*Manually declare the valid hyphenation points for the word preceding the ---.

*Load the babel package and use \allowhyphens---. I think this approach will give you something closer to what you want since you could declare some character as active (" for example) and define a command "--- to be \allowhyphens---; you then will write "--- to get an em-dash allowing hyphenation for the preceding word (this approach was used by Javier Bezos in his implementation of a similar shorthand in the spanish module for babel).

Here's some code showing the problem and the three alternatives I mentioned:
\documentclass{article}
\usepackage[english]{babel}

\begin{document}

some filler text to illustrate the problem here's a piece---perhaps an installation---, involving structural feedback

some filler text to illustrate the problem here's a piece---perhaps an installation\textemdash, involving structural feedback

some filler text to illustrate the problem here's a piece---perhaps an installation\allowhyphens---, involving structural feedback

some filler text to illustrate the problem here's a piece---perhaps an in\-stal\-la\-tion---, involving structural feedback

\end{document}

Here's some code that could be used to implement my suggestion in the third numeral above :
\documentclass{article}
\usepackage[english]{babel}

\catcode`"=13
\def"-{\allowhyphens-}

\begin{document}

some filler text to illustrate the problem here's a piece---perhaps an installation---, involving structural feedback

some filler text to illustrate the problem here's a piece---perhaps an installation"---, involving structural feedback

\end{document}

Yet another alternative, taken from this answer by Herbert to babel: Adding ngerman' s language shorthands to english as the main document language (thanks to egreg for pointing out this question) is to use the spanish modulo as a secondary language and use its already existing shorthand:
\documentclass{article}
\usepackage[spanish,english]{babel}
\useshorthands{"}
\addto\extrasenglish{\languageshorthands{spanish}}

\begin{document}

some filler text to illustrate the problem here's a piece---perhaps an installation---, involving structural feedback

some filler text to illustrate the problem here's a piece---perhaps an installation"---, involving structural feedback

\end{document}

A: The reason why installation--- doesn't allow TeX to hyphenate the word is explained in the TeXbook (p. 95):

The most common case of a discretionary break is a simple discretionary hyphen
\discretionary{-}{}{}

for which TeX accepts the abbreviation '\-'. The next most common case is
\discretionary{}{}{}

(an "empty discretionary"), which TeX automatically inserts after '-' and after every ligature that ends with '-'. In the case of plain TeX, empty discretionaries are therefore inserted after hyphens and dashes. (Each font has an associated \hyphenchar, which we can assume for simplicity is equal to '-'.)

Conversely, LaTeX defines
\DeclareTextSymbol{\textemdash}{OT1}{124}

or, with the T1 encoding,
\DeclareTextSymbol{\textemdash}{T1}{22}

so that the command \textemdash directly selects a character, without passing through the ligature mechanism, so that no empty discretionary is inserted.
In my opinion you should use ---, manually correcting possible bad breaks and deciding, in tough situations, whether hyphenating the word next to the dash is the lesser evil.

A: Another solution, besides the ones already mentioned in the other answers, consists of inserting \nobreak\hskip0pt between installation and ---. That way, TeX can hyphenate the word "installation", but there won't be line break right between tion and the em-dash.


text:
Q: Demonstrate that the product of the permutations(regardless of order) of $S_4$ is not equal to $a$ $S_4$ is the set of all permutations of length 4
Let $a=\binom{1\,2\,3\,4}{3\,2\,1\,4}$
I found that $a$ is an odd permutation and I want to demonstrate that the product of the permutations is even but Im not sure if this is true and I have no idea how to demonstrate that.

A: I think what you're saying is that if you take all the permutations in $S_4$ and multiply them together in whichever order, the result is never equal to your $a$.
Your basic plan is sound -- $a$ is indeed an odd permutation, and it will turn out that a product of all the permutations is even.
The product of all the permutations is even if and only if the total number of odd permutations in the product is even.
There are various ways of showing that. A quick and slick one is would be to know that exactly half of the elements of $S_n$ are odd (for $n\ge 2$), compute the size of $S_4$ and see that half of that number is even.
(Proof that exactly half of all permutations are odd: Fix some transposition -- say, your $a$ -- and then observe that if $\sigma$ is an even permutation, then $a\sigma$ is odd, and if $\tau$ is an even permutation, then $a\tau$ is an odd permutation such that $a(a\tau)=\tau$. So left multiplication by $a$ is a bijection between the even and the odd permutations, so there are equally many of them).


text:
Q: Ionic2 AppPreferences undefined I have the following code to get the city from Ionic2 native AppPreferences:
import { AppPreferences } from '@ionic-native/app-preferences';

constructor(public appPreferences: AppPreferences) {

    console.log("The city is : " + this.loadPreferences("selectedCity"));

}

loadPreferences(preferenceKey: any){
    this.appPreferences.fetch(preferenceKey).then((res) => { return res; });
}

Inside .then((res) => {console.log}); the value is printed and works fine. But when I return the value or assign it to some variable then I get the value "The city is: undefined". Am I doing anything wrong?

A: I got it. As @misha130 said think about each line. The following line is printed before I get the result from async method:
console.log("The city is : " + this.loadPreferences("selectedCity"));

I changed my code a little bit. Now I run my code when I get the result in async function. Thanks a lot


text:
Q: Adding text values to dynamically create text inputs Here is everything and I tried to put a suggestion in and it sort of works on the changing the color of the row but it only changes it once, every row after stays as the .odd background color.
Basically I am trying to add row dynamically, which works, mask the input text fields, which works, take the value from the endtime_1 and put it in the starttime_2(dynamic add) of the next added row when the addrow() button is clicked. Then take the value of endtime_2(dynamic add) and put it in starttime_3(dynamic add) when the addrow() button is clicked, and so on and so on and so on.... That isn't working. I would like to also color each of the odd numbered rows with the background styling.

    Select Type

        Select Property

        Start Time
        End Time

        <select name="type_1" id="type_1" class="validate[required]">
            <option selected value=''> -- Please Select -- </option>
            <option value="office">Office</option>
            <option value="work">Working</option>
            <option value="drive">Driving</option>
            <option value="break">Break</option>
            <option value="lunch">Lunch</option>
            <option value="personal">Personal</option>
    </select>

        <select name="propid_1" id="propid_1" class="validate[required]">
            <option selected value=''> -- Please Select -- </option>
        </select>

        <input type="text" class="time" id="starttime_1" name="starttime_1" size="10" />
    <input type="text" class="time" id="endtime_1" name="endtime_1" size="10" />
        <input type="button" value=' + ' onclick='addRow();' />

A: color the table rows in pure css:
tr:nth-child(odd) {background-color:#CCC;}

Otherwise, please ask a targeted question.


text:
Q: Why using multithreading so slow when reading file with tons of lines? I'm reading a file with tons of lines in it and want to compare one line with the rest of the lines step by step.
and when condition met, store value in the variable 'result' and print it after all thread stop
However, when I don't use thread it takes about 0.1 seconds but when I use 10 thread it takes more than 0.5 seconds.
Why using multi-thread take more time than one thread?
here is a sample code I wrote
import threading

result = []

def get_match(file):
    outer_lines = file.readlines()
    inner_lines = file.readlines()
    for f1 in outer_lines:
        for f2 in inner_lines:
            print('compare file line by line')
            print('store int into global result variable')

def do(thread_count=10):
    threads = []
    with open('file.txt') as file:

        for t in range(thread_count):
            t = threading.Thread(target=get_match, args=(file,))
            threads.append(t)

        for t in threads:
            t.start()

        for t in threads:
            t.join()

    print(result)

do(10)

A: It's slower because each of your threads iterates over the whole file, basically you are doing the same thing 10 times.
You need to first split the file into 10 parts and then each one of them to separate threads


text:
Q: Dygraph will not display in Bootstrap card I want to create a dygraph graph within the Bootstrap card body's second column (it just looks nice and clean). The div used by dygraph is graphdiv. I am using this.$refs.graphdiv to try to access it from within my vue script.
If I move the graphdiv
 outside the card div then it works (see the comment). Why will the dygraph not work within the bootstrap card? Is it just one of those compatibility things one must log with the developer and wait for a fix?
<template>

HEADER

</template>

Here is a reduced version of script:


text:
Q: Merge object with same keys I have a custom javascript object similar to this:
const my_obj = {
  'foo1': {
    'bar1': '1',
    'bar2': '2',
    'bar3': '3',
  },
  'foo1': {
    'bar4': '4',
    'bar5': '5',
  },
  'foo2': {
    'bar1': '1',
    'bar2': '2',
  }
}

and I want to merge elements with the same key, so in this case the object would become:
const my_obj = {
  'foo1': {
    'bar1': '1',
    'bar2': '2',
    'bar3': '3',
    'bar4': '4',
    'bar5': '5',
  },
  'foo2': {
    'bar1': '1',
    'bar2': '2',
  }
}

Is there any way to do this easily?

A: If you try to define an object with clashing keys the first is overriten by the second (at least in my attempts).
Considering you have instead two objects with same keys you can make two types of merge: shallow or deep.
If a shallow merge is sufficient, you can use Object.assign to do the job like the following, but iterating for each key:
obj3.foo1 = Object.assign({}, obj1.foo1, obj2.foo1);

For shallow copies, keep in mind that the references are maintained since Object.assign only copies the values as explained into the documentation which can be a problem for nested objects.

But if you need a deep merge it would be a little bit more tricky. The easiest way I guess is using a library like deepmerge-json:
const result = merge(obj1, obj2)

This will make a deep merge between the two objects creating a third one with no reference to the original ones.

The advantage of this approach is that the objects will be merged no matter how many levels they have.


text:
Q: DIY LED panels with even illumination? This is an electro-optical question.
I'd like to make my own large 7-segment-type displays using discrete LED devices.
What's a method to get an clean, even illumination of the segment from the LEDs (one or more)?
Ideally, there's a good general approach that will work making any shape illuminated item, not just 7-segment displays.  Segment sizes would range from 1" to 1' or more.

A: You would be looking for LED driver ICs with "dot correction" or "grayscale correction", for making such a panel / 7-segment / matrix / whatever LED display.
The idea behind such ICs is that each LED channel can be programmatically configured to adjust its current to even out against the actual output of each LED. Some such devices store the configuration in non-volatile memory within the IC, so they can be set up once and for all after putting together the LED panel / matrix. Others require the dot correction data to be transmitted to them each time the board is powered up.
Perhaps the most well-known such driver in the DIY community is the TLC5940, a 16 channel, per-channel dimmable, serially controlled, constant current LED driver. It is an expensive IC ($3.78 apiece), as has been pointed out, but has great support on common DIY microcontroller communities such as the Arduino and MSP430 LaunchPad. One reason for its popularity is that it is available as a through-hole DIP IC, unlike the various 24, 32 or even 48-channel ICs with similar functionality.
Footnote:
Dot correction is actually required for even commercially manufactured multi-LED displays, not just DIY ones. The consistency of illumination between LEDs varies across batches, and even within a batch. Though manufacturers go through a "binning" exercise to sort LEDs by illumination per current, some variation still sneaks through.


text:
Q: How to get utility function from helper file on node.js server? I have a node/express server and I'm trying to get a function from a helper file to my app.js for use. Here is the function in the helper file:

CC.CURRENT.unpack = function(value)
{
    var valuesArray = value.split("~");
    var valuesArrayLenght = valuesArray.length;
    var mask = valuesArray[valuesArrayLenght-1];
    var maskInt = parseInt(mask,16);
    var unpackedCurrent = {};
    var currentField = 0;
    for(var property in this.FIELDS)
    {
        if(this.FIELDS[property] === 0)
        {
            unpackedCurrent[property] = valuesArray[currentField];
            currentField++;
        }
        else if(maskInt&this.FIELDS[property])
        {
   //i know this is a hack, for cccagg, future code please don't hate me:(, i did this to avoid
   //subscribing to trades as well in order to show the last market
          if(property === 'LASTMARKET'){
                unpackedCurrent[property] = valuesArray[currentField];
            }else{
                 unpackedCurrent[property] = parseFloat(valuesArray[currentField]);
            }
            currentField++;
        }
    }

    return unpackedCurrent;
};

At the bottom of that helper file I did a module.export (The helper file is 400 lines long and I don't want to export every function in it):

  module.exports = {
    unpackMessage: function(value) {
      CCC.CURRENT.unpack(value);
    }
  }

Then in my app.js I called

var helperUtil = require('./helpers/ccc-streamer-utilities.js');

and finally, I called that function in app.js and console.log it:

res = helperUtil.unpackMessage(message);
console.log(res);

The problem is that the console.log gives off an undefined every time, but in this example: https://github.com/cryptoqween/cryptoqween.github.io/tree/master/streamer/current (which is not node.js) it works perfectly. So I think I am importing wrong. All I want to do is use that utility function in my app.js

A: The unPackMessage(val) call doesn't return anything:
module.exports = {
  unpackMessage: function(value) {
    CCC.CURRENT.unpack(value);
  }
}

you need to return CCC.CURRENT.UNPACK(value);
module.exports = {
  unpackMessage: function(value) {
    return CCC.CURRENT.unpack(value);
  }
}


text:
Q: How to remove opacity animation in SwiftUI NavigationLink When tapping on a NavigationLink, it reduces the opacity slightly. Is there a way to disable this. I tried using .buttonStyle(PlainButtonStyle()) but that didn't have the desired effect.
It is embedded in a scrollView (preferred over List for customizability):
ScrollView {
    ForEach(items){ item in
        NavigationLink(destination: DetailView()){
            HStack{
                Text("title")
                Spacer()
                Image(systemName: "chevron.right")
            }
            .padding()
            .background(
                RoundedRectangle(cornerRadius: 10, style: continuous)
                    .foregroundColor(Color.gray)
            )
        }
    }
}

A: Here is possible solution. Tested with Xcode 11.4 / iOS 13.4
Use custom button style that just returns label view (w/o highlight effect)
struct FlatLinkStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
    }
}

and
    NavigationLink(destination: DetailView()){
        HStack{
            Text("title")
            Spacer()
            Image(systemName: "chevron.right")
        }
        .padding()
    }.buttonStyle(FlatLinkStyle())     // << here !!


text:
Q: How to get sub-meter or centimeter GPS accuracy? I'm thinking about building a gps system for a tractor.
The gps receiver can be placed on the roof of the tractor to minimize interference.
Regular GPS receivers are accurate upto "a few meters". (https://www.adafruit.com/products/746)
I found you can correct your position with a base station. (RTK)
I have seen the Starfire gps receiver getting a good precision (a few cm i think) without basestation. I wonder how they work.
Are there other ways to get a more accurate position?

A: There are few commercial products designed to do exactly what you are planning. They usually use RTK, with a known local reference station, up to 30km radius, and rovers installed on the tractors. Correction data is transferred via cellular or local ISM band radio.
Multi constellation (GPS + GLONASS etc) receivers can provide improved performance even without RTK, but not to sub meter precision.
And, since you don't have access to mil spec receivers, that option is also moot.


text:
Q: Line plot with two y-axes using matplotlib? I have a list of (x,y) values like below.

k = [(3, 6), (4, 7), (5, 8), (6, 9), (7, 10), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)]

I would like create a plot that draws lines on opposite axes like below with the assumption that the axis values are in the range 1-15.
Please find the figure here
.
I tried using twinx and twiny, but not exactly sure how to achieve this. I think it might be easier to do using Microsoft Excel, but I have all my values in python npy files.

A: You can draw a collection of line segments using LineCollection.
It is also possible to draw each line using plt.plot, but
when there are lots of line segments, using LineCollection is more efficient:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.collections as mcoll

k = np.array([(3, 6), (4, 7), (5, 8), (6, 9), (7, 10),
              (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)])
x = np.array([0,1])

fig, ax = plt.subplots()
points = np.stack([np.tile(x, (len(k),1)), k], axis=2)
line_segments = mcoll.LineCollection(points, linestyles='solid', colors='black',
                                     linewidth=2)
ax.add_collection(line_segments)
ax.set_xticks([0, 1])
# Manually adding artists doesn't rescale the plot, so we need to autoscale (https://stackoverflow.com/q/19877666/190597)
ax.autoscale()
plt.show()

A: It could be simple :
import matplotlib.pyplot as plt
[plt.plot(d) for d in k]
plt.ylabel('some numbers')
plt.show()

gives me :

And with the labels :
import matplotlib.pyplot as plt
[plt.plot(d) for d in k]
plt.ylabel('some numbers')
ax = plt.gca()
ax.xaxis.set_ticks([0,1])
ax.xaxis.set_ticklabels(["BaseLine", "FollowUp"])
plt.show()


text:
Q: How to store a X509Certificate2 in db c# Here is the scenario:
I have several .pfx files and I need to store them in a MySQL DB.
I already tried to store the RawData thing, but when I try to sign a xml using the reconstructed certificate I get:

Signing key is not loaded.

Well so I tried to store the private key, using the function ToXmlString to generate a string from the private key and FromXmlString to load the new string, but then I get:

Object contains only the public half of a key pair. A private key must also be provided.

The point is, how to correctly store the certificate and its keys in the DB in a way that I can reconstruct it and use it for digital signing documents?
Update:
Already tried this and didn't work:
Store an X509Certificate2 in DB

A: The certificate only includes the public key, so storing only that won't work.
On the other hand, cert.PrivateKey.ToXmlString(true) should work. Are you sure that you remembered to call it with the includePrivateParameters argument set to true and that you imported it as exportable?
X509Certificate2 cert = new X509Certificate2("key.pfx", "password", X509KeyStorageFlags.Exportable);
string xml = cert.PrivateKey.ToXmlString(true);

Alternatively, you could just store the entire pfx in the database.


text:
Q: Model Update fails with no error I'm just trying to generate a user during the bootstrap process.
I hit his update statement and the  process stops, then times out after 10 seconds with "Bootstrap is taking unusually long to execute its callback (10000 milliseconds)."  Update error is never thrown. I know the user exists. I've checked before attempting update.
User.update({id:id}, {verificationCode: verificationCode})
    .then(function(updatedUser){
        console.log("VerificationCode added.", updatedUser);
        addInitialPermissions();
    })
    .catch(function(err){
        if(err) throw new Error(err);
        next(err);
    });

I have no clue what the problem can be. Would appreciate any help.
thanks

A: This is wrong:
User.update({id:id}, {verificationCode: verificationCode})
    .then(function(updatedUser){
        console.log("VerificationCode added.", updatedUser);
        addInitialPermissions();
    })
    .catch(function(err){
        if(err) throw new Error(err);
        next(err);
    });

This is correct, exec , not then:
User.update({id:id}, {verificationCode: verificationCode})
    .exec(function(err, updatedUser){
    if(err) {
     console.log(err)
    return;
    }
        console.log("VerificationCode added.", updatedUser);
        addInitialPermissions();
    });


text:
Q: google play games achievements reset (every day) Last week we soft-launched our game and we started getting errors from people. One of the bugs they (all) seem to have is that their achievements are being reset at least every day but sometimes even when restarting our game. The achievements do give the popup when being unlocked, and are even visible in the achievements UI but they keep being reset/removed.
We did know our game behaved like this for our Beta testers, but we assumed this was because everyone that was playing at the time is registered as a Beta tester.
Anyway, we've looked all over the internet to find other people that have the same problem as we do but we came up empty handed. We've checked all our settings in the play dashboard and within our game a dozen times but can't find the problem. Every post is always about resetting achievements, not keeping them.

One thing that I did notice is that almost 70% of the calls that we make with GPGS is returned by a 4xx response. We are currectly using Unity 5.3.x in combination with GPGS v0.9.32.

Does anyone have any idea on why this is happening to our achievements?

A: Alright we've found the answer: we had 2 credentials and apparently used the wrong one in our APK. We switched around the Signing-certificate fingerprint so that the fingerprint in the APK and in play services match and now it's working.
The strange thing is that everything seemed to work and we've never gotten any feedback from google that something was wrong...
Thanks for your attention to this problem!


text:
Q: Heretic order/disposition on a 3 columns grid I want to make a simple 3 columns / 3 rows grid with Susy 2 like :
 1   2   3
 4   5   6
 7   8   9

But the blocks are floating in a buggy and heretic order.
You can have a look :
http://img.spheerys.fr/images/2015/01/05/bug-susy.jpg
Here my HTML Markup :

1

2

3

4

5

6

7

8

9

Here my Susy map :
$susy: (
  global-box-sizing: border-box,
  use-custom: (
    rem: true
  ),
  columns: 12,
  column-width: 4em,
  gutters: 1/4
);

And finally, my Sass :
.block
  +span(4 of 12)
  &:nth-child(3n)
    +last
    +break

What's going wrong ?

A: :nth-child counts all sibling elements. So :nth-child(3n) doesn't just apply to every 3rd .block, it applies to every 3rd sibling that is also .block. The best solution when using :nth-child is to wrap all your list items in their own parent, without other siblings.
Susy also provides a shortcut to creating this sort of gallery layout...
html:

1

2

3

4

sass:
.block
  +gallery(4 of 12)

That should be all you need.


text:
Q: Manipulate value of ActiveRecord request in Chartkick I like to use chartkick to visualize some data. I have a Purchase model with many purchases in it.
class Purchase < ActiveRecord::Base
  attr_accessible :category, :price, :product, :purchase_type
  def invert_price
    self.price.abs
  end
end

A standard chart would look like:
<%= bar_chart Purchase.group(:category).sum(:price) %>

But my :price records are negativ. I just need a solution how I get to a inverted price (-price) or the absolute value of price (price.abs).
Trying to create a method in the Purchase model doesn't work, because it can't get resolved in a SQL query.
class Purchase < ActiveRecord::Base
  attr_accessible :category, :price, :product, :purchase_type

  def invert_price
    self.price.abs
  end

  def invert_price
    self.price.abs
  end
end

Error:
Mysql2::Error: Unknown column 'invert_price' in 'field list

Writing a own SQL query could give back the right result, but chartkick was empty after it.
<%= bar_chart Purchase.select("ABS(SUM(`candystore_purchases`.`price`)) AS sum_price, category AS category").group(:category) %>

Any ideas, how to handle this?

A: Try:
<%= bar_chart Purchase.group(:category).sum("ABS(price)") %>


text:
Q: Android only displays my 1st database search I'm trying to create an app that takes some values from a database.
 The value I am looking for in the database has multiple
 entries, but in Android it only displays the 1st one it finds. I  presume i just need 1/2 lines, but I have no clue what&where.
private void getData() {
     String qrcode = textView1.getText().toString().trim();
     if (qrcode.equals("")) {
       Toast.makeText(this, "", Toast.LENGTH_LONG).show();
       return;
     }
     loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);

     String url = Config.DATA_URL+textView1.getText().toString().trim();

     StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
       @Override
       public void onResponse(String response) {
         loading.dismiss();
         showJSON(response);
       }
     },
         new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError error) {
             Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
         }
     });

     RequestQueue requestQueue = Volley.newRequestQueue(this);
     requestQueue.add(stringRequest);
 }

 private void showJSON(String response){
     String title="";
     String image = "";
     try {
       JSONObject jsonObject = new JSONObject(response);
       JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
       JSONObject androidData = result.getJSONObject(0);
       title = androidData.getString(Config.KEY_TITLE);
       image = androidData.getString(Config.KEY_IMAGE);
     } catch (JSONException e) {
       e.printStackTrace();
     }
     textViewResult.setText("Title:\t" + title);//+"\nImagine :\t"+ image);
     Picasso.with(this).load("http://192.168.1.254/2015/380panel/uploads/images/sm/" + image).into(ImageView1);

 }

 @Override
 public void onClick(View v) {
     getData();
 }

A: It seems that you are taking only the first result of the response :
JSONObject androidData = result.getJSONObject(0);
title = androidData.getString(Config.KEY_TITLE);
image = androidData.getString(Config.KEY_IMAGE);

And you are populating only ONE textview:
textViewResult.setText("Title:\t" + title);//+"\nImagine :\t"+ image);

You need to iterate/loop for each json object received in the jsonArray and populate a list of textview if you want to see all the results!
Loop array : Android JSONArray looping


text:
Q: The maximal term of the multinomial distribution (Feller volume 1, Q28, p.171) Suppose that we have the following binomial distribution
$$\frac{n!}{k_1!k_2!... k_r!} p_1^{k_1}p_2^{k_2} ... p_r^{k_r}.$$
Prove the theorem. The maximal term of the multinomial distribution satisfies the inequalities
$$np_i -1 < k_i \le (n+r-1) p_i,$$
for $i=1, ... , r$. Hint: Prove first that the term is maximal if, and only if , $p_i k_j \le p_j(k_i+1)$ for each pair $(i,j)$. Add these inequalities for all $j$, and also for all $i \not= j$.
I first do not know how to prove the first hint. Assuming that we have the inequality in the hint, $\sum_{i \not= j} \sum_j p_ik_j \le \sum_{i \not= j} \sum_j p_j(k_i +1) \implies n(1-p_j) \le n-k_j+ r-1$. This is all I can think now. I really appreciate if you give some help.

A: For the maximum term we should have for each pair $(i,j), i \neq j$:
$$ \frac
   {\frac{p_i^{k_i} p_j^{k_j}}
         {k_i! k_j!}}
   {\frac{p_i^{k_i+1} p_j^{k_j-1}}
   {(k_i+1)!(k_j-1)!} } \geq 1,
$$
which gives
$$ \frac{(k_i + 1)}{k_j} \cdot \frac{p_j}{p_i} \geq 1, $$
$$ (k_i + 1)p_j \geq k_j p_i \tag{*}\label{*}$$
and the hint is proved.
Now adding both sides of \eqref{*} for all $j$ we get
$ \sum_j k_j p_i = n p_i $ and
$ \sum_j p_j (k_i + 1) = k_i + 1, $
and since $\sum_i k_i = n$ and $\sum_i (n p_i - 1) < n $
we get
$$ n p_i - 1 < k_i. \tag{**}\label{**} $$
Adding both sides of \eqref{*} for all $i \neq j$ we obtain
$$ \sum_{i \neq j} k_j p_i = k_j \left(\sum_i (p_i) - p_j\right) = k_j - k_j p_j, $$
$$ \begin{align} \sum_{i \neq j} p_j (k_i + 1) & = p_j\left(\sum_i k_i - k_j\right) + p_j(r-1) = \\ & = p_j(n-k_j) + p_j(r-1) = \\ & =  p_j(n+r-1) - p_j k_j, \end{align} $$
and now
$$ k_j - k_j p_j \leq p_j(n+r-1) - p_j k_j, $$
or
$$ k_j \leq p_j(n+r-1), $$
where we are allowed to replace $j$ with $i$ to obtain
$$ k_i \leq p_i(n+r-1), \tag{***}\label{***} $$
and combining $\eqref{**}$ and \eqref{***} we finally get Feller's (10.1).


text:
Q: Check a param,cookie defined against a method is not working I have the following code that is working to assign a locale based first on a param, then a previously set cookie and then by requesting the HTTP_ACCEPT_LANGUAGE.
def set_locale
  if params[:locale]
    I18n.locale = params[:locale]
  elsif cookies[:locale]
    I18n.locale = cookies[:locale]
  else
    I18n.locale = sanitizeLocale(request.env["HTTP_ACCEPT_LANGUAGE"]) # e.g. "en,es;q=0.8,de-de;q=0.5,en-us;q=0.3"
  end
  cookies[:locale] = I18n.locale
end

def sanitizeLocale(locale)
  @locale, lang_weight = cookies[:locale] || begin
    if accept_lang = request.env["HTTP_ACCEPT_LANGUAGE"] # e.g. "en,es;q=0.8,de-de;q=0.5,en-us;q=0.3"
      accept_lang.to_s.split(',').collect {|l| x,y = l.split(';q='); [x.split('-').first, (y||1).to_f]}.sort_by(&:last).reverse.find {|lang, lang_weight| %w[es en it fr de].include?(lang)}
      # returns ["en", 1.0]
    end
  end || 'en' # default
  return @locale
end

My question is how can I check both the params[:locale] given and cookies[:locale] against the sanitizeLocale. I'm interesting in only get a valid value such as es en it fr de or default to en based on the input.
I been trying to just pass its values to sanitizeLocale similarly I'm doing for HTTP_ACCEPT_LANGUAGE  for some reason I can't understand is not working and is always defaulting to en even when params[:locale] given values are valid like it.

A: First, we can simplify your Accept-Language parsing a bit:
def acceptable_langs
  extract_langs = lambda do |l|
    x, y = l.split(';q=')
    [x.split('-').first, -(y || 1).to_f] # the -1 makes sort_by nicer
  end
  known_langs = lambda { |lang| %w[es en it fr de].include?(lang.first) }
  quality = :last
  language = :first
  langs = request.env['HTTP_ACCEPT_LANGUAGE'].to_s
                 .split(',')
                 .map(&extract_langs)
                 .select(&known_langs)
                 .sort_by(&quality)
                 .collect(&:language)
  langs + ['en']
end

The to_s will take care of nils and the lambdas and extra variables are just there to clarify the logic. You don't have to do this, all you really need is a method that returns the language codes that are acceptable to both the user and your software ordered by the user's preference.
Now back to set_locale. You say that you need the language to match Accept-Langauge (with 'en' as a fallback) regardless of what the URL or cookies have to say. That means that you have to parse Accept-Language no matter what and then check params[:locale] and cookies[:locale] against that list:
def set_locale
  # Figure out what they're asking for with English as the
  # default. Note that `acceptable_langs` always forces English
  # to be in the list.
  asking_for = params[:locale] || cookies[:locale] || 'en'

  # acceptable_langs is always in preference order so we just
  # want the first one that matches our `lang`.
  lang = acceptable_langs.find { |lang| asking_for == lang }

  # Now we have an acceptable language in `lang` (thanks to all
  # the `'en'` fallbacks we sprinkled about).
  I18n.locale = cookies[:locale] = lang
end

You could also add a little "I've already done all this work" flag to the cookies so that you could simply trust cookies[:locale] if the flag is set; there's probably no reason to prematurely optimize set_locale though.


text:
Q: Android-Custom View to strictly remain within a layout custom bounds I am designing a Canvas Drawable inside a layout. This is my code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<LinearLayout
    android:layout_width="0dp"
    android:layout_weight="4"
    android:layout_height="match_parent">

    <com.sensennetworks.senanpr.ui.DrawPolygonCanvas
        android:id="@+id/drawPolygonCanvas"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</LinearLayout>

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="#000"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:onClick="onSave"
        android:text="Save" />

    <android.support.v4.widget.Space
        android:layout_width="20dp"
        android:layout_height="wrap_content" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:onClick="onReset"
        android:text="Clear" />
</LinearLayout>

This  layout file creates a custom drawable "DrawPolygonCanvas" which can be dragged, in the image below this is dragged out of bounds.

And, this creates a result like this....where the result goes out of boundary completely.

Now my question is how do I create a layout such that the "DrawPolygonCanvas" is strictly inside a layout and it does not go outside it's boundary into the black area with both the buttons.
    // Debug helpers to draw lines between the two touch points
    private HashMap<String, List<Vector2D>> polygons = new HashMap();

    public DrawPolygonCanvas(Context context) {
        super(context);
        init(context);
    }

    public DrawPolygonCanvas(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public DrawPolygonCanvas(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public DrawPolygonCanvas(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private void init(Context context) {
        Log.e(TAG, "called init");
        this.context = context;
//        Activity host = (Activity) getContext();
//        Log.e(TAG, "called getContext");
//        if (host.getIntent().hasExtra("byteArray")) {
//            Log.e(TAG, "called hasExtra");
//            byte[] byteArray = host.getIntent().getByteArrayExtra("byteArray");
//
//
//            Bitmap bm = BitmapFactory.decodeByteArray(byteArray
//                    , 0, byteArray.length);
//            ((GlobalApp) context.getApplicationContext()).setCurrentPreviewBitmap(bm);
//        }
        Log.e(TAG, "calling setOnTouchListener");
        setOnTouchListener(this);
    }

    public void clearROI() {
        Log.e(TAG, "called clearROI");
        // Get ROI from the shared preferences.
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        cameraROI = sharedPreferences.getString(SettingsActivity.ROI, AnprSettings.DEFAULT_CAMERA_ROI);
        Log.e(TAG, "Reloaded ROI = " + cameraROI);
        convertString2Polygons();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Log.e(TAG, "called onDraw");
        super.onDraw(canvas);

        if (!isInitialized) {
            // Get ROI from the shared preferences.
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            cameraROI = sharedPreferences.getString(SettingsActivity.ROI, AnprSettings.DEFAULT_CAMERA_ROI);
            if (cameraROI.isEmpty()) {
                cameraROI = AnprSettings.DEFAULT_CAMERA_ROI;
            }
            convertString2Polygons();

            circlePaint = new Paint();
            circlePaint.setColor(0xFFFF0000);

            linePaint = new Paint();
            linePaint.setColor(0xFF00FF00);
            linePaint.setStyle(Paint.Style.STROKE);
            linePaint.setStrokeWidth(10);

            isInitialized = true;
        }

        Rect dest = new Rect(0, 0, getWidth(), getHeight());
        Paint paint = new Paint();
        paint.setFilterBitmap(true);

        // get
        Bitmap bm = ((GlobalApp) this.context.getApplicationContext()).getCurrentPreviewBitmap();
        canvas.drawBitmap(bm, null, dest, paint);

        try {
            for (Map.Entry<String, List<Vector2D>> entry : polygons.entrySet()) {

                List<Vector2D> polygon = entry.getValue();

                for (int i = 0; i < polygon.size() - 1; i++) {
                    canvas.drawLine(polygon.get(i).getX(), polygon.get(i).getY(), polygon.get(i + 1).getX(), polygon.get(i + 1).getY(), linePaint);
                }
                canvas.drawLine(polygon.get(polygon.size() - 1).getX(), polygon.get(polygon.size() - 1).getY(), polygon.get(0).getX(), polygon.get(0).getY(), linePaint);

                for (int i = 0; i < polygon.size(); i++) {
                    canvas.drawCircle(polygon.get(i).getX(), polygon.get(i).getY(), 40, circlePaint);
                }
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDetachedFromWindow() {
        Log.e(TAG, "called onDetachedFromWindow");
        super.onDetachedFromWindow();

        // Convert polygon back to string.
        convertPolygons2String();

//        SharedPreferences.Editor editor = UserSharedPref.initializeSharedPreferencesForCameraROI(context).edit();
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getContext()).edit();
        editor.putString(SettingsActivity.ROI, cameraROI);
        editor.apply();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Log.e(TAG, "called onTouch");
        canvasTouchManager.update(event);
        Vector2D vct = canvasTouchManager.getPoint();

        float minDist = 200000.0f;
        float radius = 200;

        int minIndex = -1;
        String key = "";

        for (Map.Entry<String, List<Vector2D>> entry : polygons.entrySet()) {

            List<Vector2D> points = entry.getValue();
            for (int i = 0; i < points.size(); i++) {
                float dist = points.get(i) == null ? 0 : Vector2D.subtract(vct, points.get(i)).getLength();
                if (dist >= radius) {
                    continue;
                }

                if (dist < minDist) {
                    minDist = dist;
                    minIndex = i;
                    Log.e(TAG, "Matching x = " + points.get(i).getX() + ", y = " + points.get(i).getY());
                    key = entry.getKey();
                }
            }
        }

        if (minIndex != -1 && !key.isEmpty()) {
            polygons.get(key).set(minIndex, vct);
        } else {
            Log.e("OK2", "Touch point is too far, dist = " + minDist);
        }

        invalidate();

        return true;
    }
}


text:
Q: Indent first paragraph inside memoir's adjustwidth In machine-generated LaTeX that produces endnotes in memoir, I put (generate) each paragraph inside an adjustwidth environment to get the paragraph indented 26pts to line up with something else. Works fine, but I also want the first line of each of these paragraphs indented (additionally) by whatever the normal paragraph indent is. None of the crazy ideas I've tried, like:
\begin{adjustwidth}{26pt}{0pt}\par\setlength{\parindent}{1cm}\indent ...

produces success. Seems like the adjustwidth environment really doesn't want to indent that first paragraph (or my general LaTeX knowledge is too weak). Any ideas where I'm going wrong or what else I might try?

A: The easiest way to obtain your paragraph indent is to merely use \hspace{\parindent}:

\documentclass{memoir}% http://ctan.org/pkg/memoir
\usepackage{lipsum}% http://ctan.org/pkg/lipsum
\begin{document}
\lipsum[1]

\begin{adjustwidth}{26pt}{0pt}
\hspace{\parindent}\lipsum[2-3]
\end{adjustwidth}

\lipsum[4]
\end{document}