text:
Q: Error due to parsing JSON string response in android I am trying to create an app for a youtube channel and want to display the list of videos in a recyclerview. I am using YoutubeData API v3 for this. I get a JSON string response in return for my query and I am parsing it manually.
I created a class called Video to store information about a video in an object and then add it to an ArrayList to pass to recyclerview adapter. Initially it worked fine but as the number of details I wanted to pass to Video object increased, the recyclerview stopped working. It just shows the latest two videos and the rest are not displayed.
As soon as I pass videoId to the adapter the recycler view stops working. I tried parsing json on a separate thread using AsyncTask but it did not work. I am stuck in this error for a long time and can't figure out a reason. Please help !!
Here is my code :
MainActivity.java :
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    URL url = null;
    String resultString = null;
    RecyclerView rv;
    VideoAdapter adapter;
    ArrayList<Video> titles;

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

        rv = (RecyclerView) findViewById(R.id.rv_display);
        url = NetworkUtils.buildUrlFromUsername(Config.FOR_USERNAME);
        Log.i("ayusch", "url = " + url);
        new YoutubeQueryTask().execute(url);
        Log.i("ayusch", "After task");

    }

    public void formatJSON(String resultString) {
        new JSONParseTask().execute(resultString);
    }

    public class YoutubeQueryTask extends AsyncTask<URL, Void, String> {

        @Override
        protected String doInBackground(URL... params) {
            URL builtUrl = params[0];
            resultString = "no result";
            try {
                resultString = NetworkUtils.getResponseFromUrl(builtUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }

            return resultString;
        }

        @Override
        protected void onPostExecute(String s) {

            formatJSON(s);

            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
            rv.setLayoutManager(layoutManager);
            rv.setHasFixedSize(true);
            adapter = new VideoAdapter(titles);
            rv.setAdapter(adapter);
        }
    }

    public class  JSONParseTask extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... params) {
            JSONObject itemsObj, thumbnailsObject, defaultObject, obj, snippetObj;
            ArrayList<Video> videoTitles = new ArrayList<>();
            String title, thumbnailUrl, description, videoId;
            try {
                itemsObj = new JSONObject(resultString);
                JSONArray itemsArray = itemsObj.getJSONArray("items");

                for (int i = 0; i < itemsArray.length(); i++) {

                    obj = itemsArray.getJSONObject(i);
                    snippetObj = obj.getJSONObject("snippet");

                    title = snippetObj.getString("title");
                    thumbnailsObject = snippetObj.getJSONObject("thumbnails");
                    defaultObject = thumbnailsObject.getJSONObject("default");
                    thumbnailUrl = defaultObject.getString("url");
                    description = snippetObj.getString("description");
                    videoId = (obj.getJSONObject("id")).getString("videoId");
                    videoTitles.add(new Video(title, thumbnailUrl, description,videoId));
                    Log.i("ayusch", "length of array = " + i);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

           titles=videoTitles;
            return null;
        }
    }

}

VideoAdapter.java :
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.CustomHolder> {

    private int maxNumItems = 25;
    ArrayList<Video> titles;

    public VideoAdapter(ArrayList<Video> titles) {
        this.titles = titles;
    }

    @Override
    public CustomHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View root = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
        CustomHolder holder = new CustomHolder(root, parent.getContext());
        return holder;
    }

    @Override
    public void onBindViewHolder(CustomHolder holder, int position) {

        holder.tv_title.setText((titles.get(position).title));
        String url = titles.get(position).thumbnailUrl;
        Picasso.with(holder.tv_title.getContext()).load(url).into(holder.iv_thumbnail);
        holder.tv_description.setText((titles.get(position)).description);
    }

    @Override
    public int getItemCount() {
        return titles.size();
    }

    public class CustomHolder extends RecyclerView.ViewHolder {
        TextView tv_title,tv_description;
        ImageView iv_thumbnail;
        Context c;

        public CustomHolder(View itemView, Context context) {
            super(itemView);

            tv_title = (TextView) itemView.findViewById(R.id.tv_video_title);
            iv_thumbnail = (ImageView) itemView.findViewById(R.id.iv_video_thumbnail);
            tv_description = (TextView) itemView.findViewById(R.id.tv_video_description);
            c = context;
        }

    }
}

Video.java :
public class Video {
    String title;
    String thumbnailUrl;
    String description;
    String videoId;

    Video(String vidTitle, String url, String desc, String vidId) {
        title = vidTitle;
        thumbnailUrl = url;
        description = desc;
        videoId = vidId;
    }
}

Also please feel free to suggest any code improvements for performance. I am still in my learning phase and want to write good performance code and this app takes a while to load json response in recyclerview.

A: 1. Do titles ArrayList initialization and set RecyclerView adapter from onCreate() method.
2. Clear titles list from JSONParseTask for every data fetch operation.
3. Add Video object to list titles instead of videoTitles.
4. Call  adapter.notifyDataSetChanged() to update RecyclerView after adding each item to titles list.
Update your MainActivity as below:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    URL url = null;
    String resultString = null;
    RecyclerView rv;
    VideoAdapter adapter;
    ArrayList<Video> titles;

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

        rv = (RecyclerView) findViewById(R.id.rv_display);
        url = NetworkUtils.buildUrlFromUsername(Config.FOR_USERNAME);

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        rv.setLayoutManager(layoutManager);
        rv.setHasFixedSize(true);

        titles = new ArrayList<Video>();
        adapter = new VideoAdapter(titles);
        rv.setAdapter(adapter);

        Log.i("ayusch", "url = " + url);
        new YoutubeQueryTask().execute(url);
        Log.i("ayusch", "After task");
    }

    public void formatJSON(String resultString) {
        new JSONParseTask().execute(resultString);
    }

    public class YoutubeQueryTask extends AsyncTask<URL, Void, String> {

        @Override
        protected String doInBackground(URL... params) {
            URL builtUrl = params[0];
            resultString = "no result";
            try {
                resultString = NetworkUtils.getResponseFromUrl(builtUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }

            return resultString;
        }

        @Override
        protected void onPostExecute(String s) {

            formatJSON(s);
        }
    }

    public class  JSONParseTask extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... params) {
            JSONObject itemsObj, thumbnailsObject, defaultObject, obj, snippetObj;

            String title, thumbnailUrl, description, videoId;
            try {
                itemsObj = new JSONObject(resultString);
                JSONArray itemsArray = itemsObj.getJSONArray("items");

                // Required to clear list
                if (itemsArray.length() > 0)
                    titles.clear();

                for (int i = 0; i < itemsArray.length(); i++) {

                    obj = itemsArray.getJSONObject(i);
                    snippetObj = obj.getJSONObject("snippet");

                    title = snippetObj.getString("title");
                    thumbnailsObject = snippetObj.getJSONObject("thumbnails");
                    defaultObject = thumbnailsObject.getJSONObject("default");
                    thumbnailUrl = defaultObject.getString("url");
                    description = snippetObj.getString("description");
                    videoId = (obj.getJSONObject("id")).getString("videoId");

                    // Add to list
                    titles.add(new Video(title, thumbnailUrl, description,videoId));

                    // Update RecyclerView
                    adapter.notifyDataSetChanged();

                    Log.i("ayusch", "length of array = " + i);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }
    }

}

Hope this will help~

A: If you want to simplify your code for simple REST calls. You can use this library Android RESTAdapter
It is extremely trivial to use and reduces code by a lot.


text:
Q: Why std::fetch_add returns the old value? What are the design purposes or technical restrictions that make the return value of std::fetch_add is the one before changed?

A: It's not a big deal either way, you can emulate one in terms of the other.  e.g. val.add_fetch(1) can be implemented with 1 + val.add_fetch(1) if you want it.  However, GNU C __atomic builtins provide both.
Possible reason for ISO C/C++ only providing fetch_add instead of add_fetch: it makes it cheaper to implement on x86 in some cases; lock xadd [mem], reg leaves reg = old value of mem, mem = sum.  Providing that primitive instead of the other encourages people to design algorithms around that building block, maybe avoiding the need for an extra add instruction.
Most RISC ISAs with LL/SC atomics have 3-operand instructions, so they could add dst, src1, src2 and leave the value from memory undisturbed in another register if code wants it later.  (LL/SC fetch_add(x) would normally be implemented as load-linked reg1, [mem] / add reg2, reg1, x / store-conditional reg3, reg2, [mem].  With a retry loop based on the success/fail result in reg3.  If the fetch_add return value is unused, the add can overwrite reg1 instead of using a new reg.
So on most RISCs it's fine either way, and x86 is one of the more-relevant ISAs to care about efficiency on.

For some use-cases, fetch_add is also what you want.  e.g. for threads grabbing buckets in an array-based circular buffer lock-free queue, with std::atomic<unsigned> write_idx; zero-initialized to start with, you want .fetch_add to start with 0.
  static std::atomic<unsigned> write_idx = 0;  // shared var

  // in each thread:
  unsigned my_buf = write_idx.fetch_add(1) & ((1<<size) - 1);

You'll get values starting with 0 instead of 1.  This seems like a plausible pattern for lots of use-cases.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get all active categories and subcategories in product listing page? My categories and subcategories hierarchy to a product listing page :

*

*Products

*

*Refrigerator

*

*back-bar fridges

*

*Product listing(here)

Now, what i'm trying to get is while i'm in product listing page i want to get all the parent categories and subcategories with respective links.
I got answer from this question
But, i failed to get all parent items (subcategories and subcategories)
$path = $category->getPath();
What i get is : 0(root)/2(Magento root)/444(products)

And it escapes all the middle subcategories. In my case it escaped Refrigerator/backbar fridges

A: this will show like breadcrum.
I know this is quite old, but I'd like to share my solution anyway as it doesn't override/clone any core files.
In your custom module add the following to your config.xml:

<config>
    ...
    <frontend>
        <events>
            <catalog_controller_product_init>
                <observers>
                    <breadcrumb_categorypath_product_init>
                        <type>singleton</type>
                        <class><Your Namespace>_<Your Module>_Model_Observer</class>
                        <method>fullBreadcrumbCategoryPath</method>
                    </breadcrumb_categorypath_product_init>
                </observers>
            </catalog_controller_product_init>
        </events>
    </frontend>
</config>

Create an Observer.php in /app/code/local///Model/
Add the following to your Observer.php:
class <Your Namespace>_<Your Module>_Model_Observer {
    public function fullBreadcrumbCategoryPath(Varien_Event_Observer $observer) {
        $current_product = Mage::registry('current_product');

        if( $current_product ) {
            $categories = $current_product->getCategoryCollection()->addAttributeToSelect('name')->setPageSize(1);
            foreach( $categories as $category ) {
                Mage::unregister('current_category');
                Mage::register('current_category', $category);
            }
        }
    }

I hope this will help you.

A: Try this to get all active categories:
$categories = Mage::getModel('catalog/category')
                    ->getCollection()
                    ->addAttributeToSelect('*')
                    ->addIsActiveFilter();

A: May be this give help you a bit.
<?php

$parentCategoryId = 222;
$cat = Mage::getModel('catalog/category')->load($parentCategoryId);
$subcats = $cat->getChildren();

// Get 1 Level sub category of Parent category
foreach(explode(',',$subcats) as $subCatid)
              {
                $_category = Mage::getModel('catalog/category')->load($subCatid);
  if($_category->getIsActive()) {
    echo '
getURL().'" title="View the products for the "'.$_category->getName().'" category">'.$_category->getName().'
';

  }
}
*/
?>


text:
Q: Ideal way to store large data in JavaScript I'm making a web-based game that involves purchasing property, then rooms inside that property and finally assets. My current way of storing data is having one array containing property purchased (in ID form), then it compares that ID to another array which will list the rooms, then finally another array for the assets inside that room.
However, after recently being introduced to 2D arrays, I'm unsure about which method would be best for storing this data; having multiple arrays that store separate data, or having all of the property data inside one huge 4D array?

A: Why aren't you using a database and fetching only the data which is currently needed? If you need more data then query again and add it to your arrays. I don't think that the user will run through all rooms in the first attempt.
Or could you give a example on your data/model?


text:
Q: How to predict next number from sequence of number with tf model.predict? Trying to make prediction of the next number but it didn't work well.
I have a list of 500 numbers :
[..., x, x, 3, 2, 1, 7, 2, 0, 3], i want to make prediction model with those 500 numbers to give me the possible 501 number.
I tried making model example with this code, it didn't go as expected with the example of 1 to 5 numbers.
xs = np.array([1, 2, 3, 4, 5])
ys = np.array([3, 7, 11, 15, 19])

model = tf.keras.Sequential([keras.layers.Dense(1, input_shape=(1,))])
model.compile(optimizer='adam', loss='mse', metrics=['mae'])
model.fit(xs, ys, epochs=200)
result = model.predict(xs)

print(result)

I use that code expecting prediction of the next number of xs.
it gave me this instead of 6 as the next number :
Epoch 200/200
1/1 [==============================] - 0s 6ms/step - loss: 161.2350 - mae: 11.2588
1/1 [==============================] - 0s 98ms/step
[[ 0.04653116]
 [-0.1042112 ]
 [-0.25495356]
 [-0.40569592]
 [-0.55643827]]

A: To solve this kind of problem your model should be more complicated. Relationship between input value and target value are not linear (according to the example) so current model which looks like input_value x weight + bias barely can find a good solution.
I would suggest you to use something like this:
model = tf.keras.Sequential()
model.add(keras.layers.Dense(16, input_shape=(1,)))
model.add(keras.layers.Dropout(0.1))
model.add(keras.layers.Dense(16))
model.add(keras.layers.Dropout(0.1))
model.add(keras.layers.Dense(1))
model.compile(optimizer='adam', loss='mse', metrics=['mae'])
model.summary()

model.fit(xs, ys, epochs=200, verbose = 0)
result = model.predict(xs)

print(np.floor(result))

To improve results you can also play around with hyperparameters


text:
Q: Consulta SQL rango de fechas Tengo una consulta para ejecutar en access, la quería sacar en sql.
Tengo una tabla llamada prueba que contiene los campos fecha e id, estoy intentando que me devuelva todos los registros comprendidos en entre el 12/01/2019 y 12/06/2019 y la ejecuta pero devuelve los campos vacíos, veis el error?:
SELECT Fecha, id FROM PRUEBA where 'fecha' BETWEEN '12/01/2019' AND '12/06/2019'

A: @Hermes,  para mi lo que te comenta Patricio, asegurate que los campos sean datetime y si es así por default tienes que meterle el formato en YYYY/MM/DD, a no ser que le hagas un convert en la consulta para que te lo cambie.
Con ponerlo en YYYY/MM/DD seguro que te lo soluciona.


text:
Q: How to overcome the hanging of TCP client when TCP server is not running? I am trying to establish  a TCP socket connection between my Android phone and PC for file transfer. A TCP Server program will in PC and TCP client program run in Android. When the server program is running everything works fine. But when the server program is not running and when the client tries to establish the connection, the client hangs(in the sense it waits for long time till it establish theconnection ). How to overcome this problem? I want to terminate the socket as soon the client finds that no such server is running. Is it possible to do that?

A: I believe you need to play with the timeout settings of the Socket API.
See here for some more detailed discussion:
Set timeout for socket

A: You can control the connect timeout of a Socket by constructing a new Socket() and using the Socket.connect(SocketAddress, timeout) method.
Note that you can use this to decrease the default timeout, which is a bit over a minute, but not to increase it.

A: The problem seems to be in the server configuration (PC in your case). It might have prohibited the outgoing ICMP traffic, which is responsible of notifying the clients about closed ports.
Try to telnet your service port when it's not running.
Like
telnet <my.pc.address> <my-port>

On "normal" configurations it should immediately fail (exactly as your client app shoud) with
telnet: Unable to connect to remote host: Connection refused

On tricky configurations with firewalls, ICMP prohibited, etc it will "hang" for a long time, "thinking" that the service is running and waiting for it's answer.


text:
Q: Mostar elementos ArrayList Java Estoy haciendo un ejercicio donde debo hacer un programa para un punto de venta. Las funcionalidades son agrear mercancía(nombre,cantidad, precio), vender mercancía y listar inventario. Cada mercancía la agrego a un ArrayList. El problema es que a la hora de mostrar los elementos del ArrayList solo me muestra el primer elemento. Este es mi código:
CLASE INVENTARIO:
import java.util.ArrayList;

public class Inventario {

      ArrayList<Mercancia> listaMercancias = new ArrayList<>();

     public  void agregarMercancia(Mercancia objMercancia){
        listaMercancias.add(objMercancia);
    }

     public String listarInventario(){
        for(Mercancia mercancias:listaMercancias){
            return "Nombre: " + mercancias.nombre + "; " + "Cantidad restante: " + mercancias.cantidad;

        }

        return null;
    }

     public void venderMercancia(Mercancia objMercancia){

         objMercancia.cantidad -= 1;
         if (objMercancia.cantidad == 0) {
             listaMercancias.remove(objMercancia);
         }
     }

CLASE MERCANCIA:
public class Mercancia {
    String nombre;
    int cantidad;
    int precio;

    public Mercancia(String nombre, int cantidad, int precio) {
        this.nombre = nombre;
        this.cantidad = cantidad;
        this.precio = precio;
    }

}

METODO MAIN:
public static void main(String[] args) {

    Mercancia objMercancia1 = new Mercancia("producto1",5,500);
    Mercancia objMercancia2 = new Mercancia("producto2",6,200);
    Mercancia objMercancia3 = new Mercancia("producto3",2,300);

    Inventario objInventario = new Inventario();

    objInventario.agregarMercancia(objMercancia1);
    objInventario.agregarMercancia(objMercancia2);
    objInventario.agregarMercancia(objMercancia3);

    System.out.println(objInventario.listarInventario());
    System.out.println(objInventario.listaMercancias.size());

}

Cuando ejecuto el método size() me dice que hay 3 elementos que son los que agregue.

A: En listarInventario haces un return, con lo que se produce el retorno, se sale del método y sólo te devuelve el primer elemento.
Un cambio rápido sería:
public void listarInventario(){
    for(Mercancia mercancias:listaMercancias){
        System.out.println("Nombre: " + mercancias.nombre + "; " + "Cantidad restante: " + mercancias.cantidad);

    }
}

y en el main simplemente:
objInventario.listarInventario();

A: Yo te aconsejo que regrese una String utilizando el objeto StringBuilder, quedaría algo así
 public String listarInventario(){
    StringBuilder listado = new StringBuilder();
    for(Mercancia mercancias:listaMercancias){
        listado.append("Nombre: " + mercancias.nombre + "; " + "Cantidad restante: " + mercancias.cantidad);

    }

    return listado.toString();
}

A: Primeramente tu método esta retornando el valor al leer el primer elemento, por esa razón únicamente obtienes el primer valor. Te aconsejo concatenar los valores y posteriormente retornar el valor de todos los elementos.
  public String listarInventario(){
        String resultado = "";

        for(Mercancia mercancias:listaMercancias){
            resultado = resultado + "Nombre: " + mercancias.nombre + "; " + "Cantidad restante: " + mercancias.cantidad  +  "\n";

        //También puedes usar el operador +=
        //resultado += "Nombre: " + mercancias.nombre + "; " + "Cantidad restante: " + mercancias.cantidad  +  "\n";

        }

        return resultado ;
    }

De esta forma retornara el valor de todos los resultados almacenados en listaMercancias, al terminar de obtenerlos en el bucle , en caso de no obtener ningún elemento simplemente retornará un string vació.
Es recomendable el uso de la clase StringBuilder al concatenar cadenas, cuando tenemos información considerable.
  public String listarInventario(){
       StringBuilder resultado = new StringBuilder();

        for(Mercancia mercancias:listaMercancias){
            resultado.append("Nombre: " + mercancias.nombre + "; " + "Cantidad restante: " + mercancias.cantidad);

        }

        return resultado.toString();
    }

Incluso como comenta Joel, puedes implementar el método toString() en la clase Mercancia
public class Mercancia {
    String nombre;
    int cantidad;
    int precio;

    public Mercancia(String nombre, int cantidad, int precio) {
        this.nombre = nombre;
        this.cantidad = cantidad;
        this.precio = precio;
    }

     public String toString(){
        return "Nombre: " + nombre + "; " + "Cantidad restante: " +cantidad+""; Precio: "+precio;
     }

}

De esta forma podrías obtener el mismo resultado:
  public String listarInventario(){
       StringBuilder resultado = new StringBuilder();

        for(Mercancia mercancias:listaMercancias){

           resultado.append(mercancias.toString());

        }

        return resultado.toString();
    }


text:
Q: Ports used from traefik reverse proxy service are not reported from "docker ps" command The "docker ps" command does not show the traefik port 8080 and other ports used from the service
The traefik service is defined in a docker-compose.yml as follow:
...
  traefik:
    image: traefik:1.7-alpine
    command: --docker --docker.swarmMode  --docker.domain=mylocal.swarm --docker.watch --api --logLevel=INFO \
      --entryPoints='Name:http Address::80' \
      --entryPoints='Name:https Address::443 TLS'
    networks:
      - net-traefik
    deploy: *default-deploy
    ports:
      - "8091:80"
      - "8093:443"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    logging: *default-logging

The "docker ps" command output is:
CONTAINER ID    IMAGE                COMMAND                 CREATED    STATUS        PORTS
...
635a4e017bb5    traefik:1.7-alpine   "/entrypoint.sh o…"      …          …            80/tcp
...

Why only the port 80 is displayed? I expected to find also 443 and 8080

A: This port 80 is just the one that was specified under EXPOSE in the Dockerfile and therefore shows up there. The other ports you define in your file are mapped to the service you create with Docker Swarm, and not to a single container. If this would happen, then using Swarm at all is useless, because if you have more than one container – which is kind of the point of using Swarm – they cannot both be mapped to the same port.
This blog post seems to contain some good information about how the publishing of services work with Docker Swarm.

A: With swarm mode, the port is not published on the individual containers. Instead the port is published via the service, which then uses a VIP to send the request over the ingress network to one of the replicas of the service. You can use the following to see these ports:
docker service ls

Note in the docker ps command, the ports you see there include the "exposed ports" which are defined in the image. These are documentation from the image creator to the user of the image to expect something listening inside the container on this port, and in no way impacts published ports on the host or container to container networking.


text:
Q: A number is inserted, and I have to make a message box pop up with the word versions of the numbers How do I fix this program? A number is inserted, and I have to make a message box pop up with the word versions of the numbers. For example, if "301" is typed in, the message box has to say "Three Zero One". Here's what I have:
string display = "";
for (int i = 0; i < txtNumber.Text.Length; i++)
{
    if (txtNumber.Text[i] == 0)
    {
        display += "Zero ";
    }

    if (txtNumber.Text[i] == 1)
    {
        display += "One ";
    }

    if (txtNumber.Text[i] == 2)
    {
        display += "Two ";
    }

    if (txtNumber.Text[i] == 3)
    {
        display += "Three ";
    }

    if (txtNumber.Text[i] == 4)
    {
        display += "Four ";
    }

    if (txtNumber.Text[i] == 5)
    {
        display += "Five ";
    }

    if (txtNumber.Text[i] == 6)
    {
        display += "Six ";
    }

    if (txtNumber.Text[i] == 7)
    {
        display += "Seven ";
    }

    if (txtNumber.Text[i] == 8)
    {
        display += "Eight ";
    }

    if (txtNumber.Text[i] == 9)
    {
        display += "Nine ";
    }
}

MessageBox.Show(display);

There are no errors showing up on an error list, but whenever I run it and type in a number and hit enter, the message box pops up with nothing in it. Anything will help. Thank you very much!

A: Text[i] is a character that is being converted automatically to int. And since for example '0' code is not 0 - nothing is shown. Change all your if to char-to-char comparison:
if (txtNumber.Text[i] == '0')

Also you might want to consider using switch construction.

A: var numToText = new Dictionary<int, string>() { {'0', "Zero "}, ...};
foreach (var char in txtMessage.Text)
{
    display += numToText[char];
}

This is probly also a linq one-liner

A: The problem is that you are comparing characters with integers, which you cannot do.
However, you can do like this:
foreach (char c in txtNumber.Text)
{
    switch (c)
    {
        case '0': display += "Zero ";
            break;
        case '1': display += "One ";
            break;
        case '2': display += "Two ";
            break;
        case '3': display += "Three ";
            break;
        case '4': display += "Four ";
            break;
        case '5': display += "Five ";
            break;
        case '6': display += "Six ";
            break;
        case '7': display += "Seven ";
            break;
        case '8': display += "Eight ";
            break;
        case '9': display += "Nine ";
            break;
        default: display += "NaN ";
            break;
    }
}

Here we loop through all the characters in the string and compares each character with a specified case in the switch statement and if the character is neither 0-9 it dispays "NaN" (Not a Number).

A: The .Text property is of type string. Indexing into an item of type string returns values of type char. Your code is performing an incorrect implied cast the way that it's written now. For example, casting a 0 char to an int yields 48 and casting 0 int to a char yields an ASCII NUL. Try either single-quoting your digits to make them character literals (i.e. '0') or parsing the indexed item (i.e., int.Parse(txtNumber.Text[i])) to avoid an implied cast with an unexpected result.

A: You are comparing char with int in your txtNumber.Text[i] == 0 line for example.
And since I'm an humble programmer, I wrote your example with based switch stament on LINQPad like;
void Main()
{
    string s = Console.ReadLine();
    string result = "";
    foreach (var i in s)
    {
        switch (i)
        {
            case '1':
                result += "One ";
                break;
            case '2':
                result += "Two ";
                break;
            case '3':
                result += "Three ";
                break;
            case '4':
                result += "Four ";
                break;
            case '5':
                result += "Five ";
                break;
            case '6':
                result += "Six ";
                break;
            case '7':
                result += "Seven ";
                break;
            case '8':
                result += "Eight ";
                break;
            case '9':
                result += "Nine ";
                break;
            case '0':
                result += "Zero ";
                break;
        }
    }
    result = result.Trim();
    result.Dump();
}

For 301 as an input, output will be Three Zero One

A: Should be as easy as
public static string DigitsToWords( string digits )
{
  if ( !digits.All( char.IsDigit ) ) throw new ArgumentOutOfRangeException("digits");

  return string.Join( " " , digits.Select( d => words[d-'0'] ) ) ;
}
private static readonly string [] words = { "zero" , "one" , "two" , "three" , "four" , "five" , "six" , "seven" , "eight" , "nine" , } ;


text:
Q: Construct a function such that its adherent values are the compact set $K$ I really need help, this question seems really crazy, I don't know even how to begin, please any help is welcome.
QUESTION

Given a real number $a$ and a non-empty compact set $K\subset \mathbb
R$, construct a function $f:\mathbb R \to \mathbb R$ such that the
  adherent values of $f$ in the point $a$ be $K$.

EDIT
Definition of adherent values of $f$ in the point $a$

A real number $c$ is called adherent value of $f$ in the point $a$
  when there is a sequence of points $x_n\in X−\{a\}$ such that $\lim
 x_n=a$ and $\lim f(x_n)=c$

thanks a lot

A: Let $\mathbb R/\mathbb Q$ denote the quotient of the abelian group $\mathbb R$ with addition by its subgroup $\mathbb Q$.  Let $K$ be a subset of $\mathbb R$, and let $\varphi:(\mathbb R/\mathbb Q)\to K$ be a surjection.  Define $f(x)=\varphi(x+\mathbb Q)$.  This example works because every coset of $\mathbb Q$ is dense in $\mathbb R$, so for all $y\in K$ there exists a sequence $(x_n)\to a$ such that $x_n\neq a$ and $f(x_n)=y$ for all $n$.  Assuming $K$ is closed, there are no other adherent values, because the range of $f$ is $K$.


text:
Q: MODIS R Package strsplit error I'm trying to use MODIS to download some spatial data, but I'm not able to do it. When I try to download and process MODIS data with MODIS R package, I get this strange strsplit error.
 b1 <- runGdal(product = "M.D13A2", begin = Sys.Date() - 30, tileH = 18:19, tileV = 4)

Returned:
########################
outProj          =  asIn
pixelSize        =  asIn
resamplingType   =  near
Output directory =  C:/*****************************/MOD13A2.061_20210525100758  (no 'job' name specified, generated (date/time based))
########################
Local structure is up-to-date. Using offline information!
Hm, I have to search for the file. Next time provide the full path and I'll be very fast!
Error in strsplit(x, ":") : non-character argument

I don't know what is happening here.


text:
Q: How to change video playbackRate with coffeescript I have a video, and I need it to run slower.
Current code:
ready = undefined
set_rate = undefined

set_rate = =>
  $('#background').attr playbackRate: '.1'
  return

ready = =>
  set_rate()
  return

$(document).ready ready

$('#background') selects my <video>
I have also tried $('#background').playbackRate = .1 and $('#background').playbackRate = '.1'
But I can never see any difference(alerting the playbackRate results in .1), I've also tried using vlc to slow down the video, but it becomes jumpy, and un-usable.
Notice: I am using coffeescript, not javascript (even though they're 'the same')
Also, the video is muted, I believe that makes things easier.

A: The jQuery attr() method (see the docs) expects a string which is the name of the attribute you want to change, and the value you want to set it to.
$('#background').attr 'playbackRate', 0.1

EDIT
If that doesn't work, try setting it directly via the DOM element rather than jQuery (use [0] to access it from it's jQuery wrapper)
 $('#background')[0].playbackRate = 3.0;

If it's still not working, please post an example snippet of you code here or in a jsfiddle where we can reproduce and try out fixes.


text:
Q: Sums of normal random variables Consider a sample of n independent normal rvs. I would like to identify a systematic way of calculating the probability of having the sum of a subset of them larger than the sum of the rest of rvs.
An example case:
Population of fish. Mean: 10 kg, stdv: 3 kg.
I fish five fish (n=5). What is the probability of having two fish weighing more than the rest of the three fish?
The steps which can be followed is to calculate the prob for every combination of fish and then use the inclusion exclusion formula for their union. Is there anything smarter?
Note: if four fish were considered the probability of having two of them heavier than the other two should be one. How could this be computed immediately?
Thanks for the answers.

A: Your example suggests that not only are the $n$ variables $X_1,X_2,\ldots,X_n$ independent, they also have the same Normal distribution.  Let its parameters be $\mu$ (the mean) and $\sigma^2$ (the variance) and suppose the subset consists of $k$ of these variables.  We might as well index the variables so that $X_1,\ldots, X_k$ are this subset.
The question asks to compute the chance that the sum of the first $k$ variables equals or exceeds the sum of the rest:
$$p_{n,k}(\mu,\sigma) = \Pr(X_1+\cdots+X_k \ge X_{k+1}+\cdots+X_n ) =  \Pr(Y \le 0)$$
where
$$Y = -(X_1+\cdots+X_k) + (X_{k+1}+\cdots+X_n).$$
$Y$ is a linear combination of independent Normal variables and therefore has a Normal distribution--but which one?  The laws of expectation and variance immediately tell us
$$E[Y] = -k\mu + (n-k)\mu = (n-2k)\mu$$
and
$$\operatorname{Var}(Y) = k \sigma^2 + (n-k)\sigma^2 = n\sigma^2.$$
Therefore $$Z=\frac{Y - (n-2k)\mu}{\sigma\sqrt{n}}$$ has a standard Normal distribution with distribution function $\Phi,$ whence the answer is

$$p_{n,k}(\mu,\sigma) = \Pr(Y \le 0) = \Pr\left(Z \le -\frac{(n-2k)\mu}{\sigma\sqrt{n}}\right) = \Phi\left(-\frac{(n-2k)\mu}{\sigma\sqrt{n}}\right).$$

In the question, $n=5,k=2,\mu=10,$ and $\sigma=3,$ whence
$$p_{5,2}(10,3) = \Phi\left(-\frac{(5-2(2))10}{3\sqrt{10}}\right)\approx 0.0680186.$$

Generalization
Little needs to change in this analysis even when the $X_i$ have different normal distributions or are even correlated: you only need to assume they have an $n$-variate Normal distribution to assure their linear combination still has a Normal distribution.  The calculations are carried out in the same way and result in a similar formula.

Check
A commenter suggested solving this with simulation.  Although that wouldn't be a solution, it's a decent way to check a solution quickly.  Thus, in R we might establish the inputs of the simulation in some arbitrary way as
n <- 5
k <- 2
mu <- 10
sigma <- 3
n.sim <- 1e6 # Simulation size
set.seed(17) # For reproducible results

and simulate such data and compare the sums with these two lines:
x <- matrix(rnorm(n*n.sim, mu, sigma), ncol=n)
p.hat <- mean(rowSums(x[, 1:k]) >= rowSums(x[, -(1:k)]))

The post-processing consists of finding the fraction of simulated datasets in which one sum exceeds the other and comparing that to the theoretical solution:
se <- sqrt(p.hat * (1-p.hat) / n.sim)
p <- pnorm(-(n-2*k)*mu / (sigma * sqrt(n)))
signif(c(Simulation=p.hat, Theory=p, `Z-score`=(p.hat-p)/se), 3)

The output in this case is

Simulation     Theory    Z-score
    0.0677     0.0680    -1.1900

The agreement is close and the small absolute z-score allows us to attribute the discrepancy to random fluctuations rather than any error in the theoretical derivation.


text:
Q: How to rework Sql to Yii2 with Left Join? I have a db where I need to calculate the values of the two tables.
Table Forc:

*

*rft

*cos.

Table Prod:

*

*w

*efr

*result.

Formula:  $x = (w * efr) / rft * (1 + (cos / 10).
So on raw SQL it will be something like this:
UPDATE Prod
   SET result = w*eft /
      (SELECT Forc.rft * (1 + Forc.cos / 10)
         FROM Forc
        WHERE Forc.id=Prod.id)

But I don't know how it build with Left join, especially on Yii2. So that request must change the value "result", when the user enters a value in a cells as defined in formula.
How can this be done?


text:
Q: howto get the event when someone press the back key and get in a xaml site in wp7? how can i get the event when the user is on page A and go to page B. on page B he press back and returns tu page A.
need to determin when this happen, how could i do this with wp7?

A: There is PhoneApplicationPage.OnBackKeyPress that does exactly the job you are looking for.

A: The OnNavigatedTo event that handles navigation to a page, be it by NavigationService's Navigate or GoBack method, have no event information on from which page you navigated from, and neither about how you navigated.
So in short: It's not possible. And I can't imagine any good reason for it either.


text:
Q: How to set "return_value" once for TestCase. Python. Django Here is example test:

import a
import b
import c

import mock
from django.test import TestCase

@mock.patch.object(a, "method_a")
@mock.patch.object(b, "method_b")
@mock.patch.object(c, "method_c")
class SomeTestCase(TestCase):

    def setUp(self):
        # I want to set mock_method_a.return_value = 1 once here (or not here, but once)
        pass

    def test_one(self, mock_method_a, mock_method_b, mock_method_c):
        mock_method_a.return_value = 1
        mock_method_b.return_value = 2
        pass  # some test stuff

    def test_two(self, mock_method_a, mock_method_b, mock_method_c):
        mock_method_a.return_value = 1
        mock_method_b.return_value = 2
        pass  # some test stuff

    def test_three(self, mock_method_a, mock_method_b, mock_method_c):
        mock_method_a.return_value = 1
        mock_method_b.return_value = 2
        pass  # some test stuff

Queston:

How I can avoid of duplicate code for setting "return_value" in each test in TestCase?

I expect something in "setUp" method or something similar.

Is it possible?

PS: mock version mock==1.3.0, django version Django==1.8.4

A: You can set the return_value right there in the @mock.patch.object() decorators:
@mock.patch.object(c, "method_c", return_value=3)
@mock.patch.object(b, "method_b", return_value=2)
@mock.patch.object(a, "method_a", return_value=1)
class SomeTestCase(TestCase):
    def test_one(self, mock_method_a, mock_method_b, mock_method_c):
        # do test stuff, return values have been set

    def test_two(self, mock_method_a, mock_method_b, mock_method_c):
        # do test stuff, return values have been set

    def test_three(self, mock_method_a, mock_method_b, mock_method_c):
        # do test stuff, return values have been set

(Note: when decorating with @mock.patch the decorators are applied from the bottom on up, so for mock_method_a to be passed in as the first argument you need to put the decorator closest to the class definition).
The return_value keyword argument to mock.patch.object() is passed to the MagicMock() constructor. See the mock.patch.object() documentation:

Like patch(), patch.object() takes arbitrary keyword arguments for configuring the mock object it creates.

and the mock.Mock documentation:

Mock takes several optional arguments that specify the behaviour of the Mock object:

*

*[...]

*return_value: The value returned when the mock is called. By default this is a new Mock (created on first access). See the return_value attribute.

If you also want to avoid setting the mocks outside of your test case or don't like the additional arguments to each test function, then you you can also can create patchers in the setUp method, which then are removed again when the test ends by registering a callback via the unittest.TestCase.addCleanup() method.
The patchers are applied for each test, by calling the patcher.start() methods, which returns the new mock object:
class SomeTestCase(TestCase):
    def setUp(self):
        patcher_method_a = mock.patch.object(a, "method_a")
        self.mock_method_a = patcher_method_a.start()
        self.mock_method_a.return_value = 1

        patcher_method_b = mock.patch.object(b, "method_b")
        self.mock_method_b = patcher_method_b.start()
        self.mock_method_b.return_value = 2

        patcher_method_c = mock.patch.object(c, "method_c")
        self.mock_method_c = patcher_method_c.start()
        self.mock_method_c.return_value = 3

        # when the test is done, stop **all** patchers
        self.addCleanup(mock.patch.stopall)

    def test_one(self):
        # use self.mock_method_a, etc.

    def test_two(self, mock_method_a, mock_method_b, mock_method_c):
        # use self.mock_method_a, etc.

    def test_three(self, mock_method_a, mock_method_b, mock_method_c):
        # use self.mock_method_a, etc.

Note that the mock.patch.stopall() method will stop all mock patchers that have started. You can also pass the .stop attributes of each of the patchers:
self.addCleanup(patcher_method_a.stop)
self.addCleanup(patcher_method_b.stop)
self.addCleanup(patcher_method_c.stop)

If you have to create a lot of such setups, you could create a helper function that'll take care of the repeated parts:
def setup_object_patch(testcase, object, target, return_value, attrname=None):
    patcher = mock.patch.object(object, target)
    mock = patcher.start()
    mock.return_value = return_value
    setattr(testcase, attrname or f'mock_{target}', mock)
    testcase.addCleanup(patcher.stop)

and perhaps use this in a loop over a mapping:
def setUp(self):
    mocks = {
        # attribute name on test -> object, target, return_value
        'mock_method_a': (a, 'method_a', 1),
        'mock_method_b': (b, 'method_b', 2),
        'mock_method_c': (c, 'method_c', 3),
    }
    for attrname, params in mocks.items():
        setup_object_patch(*params, attrname=attrname)

The patcher.start() approach in a TestCase.setUp() method makes it easier to use inheritance, where a base testcase case is used as the basis for several test cases that all use the same shared mocking setup.


text:
Q: How to disables wordpress updates using hooks? How can I disables WordPress updates, plugins updates and themes updates using hooks. There are many plugins for unable updates but how can I do that with hooks.

A: Here is the class with hooks you just copy and paste in function.php. This code will disable your all updates (WordPress, plugins and theme).
/* The OS_Disable_WordPress_Updates class */
class OS_Disable_WordPress_Updates {
    private $__pluginsFiles;
    private $__themeFiles;

    function __construct() {
        $this->__pluginsFiles = array();
        $this->__themeFiles = array();

        add_action( 'admin_init', array(&$this, 'admin_init') );

        if( !function_exists( 'get_plugins' ) ) require_once ABSPATH . 'wp-admin/includes/plugin.php';

        if( count( get_plugins() ) > 0 ) foreach( get_plugins() as $file => $pl ) $this->__pluginsFiles[$file] = $pl['Version'];
        if( count( wp_get_themes() ) > 0 ) foreach( wp_get_themes() as $theme ) $this->__themeFiles[$theme->get_stylesheet()] = $theme->get('Version');

        add_filter( 'pre_transient_update_themes', array($this, 'last_checked_themes') );

        add_filter( 'pre_site_transient_update_themes', array($this, 'last_checked_themes') );

        add_action( 'pre_transient_update_plugins', array(&$this, 'last_checked_plugins') );

        add_filter( 'pre_site_transient_update_plugins', array($this, 'last_checked_plugins') );

        add_filter( 'pre_transient_update_core', array($this, 'last_checked_core') );

        add_filter( 'pre_site_transient_update_core', array($this, 'last_checked_core') );

        add_filter( 'auto_update_translation', '__return_false' );
        add_filter( 'automatic_updater_disabled', '__return_true' );
        add_filter( 'allow_minor_auto_core_updates', '__return_false' );
        add_filter( 'allow_major_auto_core_updates', '__return_false' );
        add_filter( 'allow_dev_auto_core_updates', '__return_false' );
        add_filter( 'auto_update_core', '__return_false' );
        add_filter( 'wp_auto_update_core', '__return_false' );
        add_filter( 'auto_core_update_send_email', '__return_false' );
        add_filter( 'send_core_update_notification_email', '__return_false' );
        add_filter( 'auto_update_plugin', '__return_false' );
        add_filter( 'auto_update_theme', '__return_false' );
        add_filter( 'automatic_updates_send_debug_email', '__return_false' );
        add_filter( 'automatic_updates_is_vcs_checkout', '__return_true' );

        add_filter( 'automatic_updates_send_debug_email ', '__return_false', 1 );
        if( !defined( 'AUTOMATIC_UPDATER_DISABLED' ) ) define( 'AUTOMATIC_UPDATER_DISABLED', true );
        if( !defined( 'WP_AUTO_UPDATE_CORE') ) define( 'WP_AUTO_UPDATE_CORE', false );

        add_filter( 'pre_http_request', array($this, 'block_request'), 10, 3 );
    }

    function OS_Disable_WordPress_Updates() {
        $this->__construct();
    }

    function admin_init() {
        if ( !function_exists("remove_action") ) return;

        remove_action( 'admin_notices', 'update_nag', 3 );
        remove_action( 'network_admin_notices', 'update_nag', 3 );
        remove_action( 'admin_notices', 'maintenance_nag' );
        remove_action( 'network_admin_notices', 'maintenance_nag' );

        remove_action( 'load-themes.php', 'wp_update_themes' );
        remove_action( 'load-update.php', 'wp_update_themes' );
        remove_action( 'admin_init', '_maybe_update_themes' );
        remove_action( 'wp_update_themes', 'wp_update_themes' );
        wp_clear_scheduled_hook( 'wp_update_themes' );

        remove_action( 'load-update-core.php', 'wp_update_themes' );
        wp_clear_scheduled_hook( 'wp_update_themes' );

        remove_action( 'load-plugins.php', 'wp_update_plugins' );
        remove_action( 'load-update.php', 'wp_update_plugins' );
        remove_action( 'admin_init', '_maybe_update_plugins' );
        remove_action( 'wp_update_plugins', 'wp_update_plugins' );
        wp_clear_scheduled_hook( 'wp_update_plugins' );

        remove_action( 'load-update-core.php', 'wp_update_plugins' );
        wp_clear_scheduled_hook( 'wp_update_plugins' );

        add_action( 'init', create_function( '', 'remove_action( \'init\', \'wp_version_check\' );' ), 2 );
        add_filter( 'pre_option_update_core', '__return_null' );

        remove_action( 'wp_version_check', 'wp_version_check' );
        remove_action( 'admin_init', '_maybe_update_core' );
        wp_clear_scheduled_hook( 'wp_version_check' );

        wp_clear_scheduled_hook( 'wp_version_check' );

        remove_action( 'wp_maybe_auto_update', 'wp_maybe_auto_update' );
        remove_action( 'admin_init', 'wp_maybe_auto_update' );
        remove_action( 'admin_init', 'wp_auto_update_core' );
        wp_clear_scheduled_hook( 'wp_maybe_auto_update' );
    }

    public function block_request($pre, $args, $url) {}

    public function last_checked_core() {}

    public function last_checked_themes() {}

    public function last_checked_plugins() {}
}

if ( class_exists('OS_Disable_WordPress_Updates') ) {
    $OS_Disable_WordPress_Updates = new OS_Disable_WordPress_Updates();
}

I think it will work.


text:
Q: Print python xml response into HTML page My .py app return xml response from API, I want to write value of messageKey 'notFound' into the .html page.
Ex of response:
<response>
<returncode>FAILED</returncode>
<messageKey>notFound</messageKey>
<message>We could not find a meeting with that meeting ID</message>
</response>

EX of .html:
#....

#....

Any kind of help please?

A: I solve this by:
.py:
@flask.route('/admin')
def index():
    return render_template("admin.html", variable=soup)

.html:

{{variable}}


text:
Q: Difference in time doesnot work in python. The truth value of a Series is ambiguous df['DiffTime']=df['time1']-df['time2']
i am trying to do difference of date and it brings up and error
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
My difference time is in format - "0 days 00:53:39"
i tried to use below to make a condition for 30minutes and above
if d['fDiffTime']>numpy.timedelta64(3219000000000,'ns'):

    display(df)

Also tried this

if d['fDiffTime']>0 days 00:30:00

Is there a way i can avoid all these and get difference time greater than 30 minutes
if d['fDiffTime']>numpy.timedelta64(3219000000000,'ns'):

    display(df)

Also tried this

if d['fDiffTime']>0 days 00:30:00

Is there a way i can avoid all these and get difference time greater than 30 minu

A: To get a time difference in say minutes use:
df['DiffTime']=(df['time1']-df['time2'])/ pd.Timedelta(minutes=1)

else use (hours = 1) or (days = 1) as required.


text:
Q: Difficult data manipulation to fill values in an R dataframe I have what appears to be a fairly difficult to vectorize / speed up problem at hand. I am able to solve the problem with a nested for-loop that scales slowly. The data I'm working with is NBA possession data, and I'm analyzing it over multiple NBA seasons (100K - 1M) rows, which is very slow (multiple minutes) in my nested for loop. I created test data to highlight the problem:
mydf = data.frame(id1 = c(100, 100, 100, 150, 150, 150),
              id2 = c(110, 110, 110, 122, 122, 122),
              P1 = c(1, 1, 1, 1, 2, 2),
              P2 = c(2, 2, 2, 3, 3, 3),
              O1 = c(4, 4, 4, 4, 4, 4),
              O2 = c(5, 5, 6, 6, 6, 6),
              A1 = 0,
              A2 = 0,
              A3 = 0,
              A4 = 0,
              A5 = 0,
              A6 = 0)

There are 6 unique users in this dataframe, (1-6), and their IDs appear in columns P1, P2, O1, and O2. Each user also gets its own column, (A1-A6). Each time a user appears in a row in columns P1 or P2, it's respective column gets a 1. Each time a user appears in a row in columns O1 or O2, it's respective column gets a -1. My for-loop for solving this problem is as follows:
for (i in 1:nrow(mydf)) {
  for (j in 3:4) {
    tmp = paste0("A",as.character(mydf[i,j]))
    mydf[i, which(colnames(mydf) == tmp)] = 1
  }

  for (j in 5:6) {
    tmp = paste0("A",as.character(mydf[i,j]))
    mydf[i, which(colnames(mydf) == tmp)] = -1
  }
}

My actual dataframe has P1-P5, O1-O5, and roughly 300 unique player IDs. Any thoughts on how I can speed this up?
Thanks!

A: Based on your sample data, this should work:
library(dplyr); library(tidyr); library(tibble)

mydf.calculated <- mydf %>%

  # make row names explicit so that we can join back by row later
  rownames_to_column("row.id") %>%
  select(row.id, starts_with("P"), starts_with("O")) %>%

  # convert to long format & define calculation based on whether P or O
  gather(operation, A, -row.id) %>%
  mutate(calculation = ifelse(grepl("P", operation), 1, -1)) %>%

  # if there are multiple P and/or O operations on the same user in the same row,
  # collapse into final calculated result
  group_by(row.id, A) %>%
  summarise(calculation = sum(calculation)) %>%
  ungroup() %>%

  # spread calculated results to respective user columns
  mutate(A = paste0("A", A)) %>%
  spread(A, calculation, fill = 0) %>%

  # sort in original row order
  arrange(row.id) %>% select(-row.id)

# combine results
cbind(mydf %>% select(-starts_with("A")),
      mydf.calculated)

  id1 id2 P1 P2 O1 O2 A1 A2 A3 A4 A5 A6
1 100 110  1  2  4  5  1  1  0 -1 -1  0
2 100 110  1  2  4  5  1  1  0 -1 -1  0
3 100 110  1  2  4  6  1  1  0 -1  0 -1
4 150 122  1  3  4  6  1  0  1 -1  0 -1
5 150 122  2  3  4  6  0  1  1 -1  0 -1
6 150 122  2  3  4  6  0  1  1 -1  0 -1

A: Not especially efficient but this works:
cA <- col(mydf[,7:12])
mydf[,7:12] <- (cA==mydf$P1)+(cA==mydf$P2)-(cA==mydf$O1)-(cA==mydf$O2)

mydf
  id1 id2 P1 P2 O1 O2 A1 A2 A3 A4 A5 A6
1 100 110  1  2  4  5  1  1  0 -1 -1  0
2 100 110  1  2  4  5  1  1  0 -1 -1  0
3 100 110  1  2  4  6  1  1  0 -1  0 -1
4 150 122  1  3  4  6  1  0  1 -1  0 -1
5 150 122  2  3  4  6  0  1  1 -1  0 -1
6 150 122  2  3  4  6  0  1  1 -1  0 -1

A: About twice as fast as your version on the sample data set; the downside is that you need to specify the number of players
for (i in 1:6) {
  mydf[paste0("A", i)] <- (i==mydf$P1 | i==mydf$P2) * 1 - 1*
                                   (i==mydf$O1 | i==mydf$O2)
}

This is only a little faster on the sample, but is easier to adapt to different numbers of P/O columns:
playercols <- function(mydf, nplayers, plus, minus) {
  for (i in 1:nplayers) {
    mydf[paste0("A", i)] <- rowSums(i==mydf[, plus]) -
      rowSums(i==mydf[, minus])
  }
  mydf
}

playercols(mydf, 6, 3:4, 5:6)

A: Having measured the runtimes of the other answers, this might be the fastest yet. It's a modified version of @Glen_b's answer that's flexible for non-sequential IDs:
vals <- gsub("^A","",names(mydf)[grep("^A",names(mydf))]),
cA <- data.frame(sapply(vals,function(i) rep(i,length(vals)))),
mydf[,grep("A",names(mydf))] <- (cA==mydf$P1)+(cA==mydf$P2)-(cA==mydf$O1)-(cA==mydf$O2)

Output:
  id1 id2 P1 P2 O1 O2 A1 A7 A3 A8 A5 A10
1 100 110  1  7 10  5  1  1  0  0 -1  -1
2 100 110  1  7 10  5  1  1  0  0 -1  -1
3 100 110  5  7  1  8 -1  1  0 -1  1   0
4 150 122  1 10  7  8  1 -1  0 -1  0   1
5 150 122  3  3  5  7  0 -1  2  0 -1   0
6 150 122  3  8  3  5  0  0  0  1 -1   0

Here's the sample data I edited to include the non-sequential IDs:
mydf = data.frame(id1 = c(100, 100, 100, 150, 150, 150),
              id2 = c(110, 110, 110, 122, 122, 122),
              P1 = c(1, 1, 5, 1, 3, 3),
              P2 = c(7, 7, 7, 10, 3, 8),
              O1 = c(10, 10, 1, 7, 5, 3),
              O2 = c(5, 5, 8, 8, 7, 5),
              A1 = 0,
              A7 = 0,
              A3 = 0,
              A8 = 0,
              A5 = 0,
              A10 = 0)

To measure the runtime, you can use a package like microbenchmark:
require(microbenchmark)

microbenchmark(
  vals <- gsub("^A","",names(mydf)[grep("^A",names(mydf))]),
  cA <- data.frame(sapply(vals,function(i) rep(i,length(vals)))),
  mydf[,grep("A",names(mydf))] <- (cA==mydf$P1)+(cA==mydf$P2)-(cA==mydf$O1)-(cA==mydf$O2)
)

Unit: microseconds
     min        lq       mean    median       uq      max neval cld
  19.263   27.4365   44.48546   37.4500   48.158  150.556   100   a
 460.698  555.1930  869.30677  692.5255 1004.787 3343.197   100   b
1378.804 1656.6080 2815.49635 2140.1545 3216.846 8664.538   100   c


text:
Q: GRAVITY FORMS: Date Validation Failing I have this filter set in my functions.php file on WordPress that validates the date, so the pickup date time and is earlier than the return date and time. When the dates and times are entered correctly it should pass the validation but it keeps failing and I just can't fathom this out. It's just stopped working all of a sudden. I can only pinpoint this to set the date/time on the server to Greenwich time.
add_filter( 'gform_validation', 'custom_validation' );
function custom_validation( $validation_result ) {

    $form = $validation_result['form'];
    $pickupDate = null;
    $returnDate = null;

    foreach( $form['fields'] as & $field ) {
        if ( $field->label == 'Pickup Date' ) {
            $pickupDate = rgpost('input_' . $field->id);
            //var_dump("Pickup Date:" . $pickupDate);
        }

        if ( $field->label == 'Pickup Time' ) {
            $pickupDate .= ' ' . rgpost('input_' . $field->id);
            //var_dump("Pickup Time:" . $pickupDate);
        }

        if ( $field->label == 'Return Date' ) {
            $returnDate = rgpost('input_' . $field->id);
            //var_dump("Return Date:" . $returnDate);
        }

        if ( $field->label == 'Return Time' ) {
            $returnDate .= ' ' . rgpost('input_' . $field->id);
            //var_dump("Return Time:" . $returnDate);

            if (strtotime($returnDate) <= strtotime($pickupDate)) {

                //var_dump($returnDate);
                //var_dump($pickupDate);

                $validation_result['is_valid'] = false;
                $field->failed_validation = true;
                $field->validation_message = 'Please ensure your selected Pickup Date and time is earlier than your Return Date and Time';
                break;
            }
        }
    }

    //Assign modified $form object back to the validation result
    $validation_result['form'] = $form;

    return $validation_result;
}

add_filter( 'gform_pre_send_email', function ( $email, $message_format ) {
    if ( $message_format != 'html' ) {
        return $email;
    }

    if (strpos($email['message'], 'Pickup Date') !== false) {
        $email['message'] = explode('Pickup Date', $email['message']);
        $email['message'][1] = str_replace('/', ', ', $email['message'][1]);
        $email['message'][1] = str_replace('<, ', '</', $email['message'][1]);
        $email['message'] = implode('Pickup Date', $email['message']);
    }

    $email['message'] = '<html>' . $email['message'] . '</html>';

    return $email;
}, 10, 2 );

The dates are getting dumped out in this format.
string(22) "Pickup Date:25/06/2020"
string(28) "Pickup Time:25/06/2020 08:00"
string(22) "Return Date:26/06/2020"
string(28) "Return Time:26/06/2020 08:00"

Can anyone even spot where the problem is at?
When you access this URL you need to click on the "Quotation Needed" button.

A: You just need to remove = from your validation condition.
add_filter( 'gform_validation', 'custom_validation' );
function custom_validation( $validation_result ) {

$form = $validation_result['form'];
$pickupDate = null;
$returnDate = null;

foreach( $form['fields'] as & $field ) {
    if ( $field->label == 'Pickup Date' ) {
        $pickupDate = rgpost('input_' . $field->id);
        //var_dump("Pickup Date:" . $pickupDate);
    }

    if ( $field->label == 'Pickup Time' ) {
        $pickupDate .= ' ' . rgpost('input_' . $field->id);
        //var_dump("Pickup Time:" . $pickupDate);
    }

    if ( $field->label == 'Return Date' ) {
        $returnDate = rgpost('input_' . $field->id);
        //var_dump("Return Date:" . $returnDate);
    }

    if ( $field->label == 'Return Time' ) {
        $returnDate .= ' ' . rgpost('input_' . $field->id);
        //var_dump("Return Time:" . $returnDate);

        if (strtotime($returnDate) < strtotime($pickupDate)) {

            //var_dump($returnDate);
            //var_dump($pickupDate);

            $validation_result['is_valid'] = false;
            $field->failed_validation = true;
            $field->validation_message = 'Please ensure your selected Pickup Date and time is earlier than your Return Date and Time';
            break;
        }
    }
}
//Assign modified $form object back to the validation result
$validation_result['form'] = $form;

return $validation_result;
}


text:
Q: Why did Bootstrap make ".row"? Besides offsetting ".container"'s padding, is there any functionality that ".row" provides? If Bootstrap hadn't given padding to the ".container", then there would have been no need of ".row".
".row"'s negative margin offests ".container"'s padding.
Or are there any other reasons why ".row" is neccessay?


text:
Q: How do I lag a pandas series and create a new time lagged data frame? I want to create a time lagged pandas data frame from a pandas series.
Given pandas series:
X = pd.Series(range(5))

Expected output:
    0   1   2
0   0   1   2.0
1   1   2   3.0
2   2   3   4.0
3   3   4   0.0

I have implemented the following function (with step size), but it takes a long time on large data-sets.
def creat_time_lagged(x, shift, step):
    df = pd.DataFrame()
    for i in range(0, len(x), step):
        if i + shift - 1 < len(x):
            df['{}'.format(i)] = x.iloc[i : i + shift].values
        else:
            df['{}'.format(i)] = np.append(x.iloc[i:].values, np.zeros(shift - len(x.iloc[i:].values)))
            break
    return df

How can I improve it?

A: Approach #1
We can leverage np.lib.stride_tricks.as_strided based scikit-image's view_as_windows to get sliding windows. More info on use of as_strided based view_as_windows.
from skimage.util.shape import view_as_windows

def create_time_lagged_viewaswindows(X, shift, step):
    a_ext = np.r_[X.values,np.zeros(shift-1,dtype=X.dtype)]
    windows_ar = view_as_windows(a_ext,shift)[:len(X)-shift+step+1:step].T
    return pd.DataFrame(windows_ar)

Bit of explanation : The basic idea is we pad on the trailing side with zeros and then create sliding windows. To create the windows, we make use of np.lib.stride_tricks.as_strided or skimage.util.view_as_windows.
Sample runs -
In [166]: X = pd.Series(range(5))

In [167]: create_time_lagged_viewaswindows(X, shift=4, step=1)
Out[167]:
   0  1  2
0  0  1  2
1  1  2  3
2  2  3  4
3  3  4  0

In [168]: create_time_lagged_viewaswindows(X, shift=4, step=2)
Out[168]:
   0  1
0  0  2
1  1  3
2  2  4
3  3  0

Approach #2
We can also make use of np.lib.stride_tricks.as_strided that would require us to manually setup the strides and shape arg with it, but we would avoid the transpose as used with earlier approach and that might be worth the extra performance boost. The implementation would look something along these lines -
def create_time_lagged_asstrided(X, shift, step):
    a_ext = np.r_[X.values,np.zeros(shift-1,dtype=X.dtype)]
    strided = np.lib.stride_tricks.as_strided
    s = a_ext.strides[0]
    ncols = (len(X)-shift+2*step)//step
    windows_ar = strided(a_ext, shape=(shift,ncols), strides=(s,step*s))
    return pd.DataFrame(windows_ar)

Timings on large array -
In [215]: X = pd.Series(range(10000))

# Original solution
In [216]: %timeit creat_time_lagged(X, shift=10, step=5)
1 loop, best of 3: 608 ms per loop

# Approach #1
In [217]: %timeit create_time_lagged_viewaswindows(X, shift=10, step=5)
10000 loops, best of 3: 146 µs per loop

# Approach #2
In [218]: %timeit create_time_lagged_asstrided(X, shift=10, step=5)
10000 loops, best of 3: 104 µs per loop


text:
Q: Error: "The value for the SHELL variable was not found the /etc/shells file" when running `pkexec` On Ubuntu 14.04, I am getting the error "The value for the SHELL variable was not found the /etc/shells file" when running pkexec to run a script.
Most likely this error started after I removed the fish shell, that was set as my default shell.
The content of /etc/shells is:

# /etc/shells: valid login shells
  /bin/sh
  /bin/dash
  /bin/bash
  /bin/rbash

How may I fix this?

A: The problem is this one: pkexec is accessing $SHELL to determine which shell to use to evaluate the remainder of the command; since you uninstalled fish but didn't do anything else, $SHELL still contains /usr/bin/fish, but pkexec doesn't deem /usr/bin/fish as a valid shell, since /usr/bin/fish has been removed from /etc/shells.
You need to do these two things:

*

*Set a new shell for your user, so that the next time the environment is load $SHELL will contain a path to a valid shell. E.g. to set Bash as the new shell for your user (replace user with your user's username):
sudo chsh -s /bin/bash user

*Log out / log in to reload the environment so that $SHELL contains the path to the new shell for your user.


text:
Q: Change page margins for table I have a large table and want to put it on a page with smaller margins. A quick and dirty way would be
\clearpage
\newgeometry{margin=1cm}
\begin{table}
...
\end{table}
\restoregeometry

However, this doesn't allow the table to float anymore.
I read the following Q&A: Standard way of handling oversize pages? But found 2 problems:

*

*for the horizontal adjustment I try use addmargin from KOMA script. It does the job, but I get an overfull hbox warning for every single line of the table, which makes log files really unreadable. Also it only changes the width of the table but not the table caption.

*for the vertical adjustment neither enlargethispage nor addlines works inside the table environment. And just doing \vspace* has the disadvantage that the table cannot be vertically centered on the page.
the perfect solution would be to have something like \newgeometry but within the floating environment. Is there anything like this?

A: Load the changepage package, and use  this code to adjust locally the margins:
\begin{table}
\begin{adjustwidth}{–some length}{–some other length}
................
\end{adjustwidth}
\end{table}

A: In this question (changepage package's \adjustwidth environment adjusts only left margin) @Werner gives the following response:

The adjustwidth environment of changepage takes two arguments, both of
  which are adjustments inward from the existing margins. So,

\begin{adjustwidth}{-1cm}{-1cm}
  % <stuff>
\end{adjustwidth}


text:
Q: GPUImage index out of bounds crash I have a camera app on the app store that uses GPUImage to take pictures and record videos. I am getting crash reports that says its crashing for a lot of users with the error
Fatal Exception: NSRangeException
*** -[NSArray| objectAtIndex:]: index 0 beyond bounds for empty array

The crash report says the crash occurs in the GPUImageStillCamera.m class at line 283. Below is the crash report. I appreciate your help in advance.
Thread : Fatal Exception: NSRangeException
0  CoreFoundation                 6484558552 __exceptionPreprocess
1  libobjc.A.dylib                6783221988 objc_exception_throw
2  CoreFoundation                 6483393332 CFRunLoopRemoveTimer
3  Selfie                         4297468448 -[GPUImageStillCamera capturePhotoProcessedUpToFilter:withImageOnGPUHandler:] (GPUImageStillCamera.m:283)
4  Selfie                         4297465636 -[GPUImageStillCamera capturePhotoAsImageProcessedUpToFilter:withOrientation:withCompletionHandler:] (GPUImageStillCamera.m:171)
5  Selfie                         4295826452 +[SEMediaCapture captureImageFromCamera:withFilter:completion:] (SEMediaCapture.m:39)
6  Selfie                         4296216108 -[SEViewController takePicture] (SEViewController.m:595)
7  Selfie                         4296201380 -[SEViewController tappedToTakeAPicture:] (SEViewController.m:216)
8  UIKit                          6564311152 _UIGestureRecognizerSendActions
9  UIKit                          6562842292 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:]
10 UIKit                          6567498636 ___UIGestureRecognizerUpdate_block_invoke662
11 UIKit                          6562595864 _UIGestureRecognizerRemoveObjectsFromArrayAndApplyBlocks
12 UIKit                          6562588612 _UIGestureRecognizerUpdate
13 UIKit                          6562834476 -[UIWindow _sendGesturesForEvent:]
14 UIKit                          6562832100 -[UIWindow sendEvent:]
15 UIKit                          6562648352 -[UIApplication sendEvent:]
16 UIKit                          6565405368 _UIApplicationHandleEventFromQueueEvent
17 UIKit                          6562641460 _UIApplicationHandleEventQueue
18 CoreFoundation                 6484263488 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
19 CoreFoundation                 6484260068 __CFRunLoopDoSources0
20 CoreFoundation                 6484252052 __CFRunLoopRun
21 CoreFoundation                 6483382996 CFRunLoopRunSpecific
22 GraphicsServices               6645217020 GSEventRunModal
23 UIKit                          6563065664 UIApplicationMain
24 Selfie                         4296168708 main (main.m:15)
25 libdyld.dylib                  6790212104 start


text:
Q: Converting Json Date into mm/dd/yy format I am getting data from Json which also contains date. Now the date is displayed in Numerics. I were able to convert Date into a readable format but that's not my requirement. I want the date to be displayed in mm/dd/yy format.
$.ajax({
        url: '@Url.Action("ReqVacancy", "AdvertisementMaintenance")',
        type: 'GET',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: { "RequisitionID": id },
        success: function (data) {
              var result1 = "";
                divid.html('');
$.each(data, function (id, result) {
                    if (result != 0) {
                        var result1 = "
"
                        + '<input type="checkbox" name="VacancyId"  id="VacancyId" value=' + result.VacancyId + '>	'

                                            + "" + result.VacancyId + "	"
                                            + "" + result.PositionId + "	"
                                            + "" + result.Reason + "	"
                                            + "" + eval('new' + result.StartDate.replace(/\//g, ' ')) + "	"
                                            + "" + eval('new' + result.EndDate.replace(/\//g, ' ')) + "	"
                                               + "
"
                        $('#tbody').append(result1);
                    }

                });
      });

And the result goes here....
    VacancyId   Position    Reason         StartDate                                                EndDate
    1           Fresher      Not Avail     Sat Mar 07 2015 00:00:00 GMT+0530 (India Standard Time)  Tue Mar 17 2015 00:00:00 GMT+0530 (India Standard Time)

My requirement is:
VacancyId   Position         Reason        StartDate          EndDate
    1           Fresher      Not Avail      03/07/2015        03/17/2015

I could do the above taking a variable and then using getMonth(), getDate() and getFullYear(). But the code goes long and I have been asked to do it within a single line of code. Any help is highly appreciated. Thanks.

A: There's nothing to do with json for your date format, you can do something like this in javascript.
var startDate = new Date(result.StartDate);
var formattedStartDate = startDate.getMonth() + "/" + startDate.getDate() + "/" + startDate.GetYear();

Your overall code should look like this.
 $.each(data, function (id, result) {
        if (result != 0) {
            var startDate = eval('new' + result.StartDate.replace(/\//g, ' '));
            var formattedStartDate = startDate.getMonth() + "/" + startDate.getDate() + "/" + startDate.GetYear();
            var endDate = eval('new' + result.EndDate.replace(/\//g, ' '));
            var formattedEndDate = endDate.getMonth() + "/" + endDate.getDate() + "/" + endDate.GetYear();
            var result1 = "
"
            + '<input type="checkbox" name="VacancyId"  id="VacancyId" value=' + result.VacancyId + '>	'

                                + "" + result.VacancyId + "	"
                                + "" + result.PositionId + "	"
                                + "" + result.Reason + "	"
                                + "" + formattedStartDate + "	"
                                + "" + formattedEndDate + "	"
                                   + "
"
            $('#tbody').append(result1);
        }

Solution: 2
Create a prototype for date as :
Date.prototype.toMMDDYYYY = function(){
  return this.getMonth() + "/" + this.getDate() + "/" + this.getFullYear()
};

Use Case:
new Date().toMMDDYYYY();

In your screen:
$.each(data, function (id, result) {
            if (result != 0) {
               var result1 = "
"
                + '<input type="checkbox" name="VacancyId"  id="VacancyId" value=' + result.VacancyId + '>	'

                                    + "" + result.VacancyId + "	"
                                    + "" + result.PositionId + "	"
                                    + "" + result.Reason + "	"
                                    + "" + new Date(result.StartDate.replace(/\//g, ' ')).toMMDDYYYY()+ "	"
                                    + "" + new Date(result.EndDate.replace(/\//g, ' ')).toMMDDYYYY()+ "	"
                                    + "
"
                $('#tbody').append(result1);
            }

Update: with live example

//Somewhere globally...
Date.prototype.toMMDDYYYY = function(){
  return this.getMonth() + "/" + this.getDate() + "/" + this.getFullYear()
};

//expecing your date string looks like this

var startDate = new Date("Sat Mar 07 2015 00:00:00 GMT+0530 (India Standard Time)");
var data = [{"PositionId":1,"Reason":"Fresher","StartDate":"/Date(1425666600000)/","EndDate":"/Date(1426530600000)/","VacancyId":1}];
$.each(data, function (id, result) {
            if (result != 0) {
              //Your rest of the code
             alert( eval("new " + result.StartDate.replace(/\//g, ' ')).toMMDDYYYY());
            }
  });

A: You can do like this
$.each(data, function (id, result) {
                    if (result != 0) {
                       var stDate=new Date(result.StartDate);
                       var endDate=new Date(result.EndDate);
                        var result1 = "
"
                        + '<input type="checkbox" name="VacancyId"  id="VacancyId" value=' + result.VacancyId + '>	'
                                            + "" + result.VacancyId + "	"
                                            + "" + result.PositionId + "	"
                                            + "" + result.Reason + "	"
                                            + "" + stDate.getMonth()+1 +"/" + stDate.getDate() + "/" + stDate.getFullYear()  + "	"
                                            + "" + endDate.getMonth()+1 +"/" + endDate.getDate() + "/" + endDate.getFullYear()  + "	"
                                               + "
"
                        $('#tbody').append(result1);
                    }

                });

A: I just got the answer from @Moksh Shah & also @Guruprasad Rao. Thanks for your help. It look like this here..
$.each(data, function (id, result) {
                  console.log(result.StartDate);
                    if (result != 0) {
//I just had to use new Date(......) here
                        var endDate = new Date(eval('new' + result.EndDate.replace(/\//g, ' ')));
                        var formattedEDate = endDate.getMonth() + 1 + '/' + endDate.getDate() + '/' + endDate.getFullYear();
                        var SDate = new Date(eval('new' + result.StartDate.replace(/\//g, ' ')));
                        var formattedSDate = SDate.getMonth() + 1 + '/' + SDate.getDate() + '/' + SDate.getFullYear();
                        //console.log(endDate);
                        var result1 = "
"
                        + '<input type="checkbox" name="VacancyId"  id="VacancyId" value=' + result.VacancyId + '>	'

                                            + "" + result.VacancyId + "	"
                                            + "" + result.PositionId + "	"
                                            + "" + result.Reason + "	"
                                            + "" + formattedSDate + "	"
                                          + "" + formattedEDate + "	"
                                               + "
"
                        $('#tbody').append(result1);
                    }

A: It can be a possible duplicate of this
Your code should look like:
      if (result != 0) {
                    var result1 = "
"
                    + '<input type="checkbox" name="VacancyId"  id="VacancyId" value=' + result.VacancyId + '>	'

                                        + "" + result.VacancyId + "	"
                                        + "" + result.PositionId + "	"
                                        + "" + result.Reason + "	"
                                        + "" + dateFormat(result.StartDate) + "	"
                                        + "" + dateFormat(result.EndDate) + "	"
                                           + "
"
                    $('#tbody').append(result1);
                }

    function dateFormat(dateObject) {
          var d = new Date(dateObject);
          var day = d.getDate();
          var month = d.getMonth();
          var year = d.getFullYear();
          if (day < 10) {
           day = "0" + day;
          }
          if (month < 10) {
            month = "0" + month;
          }
          year = year.toString().slice(2);
          var date = day + "/" + month + "/" + year;

          return date;
      }


text:
Q: LINUX - The build of my Unity game crashes after a few hours - Receiving unhandled NULL exception Description of the problem:
The build crashes and closes itself after a few hours (usually in a range between 4 and 12 hours), printing this message in the log:
Receiving unhandled NULL exception

#0  0x00000000ff382c in std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >::~vector()
#1  0x0000000102c983 in std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >::~vector()
#2  0x0000000102d9c5 in std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >::~vector()
#3  0x00000000c07080 in operator new[](unsigned long, std::nothrow_t const&)
#4  0x00000000c0719f in operator new[](unsigned long, std::nothrow_t const&)
#5  0x00000000c07522 in operator new[](unsigned long, std::nothrow_t const&)
#6  0x00000000c07798 in operator new[](unsigned long, std::nothrow_t const&)
#7  0x00000000c078db in operator new[](unsigned long, std::nothrow_t const&)
#8  0x00000000cb8d90 in operator new[](unsigned long, std::nothrow_t const&)
#9  0x007f29dc9ff182 in start_thread
#10 0x007f29dc926b1f in clone

Tech specs:

*

*Unity: 2018.4.28 LTS (running on Windows)

*OS: Ubuntu 19.04 LTS optimized for UDOO Bolt by UDOO team (https://www.udoo.org/docs-bolt/Operating_Systems/Linux/index.html)

*Hardware: UDOO Bolt v8 (https://shop.udoo.org/udoo-bolt-v8.html and https://www.udoo.org/docs-bolt/Introduction/Introduction.html)

Tests done (not fixing the bug):

*

*To separate the logs of my threads (since I have a few threads), so each thread prints the debug on a different file not using the Player.log because it is used by the main thread.

*To create a build without the threads.

*To maintain the hardware temperature very low, around 45° avoiding high temp on CPU and GPU.

*To disable the AMD virtualization from the BIOS.

*To enable the "Disable HW Statistics" checkbox in the Player Settings -> Other, since I found that this could be responsible for the error "Curl error 6: Could not resolve host: cdp.cloud.unity3d.com", whose the stacktrace is very similar to the one of the crash  (to see the stacktrace I set it to Full in the Player Settings -> Other -> Logging):

Curl error 6: Could not resolve host: cdp.cloud.unity3d.com
 #0 std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >::~vector()
 #1 ???
 #2 std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >::~vector()
 #3 std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >::~vector()
 #4 std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >::~vector()
 #5 operator new[](unsigned long, std::nothrow_t const&)
 #6 operator new[](unsigned long, std::nothrow_t const&)
 #7 operator new[](unsigned long, std::nothrow_t const&)
 #8 operator new[](unsigned long, std::nothrow_t const&)
 #9 operator new[](unsigned long, std::nothrow_t const&)
 #10 operator new[](unsigned long, std::nothrow_t const&)
 #11 start_thread
 #12 clone

Gathered info from previous tests:

*

*Sometimes there is only the error  "Receiving unhandled NULL exception" after the crash, other times there is also the full stack trace.

*Sometimes the error "Receiving unhandled NULL exception" is separated from the stack trace by some other prints.

*Enabling the Full Log in Unity, precisely in Player Settings -> Other -> Logging, a print in the update (using debug.log) generates this stack trace (which is very similar to our exception, so I am guessing that "operator new[](unsigned long, std::nothrow_t const&)" and the Vector are part of the Debug.Log and they are not linked to my problem):

DebugLog stacktrace
DebugLog from Update!

#0 std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >::~vector()
#1 std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >::~vector()
#2  (Mono JIT Code) (wrapper managed-to-native) UnityEngine.DebugLogHandler:Internal_Log (UnityEngine.LogType,string,UnityEngine.Object)
#3 mono_print_method_from_ip
#4 mono_perfcounter_foreach
#5 mono_runtime_invoke
#6 operator new[](unsigned long, std::nothrow_t const&)
#7 operator new[](unsigned long, std::nothrow_t const&)
#8 operator new[](unsigned long, std::nothrow_t const&)
#9 operator new[](unsigned long, std::nothrow_t const&)
#10 operator new[](unsigned long, std::nothrow_t const&)
#11 operator new[](unsigned long, std::nothrow_t const&)
#12 operator new[](unsigned long, std::nothrow_t const&)
#13 ???
#14 __libc_start_main
#15 ???

*

*Only one time the stack trace was different:

"Different Receiving unhandled NULL exception"
Receiving unhandled NULL exception

#0  0x007f1056492bf4 in nouveau_drm_screen_create
#1  0x007f1056495aa0 in nouveau_drm_screen_create
#2  0x007f10561a878f in nouveau_drm_screen_create
#3  0x007f1056235c84 in nouveau_drm_screen_create
#4  0x007f1056235f87 in nouveau_drm_screen_create
#5  0x000000010dcf2a in std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >::~vector()
#6  0x000000010f1169 in std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >::~vector()
#7  0x00000000b01116 in operator new[](unsigned long, std::nothrow_t const&)
#8  0x000000010ef244 in std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >::~vector()
#9  0x00000000924e9b in std::pow(float, float)
#10 0x000000009209e2 in std::pow(float, float)
#11 0x00000000920b19 in std::pow(float, float)
#12 0x00000000cb8d90 in operator new[](unsigned long, std::nothrow_t const&)
#13 0x007f105b6ed182 in start_thread
#14 0x007f105b614b1f in clone

*

*I noticed these things intercepting the signals received by the game:
Every 5 seconds (approximately), 7 signals SIGPWR  has been received,followed by 7 signals SIGXCPU.
When the game crashes, the signals SIGSEGV, SIGABRT has been received, followed by a lot of SIGSTOP, ending with SIGABRT and SIGPIPE.
This is the last part of the log of the signals.    The columns use this order:
"Epoch", "Time of Signal", "Name", "PID", "Signal", "Signaling Process Name"

Handled signals log
1601585247770866   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585247770920   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585247770934   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585247771012   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585247771033   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585247771101   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585247771112   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585247790047   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585247790085   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585247790098   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585247790155   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585247790171   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585247790234   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585247790245   Thu Oct  1 22:47:27 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585252704451   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585252704506   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585252704570   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585252704591   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585252704653   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585252704673   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585252704685   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGPWR    MyGame.x86_
1601585252723584   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585252723644   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585252723698   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585252723716   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585252723799   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585252723819   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585252723829   Thu Oct  1 22:47:32 2020 CEST        MyGame.x86_   30851   SIGXCPU   MyGame.x86_
1601585253349839   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSEGV   MyGame.x86_
1601585253360946   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGABRT   MyGame.x86_
1601585253471368   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253471658   Thu Oct  1 22:47:33 2020 CEST        MyGame:cs0   30851   SIGSTOP   gdb
1601585253471690   Thu Oct  1 22:47:33 2020 CEST        MyGame:sh0   30851   SIGSTOP   gdb
1601585253471704   Thu Oct  1 22:47:33 2020 CEST        MyGame:sh1   30851   SIGSTOP   gdb
1601585253471731   Thu Oct  1 22:47:33 2020 CEST        MyGame:sh2   30851   SIGSTOP   gdb
1601585253471752   Thu Oct  1 22:47:33 2020 CEST        MyGame:sh3   30851   SIGSTOP   gdb
1601585253471763   Thu Oct  1 22:47:33 2020 CEST        MyGame:sh4   30851   SIGSTOP   gdb
1601585253471774   Thu Oct  1 22:47:33 2020 CEST        MyGame:sh5   30851   SIGSTOP   gdb
1601585253471859   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253471890   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253471904   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253471917   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253471937   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253471953   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253471968   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253471980   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253471990   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472015   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472027   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472043   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472059   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472074   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472084   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472103   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472121   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472136   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472150   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472165   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472176   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472194   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472208   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472223   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472246   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472275   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472291   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472316   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472333   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472348   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472363   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472391   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472408   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472418   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472435   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472451   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472482   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585253472593   Thu Oct  1 22:47:33 2020 CEST        MyGame.x86_   30851   SIGSTOP   gdb
1601585254227807   Thu Oct  1 22:47:34 2020 CEST        MyGame.x86_   30851   SIGCHLD   gdb
1601585254227927   Thu Oct  1 22:47:34 2020 CEST        MyGame.x86_   30851   SIGABRT   MyGame.x86_
1601585254309322   Thu Oct  1 22:47:34 2020 CEST        MyGame.x86_   30851   SIGPIPE   MyGame.x86_
1601585254309342   Thu Oct  1 22:47:34 2020 CEST        MyGame.x86_   30851   SIGPIPE   MyGame.x86_

Resources used:
I used the following script in order to intercept the signals, running it with the command "sudo stap myscript.stp".
#! /usr/bin/env stap

probe signal.send {
  if ((isinstr(pid_name, "MyGame"))) {
      printf("%10d   %-34s   %-10s   %5d   %-7s   %s\n",
      gettimeofday_us(), tz_ctime(gettimeofday_s()),
      pid_name, sig_pid, sig_name, execname());
  }
}

probe begin {
  printf("systemtap script started at: %s\n\n", tz_ctime(gettimeofday_s()));
  printf("%50s%-18s\n", "",  "Signaled Process");
  printf("%-10s   %-34s   %-10s   %5s   %-7s   %s\n",
    "Epoch", "Time of Signal", "Name", "PID", "Signal", "Signaling Process Name");
  printf("---------------------------------------------------------------");
  printf("---------------------------------------------------------------");
  printf("\n");
}

probe end {
  printf("\n");
}

Doubts

*

*Are the signals received during the crash the cause of it? Or are they a consequence?

*Could "Curl error 6: Could not resolve host: cdp.cloud.unity3d.com" be the problem?

*The crash seems caused by a segmentation fault. Is my game that is generating this segmentation fault? Or could it be a library or something else? How can I understand it?

What I am trying to do (but I'm currently stuck):

*

*I would like to create a dump analyzing it with a debugger.

*I would like to find a method to catch the not handled exception, making easier the research of the problem.

UPDATE x1:
I was able to create the core dump. You can find the full log here:
https://pastebin.com/1Bm70rNd
While the native stacktrace of the exception is:
/home/username0/MyGame_Game/Game/MyGame_Data/MonoBleedingEdge/x86_64/libmonobdwgc-2.0.so(+0xd5378) [0x7f644c157378]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x15540) [0x7f645dd08540]
/lib/x86_64-linux-gnu/libc.so.6(gsignal+0xcb) [0x7f645db463eb]
/lib/x86_64-linux-gnu/libc.so.6(abort+0x12b) [0x7f645db25899]
MyGame_Game/Game/MyGame.x86_64() [0xd341e6]
/home/username0/MyGame_Game/Game/MyGame_Data/MonoBleedingEdge/x86_64/libmonobdwgc-2.0.so(+0x14ea2e) [0x7f644c1d0a2e]    /home/username0/MyGame_Game/Game/MyGame_Data/MonoBleedingEdge/x86_64/libmonobdwgc-2.0.so(+0x5be11) [0x7f644c0dde11]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x15540) [0x7f645dd08540]
MyGame_Game/Game/MyGame.x86_64() [0xb23e60]
MyGame_Game/Game/MyGame.x86_64() [0xff382c]
MyGame_Game/Game/MyGame.x86_64() [0x102c983]
MyGame_Game/Game/MyGame.x86_64() [0x102d9c5]
MyGame_Game/Game/MyGame.x86_64() [0xc07080]
MyGame_Game/Game/MyGame.x86_64() [0xc0719f]
MyGame_Game/Game/MyGame.x86_64() [0xc07522]
MyGame_Game/Game/MyGame.x86_64() [0xc07798]
MyGame_Game/Game/MyGame.x86_64() [0xc078db]
MyGame_Game/Game/MyGame.x86_64() [0xcb8d90]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x9669) [0x7f645dcfc669]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x43) [0x7f645dc222b3]

Searching online about this exception I found it could be a bug of Mono and/or a driver compatibility issue. Now I'm updating Ubuntu from 19.04 to 20.04 to try the amdgpu-pro drivers (instead of amdgpu included in Ubuntu) since I can't find the amdgpu-pro driver for Ubuntu 19.04.

A: Finally, I found out that my problem was a Trail option of a particle.
While I was searching on the internet, I found other people saying the trail renderer could be the problem, but I didn't know I was using it since it was inside a particle (I have a few of them), so I was excluding this cause.
I also checked the driver compatibility issue, I updated to Ubuntu 20.04 and I installed the amdgpu-pro driver, but it didn't solve anything.
Hope this will be helpful.